1 import express from 'express'
8 UnauthorizedClientError,
9 UnsupportedGrantTypeError
10 } from '@node-oauth/oauth2-server'
11 import { randomBytesPromise } from '@server/helpers/core-utils'
12 import { isOTPValid } from '@server/helpers/otp'
13 import { MOAuthClient } from '@server/types/models'
14 import { sha1 } from '@shared/extra-utils'
15 import { HttpStatusCode } from '@shared/models'
16 import { OAUTH_LIFETIME, OTP } from '../../initializers/constants'
17 import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model'
19 class MissingTwoFactorError extends Error {
20 code = HttpStatusCode.UNAUTHORIZED_401
21 name = 'missing_two_factor'
24 class InvalidTwoFactorError extends Error {
25 code = HttpStatusCode.BAD_REQUEST_400
26 name = 'invalid_two_factor'
31 * Reimplement some functions of OAuth2Server to inject external auth methods
34 const oAuthServer = new OAuth2Server({
35 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
36 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
38 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
39 model: require('./oauth-model')
42 // ---------------------------------------------------------------------------
44 async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {
45 const request = new Request(req)
46 const { refreshTokenAuthName, bypassLogin } = options
48 if (request.method !== 'POST') {
49 throw new InvalidRequestError('Invalid request: method must be POST')
52 if (!request.is([ 'application/x-www-form-urlencoded' ])) {
53 throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')
56 const clientId = request.body.client_id
57 const clientSecret = request.body.client_secret
59 if (!clientId || !clientSecret) {
60 throw new InvalidClientError('Invalid client: cannot retrieve client credentials')
63 const client = await getClient(clientId, clientSecret)
65 throw new InvalidClientError('Invalid client: client is invalid')
68 const grantType = request.body.grant_type
70 throw new InvalidRequestError('Missing parameter: `grant_type`')
73 if (![ 'password', 'refresh_token' ].includes(grantType)) {
74 throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid')
77 if (!client.grants.includes(grantType)) {
78 throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')
81 if (grantType === 'password') {
82 return handlePasswordGrant({
89 return handleRefreshGrant({
96 function handleOAuthAuthenticate (
100 return oAuthServer.authenticate(new Request(req), new Response(res))
104 MissingTwoFactorError,
105 InvalidTwoFactorError,
108 handleOAuthAuthenticate
111 // ---------------------------------------------------------------------------
113 async function handlePasswordGrant (options: {
116 bypassLogin?: BypassLogin
118 const { request, client, bypassLogin } = options
120 if (!request.body.username) {
121 throw new InvalidRequestError('Missing parameter: `username`')
124 if (!bypassLogin && !request.body.password) {
125 throw new InvalidRequestError('Missing parameter: `password`')
128 const user = await getUser(request.body.username, request.body.password, bypassLogin)
129 if (!user) throw new InvalidGrantError('Invalid grant: user credentials are invalid')
131 if (user.otpSecret) {
132 if (!request.headers[OTP.HEADER_NAME]) {
133 throw new MissingTwoFactorError('Missing two factor header')
136 if (await isOTPValid({ encryptedSecret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) {
137 throw new InvalidTwoFactorError('Invalid two factor header')
141 const token = await buildToken()
143 return saveToken(token, client, user, { bypassLogin })
146 async function handleRefreshGrant (options: {
149 refreshTokenAuthName: string
151 const { request, client, refreshTokenAuthName } = options
153 if (!request.body.refresh_token) {
154 throw new InvalidRequestError('Missing parameter: `refresh_token`')
157 const refreshToken = await getRefreshToken(request.body.refresh_token)
160 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
163 if (refreshToken.client.id !== client.id) {
164 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
167 if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {
168 throw new InvalidGrantError('Invalid grant: refresh token has expired')
171 await revokeToken({ refreshToken: refreshToken.refreshToken })
173 const token = await buildToken()
175 return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })
178 function generateRandomToken () {
179 return randomBytesPromise(256)
180 .then(buffer => sha1(buffer))
183 function getTokenExpiresAt (type: 'access' | 'refresh') {
184 const lifetime = type === 'access'
185 ? OAUTH_LIFETIME.ACCESS_TOKEN
186 : OAUTH_LIFETIME.REFRESH_TOKEN
188 return new Date(Date.now() + lifetime * 1000)
191 async function buildToken () {
192 const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])
197 accessTokenExpiresAt: getTokenExpiresAt('access'),
198 refreshTokenExpiresAt: getTokenExpiresAt('refresh')