diff options
author | Chocobozzz <me@florianbigard.com> | 2023-07-31 14:34:36 +0200 |
---|---|---|
committer | Chocobozzz <me@florianbigard.com> | 2023-08-11 15:02:33 +0200 |
commit | 3a4992633ee62d5edfbb484d9c6bcb3cf158489d (patch) | |
tree | e4510b39bdac9c318fdb4b47018d08f15368b8f0 /server/lib/auth | |
parent | 04d1da5621d25d59bd5fa1543b725c497bf5d9a8 (diff) | |
download | PeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.tar.gz PeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.tar.zst PeerTube-3a4992633ee62d5edfbb484d9c6bcb3cf158489d.zip |
Migrate server to ESM
Sorry for the very big commit that may lead to git log issues and merge
conflicts, but it's a major step forward:
* Server can be faster at startup because imports() are async and we can
easily lazy import big modules
* Angular doesn't seem to support ES import (with .js extension), so we
had to correctly organize peertube into a monorepo:
* Use yarn workspace feature
* Use typescript reference projects for dependencies
* Shared projects have been moved into "packages", each one is now a
node module (with a dedicated package.json/tsconfig.json)
* server/tools have been moved into apps/ and is now a dedicated app
bundled and published on NPM so users don't have to build peertube
cli tools manually
* server/tests have been moved into packages/ so we don't compile
them every time we want to run the server
* Use isolatedModule option:
* Had to move from const enum to const
(https://www.typescriptlang.org/docs/handbook/enums.html#objects-vs-enums)
* Had to explictely specify "type" imports when used in decorators
* Prefer tsx (that uses esbuild under the hood) instead of ts-node to
load typescript files (tests with mocha or scripts):
* To reduce test complexity as esbuild doesn't support decorator
metadata, we only test server files that do not import server
models
* We still build tests files into js files for a faster CI
* Remove unmaintained peertube CLI import script
* Removed some barrels to speed up execution (less imports)
Diffstat (limited to 'server/lib/auth')
-rw-r--r-- | server/lib/auth/external-auth.ts | 231 | ||||
-rw-r--r-- | server/lib/auth/oauth-model.ts | 294 | ||||
-rw-r--r-- | server/lib/auth/oauth.ts | 223 | ||||
-rw-r--r-- | server/lib/auth/tokens-cache.ts | 52 |
4 files changed, 0 insertions, 800 deletions
diff --git a/server/lib/auth/external-auth.ts b/server/lib/auth/external-auth.ts deleted file mode 100644 index bc5b74257..000000000 --- a/server/lib/auth/external-auth.ts +++ /dev/null | |||
@@ -1,231 +0,0 @@ | |||
1 | |||
2 | import { | ||
3 | isUserAdminFlagsValid, | ||
4 | isUserDisplayNameValid, | ||
5 | isUserRoleValid, | ||
6 | isUserUsernameValid, | ||
7 | isUserVideoQuotaDailyValid, | ||
8 | isUserVideoQuotaValid | ||
9 | } from '@server/helpers/custom-validators/users' | ||
10 | import { logger } from '@server/helpers/logger' | ||
11 | import { generateRandomString } from '@server/helpers/utils' | ||
12 | import { PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME } from '@server/initializers/constants' | ||
13 | import { PluginManager } from '@server/lib/plugins/plugin-manager' | ||
14 | import { OAuthTokenModel } from '@server/models/oauth/oauth-token' | ||
15 | import { MUser } from '@server/types/models' | ||
16 | import { | ||
17 | RegisterServerAuthenticatedResult, | ||
18 | RegisterServerAuthPassOptions, | ||
19 | RegisterServerExternalAuthenticatedResult | ||
20 | } from '@server/types/plugins/register-server-auth.model' | ||
21 | import { UserAdminFlag, UserRole } from '@shared/models' | ||
22 | import { BypassLogin } from './oauth-model' | ||
23 | |||
24 | export type ExternalUser = | ||
25 | Pick<MUser, 'username' | 'email' | 'role' | 'adminFlags' | 'videoQuotaDaily' | 'videoQuota'> & | ||
26 | { displayName: string } | ||
27 | |||
28 | // Token is the key, expiration date is the value | ||
29 | const authBypassTokens = new Map<string, { | ||
30 | expires: Date | ||
31 | user: ExternalUser | ||
32 | userUpdater: RegisterServerAuthenticatedResult['userUpdater'] | ||
33 | authName: string | ||
34 | npmName: string | ||
35 | }>() | ||
36 | |||
37 | async function onExternalUserAuthenticated (options: { | ||
38 | npmName: string | ||
39 | authName: string | ||
40 | authResult: RegisterServerExternalAuthenticatedResult | ||
41 | }) { | ||
42 | const { npmName, authName, authResult } = options | ||
43 | |||
44 | if (!authResult.req || !authResult.res) { | ||
45 | logger.error('Cannot authenticate external user for auth %s of plugin %s: no req or res are provided.', authName, npmName) | ||
46 | return | ||
47 | } | ||
48 | |||
49 | const { res } = authResult | ||
50 | |||
51 | if (!isAuthResultValid(npmName, authName, authResult)) { | ||
52 | res.redirect('/login?externalAuthError=true') | ||
53 | return | ||
54 | } | ||
55 | |||
56 | logger.info('Generating auth bypass token for %s in auth %s of plugin %s.', authResult.username, authName, npmName) | ||
57 | |||
58 | const bypassToken = await generateRandomString(32) | ||
59 | |||
60 | const expires = new Date() | ||
61 | expires.setTime(expires.getTime() + PLUGIN_EXTERNAL_AUTH_TOKEN_LIFETIME) | ||
62 | |||
63 | const user = buildUserResult(authResult) | ||
64 | authBypassTokens.set(bypassToken, { | ||
65 | expires, | ||
66 | user, | ||
67 | npmName, | ||
68 | authName, | ||
69 | userUpdater: authResult.userUpdater | ||
70 | }) | ||
71 | |||
72 | // Cleanup expired tokens | ||
73 | const now = new Date() | ||
74 | for (const [ key, value ] of authBypassTokens) { | ||
75 | if (value.expires.getTime() < now.getTime()) { | ||
76 | authBypassTokens.delete(key) | ||
77 | } | ||
78 | } | ||
79 | |||
80 | res.redirect(`/login?externalAuthToken=${bypassToken}&username=${user.username}`) | ||
81 | } | ||
82 | |||
83 | async function getAuthNameFromRefreshGrant (refreshToken?: string) { | ||
84 | if (!refreshToken) return undefined | ||
85 | |||
86 | const tokenModel = await OAuthTokenModel.loadByRefreshToken(refreshToken) | ||
87 | |||
88 | return tokenModel?.authName | ||
89 | } | ||
90 | |||
91 | async function getBypassFromPasswordGrant (username: string, password: string): Promise<BypassLogin> { | ||
92 | const plugins = PluginManager.Instance.getIdAndPassAuths() | ||
93 | const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = [] | ||
94 | |||
95 | for (const plugin of plugins) { | ||
96 | const auths = plugin.idAndPassAuths | ||
97 | |||
98 | for (const auth of auths) { | ||
99 | pluginAuths.push({ | ||
100 | npmName: plugin.npmName, | ||
101 | registerAuthOptions: auth | ||
102 | }) | ||
103 | } | ||
104 | } | ||
105 | |||
106 | pluginAuths.sort((a, b) => { | ||
107 | const aWeight = a.registerAuthOptions.getWeight() | ||
108 | const bWeight = b.registerAuthOptions.getWeight() | ||
109 | |||
110 | // DESC weight order | ||
111 | if (aWeight === bWeight) return 0 | ||
112 | if (aWeight < bWeight) return 1 | ||
113 | return -1 | ||
114 | }) | ||
115 | |||
116 | const loginOptions = { | ||
117 | id: username, | ||
118 | password | ||
119 | } | ||
120 | |||
121 | for (const pluginAuth of pluginAuths) { | ||
122 | const authOptions = pluginAuth.registerAuthOptions | ||
123 | const authName = authOptions.authName | ||
124 | const npmName = pluginAuth.npmName | ||
125 | |||
126 | logger.debug( | ||
127 | 'Using auth method %s of plugin %s to login %s with weight %d.', | ||
128 | authName, npmName, loginOptions.id, authOptions.getWeight() | ||
129 | ) | ||
130 | |||
131 | try { | ||
132 | const loginResult = await authOptions.login(loginOptions) | ||
133 | |||
134 | if (!loginResult) continue | ||
135 | if (!isAuthResultValid(pluginAuth.npmName, authOptions.authName, loginResult)) continue | ||
136 | |||
137 | logger.info( | ||
138 | 'Login success with auth method %s of plugin %s for %s.', | ||
139 | authName, npmName, loginOptions.id | ||
140 | ) | ||
141 | |||
142 | return { | ||
143 | bypass: true, | ||
144 | pluginName: pluginAuth.npmName, | ||
145 | authName: authOptions.authName, | ||
146 | user: buildUserResult(loginResult), | ||
147 | userUpdater: loginResult.userUpdater | ||
148 | } | ||
149 | } catch (err) { | ||
150 | logger.error('Error in auth method %s of plugin %s', authOptions.authName, pluginAuth.npmName, { err }) | ||
151 | } | ||
152 | } | ||
153 | |||
154 | return undefined | ||
155 | } | ||
156 | |||
157 | function getBypassFromExternalAuth (username: string, externalAuthToken: string): BypassLogin { | ||
158 | const obj = authBypassTokens.get(externalAuthToken) | ||
159 | if (!obj) throw new Error('Cannot authenticate user with unknown bypass token') | ||
160 | |||
161 | const { expires, user, authName, npmName } = obj | ||
162 | |||
163 | const now = new Date() | ||
164 | if (now.getTime() > expires.getTime()) { | ||
165 | throw new Error('Cannot authenticate user with an expired external auth token') | ||
166 | } | ||
167 | |||
168 | if (user.username !== username) { | ||
169 | throw new Error(`Cannot authenticate user ${user.username} with invalid username ${username}`) | ||
170 | } | ||
171 | |||
172 | logger.info( | ||
173 | 'Auth success with external auth method %s of plugin %s for %s.', | ||
174 | authName, npmName, user.email | ||
175 | ) | ||
176 | |||
177 | return { | ||
178 | bypass: true, | ||
179 | pluginName: npmName, | ||
180 | authName, | ||
181 | userUpdater: obj.userUpdater, | ||
182 | user | ||
183 | } | ||
184 | } | ||
185 | |||
186 | function isAuthResultValid (npmName: string, authName: string, result: RegisterServerAuthenticatedResult) { | ||
187 | const returnError = (field: string) => { | ||
188 | logger.error('Auth method %s of plugin %s did not provide a valid %s.', authName, npmName, field, { [field]: result[field] }) | ||
189 | return false | ||
190 | } | ||
191 | |||
192 | if (!isUserUsernameValid(result.username)) return returnError('username') | ||
193 | if (!result.email) return returnError('email') | ||
194 | |||
195 | // Following fields are optional | ||
196 | if (result.role && !isUserRoleValid(result.role)) return returnError('role') | ||
197 | if (result.displayName && !isUserDisplayNameValid(result.displayName)) return returnError('displayName') | ||
198 | if (result.adminFlags && !isUserAdminFlagsValid(result.adminFlags)) return returnError('adminFlags') | ||
199 | if (result.videoQuota && !isUserVideoQuotaValid(result.videoQuota + '')) return returnError('videoQuota') | ||
200 | if (result.videoQuotaDaily && !isUserVideoQuotaDailyValid(result.videoQuotaDaily + '')) return returnError('videoQuotaDaily') | ||
201 | |||
202 | if (result.userUpdater && typeof result.userUpdater !== 'function') { | ||
203 | logger.error('Auth method %s of plugin %s did not provide a valid user updater function.', authName, npmName) | ||
204 | return false | ||
205 | } | ||
206 | |||
207 | return true | ||
208 | } | ||
209 | |||
210 | function buildUserResult (pluginResult: RegisterServerAuthenticatedResult) { | ||
211 | return { | ||
212 | username: pluginResult.username, | ||
213 | email: pluginResult.email, | ||
214 | role: pluginResult.role ?? UserRole.USER, | ||
215 | displayName: pluginResult.displayName || pluginResult.username, | ||
216 | |||
217 | adminFlags: pluginResult.adminFlags ?? UserAdminFlag.NONE, | ||
218 | |||
219 | videoQuota: pluginResult.videoQuota, | ||
220 | videoQuotaDaily: pluginResult.videoQuotaDaily | ||
221 | } | ||
222 | } | ||
223 | |||
224 | // --------------------------------------------------------------------------- | ||
225 | |||
226 | export { | ||
227 | onExternalUserAuthenticated, | ||
228 | getBypassFromExternalAuth, | ||
229 | getAuthNameFromRefreshGrant, | ||
230 | getBypassFromPasswordGrant | ||
231 | } | ||
diff --git a/server/lib/auth/oauth-model.ts b/server/lib/auth/oauth-model.ts deleted file mode 100644 index d3a5eccd5..000000000 --- a/server/lib/auth/oauth-model.ts +++ /dev/null | |||
@@ -1,294 +0,0 @@ | |||
1 | import express from 'express' | ||
2 | import { AccessDeniedError } from '@node-oauth/oauth2-server' | ||
3 | import { PluginManager } from '@server/lib/plugins/plugin-manager' | ||
4 | import { AccountModel } from '@server/models/account/account' | ||
5 | import { AuthenticatedResultUpdaterFieldName, RegisterServerAuthenticatedResult } from '@server/types' | ||
6 | import { MOAuthClient } from '@server/types/models' | ||
7 | import { MOAuthTokenUser } from '@server/types/models/oauth/oauth-token' | ||
8 | import { MUser, MUserDefault } from '@server/types/models/user/user' | ||
9 | import { pick } from '@shared/core-utils' | ||
10 | import { AttributesOnly } from '@shared/typescript-utils' | ||
11 | import { logger } from '../../helpers/logger' | ||
12 | import { CONFIG } from '../../initializers/config' | ||
13 | import { OAuthClientModel } from '../../models/oauth/oauth-client' | ||
14 | import { OAuthTokenModel } from '../../models/oauth/oauth-token' | ||
15 | import { UserModel } from '../../models/user/user' | ||
16 | import { findAvailableLocalActorName } from '../local-actor' | ||
17 | import { buildUser, createUserAccountAndChannelAndPlaylist } from '../user' | ||
18 | import { ExternalUser } from './external-auth' | ||
19 | import { TokensCache } from './tokens-cache' | ||
20 | |||
21 | type TokenInfo = { | ||
22 | accessToken: string | ||
23 | refreshToken: string | ||
24 | accessTokenExpiresAt: Date | ||
25 | refreshTokenExpiresAt: Date | ||
26 | } | ||
27 | |||
28 | export type BypassLogin = { | ||
29 | bypass: boolean | ||
30 | pluginName: string | ||
31 | authName?: string | ||
32 | user: ExternalUser | ||
33 | userUpdater: RegisterServerAuthenticatedResult['userUpdater'] | ||
34 | } | ||
35 | |||
36 | async function getAccessToken (bearerToken: string) { | ||
37 | logger.debug('Getting access token.') | ||
38 | |||
39 | if (!bearerToken) return undefined | ||
40 | |||
41 | let tokenModel: MOAuthTokenUser | ||
42 | |||
43 | if (TokensCache.Instance.hasToken(bearerToken)) { | ||
44 | tokenModel = TokensCache.Instance.getByToken(bearerToken) | ||
45 | } else { | ||
46 | tokenModel = await OAuthTokenModel.getByTokenAndPopulateUser(bearerToken) | ||
47 | |||
48 | if (tokenModel) TokensCache.Instance.setToken(tokenModel) | ||
49 | } | ||
50 | |||
51 | if (!tokenModel) return undefined | ||
52 | |||
53 | if (tokenModel.User.pluginAuth) { | ||
54 | const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'access') | ||
55 | |||
56 | if (valid !== true) return undefined | ||
57 | } | ||
58 | |||
59 | return tokenModel | ||
60 | } | ||
61 | |||
62 | function getClient (clientId: string, clientSecret: string) { | ||
63 | logger.debug('Getting Client (clientId: ' + clientId + ', clientSecret: ' + clientSecret + ').') | ||
64 | |||
65 | return OAuthClientModel.getByIdAndSecret(clientId, clientSecret) | ||
66 | } | ||
67 | |||
68 | async function getRefreshToken (refreshToken: string) { | ||
69 | logger.debug('Getting RefreshToken (refreshToken: ' + refreshToken + ').') | ||
70 | |||
71 | const tokenInfo = await OAuthTokenModel.getByRefreshTokenAndPopulateClient(refreshToken) | ||
72 | if (!tokenInfo) return undefined | ||
73 | |||
74 | const tokenModel = tokenInfo.token | ||
75 | |||
76 | if (tokenModel.User.pluginAuth) { | ||
77 | const valid = await PluginManager.Instance.isTokenValid(tokenModel, 'refresh') | ||
78 | |||
79 | if (valid !== true) return undefined | ||
80 | } | ||
81 | |||
82 | return tokenInfo | ||
83 | } | ||
84 | |||
85 | async function getUser (usernameOrEmail?: string, password?: string, bypassLogin?: BypassLogin) { | ||
86 | // Special treatment coming from a plugin | ||
87 | if (bypassLogin && bypassLogin.bypass === true) { | ||
88 | logger.info('Bypassing oauth login by plugin %s.', bypassLogin.pluginName) | ||
89 | |||
90 | let user = await UserModel.loadByEmail(bypassLogin.user.email) | ||
91 | |||
92 | if (!user) user = await createUserFromExternal(bypassLogin.pluginName, bypassLogin.user) | ||
93 | else user = await updateUserFromExternal(user, bypassLogin.user, bypassLogin.userUpdater) | ||
94 | |||
95 | // Cannot create a user | ||
96 | if (!user) throw new AccessDeniedError('Cannot create such user: an actor with that name already exists.') | ||
97 | |||
98 | // If the user does not belongs to a plugin, it was created before its installation | ||
99 | // Then we just go through a regular login process | ||
100 | if (user.pluginAuth !== null) { | ||
101 | // This user does not belong to this plugin, skip it | ||
102 | if (user.pluginAuth !== bypassLogin.pluginName) { | ||
103 | logger.info( | ||
104 | 'Cannot bypass oauth login by plugin %s because %s has another plugin auth method (%s).', | ||
105 | bypassLogin.pluginName, bypassLogin.user.email, user.pluginAuth | ||
106 | ) | ||
107 | |||
108 | return null | ||
109 | } | ||
110 | |||
111 | checkUserValidityOrThrow(user) | ||
112 | |||
113 | return user | ||
114 | } | ||
115 | } | ||
116 | |||
117 | logger.debug('Getting User (username/email: ' + usernameOrEmail + ', password: ******).') | ||
118 | |||
119 | const user = await UserModel.loadByUsernameOrEmail(usernameOrEmail) | ||
120 | |||
121 | // If we don't find the user, or if the user belongs to a plugin | ||
122 | if (!user || user.pluginAuth !== null || !password) return null | ||
123 | |||
124 | const passwordMatch = await user.isPasswordMatch(password) | ||
125 | if (passwordMatch !== true) return null | ||
126 | |||
127 | checkUserValidityOrThrow(user) | ||
128 | |||
129 | if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) { | ||
130 | throw new AccessDeniedError('User email is not verified.') | ||
131 | } | ||
132 | |||
133 | return user | ||
134 | } | ||
135 | |||
136 | async function revokeToken ( | ||
137 | tokenInfo: { refreshToken: string }, | ||
138 | options: { | ||
139 | req?: express.Request | ||
140 | explicitLogout?: boolean | ||
141 | } = {} | ||
142 | ): Promise<{ success: boolean, redirectUrl?: string }> { | ||
143 | const { req, explicitLogout } = options | ||
144 | |||
145 | const token = await OAuthTokenModel.getByRefreshTokenAndPopulateUser(tokenInfo.refreshToken) | ||
146 | |||
147 | if (token) { | ||
148 | let redirectUrl: string | ||
149 | |||
150 | if (explicitLogout === true && token.User.pluginAuth && token.authName) { | ||
151 | redirectUrl = await PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName, token.User, req) | ||
152 | } | ||
153 | |||
154 | TokensCache.Instance.clearCacheByToken(token.accessToken) | ||
155 | |||
156 | token.destroy() | ||
157 | .catch(err => logger.error('Cannot destroy token when revoking token.', { err })) | ||
158 | |||
159 | return { success: true, redirectUrl } | ||
160 | } | ||
161 | |||
162 | return { success: false } | ||
163 | } | ||
164 | |||
165 | async function saveToken ( | ||
166 | token: TokenInfo, | ||
167 | client: MOAuthClient, | ||
168 | user: MUser, | ||
169 | options: { | ||
170 | refreshTokenAuthName?: string | ||
171 | bypassLogin?: BypassLogin | ||
172 | } = {} | ||
173 | ) { | ||
174 | const { refreshTokenAuthName, bypassLogin } = options | ||
175 | let authName: string = null | ||
176 | |||
177 | if (bypassLogin?.bypass === true) { | ||
178 | authName = bypassLogin.authName | ||
179 | } else if (refreshTokenAuthName) { | ||
180 | authName = refreshTokenAuthName | ||
181 | } | ||
182 | |||
183 | logger.debug('Saving token ' + token.accessToken + ' for client ' + client.id + ' and user ' + user.id + '.') | ||
184 | |||
185 | const tokenToCreate = { | ||
186 | accessToken: token.accessToken, | ||
187 | accessTokenExpiresAt: token.accessTokenExpiresAt, | ||
188 | refreshToken: token.refreshToken, | ||
189 | refreshTokenExpiresAt: token.refreshTokenExpiresAt, | ||
190 | authName, | ||
191 | oAuthClientId: client.id, | ||
192 | userId: user.id | ||
193 | } | ||
194 | |||
195 | const tokenCreated = await OAuthTokenModel.create(tokenToCreate) | ||
196 | |||
197 | user.lastLoginDate = new Date() | ||
198 | await user.save() | ||
199 | |||
200 | return { | ||
201 | accessToken: tokenCreated.accessToken, | ||
202 | accessTokenExpiresAt: tokenCreated.accessTokenExpiresAt, | ||
203 | refreshToken: tokenCreated.refreshToken, | ||
204 | refreshTokenExpiresAt: tokenCreated.refreshTokenExpiresAt, | ||
205 | client, | ||
206 | user, | ||
207 | accessTokenExpiresIn: buildExpiresIn(tokenCreated.accessTokenExpiresAt), | ||
208 | refreshTokenExpiresIn: buildExpiresIn(tokenCreated.refreshTokenExpiresAt) | ||
209 | } | ||
210 | } | ||
211 | |||
212 | export { | ||
213 | getAccessToken, | ||
214 | getClient, | ||
215 | getRefreshToken, | ||
216 | getUser, | ||
217 | revokeToken, | ||
218 | saveToken | ||
219 | } | ||
220 | |||
221 | // --------------------------------------------------------------------------- | ||
222 | |||
223 | async function createUserFromExternal (pluginAuth: string, userOptions: ExternalUser) { | ||
224 | const username = await findAvailableLocalActorName(userOptions.username) | ||
225 | |||
226 | const userToCreate = buildUser({ | ||
227 | ...pick(userOptions, [ 'email', 'role', 'adminFlags', 'videoQuota', 'videoQuotaDaily' ]), | ||
228 | |||
229 | username, | ||
230 | emailVerified: null, | ||
231 | password: null, | ||
232 | pluginAuth | ||
233 | }) | ||
234 | |||
235 | const { user } = await createUserAccountAndChannelAndPlaylist({ | ||
236 | userToCreate, | ||
237 | userDisplayName: userOptions.displayName | ||
238 | }) | ||
239 | |||
240 | return user | ||
241 | } | ||
242 | |||
243 | async function updateUserFromExternal ( | ||
244 | user: MUserDefault, | ||
245 | userOptions: ExternalUser, | ||
246 | userUpdater: RegisterServerAuthenticatedResult['userUpdater'] | ||
247 | ) { | ||
248 | if (!userUpdater) return user | ||
249 | |||
250 | { | ||
251 | type UserAttributeKeys = keyof AttributesOnly<UserModel> | ||
252 | const mappingKeys: { [ id in UserAttributeKeys ]?: AuthenticatedResultUpdaterFieldName } = { | ||
253 | role: 'role', | ||
254 | adminFlags: 'adminFlags', | ||
255 | videoQuota: 'videoQuota', | ||
256 | videoQuotaDaily: 'videoQuotaDaily' | ||
257 | } | ||
258 | |||
259 | for (const modelKey of Object.keys(mappingKeys)) { | ||
260 | const pluginOptionKey = mappingKeys[modelKey] | ||
261 | |||
262 | const newValue = userUpdater({ fieldName: pluginOptionKey, currentValue: user[modelKey], newValue: userOptions[pluginOptionKey] }) | ||
263 | user.set(modelKey, newValue) | ||
264 | } | ||
265 | } | ||
266 | |||
267 | { | ||
268 | type AccountAttributeKeys = keyof Partial<AttributesOnly<AccountModel>> | ||
269 | const mappingKeys: { [ id in AccountAttributeKeys ]?: AuthenticatedResultUpdaterFieldName } = { | ||
270 | name: 'displayName' | ||
271 | } | ||
272 | |||
273 | for (const modelKey of Object.keys(mappingKeys)) { | ||
274 | const optionKey = mappingKeys[modelKey] | ||
275 | |||
276 | const newValue = userUpdater({ fieldName: optionKey, currentValue: user.Account[modelKey], newValue: userOptions[optionKey] }) | ||
277 | user.Account.set(modelKey, newValue) | ||
278 | } | ||
279 | } | ||
280 | |||
281 | logger.debug('Updated user %s with plugin userUpdated function.', user.email, { user, userOptions }) | ||
282 | |||
283 | user.Account = await user.Account.save() | ||
284 | |||
285 | return user.save() | ||
286 | } | ||
287 | |||
288 | function checkUserValidityOrThrow (user: MUser) { | ||
289 | if (user.blocked) throw new AccessDeniedError('User is blocked.') | ||
290 | } | ||
291 | |||
292 | function buildExpiresIn (expiresAt: Date) { | ||
293 | return Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000) | ||
294 | } | ||
diff --git a/server/lib/auth/oauth.ts b/server/lib/auth/oauth.ts deleted file mode 100644 index 887c4f7c9..000000000 --- a/server/lib/auth/oauth.ts +++ /dev/null | |||
@@ -1,223 +0,0 @@ | |||
1 | import express from 'express' | ||
2 | import OAuth2Server, { | ||
3 | InvalidClientError, | ||
4 | InvalidGrantError, | ||
5 | InvalidRequestError, | ||
6 | Request, | ||
7 | Response, | ||
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 { UserRegistrationModel } from '@server/models/user/user-registration' | ||
15 | import { MOAuthClient } from '@server/types/models' | ||
16 | import { sha1 } from '@shared/extra-utils' | ||
17 | import { HttpStatusCode, ServerErrorCode, UserRegistrationState } from '@shared/models' | ||
18 | import { OTP } from '../../initializers/constants' | ||
19 | import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model' | ||
20 | |||
21 | class MissingTwoFactorError extends Error { | ||
22 | code = HttpStatusCode.UNAUTHORIZED_401 | ||
23 | name = ServerErrorCode.MISSING_TWO_FACTOR | ||
24 | } | ||
25 | |||
26 | class InvalidTwoFactorError extends Error { | ||
27 | code = HttpStatusCode.BAD_REQUEST_400 | ||
28 | name = ServerErrorCode.INVALID_TWO_FACTOR | ||
29 | } | ||
30 | |||
31 | class RegistrationWaitingForApproval extends Error { | ||
32 | code = HttpStatusCode.BAD_REQUEST_400 | ||
33 | name = ServerErrorCode.ACCOUNT_WAITING_FOR_APPROVAL | ||
34 | } | ||
35 | |||
36 | class RegistrationApprovalRejected extends Error { | ||
37 | code = HttpStatusCode.BAD_REQUEST_400 | ||
38 | name = ServerErrorCode.ACCOUNT_APPROVAL_REJECTED | ||
39 | } | ||
40 | |||
41 | /** | ||
42 | * | ||
43 | * Reimplement some functions of OAuth2Server to inject external auth methods | ||
44 | * | ||
45 | */ | ||
46 | const oAuthServer = new OAuth2Server({ | ||
47 | // Wants seconds | ||
48 | accessTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN / 1000, | ||
49 | refreshTokenLifetime: CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN / 1000, | ||
50 | |||
51 | // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications | ||
52 | model: require('./oauth-model') | ||
53 | }) | ||
54 | |||
55 | // --------------------------------------------------------------------------- | ||
56 | |||
57 | async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) { | ||
58 | const request = new Request(req) | ||
59 | const { refreshTokenAuthName, bypassLogin } = options | ||
60 | |||
61 | if (request.method !== 'POST') { | ||
62 | throw new InvalidRequestError('Invalid request: method must be POST') | ||
63 | } | ||
64 | |||
65 | if (!request.is([ 'application/x-www-form-urlencoded' ])) { | ||
66 | throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded') | ||
67 | } | ||
68 | |||
69 | const clientId = request.body.client_id | ||
70 | const clientSecret = request.body.client_secret | ||
71 | |||
72 | if (!clientId || !clientSecret) { | ||
73 | throw new InvalidClientError('Invalid client: cannot retrieve client credentials') | ||
74 | } | ||
75 | |||
76 | const client = await getClient(clientId, clientSecret) | ||
77 | if (!client) { | ||
78 | throw new InvalidClientError('Invalid client: client is invalid') | ||
79 | } | ||
80 | |||
81 | const grantType = request.body.grant_type | ||
82 | if (!grantType) { | ||
83 | throw new InvalidRequestError('Missing parameter: `grant_type`') | ||
84 | } | ||
85 | |||
86 | if (![ 'password', 'refresh_token' ].includes(grantType)) { | ||
87 | throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid') | ||
88 | } | ||
89 | |||
90 | if (!client.grants.includes(grantType)) { | ||
91 | throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid') | ||
92 | } | ||
93 | |||
94 | if (grantType === 'password') { | ||
95 | return handlePasswordGrant({ | ||
96 | request, | ||
97 | client, | ||
98 | bypassLogin | ||
99 | }) | ||
100 | } | ||
101 | |||
102 | return handleRefreshGrant({ | ||
103 | request, | ||
104 | client, | ||
105 | refreshTokenAuthName | ||
106 | }) | ||
107 | } | ||
108 | |||
109 | function handleOAuthAuthenticate ( | ||
110 | req: express.Request, | ||
111 | res: express.Response | ||
112 | ) { | ||
113 | return oAuthServer.authenticate(new Request(req), new Response(res)) | ||
114 | } | ||
115 | |||
116 | export { | ||
117 | MissingTwoFactorError, | ||
118 | InvalidTwoFactorError, | ||
119 | |||
120 | handleOAuthToken, | ||
121 | handleOAuthAuthenticate | ||
122 | } | ||
123 | |||
124 | // --------------------------------------------------------------------------- | ||
125 | |||
126 | async function handlePasswordGrant (options: { | ||
127 | request: Request | ||
128 | client: MOAuthClient | ||
129 | bypassLogin?: BypassLogin | ||
130 | }) { | ||
131 | const { request, client, bypassLogin } = options | ||
132 | |||
133 | if (!request.body.username) { | ||
134 | throw new InvalidRequestError('Missing parameter: `username`') | ||
135 | } | ||
136 | |||
137 | if (!bypassLogin && !request.body.password) { | ||
138 | throw new InvalidRequestError('Missing parameter: `password`') | ||
139 | } | ||
140 | |||
141 | const user = await getUser(request.body.username, request.body.password, bypassLogin) | ||
142 | if (!user) { | ||
143 | const registration = await UserRegistrationModel.loadByEmailOrUsername(request.body.username) | ||
144 | |||
145 | if (registration?.state === UserRegistrationState.REJECTED) { | ||
146 | throw new RegistrationApprovalRejected('Registration approval for this account has been rejected') | ||
147 | } else if (registration?.state === UserRegistrationState.PENDING) { | ||
148 | throw new RegistrationWaitingForApproval('Registration for this account is awaiting approval') | ||
149 | } | ||
150 | |||
151 | throw new InvalidGrantError('Invalid grant: user credentials are invalid') | ||
152 | } | ||
153 | |||
154 | if (user.otpSecret) { | ||
155 | if (!request.headers[OTP.HEADER_NAME]) { | ||
156 | throw new MissingTwoFactorError('Missing two factor header') | ||
157 | } | ||
158 | |||
159 | if (await isOTPValid({ encryptedSecret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) { | ||
160 | throw new InvalidTwoFactorError('Invalid two factor header') | ||
161 | } | ||
162 | } | ||
163 | |||
164 | const token = await buildToken() | ||
165 | |||
166 | return saveToken(token, client, user, { bypassLogin }) | ||
167 | } | ||
168 | |||
169 | async function handleRefreshGrant (options: { | ||
170 | request: Request | ||
171 | client: MOAuthClient | ||
172 | refreshTokenAuthName: string | ||
173 | }) { | ||
174 | const { request, client, refreshTokenAuthName } = options | ||
175 | |||
176 | if (!request.body.refresh_token) { | ||
177 | throw new InvalidRequestError('Missing parameter: `refresh_token`') | ||
178 | } | ||
179 | |||
180 | const refreshToken = await getRefreshToken(request.body.refresh_token) | ||
181 | |||
182 | if (!refreshToken) { | ||
183 | throw new InvalidGrantError('Invalid grant: refresh token is invalid') | ||
184 | } | ||
185 | |||
186 | if (refreshToken.client.id !== client.id) { | ||
187 | throw new InvalidGrantError('Invalid grant: refresh token is invalid') | ||
188 | } | ||
189 | |||
190 | if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) { | ||
191 | throw new InvalidGrantError('Invalid grant: refresh token has expired') | ||
192 | } | ||
193 | |||
194 | await revokeToken({ refreshToken: refreshToken.refreshToken }) | ||
195 | |||
196 | const token = await buildToken() | ||
197 | |||
198 | return saveToken(token, client, refreshToken.user, { refreshTokenAuthName }) | ||
199 | } | ||
200 | |||
201 | function generateRandomToken () { | ||
202 | return randomBytesPromise(256) | ||
203 | .then(buffer => sha1(buffer)) | ||
204 | } | ||
205 | |||
206 | function getTokenExpiresAt (type: 'access' | 'refresh') { | ||
207 | const lifetime = type === 'access' | ||
208 | ? CONFIG.OAUTH2.TOKEN_LIFETIME.ACCESS_TOKEN | ||
209 | : CONFIG.OAUTH2.TOKEN_LIFETIME.REFRESH_TOKEN | ||
210 | |||
211 | return new Date(Date.now() + lifetime) | ||
212 | } | ||
213 | |||
214 | async function buildToken () { | ||
215 | const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ]) | ||
216 | |||
217 | return { | ||
218 | accessToken, | ||
219 | refreshToken, | ||
220 | accessTokenExpiresAt: getTokenExpiresAt('access'), | ||
221 | refreshTokenExpiresAt: getTokenExpiresAt('refresh') | ||
222 | } | ||
223 | } | ||
diff --git a/server/lib/auth/tokens-cache.ts b/server/lib/auth/tokens-cache.ts deleted file mode 100644 index e7b12159b..000000000 --- a/server/lib/auth/tokens-cache.ts +++ /dev/null | |||
@@ -1,52 +0,0 @@ | |||
1 | import { LRUCache } from 'lru-cache' | ||
2 | import { MOAuthTokenUser } from '@server/types/models' | ||
3 | import { LRU_CACHE } from '../../initializers/constants' | ||
4 | |||
5 | export class TokensCache { | ||
6 | |||
7 | private static instance: TokensCache | ||
8 | |||
9 | private readonly accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE }) | ||
10 | private readonly userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE }) | ||
11 | |||
12 | private constructor () { } | ||
13 | |||
14 | static get Instance () { | ||
15 | return this.instance || (this.instance = new this()) | ||
16 | } | ||
17 | |||
18 | hasToken (token: string) { | ||
19 | return this.accessTokenCache.has(token) | ||
20 | } | ||
21 | |||
22 | getByToken (token: string) { | ||
23 | return this.accessTokenCache.get(token) | ||
24 | } | ||
25 | |||
26 | setToken (token: MOAuthTokenUser) { | ||
27 | this.accessTokenCache.set(token.accessToken, token) | ||
28 | this.userHavingToken.set(token.userId, token.accessToken) | ||
29 | } | ||
30 | |||
31 | deleteUserToken (userId: number) { | ||
32 | this.clearCacheByUserId(userId) | ||
33 | } | ||
34 | |||
35 | clearCacheByUserId (userId: number) { | ||
36 | const token = this.userHavingToken.get(userId) | ||
37 | |||
38 | if (token !== undefined) { | ||
39 | this.accessTokenCache.delete(token) | ||
40 | this.userHavingToken.delete(userId) | ||
41 | } | ||
42 | } | ||
43 | |||
44 | clearCacheByToken (token: string) { | ||
45 | const tokenModel = this.accessTokenCache.get(token) | ||
46 | |||
47 | if (tokenModel !== undefined) { | ||
48 | this.userHavingToken.delete(tokenModel.userId) | ||
49 | this.accessTokenCache.delete(token) | ||
50 | } | ||
51 | } | ||
52 | } | ||