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 { CONFIG } from '@server/initializers/config'
14 import { MOAuthClient } from '@server/types/models'
15 import { sha1 } from '@shared/extra-utils'
16 import { HttpStatusCode } from '@shared/models'
17 import { OTP } from '../../initializers/constants'
18 import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model'
20 class MissingTwoFactorError extends Error {
21 code = HttpStatusCode.UNAUTHORIZED_401
22 name = 'missing_two_factor'
25 class InvalidTwoFactorError extends Error {
26 code = HttpStatusCode.BAD_REQUEST_400
27 name = 'invalid_two_factor'
32 * Reimplement some functions of OAuth2Server to inject external auth methods
35 const oAuthServer = new OAuth2Server({
37 accessTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN / 1000,
38 refreshTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN / 1000,
40 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
41 model: require('./oauth-model')
44 // ---------------------------------------------------------------------------
46 async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {
47 const request = new Request(req)
48 const { refreshTokenAuthName, bypassLogin } = options
50 if (request.method !== 'POST') {
51 throw new InvalidRequestError('Invalid request: method must be POST')
54 if (!request.is([ 'application/x-www-form-urlencoded' ])) {
55 throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')
58 const clientId = request.body.client_id
59 const clientSecret = request.body.client_secret
61 if (!clientId || !clientSecret) {
62 throw new InvalidClientError('Invalid client: cannot retrieve client credentials')
65 const client = await getClient(clientId, clientSecret)
67 throw new InvalidClientError('Invalid client: client is invalid')
70 const grantType = request.body.grant_type
72 throw new InvalidRequestError('Missing parameter: `grant_type`')
75 if (![ 'password', 'refresh_token' ].includes(grantType)) {
76 throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid')
79 if (!client.grants.includes(grantType)) {
80 throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')
83 if (grantType === 'password') {
84 return handlePasswordGrant({
91 return handleRefreshGrant({
98 function handleOAuthAuthenticate (
100 res: express.Response
102 return oAuthServer.authenticate(new Request(req), new Response(res))
106 MissingTwoFactorError,
107 InvalidTwoFactorError,
110 handleOAuthAuthenticate
113 // ---------------------------------------------------------------------------
115 async function handlePasswordGrant (options: {
118 bypassLogin?: BypassLogin
120 const { request, client, bypassLogin } = options
122 if (!request.body.username) {
123 throw new InvalidRequestError('Missing parameter: `username`')
126 if (!bypassLogin && !request.body.password) {
127 throw new InvalidRequestError('Missing parameter: `password`')
130 const user = await getUser(request.body.username, request.body.password, bypassLogin)
131 if (!user) throw new InvalidGrantError('Invalid grant: user credentials are invalid')
133 if (user.otpSecret) {
134 if (!request.headers[OTP.HEADER_NAME]) {
135 throw new MissingTwoFactorError('Missing two factor header')
138 if (await isOTPValid({ encryptedSecret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) {
139 throw new InvalidTwoFactorError('Invalid two factor header')
143 const token = await buildToken()
145 return saveToken(token, client, user, { bypassLogin })
148 async function handleRefreshGrant (options: {
151 refreshTokenAuthName: string
153 const { request, client, refreshTokenAuthName } = options
155 if (!request.body.refresh_token) {
156 throw new InvalidRequestError('Missing parameter: `refresh_token`')
159 const refreshToken = await getRefreshToken(request.body.refresh_token)
162 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
165 if (refreshToken.client.id !== client.id) {
166 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
169 if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {
170 throw new InvalidGrantError('Invalid grant: refresh token has expired')
173 await revokeToken({ refreshToken: refreshToken.refreshToken })
175 const token = await buildToken()
177 return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })
180 function generateRandomToken () {
181 return randomBytesPromise(256)
182 .then(buffer => sha1(buffer))
185 function getTokenExpiresAt (type: 'access' | 'refresh') {
186 const lifetime = type === 'access'
187 ? CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN
188 : CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN
190 return new Date(Date.now() + lifetime)
193 async function buildToken () {
194 const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])
199 accessTokenExpiresAt: getTokenExpiresAt('access'),
200 refreshTokenExpiresAt: getTokenExpiresAt('refresh')