]>
Commit | Line | Data |
---|---|---|
41fb13c3 | 1 | import express from 'express' |
031bbcd2 | 2 | import OAuth2Server, { |
f43db2f4 C |
3 | InvalidClientError, |
4 | InvalidGrantError, | |
5 | InvalidRequestError, | |
6 | Request, | |
7 | Response, | |
8 | UnauthorizedClientError, | |
9 | UnsupportedGrantTypeError | |
031bbcd2 | 10 | } from '@node-oauth/oauth2-server' |
06aad801 | 11 | import { randomBytesPromise } from '@server/helpers/core-utils' |
a3e5f804 | 12 | import { isOTPValid } from '@server/helpers/otp' |
f43db2f4 | 13 | import { MOAuthClient } from '@server/types/models' |
f304a158 | 14 | import { sha1 } from '@shared/extra-utils' |
56f47830 C |
15 | import { HttpStatusCode } from '@shared/models' |
16 | import { OAUTH_LIFETIME, OTP } from '../../initializers/constants' | |
f43db2f4 | 17 | import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model' |
56f47830 C |
18 | |
19 | class MissingTwoFactorError extends Error { | |
20 | code = HttpStatusCode.UNAUTHORIZED_401 | |
21 | name = 'missing_two_factor' | |
22 | } | |
23 | ||
24 | class InvalidTwoFactorError extends Error { | |
25 | code = HttpStatusCode.BAD_REQUEST_400 | |
26 | name = 'invalid_two_factor' | |
27 | } | |
f43db2f4 C |
28 | |
29 | /** | |
30 | * | |
31 | * Reimplement some functions of OAuth2Server to inject external auth methods | |
32 | * | |
33 | */ | |
031bbcd2 | 34 | const oAuthServer = new OAuth2Server({ |
f43db2f4 C |
35 | accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN, |
36 | refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN, | |
37 | ||
38 | // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications | |
39 | model: require('./oauth-model') | |
40 | }) | |
41 | ||
42 | // --------------------------------------------------------------------------- | |
43 | ||
44 | async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) { | |
45 | const request = new Request(req) | |
46 | const { refreshTokenAuthName, bypassLogin } = options | |
47 | ||
48 | if (request.method !== 'POST') { | |
49 | throw new InvalidRequestError('Invalid request: method must be POST') | |
50 | } | |
51 | ||
52 | if (!request.is([ 'application/x-www-form-urlencoded' ])) { | |
53 | throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded') | |
54 | } | |
55 | ||
56 | const clientId = request.body.client_id | |
57 | const clientSecret = request.body.client_secret | |
58 | ||
59 | if (!clientId || !clientSecret) { | |
60 | throw new InvalidClientError('Invalid client: cannot retrieve client credentials') | |
61 | } | |
62 | ||
63 | const client = await getClient(clientId, clientSecret) | |
64 | if (!client) { | |
65 | throw new InvalidClientError('Invalid client: client is invalid') | |
66 | } | |
67 | ||
68 | const grantType = request.body.grant_type | |
69 | if (!grantType) { | |
70 | throw new InvalidRequestError('Missing parameter: `grant_type`') | |
71 | } | |
72 | ||
73 | if (![ 'password', 'refresh_token' ].includes(grantType)) { | |
74 | throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid') | |
75 | } | |
76 | ||
77 | if (!client.grants.includes(grantType)) { | |
78 | throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid') | |
79 | } | |
80 | ||
81 | if (grantType === 'password') { | |
82 | return handlePasswordGrant({ | |
83 | request, | |
84 | client, | |
85 | bypassLogin | |
86 | }) | |
87 | } | |
88 | ||
89 | return handleRefreshGrant({ | |
90 | request, | |
91 | client, | |
92 | refreshTokenAuthName | |
93 | }) | |
94 | } | |
95 | ||
98ab5dc8 | 96 | function handleOAuthAuthenticate ( |
f43db2f4 | 97 | req: express.Request, |
3545e72c | 98 | res: express.Response |
f43db2f4 | 99 | ) { |
3545e72c | 100 | return oAuthServer.authenticate(new Request(req), new Response(res)) |
f43db2f4 C |
101 | } |
102 | ||
103 | export { | |
56f47830 C |
104 | MissingTwoFactorError, |
105 | InvalidTwoFactorError, | |
106 | ||
f43db2f4 C |
107 | handleOAuthToken, |
108 | handleOAuthAuthenticate | |
109 | } | |
110 | ||
111 | // --------------------------------------------------------------------------- | |
112 | ||
113 | async function handlePasswordGrant (options: { | |
114 | request: Request | |
115 | client: MOAuthClient | |
116 | bypassLogin?: BypassLogin | |
117 | }) { | |
118 | const { request, client, bypassLogin } = options | |
119 | ||
120 | if (!request.body.username) { | |
121 | throw new InvalidRequestError('Missing parameter: `username`') | |
122 | } | |
123 | ||
124 | if (!bypassLogin && !request.body.password) { | |
125 | throw new InvalidRequestError('Missing parameter: `password`') | |
126 | } | |
127 | ||
128 | const user = await getUser(request.body.username, request.body.password, bypassLogin) | |
129 | if (!user) throw new InvalidGrantError('Invalid grant: user credentials are invalid') | |
130 | ||
56f47830 C |
131 | if (user.otpSecret) { |
132 | if (!request.headers[OTP.HEADER_NAME]) { | |
133 | throw new MissingTwoFactorError('Missing two factor header') | |
134 | } | |
135 | ||
a3e5f804 | 136 | if (await isOTPValid({ encryptedSecret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) { |
56f47830 C |
137 | throw new InvalidTwoFactorError('Invalid two factor header') |
138 | } | |
139 | } | |
140 | ||
f43db2f4 C |
141 | const token = await buildToken() |
142 | ||
143 | return saveToken(token, client, user, { bypassLogin }) | |
144 | } | |
145 | ||
146 | async function handleRefreshGrant (options: { | |
147 | request: Request | |
148 | client: MOAuthClient | |
149 | refreshTokenAuthName: string | |
150 | }) { | |
151 | const { request, client, refreshTokenAuthName } = options | |
152 | ||
153 | if (!request.body.refresh_token) { | |
154 | throw new InvalidRequestError('Missing parameter: `refresh_token`') | |
155 | } | |
156 | ||
157 | const refreshToken = await getRefreshToken(request.body.refresh_token) | |
158 | ||
159 | if (!refreshToken) { | |
160 | throw new InvalidGrantError('Invalid grant: refresh token is invalid') | |
161 | } | |
162 | ||
163 | if (refreshToken.client.id !== client.id) { | |
164 | throw new InvalidGrantError('Invalid grant: refresh token is invalid') | |
165 | } | |
166 | ||
167 | if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) { | |
168 | throw new InvalidGrantError('Invalid grant: refresh token has expired') | |
169 | } | |
170 | ||
171 | await revokeToken({ refreshToken: refreshToken.refreshToken }) | |
172 | ||
173 | const token = await buildToken() | |
174 | ||
175 | return saveToken(token, client, refreshToken.user, { refreshTokenAuthName }) | |
176 | } | |
177 | ||
178 | function generateRandomToken () { | |
179 | return randomBytesPromise(256) | |
180 | .then(buffer => sha1(buffer)) | |
181 | } | |
182 | ||
183 | function getTokenExpiresAt (type: 'access' | 'refresh') { | |
184 | const lifetime = type === 'access' | |
185 | ? OAUTH_LIFETIME.ACCESS_TOKEN | |
186 | : OAUTH_LIFETIME.REFRESH_TOKEN | |
187 | ||
188 | return new Date(Date.now() + lifetime * 1000) | |
189 | } | |
190 | ||
191 | async function buildToken () { | |
192 | const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ]) | |
193 | ||
194 | return { | |
195 | accessToken, | |
196 | refreshToken, | |
197 | accessTokenExpiresAt: getTokenExpiresAt('access'), | |
198 | refreshTokenExpiresAt: getTokenExpiresAt('refresh') | |
199 | } | |
200 | } |