alp-node-auth 9.3.0 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/definitions/authApolloContext.d.ts +1 -1
- package/dist/definitions/authApolloContext.d.ts.map +1 -1
- package/dist/definitions/authSocketIO.d.ts +1 -1
- package/dist/definitions/authSocketIO.d.ts.map +1 -1
- package/dist/definitions/createAuthController.d.ts +2 -2
- package/dist/definitions/createAuthController.d.ts.map +1 -1
- package/dist/definitions/index.d.ts +2 -3
- package/dist/definitions/index.d.ts.map +1 -1
- package/dist/definitions/services/authentification/AuthenticationService.d.ts +2 -2
- package/dist/definitions/services/authentification/AuthenticationService.d.ts.map +1 -1
- package/dist/definitions/services/authentification/types.d.ts +2 -1
- package/dist/definitions/services/authentification/types.d.ts.map +1 -1
- package/dist/index-node18.mjs +18 -21
- package/dist/index-node18.mjs.map +1 -1
- package/package.json +3 -6
- package/src/authApolloContext.ts +1 -1
- package/src/authSocketIO.ts +1 -1
- package/src/createAuthController.ts +4 -5
- package/src/index.ts +2 -3
- package/src/services/authentification/AuthenticationService.ts +24 -21
- package/src/services/authentification/types.ts +6 -1
- package/strategies/strategies.d.ts +6 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,21 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [10.0.0](https://github.com/christophehurpeau/alp/compare/alp-node-auth@9.3.0...alp-node-auth@10.0.0) (2024-01-06)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### ⚠ BREAKING CHANGES
|
|
10
|
+
|
|
11
|
+
* merge to alp-node to improve maintenability, remove alp-types
|
|
12
|
+
|
|
13
|
+
### Features
|
|
14
|
+
|
|
15
|
+
* merge to alp-node to improve maintenability, remove alp-types ([ead9a2f](https://github.com/christophehurpeau/alp/commit/ead9a2fd1bcbedce0be29ea0e444c5cead99c64d))
|
|
16
|
+
|
|
17
|
+
Version bump for dependency: alp-node
|
|
18
|
+
Version bump for dependency: alp-node
|
|
19
|
+
|
|
20
|
+
|
|
6
21
|
## [9.3.0](https://github.com/christophehurpeau/alp/compare/alp-node-auth@9.2.0...alp-node-auth@9.3.0) (2024-01-06)
|
|
7
22
|
|
|
8
23
|
Note: no notable changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { NodeConfig } from 'alp-
|
|
1
|
+
import type { NodeConfig } from 'alp-node';
|
|
2
2
|
import type MongoUsersManager from './MongoUsersManager';
|
|
3
3
|
import type { User } from './types';
|
|
4
4
|
export declare const createAuthApolloContext: <U extends User = User>(config: NodeConfig, usersManager: MongoUsersManager<U, import("./types").UserSanitized>) => any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authApolloContext.d.ts","sourceRoot":"","sources":["../../src/authApolloContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"authApolloContext.d.ts","sourceRoot":"","sources":["../../src/authApolloContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAE3C,OAAO,KAAK,iBAAiB,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAiBpC,eAAO,MAAM,uBAAuB,kCAC1B,UAAU,0EAEjB,GA2BF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { NodeApplication } from 'alp-
|
|
1
|
+
import type { NodeApplication } from 'alp-node';
|
|
2
2
|
import type MongoUsersManager from './MongoUsersManager';
|
|
3
3
|
import type { User } from './types';
|
|
4
4
|
export declare const authSocketIO: <U extends User = User>(app: NodeApplication, usersManager: MongoUsersManager<U, import("./types").UserSanitized>, io: any, jwtAudience?: string) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authSocketIO.d.ts","sourceRoot":"","sources":["../../src/authSocketIO.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"authSocketIO.d.ts","sourceRoot":"","sources":["../../src/authSocketIO.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEhD,OAAO,KAAK,iBAAiB,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAMpC,eAAO,MAAM,YAAY,+BAClB,eAAe,2EAGhB,GAAG,gBACO,MAAM,KACnB,IAgCF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
import type { Context } from 'alp-
|
|
1
|
+
/// <reference types="koa" />
|
|
2
|
+
import type { AlpRouteRef, Context } from 'alp-node';
|
|
3
3
|
import type MongoUsersManager from './MongoUsersManager';
|
|
4
4
|
import type { AuthenticationService, AccessResponseHooks } from './services/authentification/AuthenticationService';
|
|
5
5
|
import type { AllowedStrategyKeys, AllowedMapParamsStrategy } from './services/authentification/types';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAuthController.d.ts","sourceRoot":"","sources":["../../src/createAuthController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,
|
|
1
|
+
{"version":3,"file":"createAuthController.d.ts","sourceRoot":"","sources":["../../src/createAuthController.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,KAAK,iBAAiB,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EACV,qBAAqB,EACrB,mBAAmB,EACpB,MAAM,mDAAmD,CAAC;AAC3D,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACzB,MAAM,mCAAmC,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AAU,SAAS,aAAa,GAAG,aAAa,EAChD,EACA,YAAY,EACZ,qBAAqB,EACrB,aAAmB,EACnB,eAAe,EACf,SAAc,GACf,EAAE,0BAA0B,CAAC,YAAY,EAAE,CAAC,EAAE,UAAU,CAAC,GAAG,cAAc,CAsD1E"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
import type { IncomingMessage } from 'node:http';
|
|
3
|
-
import type { Context } from 'alp-node';
|
|
4
|
-
import type { NodeApplication } from 'alp-types';
|
|
3
|
+
import type { Context, NodeApplication } from 'alp-node';
|
|
5
4
|
import type MongoUsersManager from './MongoUsersManager';
|
|
6
5
|
import type { AuthController as AuthControllerType, AuthHooks } from './createAuthController';
|
|
7
6
|
import type { AuthRoutes as AuthRoutesType } from './createRoutes';
|
|
@@ -16,7 +15,7 @@ export { authSocketIO } from './authSocketIO';
|
|
|
16
15
|
export { createAuthApolloContext } from './authApolloContext';
|
|
17
16
|
export { STATUSES } from './services/user/UserAccountsService';
|
|
18
17
|
export * from './types';
|
|
19
|
-
declare module 'alp-
|
|
18
|
+
declare module 'alp-node' {
|
|
20
19
|
interface ContextState {
|
|
21
20
|
loggedInUserId: NonNullable<ContextState['loggedInUser']>['_id'] | null | undefined;
|
|
22
21
|
loggedInUser: User | null | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAEjD,OAAO,KAAK,EAAE,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAEjD,OAAO,KAAK,EAAE,OAAO,EAAgB,eAAe,EAAE,MAAM,UAAU,CAAC;AAGvE,OAAO,KAAK,iBAAiB,MAAM,qBAAq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,EAAE,WAAW,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC,EAC3D,YAAY,EAAE,WAAW,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC,KACpD,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,MAAM,EAAE,MAAM,IAAI,CAAC;KACpB;CACF;AAMD,MAAM,MAAM,cAAc,GAAG,kBAAkB,CAAC;AAChD,MAAM,MAAM,UAAU,GAAG,cAAc,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,mDAAmD,CAAC;AAE1F,MAAM,CAAC,OAAO,UAAU,IAAI,CAC1B,YAAY,SAAS,mBAAmB,GAAG,QAAQ,EACnD,CAAC,SAAS,IAAI,GAAG,IAAI,EACrB,UAAU,SAAS,aAAa,GAAG,aAAa,EAChD,EACA,aAAa,EACb,YAAY,EACZ,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,SAAS,EACT,WAAW,GACZ,EAAE;IACD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,iBAAiB,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;IAC/C,UAAU,EAAE,UAAU,CAAC,YAAY,CAAC,CAAC;IACrC,eAAe,CAAC,EAAE,YAAY,CAAC;IAC/B,iBAAiB,EAAE,MAAM,CAAC,YAAY,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7D,SAAS,CAAC,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;IACpC,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,SAEc,eAAe;;uCAqFjB,eAAe;;yBAUf,OAAO;EAsCnB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
+
/// <reference types="koa" />
|
|
2
3
|
import { EventEmitter } from 'node:events';
|
|
3
|
-
import 'alp-
|
|
4
|
-
import type { Context, NodeConfig } from 'alp-types';
|
|
4
|
+
import type { Context, NodeConfig } from 'alp-node';
|
|
5
5
|
import type { Strategy as Oauth2Strategy } from '../../../strategies/strategies.d';
|
|
6
6
|
import type { AccountId, User, Account, UserSanitized } from '../../types';
|
|
7
7
|
import type UserAccountsService from '../user/UserAccountsService';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationService.d.ts","sourceRoot":"","sources":["../../../../src/services/authentification/AuthenticationService.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"AuthenticationService.d.ts","sourceRoot":"","sources":["../../../../src/services/authentification/AuthenticationService.ts"],"names":[],"mappings":";;AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEpD,OAAO,KAAK,EAAE,QAAQ,IAAI,cAAc,EAAE,MAAM,kCAAkC,CAAC;AACnF,OAAO,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE3E,OAAO,KAAK,mBAAmB,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAI3D,MAAM,WAAW,sBAAsB;IACrC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,UAAU,CAAC,YAAY,SAAS,mBAAmB,IAAI,MAAM,CACvE,YAAY,EACZ,cAAc,CAA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EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM;IAS7C,eAAe,CACnB,GAAG,EAAE,OAAO,EACZ,QAAQ,EAAE,YAAY,EACtB,EACE,YAAY,EACZ,QAAQ,EACR,IAAI,EACJ,SAAS,GACV,EAAE;QACD,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAClC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAC9B,IAAI,CAAC,EAAE,CAAC,CAAC;QACT,SAAS,CAAC,EAAE,SAAS,CAAC;KACvB,EACD,MAAM,CAAC,EAAE,GAAG,GACX,OAAO,CAAC,IAAI,CAAC;IAuCV,cAAc,CAAC,WAAW,SAAS,YAAY,EACnD,GAAG,EAAE,OAAO,EACZ,QAAQ,EAAE,WAAW,EACrB,UAAU,EAAE,OAAO,EACnB,KAAK,EAAE,mBAAmB,CAAC,YAAY,EAAE,CAAC,CAAC,GAC1C,OAAO,CAAC,CAAC,CAAC;IAoEb,oBAAoB,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;CAsBlE"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
export type GoogleParams = 'access_type' | 'include_granted_scopes' | 'login_hint' | 'prompt';
|
|
2
|
+
export type SlackParams = 'client_id' | 'team';
|
|
2
3
|
export type AllowedStrategyKeys = 'google' | 'slack';
|
|
3
4
|
export interface AllowedMapParamsStrategy {
|
|
4
5
|
google: GoogleParams;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/services/authentification/types.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/services/authentification/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GACpB,aAAa,GACb,wBAAwB,GACxB,YAAY,GACZ,QAAQ,CAAC;AACb,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG,MAAM,CAAC;AAE/C,MAAM,MAAM,mBAAmB,GAAG,QAAQ,GAAG,OAAO,CAAC;AAErD,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,MAAM,WAAW,MAAM;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;CACjB"}
|
package/dist/index-node18.mjs
CHANGED
|
@@ -2,7 +2,6 @@ import { promisify } from 'node:util';
|
|
|
2
2
|
import jsonwebtoken from 'jsonwebtoken';
|
|
3
3
|
import { Logger } from 'nightingale-logger';
|
|
4
4
|
import { EventEmitter } from 'node:events';
|
|
5
|
-
import 'alp-router';
|
|
6
5
|
import { randomBytes } from 'node:crypto';
|
|
7
6
|
import Cookies from 'cookies';
|
|
8
7
|
|
|
@@ -26,7 +25,7 @@ function createAuthController({
|
|
|
26
25
|
*/
|
|
27
26
|
async addScope(ctx) {
|
|
28
27
|
if (!ctx.state.loggedInUser) {
|
|
29
|
-
|
|
28
|
+
ctx.redirectTo(homeRouterKey);
|
|
30
29
|
return;
|
|
31
30
|
}
|
|
32
31
|
const strategy = ctx.namedParam('strategy') || defaultStrategy;
|
|
@@ -46,11 +45,11 @@ function createAuthController({
|
|
|
46
45
|
});
|
|
47
46
|
const keyPath = usersManager.store.keyPath;
|
|
48
47
|
await ctx.setLoggedIn(loggedInUser[keyPath], loggedInUser);
|
|
49
|
-
|
|
48
|
+
ctx.redirectTo(homeRouterKey);
|
|
50
49
|
},
|
|
51
50
|
async logout(ctx) {
|
|
52
51
|
ctx.logout();
|
|
53
|
-
|
|
52
|
+
ctx.redirectTo(homeRouterKey);
|
|
54
53
|
}
|
|
55
54
|
};
|
|
56
55
|
}
|
|
@@ -200,30 +199,28 @@ class AuthenticationService extends EventEmitter {
|
|
|
200
199
|
access_type: refreshToken ? 'offline' : 'online',
|
|
201
200
|
...params
|
|
202
201
|
});
|
|
203
|
-
|
|
202
|
+
ctx.redirect(redirectUri);
|
|
204
203
|
}
|
|
205
204
|
async accessResponse(ctx, strategy, isLoggedIn, hooks) {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const code = ctx.query.code;
|
|
213
|
-
const state = ctx.query.state;
|
|
205
|
+
const errorParam = ctx.params.queryParam('error').notEmpty();
|
|
206
|
+
if (errorParam.isValid()) {
|
|
207
|
+
ctx.throw(errorParam.value, 403);
|
|
208
|
+
}
|
|
209
|
+
const code = ctx.validParams.queryParam('code').notEmpty().value;
|
|
210
|
+
const state = ctx.validParams.queryParam('state').notEmpty().value;
|
|
214
211
|
const cookieName = `auth_${strategy}_${state}`;
|
|
215
|
-
|
|
212
|
+
const cookie = ctx.cookies.get(cookieName);
|
|
216
213
|
ctx.cookies.set(cookieName, '', {
|
|
217
214
|
expires: new Date(1)
|
|
218
215
|
});
|
|
219
216
|
if (!cookie) {
|
|
220
217
|
throw new Error('No cookie for this state');
|
|
221
218
|
}
|
|
222
|
-
|
|
223
|
-
if (!
|
|
219
|
+
const parsedCookie = JSON.parse(cookie);
|
|
220
|
+
if (!parsedCookie?.scope) {
|
|
224
221
|
throw new Error('Unexpected cookie value');
|
|
225
222
|
}
|
|
226
|
-
if (!
|
|
223
|
+
if (!parsedCookie.isLoginAccess) {
|
|
227
224
|
if (!isLoggedIn) {
|
|
228
225
|
throw new Error('You are not connected');
|
|
229
226
|
}
|
|
@@ -232,8 +229,8 @@ class AuthenticationService extends EventEmitter {
|
|
|
232
229
|
code,
|
|
233
230
|
redirectUri: this.redirectUri(ctx, strategy)
|
|
234
231
|
});
|
|
235
|
-
if (
|
|
236
|
-
const user = await this.userAccountsService.findOrCreateFromStrategy(strategy, tokens,
|
|
232
|
+
if (parsedCookie.isLoginAccess) {
|
|
233
|
+
const user = await this.userAccountsService.findOrCreateFromStrategy(strategy, tokens, parsedCookie.scope, parsedCookie.scopeKey);
|
|
237
234
|
if (hooks.afterLoginSuccess) {
|
|
238
235
|
await hooks.afterLoginSuccess(strategy, user);
|
|
239
236
|
}
|
|
@@ -243,9 +240,9 @@ class AuthenticationService extends EventEmitter {
|
|
|
243
240
|
const {
|
|
244
241
|
account,
|
|
245
242
|
user
|
|
246
|
-
} = await this.userAccountsService.update(loggedInUser, strategy, tokens,
|
|
243
|
+
} = await this.userAccountsService.update(loggedInUser, strategy, tokens, parsedCookie.scope, parsedCookie.scopeKey);
|
|
247
244
|
if (hooks.afterScopeUpdate) {
|
|
248
|
-
await hooks.afterScopeUpdate(strategy,
|
|
245
|
+
await hooks.afterScopeUpdate(strategy, parsedCookie.scopeKey, account, user);
|
|
249
246
|
}
|
|
250
247
|
return loggedInUser;
|
|
251
248
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-node18.mjs","sources":["../src/createAuthController.ts","../src/createRoutes.ts","../src/utils/generators.ts","../src/services/authentification/AuthenticationService.ts","../src/services/user/UserAccountsService.ts","../src/utils/cookies.ts","../src/utils/createFindLoggedInUser.ts","../src/MongoUsersManager.ts","../src/services/user/UserAccountGoogleService.ts","../src/services/user/UserAccountSlackService.ts","../src/authSocketIO.ts","../src/authApolloContext.ts","../src/index.ts"],"sourcesContent":["import type { AlpRouteRef } from 'alp-router';\nimport type { Context } from 'alp-types';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type {\n AuthenticationService,\n AccessResponseHooks,\n} from './services/authentification/AuthenticationService';\nimport type {\n AllowedStrategyKeys,\n AllowedMapParamsStrategy,\n} from './services/authentification/types';\nimport type { User, UserSanitized } from './types';\n\nexport interface CreateAuthControllerParams<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n> {\n authenticationService: AuthenticationService<StrategyKeys, U, UserSanitized>;\n homeRouterKey?: string;\n usersManager: MongoUsersManager<U, USanitized>;\n defaultStrategy?: StrategyKeys;\n authHooks?: AuthHooks<StrategyKeys>;\n}\n\nexport interface AuthController {\n login: AlpRouteRef;\n addScope: AlpRouteRef;\n response: AlpRouteRef;\n logout: AlpRouteRef;\n}\n\ntype OptionalRecord<K extends keyof any, T> = { [P in K]?: T };\n\nexport interface AuthHooks<StrategyKeys extends AllowedStrategyKeys>\n extends AccessResponseHooks<StrategyKeys> {\n paramsForLogin?: <StrategyKey extends StrategyKeys>(\n strategy: StrategyKey,\n ctx: Context,\n ) =>\n | OptionalRecord<AllowedMapParamsStrategy[StrategyKey], any>\n | Promise<OptionalRecord<AllowedMapParamsStrategy[StrategyKey], any>>\n | Promise<void>\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n | void;\n}\n\nexport function createAuthController<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n>({\n usersManager,\n authenticationService,\n homeRouterKey = '/',\n defaultStrategy,\n authHooks = {},\n}: CreateAuthControllerParams<StrategyKeys, U, USanitized>): AuthController {\n return {\n async login(ctx: Context): Promise<void> {\n const strategy: StrategyKeys = (ctx.namedParam('strategy') ||\n defaultStrategy) as StrategyKeys;\n if (!strategy) throw new Error('Strategy missing');\n const params =\n (authHooks.paramsForLogin &&\n (await authHooks.paramsForLogin(strategy, ctx))) ||\n {};\n await authenticationService.redirectAuthUrl(ctx, strategy, {}, params);\n },\n\n /**\n * Add scope in existing\n * The user must already be connected\n */\n async addScope(ctx: Context): Promise<void> {\n if (!ctx.state.loggedInUser) {\n await ctx.redirectTo(homeRouterKey);\n return;\n }\n\n const strategy: StrategyKeys = (ctx.namedParam('strategy') ||\n defaultStrategy) as StrategyKeys;\n if (!strategy) throw new Error('Strategy missing');\n const scopeKey = ctx.namedParam('scopeKey');\n if (!scopeKey) throw new Error('Scope missing');\n await authenticationService.redirectAuthUrl(ctx, strategy, { scopeKey });\n },\n\n async response(ctx: Context): Promise<void> {\n const strategy: StrategyKeys = ctx.namedParam('strategy') as StrategyKeys;\n ctx.assert(strategy);\n\n const loggedInUser = await authenticationService.accessResponse(\n ctx,\n strategy,\n !!ctx.state.loggedInUser,\n {\n afterLoginSuccess: authHooks.afterLoginSuccess,\n afterScopeUpdate: authHooks.afterScopeUpdate,\n },\n );\n const keyPath = usersManager.store.keyPath;\n await ctx.setLoggedIn(loggedInUser[keyPath], loggedInUser);\n await ctx.redirectTo(homeRouterKey);\n },\n\n async logout(ctx: Context): Promise<void> {\n ctx.logout();\n await ctx.redirectTo(homeRouterKey);\n },\n };\n}\n","import type { AuthController } from './createAuthController';\n\nexport interface AuthRoutes {\n login: [string, (segment: any) => void];\n addScope: [string, AuthController['addScope']];\n logout: [string, AuthController['logout']];\n}\n\nexport const createRoutes = (controller: AuthController): AuthRoutes => ({\n login: [\n '/login/:strategy?',\n (segment: any) => {\n segment.add('/response', controller.response, 'authResponse');\n segment.defaultRoute(controller.login, 'login');\n },\n ],\n addScope: ['/add-scope/:strategy/:scopeKey', controller.addScope],\n logout: ['/logout', controller.logout],\n});\n","import { randomBytes } from 'node:crypto';\nimport { promisify } from 'node:util';\n\nconst randomBytesPromisified = promisify(randomBytes);\n\nexport async function randomBase64(size: number): Promise<string> {\n const buffer = await randomBytesPromisified(size);\n return buffer.toString('base64');\n}\n\nexport async function randomHex(size: number): Promise<string> {\n const buffer = await randomBytesPromisified(size);\n return buffer.toString('hex');\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable camelcase, max-lines */\nimport { EventEmitter } from 'node:events';\nimport 'alp-router';\nimport type { Context, NodeConfig } from 'alp-types';\nimport { Logger } from 'nightingale-logger';\nimport type { Strategy as Oauth2Strategy } from '../../../strategies/strategies.d';\nimport type { AccountId, User, Account, UserSanitized } from '../../types';\nimport { randomHex } from '../../utils/generators';\nimport type UserAccountsService from '../user/UserAccountsService';\nimport type { AllowedStrategyKeys, Tokens } from './types';\n\nconst logger = new Logger('alp:auth:authentication');\n\nexport interface GenerateAuthUrlOptions {\n accessType?: string;\n grantType?: string;\n includeGrantedScopes?: boolean;\n loginHint?: string;\n prompt?: string;\n redirectUri?: string;\n scope?: string;\n state?: string;\n}\n\nexport interface GetTokensOptions {\n code: string;\n redirectUri: string;\n}\n\nexport type Strategies<StrategyKeys extends AllowedStrategyKeys> = Record<\n StrategyKeys,\n Oauth2Strategy<any>\n>;\n\nexport interface AccessResponseHooks<StrategyKeys, U extends User = User> {\n afterLoginSuccess?: <StrategyKey extends StrategyKeys>(\n strategy: StrategyKey,\n loggedInUser: U,\n ) => Promise<void> | void;\n\n afterScopeUpdate?: <StrategyKey extends StrategyKeys>(\n strategy: StrategyKey,\n scopeKey: string,\n account: Account,\n user: U,\n ) => Promise<void> | void;\n}\n\nexport class AuthenticationService<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n // eslint-disable-next-line unicorn/prefer-event-target\n> extends EventEmitter {\n config: NodeConfig;\n\n strategies: Strategies<StrategyKeys>;\n\n userAccountsService: UserAccountsService<StrategyKeys, U, USanitized>;\n\n constructor(\n config: NodeConfig,\n strategies: Strategies<StrategyKeys>,\n userAccountsService: UserAccountsService<StrategyKeys, U, USanitized>,\n ) {\n super();\n this.config = config;\n this.strategies = strategies;\n this.userAccountsService = userAccountsService;\n }\n\n generateAuthUrl<T extends StrategyKeys>(strategy: T, params: any): string {\n logger.debug('generateAuthUrl', { strategy, params });\n const strategyInstance = this.strategies[strategy];\n switch (strategyInstance.type) {\n case 'oauth2':\n return strategyInstance.oauth2.authorizationCode.authorizeURL(params);\n default:\n throw new Error('Invalid strategy');\n }\n }\n\n async getTokens(\n strategy: StrategyKeys,\n options: GetTokensOptions,\n ): Promise<Tokens> {\n logger.debug('getTokens', { strategy, options });\n const strategyInstance = this.strategies[strategy];\n switch (strategyInstance.type) {\n case 'oauth2': {\n const result = await strategyInstance.oauth2.authorizationCode.getToken(\n {\n code: options.code,\n redirect_uri: options.redirectUri,\n },\n );\n if (!result) return result;\n const tokens = result.token;\n\n return {\n accessToken: tokens.access_token as string,\n refreshToken: tokens.refresh_token as string,\n tokenType: tokens.token_type as string,\n expiresIn: tokens.expires_in as number,\n expireDate: (() => {\n if (tokens.expires_in == null) return null;\n const d = new Date();\n d.setTime(d.getTime() + (tokens.expires_in as number) * 1000);\n return d;\n })(),\n idToken: tokens.id_token as string,\n };\n // return strategyInstance.accessToken.create(result);\n }\n\n default:\n throw new Error('Invalid stategy');\n }\n }\n\n async refreshToken(\n strategy: StrategyKeys,\n tokensParam: { refreshToken: string },\n ): Promise<Tokens> {\n logger.debug('refreshToken', { strategy });\n if (!tokensParam.refreshToken) {\n throw new Error('Missing refresh token');\n }\n const strategyInstance = this.strategies[strategy];\n switch (strategyInstance.type) {\n case 'oauth2': {\n const token = strategyInstance.oauth2.clientCredentials.createToken({\n refresh_token: tokensParam.refreshToken,\n });\n const result = await token.refresh();\n const tokens = result.token;\n return {\n accessToken: tokens.access_token as string,\n tokenType: tokens.token_type as string,\n expiresIn: tokens.expires_in as number,\n expireDate: (() => {\n if (tokens.expires_in == null) return null;\n const d = new Date();\n d.setTime(d.getTime() + (tokens.expires_in as number) * 1000);\n return d;\n })(),\n idToken: tokens.id_token as string,\n };\n }\n\n default:\n throw new Error('Invalid stategy');\n }\n }\n\n redirectUri(ctx: Context, strategy: string): string {\n const host = `http${this.config.get('allowHttps') ? 's' : ''}://${\n ctx.request.host\n }`;\n return `${host}${ctx.urlGenerator('authResponse', {\n strategy,\n })}`;\n }\n\n async redirectAuthUrl(\n ctx: Context,\n strategy: StrategyKeys,\n {\n refreshToken,\n scopeKey,\n user,\n accountId,\n }: {\n refreshToken?: string | undefined;\n scopeKey?: string | undefined;\n user?: U;\n accountId?: AccountId;\n },\n params?: any,\n ): Promise<void> {\n logger.debug('redirectAuthUrl', { strategy, scopeKey, refreshToken });\n const state = await randomHex(8);\n const isLoginAccess = !scopeKey || scopeKey === 'login';\n const scope = this.userAccountsService.getScope(\n strategy,\n scopeKey || 'login',\n user,\n accountId,\n );\n\n if (!scope) {\n throw new Error('Invalid empty scope');\n }\n\n ctx.cookies.set(\n `auth_${strategy}_${state}`,\n JSON.stringify({\n scopeKey,\n scope,\n isLoginAccess,\n }),\n {\n maxAge: 10 * 60 * 1000,\n httpOnly: true,\n secure: this.config.get('allowHttps'),\n },\n );\n const redirectUri = this.generateAuthUrl(strategy, {\n redirect_uri: this.redirectUri(ctx, strategy),\n scope,\n state,\n access_type: refreshToken ? 'offline' : 'online',\n ...params,\n });\n\n return ctx.redirect(redirectUri);\n }\n\n async accessResponse<StrategyKey extends StrategyKeys>(\n ctx: Context,\n strategy: StrategyKey,\n isLoggedIn: boolean,\n hooks: AccessResponseHooks<StrategyKeys, U>,\n ): Promise<U> {\n if (ctx.query.error) {\n const error: any = new Error(ctx.query.error);\n error.status = 403;\n error.expose = true;\n throw error;\n }\n\n const code = ctx.query.code;\n const state = ctx.query.state;\n const cookieName = `auth_${strategy}_${state as string}`;\n let cookie = ctx.cookies.get(cookieName);\n ctx.cookies.set(cookieName, '', { expires: new Date(1) });\n if (!cookie) {\n throw new Error('No cookie for this state');\n }\n\n cookie = JSON.parse(cookie);\n if (!cookie?.scope) {\n throw new Error('Unexpected cookie value');\n }\n\n if (!cookie.isLoginAccess) {\n if (!isLoggedIn) {\n throw new Error('You are not connected');\n }\n }\n\n const tokens: Tokens = await this.getTokens(strategy, {\n code,\n redirectUri: this.redirectUri(ctx, strategy),\n });\n\n if (cookie.isLoginAccess) {\n const user = await this.userAccountsService.findOrCreateFromStrategy(\n strategy,\n tokens,\n cookie.scope,\n cookie.scopeKey,\n );\n\n if (hooks.afterLoginSuccess) {\n await hooks.afterLoginSuccess(strategy, user);\n }\n\n return user;\n }\n\n const loggedInUser = ctx.state.loggedInUser as U;\n const { account, user } = await this.userAccountsService.update(\n loggedInUser,\n strategy,\n tokens,\n cookie.scope,\n cookie.scopeKey,\n );\n\n if (hooks.afterScopeUpdate) {\n await hooks.afterScopeUpdate(strategy, cookie.scopeKey, account, user);\n }\n\n return loggedInUser;\n }\n\n refreshAccountTokens(user: U, account: Account): Promise<boolean> {\n if (\n account.tokenExpireDate &&\n account.tokenExpireDate.getTime() > Date.now()\n ) {\n return Promise.resolve(false);\n }\n return this.refreshToken(account.provider as StrategyKeys, {\n // accessToken: account.accessToken,\n refreshToken: account.refreshToken!,\n }).then((tokens: Tokens) => {\n if (!tokens) {\n // serviceGoogle.updateFields({ accessToken:null, refreshToken:null, status: .OUTDATED });\n return false;\n }\n account.accessToken = tokens.accessToken;\n account.tokenExpireDate = tokens.expireDate;\n return this.userAccountsService\n .updateAccount(user, account)\n .then(() => true);\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-shadow */\nimport { EventEmitter } from 'node:events';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from '../../MongoUsersManager';\nimport type { AccountId, User, Account, UserSanitized } from '../../types';\nimport type { AllowedStrategyKeys } from '../authentification/types';\nimport type { AccountService, TokensObject } from './types';\n\nconst logger = new Logger('alp:auth:userAccounts');\n\nexport const STATUSES = {\n VALIDATED: 'validated',\n DELETED: 'deleted',\n};\n\nexport default class UserAccountsService<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n // eslint-disable-next-line unicorn/prefer-event-target\n> extends EventEmitter {\n private readonly strategyToService: Record<StrategyKeys, AccountService<any>>;\n\n usersManager: MongoUsersManager<U, USanitized>;\n\n constructor(\n usersManager: MongoUsersManager<U, USanitized>,\n strategyToService: Record<StrategyKeys, AccountService<any>>,\n ) {\n super();\n this.usersManager = usersManager;\n this.strategyToService = strategyToService;\n }\n\n getScope(\n strategy: StrategyKeys,\n scopeKey: string,\n user?: U,\n accountId?: AccountId,\n ): string {\n logger.debug('getScope', { strategy, userId: user?._id });\n const service = this.strategyToService[strategy];\n if (!service) {\n throw new Error('Strategy not supported');\n }\n\n const newScope = service.scopeKeyToScope[scopeKey];\n if (!user || !accountId) {\n return newScope;\n }\n const account = user.accounts.find(\n (account) =>\n account.provider === strategy && account.accountId === accountId,\n );\n\n if (!account) {\n throw new Error('Could not found associated account');\n }\n return service.getScope(account.scope, newScope).join(' ');\n }\n\n async update(\n user: U,\n strategy: StrategyKeys,\n tokens: TokensObject,\n scope: string,\n subservice: string,\n ): Promise<{ user: U; account: U['accounts'][number] }> {\n const service = this.strategyToService[strategy];\n const profile = await service.getProfile(tokens);\n const accountId = service.getId(profile);\n const account = user.accounts.find(\n (account) =>\n account.provider === strategy && account.accountId === accountId,\n );\n if (!account) {\n // TODO check if already exists in other user => merge\n // TODO else add a new account in this user\n throw new Error('Could not found associated account');\n }\n account.status = 'valid';\n account.accessToken = tokens.accessToken;\n if (tokens.refreshToken) {\n account.refreshToken = tokens.refreshToken;\n }\n if (tokens.expireDate !== undefined) {\n account.tokenExpireDate = tokens.expireDate;\n }\n account.scope = service.getScope(account.scope, scope);\n account.subservices = account.subservices || [];\n if (subservice && !account.subservices.includes(subservice)) {\n account.subservices.push(subservice);\n }\n\n await this.usersManager.replaceOne(user);\n return { user, account };\n }\n\n async findOrCreateFromStrategy(\n strategy: StrategyKeys,\n tokens: TokensObject,\n scope: string,\n subservice: string,\n ): Promise<U> {\n const service = this.strategyToService[strategy];\n if (!service) throw new Error('Strategy not supported');\n\n const profile = await service.getProfile(tokens);\n const accountId = service.getId(profile);\n if (!accountId) throw new Error('Invalid profile: no id found');\n\n const emails = service.getEmails(profile);\n\n let user: Partial<U> | undefined =\n await this.usersManager.findOneByAccountOrEmails({\n provider: service.providerKey,\n accountId,\n emails,\n });\n\n logger.info(!user ? 'create user' : 'existing user', {\n userId: user?._id,\n accountId,\n /*emails , user*/\n });\n\n if (!user) {\n user = {};\n }\n\n Object.assign(user, {\n displayName: service.getDisplayName(profile),\n fullName: service.getFullName(profile),\n status: STATUSES.VALIDATED,\n });\n\n if (!user.accounts) user.accounts = [];\n\n let account: Partial<Account> | undefined = user.accounts.find(\n (account: Account) =>\n account.provider === strategy && account.accountId === accountId,\n );\n\n if (!account) {\n account = { provider: strategy, accountId };\n // @ts-expect-error well...\n user.accounts.push(account);\n }\n\n account.name = service.getAccountName(profile);\n account.status = 'valid';\n account.profile = profile;\n account.accessToken = tokens.accessToken;\n if (tokens.refreshToken) {\n account.refreshToken = tokens.refreshToken;\n }\n if (tokens.expireDate !== undefined) {\n account.tokenExpireDate = tokens.expireDate;\n }\n account.scope = service.getScope(account.scope, scope);\n\n if (!account.subservices) account.subservices = [];\n if (subservice && !account.subservices.includes(subservice)) {\n account.subservices.push(subservice);\n }\n\n if (!user.emails) user.emails = [];\n const userEmails = user.emails;\n emails.forEach((email: string) => {\n if (!userEmails.includes(email)) {\n userEmails.push(email);\n }\n });\n\n user.emailDomains = [\n // eslint-disable-next-line unicorn/no-array-reduce\n ...user.emails.reduce(\n (domains: Set<string>, email: string) =>\n domains.add(email.split('@', 2)[1]),\n new Set<string>(),\n ),\n ];\n\n const keyPath = this.usersManager.store.keyPath;\n\n if (user[keyPath]) {\n await this.usersManager.replaceOne(user as U);\n } else {\n await this.usersManager.insertOne(user as U);\n }\n\n return user as U;\n }\n\n async updateAccount(user: U, account: Account): Promise<U> {\n await this.usersManager.updateAccount(user, account);\n return user;\n }\n}\n","import type { IncomingMessage } from 'node:http';\nimport type { Option } from 'cookies';\nimport Cookies from 'cookies';\n\nexport const COOKIE_NAME_TOKEN = 'loggedInUserToken';\nexport const COOKIE_NAME_STATE = 'loggedInUserState';\n\nexport const getTokenFromRequest = (\n req: IncomingMessage,\n options?: Pick<Option, Exclude<keyof Option, 'secure'>>,\n): string | undefined => {\n if (req.headers.authorization?.startsWith('Bearer ')) {\n return req.headers.authorization.slice('Bearer '.length);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const cookies = new Cookies(req, null as unknown as any, {\n ...options,\n secure: true,\n });\n\n return cookies.get(COOKIE_NAME_TOKEN);\n};\n","import { promisify } from 'node:util';\nimport type {\n GetPublicKeyOrSecret,\n Secret,\n VerifyCallback,\n VerifyOptions,\n} from 'jsonwebtoken';\nimport jsonwebtoken from 'jsonwebtoken';\nimport type { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from '../MongoUsersManager';\nimport type { User, UserSanitized } from '../types';\n\ntype Verify = (\n token: string,\n secretOrPublicKey: GetPublicKeyOrSecret | Secret,\n options?: VerifyOptions,\n callback?: VerifyCallback,\n) => void;\n\nconst verifyPromisified = promisify<\n Parameters<Verify>[0],\n Parameters<Verify>[1],\n Parameters<Verify>[2],\n Parameters<VerifyCallback>[1]\n>(jsonwebtoken.verify as Verify);\n\nconst createDecodeJWT =\n (secretKey: string) =>\n async (token: string, jwtAudience: string): Promise<string | undefined> => {\n const result = await verifyPromisified(token, secretKey, {\n algorithms: ['HS512'],\n audience: jwtAudience,\n });\n return (result as any)?.loggedInUserId as string | undefined;\n };\n\nexport type FindLoggedInUser<U extends User> = (\n jwtAudience?: string,\n token?: string,\n) => Promise<[U['_id'] | null | undefined, U | null | undefined]>;\n\nexport const createFindLoggedInUser = <\n U extends User,\n USanitized extends UserSanitized,\n>(\n secretKey: string,\n usersManager: MongoUsersManager<U, USanitized>,\n logger: Logger,\n): FindLoggedInUser<U> => {\n const decodeJwt = createDecodeJWT(secretKey);\n\n const findLoggedInUser: FindLoggedInUser<U> = async (jwtAudience, token) => {\n if (!token || !jwtAudience) return [null, null];\n\n let loggedInUserId;\n try {\n loggedInUserId = await decodeJwt(token, jwtAudience);\n } catch (error: unknown) {\n logger.debug('failed to verify authentification', { err: error });\n }\n\n if (loggedInUserId == null) return [null, null];\n\n const loggedInUser = await usersManager.findById(loggedInUserId);\n\n if (!loggedInUser) return [null, null];\n\n return [loggedInUserId, loggedInUser];\n };\n\n return findLoggedInUser;\n};\n","import type { MongoInsertType, MongoStore, Update } from 'liwi-mongo';\nimport type { User, Account, UserSanitized } from './types';\n\nexport default class MongoUsersManager<\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n> {\n store: MongoStore<U>;\n\n constructor(store: MongoStore<U>) {\n this.store = store;\n }\n\n /** @deprecated use findById instead */\n findConnected(connected: string): Promise<U | undefined> {\n return this.store.findByKey(connected);\n }\n\n findById(userId: string): Promise<U | undefined> {\n return this.store.findByKey(userId);\n }\n\n insertOne(user: MongoInsertType<U>): Promise<any> {\n return this.store.insertOne(user);\n }\n\n replaceOne(user: U): Promise<any> {\n return this.store.replaceOne(user);\n }\n\n sanitize(user: U): USanitized {\n return this.sanitizeBaseUser(user) as USanitized;\n }\n\n findOneByAccountOrEmails({\n accountId,\n emails,\n provider,\n }: {\n accountId: number | string;\n emails?: string[];\n provider: string;\n }): Promise<U | undefined> {\n let query: any = {\n 'accounts.provider': provider,\n 'accounts.accountId': accountId,\n };\n\n if (emails && emails.length > 0) {\n query = {\n $or: [\n query,\n {\n emails: { $in: emails },\n },\n ],\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return this.store.findOne(query);\n }\n\n updateAccount(user: U, account: Account): Promise<U> {\n const accountIndex = user.accounts.indexOf(account);\n if (accountIndex === -1) {\n throw new Error('Invalid account');\n }\n\n return this.store.partialUpdateOne(user, {\n $set: {\n [`accounts.${accountIndex}`]: account,\n },\n } as Update<U>);\n }\n\n // eslint-disable-next-line @typescript-eslint/class-methods-use-this\n sanitizeBaseUser(user: U): UserSanitized {\n return {\n _id: user._id,\n created: user.created,\n updated: user.updated,\n displayName: user.displayName,\n fullName: user.fullName,\n status: user.status,\n emails: user.emails,\n emailDomains: user.emailDomains,\n accounts: user.accounts.map((account: Account) => ({\n provider: account.provider,\n accountId: account.accountId,\n name: account.name,\n status: account.status,\n profile: account.profile,\n })),\n };\n }\n}\n","/* eslint-disable @typescript-eslint/class-methods-use-this */\n/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\nimport type { Tokens } from '../authentification/types';\nimport type { AccountService, FullName } from './types';\n\nexport default class UserAccountGoogleService<ScopeKeys extends 'login'>\n implements AccountService<ScopeKeys>\n{\n scopeKeyToScope: Record<ScopeKeys, string>;\n\n constructor(scopeKeyToScope: Record<Exclude<'login', ScopeKeys>, string>) {\n this.scopeKeyToScope = {\n ...scopeKeyToScope,\n login: 'openid profile email',\n };\n }\n\n providerKey = 'google';\n\n getProfile(tokens: Tokens): Promise<any> {\n return fetch(\n `https://www.googleapis.com/oauth2/v1/userinfo?access_token=${tokens.accessToken}`,\n ).then((response) => response.json());\n }\n\n getId(profile: any): any {\n return profile.id;\n }\n\n getAccountName(profile: any): string | null | undefined {\n return profile.email;\n }\n\n getEmails(profile: any): string[] {\n const emails: string[] = [];\n\n if (profile.email) {\n emails.push(profile.email);\n }\n\n return emails;\n }\n\n getDisplayName(profile: any): string | null | undefined {\n return profile.name;\n }\n\n getFullName(profile: any): FullName {\n return {\n givenName: profile.given_name,\n familyName: profile.family_name,\n };\n }\n\n getDefaultScope(newScope: string): string[] {\n return this.getScope(undefined, newScope);\n }\n\n getScope(oldScope: string[] | undefined, newScope: string): string[] {\n return !oldScope\n ? newScope.split(' ')\n : [...oldScope, ...newScope.split(' ')].filter(\n (item, i, ar) => ar.indexOf(item) === i,\n );\n }\n}\n","/* eslint-disable @typescript-eslint/class-methods-use-this */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\nimport type { Tokens } from '../authentification/types';\nimport type { AccountService, FullName } from './types';\n\n// https://api.slack.com/methods/users.identity\n\nexport default class UserAccountSlackService<ScopeKeys extends 'login'>\n implements AccountService<ScopeKeys>\n{\n scopeKeyToScope: Record<ScopeKeys, string>;\n\n constructor(scopeKeyToScope: Record<Exclude<'login', ScopeKeys>, string>) {\n this.scopeKeyToScope = {\n ...scopeKeyToScope,\n login: 'identity.basic identity.email identity.avatar',\n };\n }\n\n providerKey = 'google';\n\n getProfile(tokens: Tokens): Promise<any> {\n return fetch(\n `https://slack.com/api/users.identity?token=${tokens.accessToken}`,\n ).then((response) => response.json());\n }\n\n getId(profile: any): string | null {\n if (!profile?.team?.id || !profile.user?.id) {\n return null;\n }\n return `team:${profile.team.id as string};user:${\n profile.user.id as string\n }`;\n }\n\n getAccountName(profile: any): string | null | undefined {\n return profile.user.email;\n }\n\n getEmails(profile: any): string[] {\n return profile.user.email ? [profile.user.email] : [];\n }\n\n getDisplayName(profile: any): string | null | undefined {\n return profile.user.name;\n }\n\n getFullName(profile: any): FullName | null {\n return null;\n }\n\n getDefaultScope(newScope: string): string[] {\n return this.getScope(undefined, newScope);\n }\n\n getScope(oldScope: string[] | undefined, newScope: string): string[] {\n return !oldScope\n ? newScope.split(' ')\n : [...oldScope, ...newScope.split(' ')].filter(\n (item, i, ar) => ar.indexOf(item) === i,\n );\n }\n}\n","import type { NodeApplication } from 'alp-types';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type { User } from './types';\nimport { getTokenFromRequest } from './utils/cookies';\nimport { createFindLoggedInUser } from './utils/createFindLoggedInUser';\n\nconst logger = new Logger('alp:auth');\n\nexport const authSocketIO = <U extends User = User>(\n app: NodeApplication,\n usersManager: MongoUsersManager<U>,\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n io: any,\n jwtAudience?: string,\n): void => {\n const findLoggedInUser = createFindLoggedInUser(\n app.config.get<Map<string, string>>('authentication').get('secretKey')!,\n usersManager,\n logger,\n );\n\n const users = new Map();\n io.users = users;\n\n io.use(async (socket: any, next: any) => {\n const handshakeData = socket.request;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const token = getTokenFromRequest(handshakeData);\n\n if (!token) return next();\n\n const [loggedInUserId, loggedInUser] = await findLoggedInUser(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n jwtAudience || handshakeData.headers['user-agent'],\n token,\n );\n\n if (!loggedInUserId || !loggedInUser) return next();\n\n socket.user = loggedInUser;\n users.set(socket.client.id, loggedInUser);\n\n socket.on('disconnected', () => users.delete(socket.client.id));\n\n await next();\n });\n};\n","import type { IncomingMessage } from 'node:http';\nimport type { NodeConfig } from 'alp-types';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type { User } from './types';\nimport { getTokenFromRequest, COOKIE_NAME_TOKEN } from './utils/cookies';\nimport { createFindLoggedInUser } from './utils/createFindLoggedInUser';\n\nconst logger = new Logger('alp:auth');\n\nconst getTokenFromReq = (\n req: IncomingMessage & { cookies?: Record<string, string> },\n): string | undefined => {\n if (req.cookies) return req.cookies[COOKIE_NAME_TOKEN];\n return getTokenFromRequest(req);\n};\n\n/*\n * Not tested yet.\n * @internal\n */\nexport const createAuthApolloContext = <U extends User = User>(\n config: NodeConfig,\n usersManager: MongoUsersManager<U>,\n): any => {\n const findLoggedInUser = createFindLoggedInUser(\n config.get<Map<string, string>>('authentication').get('secretKey')!,\n usersManager,\n logger,\n );\n\n return async ({ req, connection }: { req: any; connection: any }) => {\n if (connection?.loggedInUser) {\n return { user: connection.loggedInUser };\n }\n\n if (!req) return null;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const token = getTokenFromReq(req);\n\n if (!token) return { user: undefined };\n\n const [, loggedInUser] = await findLoggedInUser(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n req.headers['user-agent'],\n token,\n );\n\n return { user: loggedInUser };\n };\n};\n","/* eslint-disable max-lines */\nimport type { IncomingMessage } from 'node:http';\nimport { promisify } from 'node:util';\nimport type { Context } from 'alp-node';\nimport type { ContextState, NodeApplication } from 'alp-types';\nimport jsonwebtoken from 'jsonwebtoken';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type {\n AuthController as AuthControllerType,\n AuthHooks,\n} from './createAuthController';\nimport { createAuthController } from './createAuthController';\nimport type { AuthRoutes as AuthRoutesType } from './createRoutes';\nimport { createRoutes } from './createRoutes';\nimport type { Strategies } from './services/authentification/AuthenticationService';\nimport { AuthenticationService } from './services/authentification/AuthenticationService';\nimport type { AllowedStrategyKeys } from './services/authentification/types';\nimport UserAccountsService from './services/user/UserAccountsService';\nimport type { AccountService } from './services/user/types';\nimport type { User, UserSanitized } from './types';\nimport {\n getTokenFromRequest,\n COOKIE_NAME_TOKEN,\n COOKIE_NAME_STATE,\n} from './utils/cookies';\nimport { createFindLoggedInUser } from './utils/createFindLoggedInUser';\n\nexport { default as MongoUsersManager } from './MongoUsersManager';\nexport { default as UserAccountGoogleService } from './services/user/UserAccountGoogleService';\nexport { default as UserAccountSlackService } from './services/user/UserAccountSlackService';\nexport { authSocketIO } from './authSocketIO';\nexport { createAuthApolloContext } from './authApolloContext';\nexport { STATUSES } from './services/user/UserAccountsService';\n\nexport * from './types';\n\ndeclare module 'alp-types' {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n interface ContextState {\n loggedInUserId:\n | NonNullable<ContextState['loggedInUser']>['_id']\n | null\n | undefined;\n loggedInUser: User | null | undefined;\n }\n\n interface ContextSanitizedState {\n loggedInUserId:\n | NonNullable<ContextSanitizedState['loggedInUser']>['_id']\n | null\n | undefined;\n loggedInUser: UserSanitized | null | undefined;\n }\n\n interface BaseContext {\n setLoggedIn: (\n loggedInUserId: NonNullable<ContextState['loggedInUserId']>,\n loggedInUser: NonNullable<ContextState['loggedInUser']>,\n ) => Promise<void>;\n logout: () => void;\n }\n}\n\nconst logger = new Logger('alp:auth');\n\nconst signPromisified: any = promisify(jsonwebtoken.sign);\n\nexport type AuthController = AuthControllerType;\nexport type AuthRoutes = AuthRoutesType;\nexport { AuthenticationService } from './services/authentification/AuthenticationService';\n\nexport default function init<\n StrategyKeys extends AllowedStrategyKeys = 'google',\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n>({\n homeRouterKey,\n usersManager,\n strategies,\n defaultStrategy,\n strategyToService,\n authHooks,\n jwtAudience,\n}: {\n homeRouterKey?: string;\n usersManager: MongoUsersManager<U, USanitized>;\n strategies: Strategies<StrategyKeys>;\n defaultStrategy?: StrategyKeys;\n strategyToService: Record<StrategyKeys, AccountService<any>>;\n authHooks?: AuthHooks<StrategyKeys>;\n jwtAudience?: string;\n}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return (app: NodeApplication) => {\n const userAccountsService = new UserAccountsService(\n usersManager,\n strategyToService,\n );\n\n const authenticationService = new AuthenticationService(\n app.config,\n strategies,\n userAccountsService,\n );\n\n const controller = createAuthController({\n usersManager,\n authenticationService,\n homeRouterKey,\n defaultStrategy,\n authHooks,\n });\n\n app.context.setLoggedIn = async function (\n this: Context,\n loggedInUserId: NonNullable<ContextState['loggedInUser']>['_id'],\n loggedInUser: NonNullable<ContextState['loggedInUser']>,\n ): Promise<void> {\n logger.debug('setLoggedIn', { loggedInUser });\n if (!loggedInUserId) {\n throw new Error('Illegal value for setLoggedIn');\n }\n\n this.state.loggedInUserId = loggedInUserId;\n this.state.loggedInUser = loggedInUser;\n\n const token = await signPromisified(\n { loggedInUserId, time: Date.now() },\n this.config\n .get<Map<string, unknown>>('authentication')\n .get('secretKey'),\n {\n algorithm: 'HS512',\n audience: jwtAudience || this.request.headers['user-agent'],\n expiresIn: '30 days',\n },\n );\n\n const calcExpiresTime = (): number => {\n const date = new Date();\n date.setDate(date.getDate() + 30);\n return date.getTime();\n };\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.cookies.set(COOKIE_NAME_TOKEN, token, {\n httpOnly: true,\n secure: this.config.get('allowHttps'),\n });\n\n this.cookies.set(\n COOKIE_NAME_STATE,\n JSON.stringify({ loggedInUserId, expiresIn: calcExpiresTime() }),\n {\n httpOnly: false,\n secure: this.config.get('allowHttps'),\n },\n );\n };\n\n app.context.logout = function (this: Context): void {\n delete this.state.loggedInUserId;\n delete this.state.loggedInUser;\n this.cookies.set(COOKIE_NAME_TOKEN, '', { expires: new Date(1) });\n this.cookies.set(COOKIE_NAME_STATE, '', { expires: new Date(1) });\n };\n\n const findLoggedInUser = createFindLoggedInUser(\n app.config\n .get<Map<string, unknown>>('authentication')\n .get('secretKey') as string,\n usersManager,\n logger,\n );\n\n return {\n routes: createRoutes(controller),\n findLoggedInUserFromRequest: (\n req: IncomingMessage,\n ): ReturnType<typeof findLoggedInUser> => {\n const token = getTokenFromRequest(req);\n return findLoggedInUser(\n jwtAudience || req.headers['user-agent'],\n token,\n );\n },\n findLoggedInUser,\n middleware: async <T>(\n ctx: Context,\n next: () => Promise<T> | T,\n ): Promise<T> => {\n const token = ctx.cookies.get(COOKIE_NAME_TOKEN);\n const userAgent = ctx.request.headers['user-agent'];\n logger.debug('middleware', { token });\n\n const setState = (\n loggedInUserId: U['_id'] | null | undefined,\n loggedInUser: U | null | undefined,\n ): void => {\n ctx.state.loggedInUserId = loggedInUserId;\n ctx.state.user = loggedInUser;\n ctx.sanitizedState.loggedInUserId = loggedInUserId;\n ctx.sanitizedState.loggedInUser =\n loggedInUser && usersManager.sanitize(loggedInUser);\n };\n\n const [loggedInUserId, loggedInUser] = await findLoggedInUser(\n jwtAudience || userAgent,\n token,\n );\n logger.debug('middleware', { loggedInUserId });\n\n if (loggedInUserId == null || loggedInUser == null) {\n if (token) {\n ctx.cookies.set(COOKIE_NAME_TOKEN, '', { expires: new Date(1) });\n ctx.cookies.set(COOKIE_NAME_STATE, '', { expires: new Date(1) });\n }\n setState(null, null);\n return next();\n }\n\n setState(loggedInUserId, loggedInUser);\n return next();\n },\n };\n };\n}\n"],"names":["createAuthController","usersManager","authenticationService","homeRouterKey","defaultStrategy","authHooks","login","ctx","strategy","namedParam","Error","params","paramsForLogin","redirectAuthUrl","addScope","state","loggedInUser","redirectTo","scopeKey","response","assert","accessResponse","afterLoginSuccess","afterScopeUpdate","keyPath","store","setLoggedIn","logout","createRoutes","controller","segment","add","defaultRoute","randomBytesPromisified","promisify","randomBytes","randomHex","size","buffer","toString","logger","Logger","AuthenticationService","EventEmitter","constructor","config","strategies","userAccountsService","generateAuthUrl","debug","strategyInstance","type","oauth2","authorizationCode","authorizeURL","getTokens","options","result","getToken","code","redirect_uri","redirectUri","tokens","token","accessToken","access_token","refreshToken","refresh_token","tokenType","token_type","expiresIn","expires_in","expireDate","d","Date","setTime","getTime","idToken","id_token","tokensParam","clientCredentials","createToken","refresh","host","get","request","urlGenerator","user","accountId","scope","getScope","cookies","set","JSON","stringify","isLoginAccess","maxAge","httpOnly","secure","access_type","redirect","isLoggedIn","hooks","query","error","status","expose","cookieName","cookie","expires","parse","findOrCreateFromStrategy","account","update","refreshAccountTokens","tokenExpireDate","now","Promise","resolve","provider","then","updateAccount","STATUSES","VALIDATED","DELETED","UserAccountsService","strategyToService","userId","_id","service","newScope","scopeKeyToScope","accounts","find","join","subservice","profile","getProfile","getId","undefined","subservices","includes","push","replaceOne","emails","getEmails","findOneByAccountOrEmails","providerKey","info","Object","assign","displayName","getDisplayName","fullName","getFullName","name","getAccountName","userEmails","forEach","email","emailDomains","reduce","domains","split","Set","insertOne","COOKIE_NAME_TOKEN","COOKIE_NAME_STATE","getTokenFromRequest","req","headers","authorization","startsWith","slice","Cookies","verifyPromisified","jsonwebtoken","verify","createDecodeJWT","secretKey","jwtAudience","algorithms","audience","loggedInUserId","createFindLoggedInUser","decodeJwt","err","findById","MongoUsersManager","findConnected","connected","findByKey","sanitize","sanitizeBaseUser","length","$or","$in","findOne","accountIndex","indexOf","partialUpdateOne","$set","created","updated","map","UserAccountGoogleService","fetch","json","id","givenName","given_name","familyName","family_name","getDefaultScope","oldScope","filter","item","i","ar","UserAccountSlackService","team","authSocketIO","app","io","findLoggedInUser","users","Map","use","socket","next","handshakeData","client","on","delete","getTokenFromReq","createAuthApolloContext","connection","signPromisified","sign","init","context","time","algorithm","date","setDate","getDate","routes","findLoggedInUserFromRequest","middleware","userAgent","setState","sanitizedState"],"mappings":";;;;;;;;AA+CO,SAASA,oBAAoBA,CAIlC;EACAC,YAAY;EACZC,qBAAqB;AACrB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,gBAAgB,CAC3D5C,WAAW,IAAIqE,SAAS,EACxB1L,KACF,CAAC,CAAA;AACDvB,QAAAA,MAAM,CAACS,KAAK,CAAC,YAAY,EAAE;AAAEsI,UAAAA,cAAAA;AAAe,SAAC,CAAC,CAAA;AAE9C,QAAA,IAAIA,cAAc,IAAI,IAAI,IAAIvK,YAAY,IAAI,IAAI,EAAE;AAClD,UAAA,IAAI+C,KAAK,EAAE;YACTxD,GAAG,CAACoF,OAAO,CAACC,GAAG,CAAC0E,iBAAiB,EAAE,EAAE,EAAE;AAAEzD,cAAAA,OAAO,EAAE,IAAInC,IAAI,CAAC,CAAC,CAAA;AAAE,aAAC,CAAC,CAAA;YAChEnE,GAAG,CAACoF,OAAO,CAACC,GAAG,CAAC2E,iBAAiB,EAAE,EAAE,EAAE;AAAE1D,cAAAA,OAAO,EAAE,IAAInC,IAAI,CAAC,CAAC,CAAA;AAAE,aAAC,CAAC,CAAA;AAClE,WAAA;AACAgL,UAAAA,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;UACpB,OAAOrB,IAAI,EAAE,CAAA;AACf,SAAA;AAEAqB,QAAAA,QAAQ,CAACnE,cAAc,EAAEvK,YAAY,CAAC,CAAA;QACtC,OAAOqN,IAAI,EAAE,CAAA;AACf,OAAA;KACD,CAAA;GACF,CAAA;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"index-node18.mjs","sources":["../src/createAuthController.ts","../src/createRoutes.ts","../src/utils/generators.ts","../src/services/authentification/AuthenticationService.ts","../src/services/user/UserAccountsService.ts","../src/utils/cookies.ts","../src/utils/createFindLoggedInUser.ts","../src/MongoUsersManager.ts","../src/services/user/UserAccountGoogleService.ts","../src/services/user/UserAccountSlackService.ts","../src/authSocketIO.ts","../src/authApolloContext.ts","../src/index.ts"],"sourcesContent":["import type { AlpRouteRef, Context } from 'alp-node';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type {\n AuthenticationService,\n AccessResponseHooks,\n} from './services/authentification/AuthenticationService';\nimport type {\n AllowedStrategyKeys,\n AllowedMapParamsStrategy,\n} from './services/authentification/types';\nimport type { User, UserSanitized } from './types';\n\nexport interface CreateAuthControllerParams<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n> {\n authenticationService: AuthenticationService<StrategyKeys, U, UserSanitized>;\n homeRouterKey?: string;\n usersManager: MongoUsersManager<U, USanitized>;\n defaultStrategy?: StrategyKeys;\n authHooks?: AuthHooks<StrategyKeys>;\n}\n\nexport interface AuthController {\n login: AlpRouteRef;\n addScope: AlpRouteRef;\n response: AlpRouteRef;\n logout: AlpRouteRef;\n}\n\ntype OptionalRecord<K extends keyof any, T> = { [P in K]?: T };\n\nexport interface AuthHooks<StrategyKeys extends AllowedStrategyKeys>\n extends AccessResponseHooks<StrategyKeys> {\n paramsForLogin?: <StrategyKey extends StrategyKeys>(\n strategy: StrategyKey,\n ctx: Context,\n ) =>\n | OptionalRecord<AllowedMapParamsStrategy[StrategyKey], any>\n | Promise<OptionalRecord<AllowedMapParamsStrategy[StrategyKey], any>>\n | Promise<void>\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n | void;\n}\n\nexport function createAuthController<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n>({\n usersManager,\n authenticationService,\n homeRouterKey = '/',\n defaultStrategy,\n authHooks = {},\n}: CreateAuthControllerParams<StrategyKeys, U, USanitized>): AuthController {\n return {\n async login(ctx: Context): Promise<void> {\n const strategy: StrategyKeys = (ctx.namedParam('strategy') ||\n defaultStrategy) as StrategyKeys;\n if (!strategy) throw new Error('Strategy missing');\n const params =\n (authHooks.paramsForLogin &&\n (await authHooks.paramsForLogin(strategy, ctx))) ||\n {};\n await authenticationService.redirectAuthUrl(ctx, strategy, {}, params);\n },\n\n /**\n * Add scope in existing\n * The user must already be connected\n */\n async addScope(ctx: Context): Promise<void> {\n if (!ctx.state.loggedInUser) {\n ctx.redirectTo(homeRouterKey);\n return;\n }\n\n const strategy: StrategyKeys = (ctx.namedParam('strategy') ||\n defaultStrategy) as StrategyKeys;\n if (!strategy) throw new Error('Strategy missing');\n const scopeKey = ctx.namedParam('scopeKey');\n if (!scopeKey) throw new Error('Scope missing');\n await authenticationService.redirectAuthUrl(ctx, strategy, { scopeKey });\n },\n\n async response(ctx: Context): Promise<void> {\n const strategy: StrategyKeys = ctx.namedParam('strategy') as StrategyKeys;\n ctx.assert(strategy);\n\n const loggedInUser = await authenticationService.accessResponse(\n ctx,\n strategy,\n !!ctx.state.loggedInUser,\n {\n afterLoginSuccess: authHooks.afterLoginSuccess,\n afterScopeUpdate: authHooks.afterScopeUpdate,\n },\n );\n const keyPath = usersManager.store.keyPath;\n await ctx.setLoggedIn(loggedInUser[keyPath], loggedInUser);\n ctx.redirectTo(homeRouterKey);\n },\n\n async logout(ctx: Context): Promise<void> {\n ctx.logout();\n ctx.redirectTo(homeRouterKey);\n },\n };\n}\n","import type { AuthController } from './createAuthController';\n\nexport interface AuthRoutes {\n login: [string, (segment: any) => void];\n addScope: [string, AuthController['addScope']];\n logout: [string, AuthController['logout']];\n}\n\nexport const createRoutes = (controller: AuthController): AuthRoutes => ({\n login: [\n '/login/:strategy?',\n (segment: any) => {\n segment.add('/response', controller.response, 'authResponse');\n segment.defaultRoute(controller.login, 'login');\n },\n ],\n addScope: ['/add-scope/:strategy/:scopeKey', controller.addScope],\n logout: ['/logout', controller.logout],\n});\n","import { randomBytes } from 'node:crypto';\nimport { promisify } from 'node:util';\n\nconst randomBytesPromisified = promisify(randomBytes);\n\nexport async function randomBase64(size: number): Promise<string> {\n const buffer = await randomBytesPromisified(size);\n return buffer.toString('base64');\n}\n\nexport async function randomHex(size: number): Promise<string> {\n const buffer = await randomBytesPromisified(size);\n return buffer.toString('hex');\n}\n","/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-unsafe-assignment */\n/* eslint-disable camelcase, max-lines */\nimport { EventEmitter } from 'node:events';\nimport type { Context, NodeConfig } from 'alp-node';\nimport { Logger } from 'nightingale-logger';\nimport type { Strategy as Oauth2Strategy } from '../../../strategies/strategies.d';\nimport type { AccountId, User, Account, UserSanitized } from '../../types';\nimport { randomHex } from '../../utils/generators';\nimport type UserAccountsService from '../user/UserAccountsService';\nimport type { AllowedStrategyKeys, Tokens } from './types';\n\nconst logger = new Logger('alp:auth:authentication');\n\nexport interface GenerateAuthUrlOptions {\n accessType?: string;\n grantType?: string;\n includeGrantedScopes?: boolean;\n loginHint?: string;\n prompt?: string;\n redirectUri?: string;\n scope?: string;\n state?: string;\n}\n\nexport interface GetTokensOptions {\n code: string;\n redirectUri: string;\n}\n\nexport type Strategies<StrategyKeys extends AllowedStrategyKeys> = Record<\n StrategyKeys,\n Oauth2Strategy<any>\n>;\n\nexport interface AccessResponseHooks<StrategyKeys, U extends User = User> {\n afterLoginSuccess?: <StrategyKey extends StrategyKeys>(\n strategy: StrategyKey,\n loggedInUser: U,\n ) => Promise<void> | void;\n\n afterScopeUpdate?: <StrategyKey extends StrategyKeys>(\n strategy: StrategyKey,\n scopeKey: string,\n account: Account,\n user: U,\n ) => Promise<void> | void;\n}\n\nexport class AuthenticationService<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n // eslint-disable-next-line unicorn/prefer-event-target\n> extends EventEmitter {\n config: NodeConfig;\n\n strategies: Strategies<StrategyKeys>;\n\n userAccountsService: UserAccountsService<StrategyKeys, U, USanitized>;\n\n constructor(\n config: NodeConfig,\n strategies: Strategies<StrategyKeys>,\n userAccountsService: UserAccountsService<StrategyKeys, U, USanitized>,\n ) {\n super();\n this.config = config;\n this.strategies = strategies;\n this.userAccountsService = userAccountsService;\n }\n\n generateAuthUrl<T extends StrategyKeys>(strategy: T, params: any): string {\n logger.debug('generateAuthUrl', { strategy, params });\n const strategyInstance = this.strategies[strategy];\n switch (strategyInstance.type) {\n case 'oauth2':\n return strategyInstance.oauth2.authorizationCode.authorizeURL(params);\n default:\n throw new Error('Invalid strategy');\n }\n }\n\n async getTokens(\n strategy: StrategyKeys,\n options: GetTokensOptions,\n ): Promise<Tokens> {\n logger.debug('getTokens', { strategy, options });\n const strategyInstance = this.strategies[strategy];\n switch (strategyInstance.type) {\n case 'oauth2': {\n const result = await strategyInstance.oauth2.authorizationCode.getToken(\n {\n code: options.code,\n redirect_uri: options.redirectUri,\n },\n );\n if (!result) return result;\n const tokens = result.token;\n\n return {\n accessToken: tokens.access_token as string,\n refreshToken: tokens.refresh_token as string,\n tokenType: tokens.token_type as string,\n expiresIn: tokens.expires_in as number,\n expireDate: (() => {\n if (tokens.expires_in == null) return null;\n const d = new Date();\n d.setTime(d.getTime() + (tokens.expires_in as number) * 1000);\n return d;\n })(),\n idToken: tokens.id_token as string,\n };\n // return strategyInstance.accessToken.create(result);\n }\n\n default:\n throw new Error('Invalid stategy');\n }\n }\n\n async refreshToken(\n strategy: StrategyKeys,\n tokensParam: { refreshToken: string },\n ): Promise<Tokens> {\n logger.debug('refreshToken', { strategy });\n if (!tokensParam.refreshToken) {\n throw new Error('Missing refresh token');\n }\n const strategyInstance = this.strategies[strategy];\n switch (strategyInstance.type) {\n case 'oauth2': {\n const token = strategyInstance.oauth2.clientCredentials.createToken({\n refresh_token: tokensParam.refreshToken,\n });\n const result = await token.refresh();\n const tokens = result.token;\n return {\n accessToken: tokens.access_token as string,\n tokenType: tokens.token_type as string,\n expiresIn: tokens.expires_in as number,\n expireDate: (() => {\n if (tokens.expires_in == null) return null;\n const d = new Date();\n d.setTime(d.getTime() + (tokens.expires_in as number) * 1000);\n return d;\n })(),\n idToken: tokens.id_token as string,\n };\n }\n\n default:\n throw new Error('Invalid stategy');\n }\n }\n\n redirectUri(ctx: Context, strategy: string): string {\n const host = `http${this.config.get('allowHttps') ? 's' : ''}://${\n ctx.request.host\n }`;\n return `${host}${ctx.urlGenerator('authResponse', {\n strategy,\n })}`;\n }\n\n async redirectAuthUrl(\n ctx: Context,\n strategy: StrategyKeys,\n {\n refreshToken,\n scopeKey,\n user,\n accountId,\n }: {\n refreshToken?: string | undefined;\n scopeKey?: string | undefined;\n user?: U;\n accountId?: AccountId;\n },\n params?: any,\n ): Promise<void> {\n logger.debug('redirectAuthUrl', { strategy, scopeKey, refreshToken });\n const state = await randomHex(8);\n const isLoginAccess = !scopeKey || scopeKey === 'login';\n const scope = this.userAccountsService.getScope(\n strategy,\n scopeKey || 'login',\n user,\n accountId,\n );\n\n if (!scope) {\n throw new Error('Invalid empty scope');\n }\n\n ctx.cookies.set(\n `auth_${strategy}_${state}`,\n JSON.stringify({\n scopeKey,\n scope,\n isLoginAccess,\n }),\n {\n maxAge: 10 * 60 * 1000,\n httpOnly: true,\n secure: this.config.get('allowHttps'),\n },\n );\n const redirectUri = this.generateAuthUrl(strategy, {\n redirect_uri: this.redirectUri(ctx, strategy),\n scope,\n state,\n access_type: refreshToken ? 'offline' : 'online',\n ...params,\n });\n\n ctx.redirect(redirectUri);\n }\n\n async accessResponse<StrategyKey extends StrategyKeys>(\n ctx: Context,\n strategy: StrategyKey,\n isLoggedIn: boolean,\n hooks: AccessResponseHooks<StrategyKeys, U>,\n ): Promise<U> {\n const errorParam = ctx.params.queryParam('error').notEmpty();\n if (errorParam.isValid()) {\n ctx.throw(errorParam.value, 403);\n }\n\n const code = ctx.validParams.queryParam('code').notEmpty().value;\n const state = ctx.validParams.queryParam('state').notEmpty().value;\n\n const cookieName = `auth_${strategy}_${state}`;\n const cookie = ctx.cookies.get(cookieName);\n ctx.cookies.set(cookieName, '', { expires: new Date(1) });\n if (!cookie) {\n throw new Error('No cookie for this state');\n }\n\n const parsedCookie = JSON.parse(cookie);\n if (!parsedCookie?.scope) {\n throw new Error('Unexpected cookie value');\n }\n\n if (!parsedCookie.isLoginAccess) {\n if (!isLoggedIn) {\n throw new Error('You are not connected');\n }\n }\n\n const tokens: Tokens = await this.getTokens(strategy, {\n code,\n redirectUri: this.redirectUri(ctx, strategy),\n });\n\n if (parsedCookie.isLoginAccess) {\n const user = await this.userAccountsService.findOrCreateFromStrategy(\n strategy,\n tokens,\n parsedCookie.scope,\n parsedCookie.scopeKey,\n );\n\n if (hooks.afterLoginSuccess) {\n await hooks.afterLoginSuccess(strategy, user);\n }\n\n return user;\n }\n\n const loggedInUser = ctx.state.loggedInUser as U;\n const { account, user } = await this.userAccountsService.update(\n loggedInUser,\n strategy,\n tokens,\n parsedCookie.scope,\n parsedCookie.scopeKey,\n );\n\n if (hooks.afterScopeUpdate) {\n await hooks.afterScopeUpdate(\n strategy,\n parsedCookie.scopeKey,\n account,\n user,\n );\n }\n\n return loggedInUser;\n }\n\n refreshAccountTokens(user: U, account: Account): Promise<boolean> {\n if (\n account.tokenExpireDate &&\n account.tokenExpireDate.getTime() > Date.now()\n ) {\n return Promise.resolve(false);\n }\n return this.refreshToken(account.provider as StrategyKeys, {\n // accessToken: account.accessToken,\n refreshToken: account.refreshToken!,\n }).then((tokens: Tokens) => {\n if (!tokens) {\n // serviceGoogle.updateFields({ accessToken:null, refreshToken:null, status: .OUTDATED });\n return false;\n }\n account.accessToken = tokens.accessToken;\n account.tokenExpireDate = tokens.expireDate;\n return this.userAccountsService\n .updateAccount(user, account)\n .then(() => true);\n });\n }\n}\n","/* eslint-disable @typescript-eslint/no-shadow */\nimport { EventEmitter } from 'node:events';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from '../../MongoUsersManager';\nimport type { AccountId, User, Account, UserSanitized } from '../../types';\nimport type { AllowedStrategyKeys } from '../authentification/types';\nimport type { AccountService, TokensObject } from './types';\n\nconst logger = new Logger('alp:auth:userAccounts');\n\nexport const STATUSES = {\n VALIDATED: 'validated',\n DELETED: 'deleted',\n};\n\nexport default class UserAccountsService<\n StrategyKeys extends AllowedStrategyKeys,\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n // eslint-disable-next-line unicorn/prefer-event-target\n> extends EventEmitter {\n private readonly strategyToService: Record<StrategyKeys, AccountService<any>>;\n\n usersManager: MongoUsersManager<U, USanitized>;\n\n constructor(\n usersManager: MongoUsersManager<U, USanitized>,\n strategyToService: Record<StrategyKeys, AccountService<any>>,\n ) {\n super();\n this.usersManager = usersManager;\n this.strategyToService = strategyToService;\n }\n\n getScope(\n strategy: StrategyKeys,\n scopeKey: string,\n user?: U,\n accountId?: AccountId,\n ): string {\n logger.debug('getScope', { strategy, userId: user?._id });\n const service = this.strategyToService[strategy];\n if (!service) {\n throw new Error('Strategy not supported');\n }\n\n const newScope = service.scopeKeyToScope[scopeKey];\n if (!user || !accountId) {\n return newScope;\n }\n const account = user.accounts.find(\n (account) =>\n account.provider === strategy && account.accountId === accountId,\n );\n\n if (!account) {\n throw new Error('Could not found associated account');\n }\n return service.getScope(account.scope, newScope).join(' ');\n }\n\n async update(\n user: U,\n strategy: StrategyKeys,\n tokens: TokensObject,\n scope: string,\n subservice: string,\n ): Promise<{ user: U; account: U['accounts'][number] }> {\n const service = this.strategyToService[strategy];\n const profile = await service.getProfile(tokens);\n const accountId = service.getId(profile);\n const account = user.accounts.find(\n (account) =>\n account.provider === strategy && account.accountId === accountId,\n );\n if (!account) {\n // TODO check if already exists in other user => merge\n // TODO else add a new account in this user\n throw new Error('Could not found associated account');\n }\n account.status = 'valid';\n account.accessToken = tokens.accessToken;\n if (tokens.refreshToken) {\n account.refreshToken = tokens.refreshToken;\n }\n if (tokens.expireDate !== undefined) {\n account.tokenExpireDate = tokens.expireDate;\n }\n account.scope = service.getScope(account.scope, scope);\n account.subservices = account.subservices || [];\n if (subservice && !account.subservices.includes(subservice)) {\n account.subservices.push(subservice);\n }\n\n await this.usersManager.replaceOne(user);\n return { user, account };\n }\n\n async findOrCreateFromStrategy(\n strategy: StrategyKeys,\n tokens: TokensObject,\n scope: string,\n subservice: string,\n ): Promise<U> {\n const service = this.strategyToService[strategy];\n if (!service) throw new Error('Strategy not supported');\n\n const profile = await service.getProfile(tokens);\n const accountId = service.getId(profile);\n if (!accountId) throw new Error('Invalid profile: no id found');\n\n const emails = service.getEmails(profile);\n\n let user: Partial<U> | undefined =\n await this.usersManager.findOneByAccountOrEmails({\n provider: service.providerKey,\n accountId,\n emails,\n });\n\n logger.info(!user ? 'create user' : 'existing user', {\n userId: user?._id,\n accountId,\n /*emails , user*/\n });\n\n if (!user) {\n user = {};\n }\n\n Object.assign(user, {\n displayName: service.getDisplayName(profile),\n fullName: service.getFullName(profile),\n status: STATUSES.VALIDATED,\n });\n\n if (!user.accounts) user.accounts = [];\n\n let account: Partial<Account> | undefined = user.accounts.find(\n (account: Account) =>\n account.provider === strategy && account.accountId === accountId,\n );\n\n if (!account) {\n account = { provider: strategy, accountId };\n // @ts-expect-error well...\n user.accounts.push(account);\n }\n\n account.name = service.getAccountName(profile);\n account.status = 'valid';\n account.profile = profile;\n account.accessToken = tokens.accessToken;\n if (tokens.refreshToken) {\n account.refreshToken = tokens.refreshToken;\n }\n if (tokens.expireDate !== undefined) {\n account.tokenExpireDate = tokens.expireDate;\n }\n account.scope = service.getScope(account.scope, scope);\n\n if (!account.subservices) account.subservices = [];\n if (subservice && !account.subservices.includes(subservice)) {\n account.subservices.push(subservice);\n }\n\n if (!user.emails) user.emails = [];\n const userEmails = user.emails;\n emails.forEach((email: string) => {\n if (!userEmails.includes(email)) {\n userEmails.push(email);\n }\n });\n\n user.emailDomains = [\n // eslint-disable-next-line unicorn/no-array-reduce\n ...user.emails.reduce(\n (domains: Set<string>, email: string) =>\n domains.add(email.split('@', 2)[1]),\n new Set<string>(),\n ),\n ];\n\n const keyPath = this.usersManager.store.keyPath;\n\n if (user[keyPath]) {\n await this.usersManager.replaceOne(user as U);\n } else {\n await this.usersManager.insertOne(user as U);\n }\n\n return user as U;\n }\n\n async updateAccount(user: U, account: Account): Promise<U> {\n await this.usersManager.updateAccount(user, account);\n return user;\n }\n}\n","import type { IncomingMessage } from 'node:http';\nimport type { Option } from 'cookies';\nimport Cookies from 'cookies';\n\nexport const COOKIE_NAME_TOKEN = 'loggedInUserToken';\nexport const COOKIE_NAME_STATE = 'loggedInUserState';\n\nexport const getTokenFromRequest = (\n req: IncomingMessage,\n options?: Pick<Option, Exclude<keyof Option, 'secure'>>,\n): string | undefined => {\n if (req.headers.authorization?.startsWith('Bearer ')) {\n return req.headers.authorization.slice('Bearer '.length);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const cookies = new Cookies(req, null as unknown as any, {\n ...options,\n secure: true,\n });\n\n return cookies.get(COOKIE_NAME_TOKEN);\n};\n","import { promisify } from 'node:util';\nimport type {\n GetPublicKeyOrSecret,\n Secret,\n VerifyCallback,\n VerifyOptions,\n} from 'jsonwebtoken';\nimport jsonwebtoken from 'jsonwebtoken';\nimport type { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from '../MongoUsersManager';\nimport type { User, UserSanitized } from '../types';\n\ntype Verify = (\n token: string,\n secretOrPublicKey: GetPublicKeyOrSecret | Secret,\n options?: VerifyOptions,\n callback?: VerifyCallback,\n) => void;\n\nconst verifyPromisified = promisify<\n Parameters<Verify>[0],\n Parameters<Verify>[1],\n Parameters<Verify>[2],\n Parameters<VerifyCallback>[1]\n>(jsonwebtoken.verify as Verify);\n\nconst createDecodeJWT =\n (secretKey: string) =>\n async (token: string, jwtAudience: string): Promise<string | undefined> => {\n const result = await verifyPromisified(token, secretKey, {\n algorithms: ['HS512'],\n audience: jwtAudience,\n });\n return (result as any)?.loggedInUserId as string | undefined;\n };\n\nexport type FindLoggedInUser<U extends User> = (\n jwtAudience?: string,\n token?: string,\n) => Promise<[U['_id'] | null | undefined, U | null | undefined]>;\n\nexport const createFindLoggedInUser = <\n U extends User,\n USanitized extends UserSanitized,\n>(\n secretKey: string,\n usersManager: MongoUsersManager<U, USanitized>,\n logger: Logger,\n): FindLoggedInUser<U> => {\n const decodeJwt = createDecodeJWT(secretKey);\n\n const findLoggedInUser: FindLoggedInUser<U> = async (jwtAudience, token) => {\n if (!token || !jwtAudience) return [null, null];\n\n let loggedInUserId;\n try {\n loggedInUserId = await decodeJwt(token, jwtAudience);\n } catch (error: unknown) {\n logger.debug('failed to verify authentification', { err: error });\n }\n\n if (loggedInUserId == null) return [null, null];\n\n const loggedInUser = await usersManager.findById(loggedInUserId);\n\n if (!loggedInUser) return [null, null];\n\n return [loggedInUserId, loggedInUser];\n };\n\n return findLoggedInUser;\n};\n","import type { MongoInsertType, MongoStore, Update } from 'liwi-mongo';\nimport type { User, Account, UserSanitized } from './types';\n\nexport default class MongoUsersManager<\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n> {\n store: MongoStore<U>;\n\n constructor(store: MongoStore<U>) {\n this.store = store;\n }\n\n /** @deprecated use findById instead */\n findConnected(connected: string): Promise<U | undefined> {\n return this.store.findByKey(connected);\n }\n\n findById(userId: string): Promise<U | undefined> {\n return this.store.findByKey(userId);\n }\n\n insertOne(user: MongoInsertType<U>): Promise<any> {\n return this.store.insertOne(user);\n }\n\n replaceOne(user: U): Promise<any> {\n return this.store.replaceOne(user);\n }\n\n sanitize(user: U): USanitized {\n return this.sanitizeBaseUser(user) as USanitized;\n }\n\n findOneByAccountOrEmails({\n accountId,\n emails,\n provider,\n }: {\n accountId: number | string;\n emails?: string[];\n provider: string;\n }): Promise<U | undefined> {\n let query: any = {\n 'accounts.provider': provider,\n 'accounts.accountId': accountId,\n };\n\n if (emails && emails.length > 0) {\n query = {\n $or: [\n query,\n {\n emails: { $in: emails },\n },\n ],\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return this.store.findOne(query);\n }\n\n updateAccount(user: U, account: Account): Promise<U> {\n const accountIndex = user.accounts.indexOf(account);\n if (accountIndex === -1) {\n throw new Error('Invalid account');\n }\n\n return this.store.partialUpdateOne(user, {\n $set: {\n [`accounts.${accountIndex}`]: account,\n },\n } as Update<U>);\n }\n\n // eslint-disable-next-line @typescript-eslint/class-methods-use-this\n sanitizeBaseUser(user: U): UserSanitized {\n return {\n _id: user._id,\n created: user.created,\n updated: user.updated,\n displayName: user.displayName,\n fullName: user.fullName,\n status: user.status,\n emails: user.emails,\n emailDomains: user.emailDomains,\n accounts: user.accounts.map((account: Account) => ({\n provider: account.provider,\n accountId: account.accountId,\n name: account.name,\n status: account.status,\n profile: account.profile,\n })),\n };\n }\n}\n","/* eslint-disable @typescript-eslint/class-methods-use-this */\n/* eslint-disable @typescript-eslint/no-unsafe-argument */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\nimport type { Tokens } from '../authentification/types';\nimport type { AccountService, FullName } from './types';\n\nexport default class UserAccountGoogleService<ScopeKeys extends 'login'>\n implements AccountService<ScopeKeys>\n{\n scopeKeyToScope: Record<ScopeKeys, string>;\n\n constructor(scopeKeyToScope: Record<Exclude<'login', ScopeKeys>, string>) {\n this.scopeKeyToScope = {\n ...scopeKeyToScope,\n login: 'openid profile email',\n };\n }\n\n providerKey = 'google';\n\n getProfile(tokens: Tokens): Promise<any> {\n return fetch(\n `https://www.googleapis.com/oauth2/v1/userinfo?access_token=${tokens.accessToken}`,\n ).then((response) => response.json());\n }\n\n getId(profile: any): any {\n return profile.id;\n }\n\n getAccountName(profile: any): string | null | undefined {\n return profile.email;\n }\n\n getEmails(profile: any): string[] {\n const emails: string[] = [];\n\n if (profile.email) {\n emails.push(profile.email);\n }\n\n return emails;\n }\n\n getDisplayName(profile: any): string | null | undefined {\n return profile.name;\n }\n\n getFullName(profile: any): FullName {\n return {\n givenName: profile.given_name,\n familyName: profile.family_name,\n };\n }\n\n getDefaultScope(newScope: string): string[] {\n return this.getScope(undefined, newScope);\n }\n\n getScope(oldScope: string[] | undefined, newScope: string): string[] {\n return !oldScope\n ? newScope.split(' ')\n : [...oldScope, ...newScope.split(' ')].filter(\n (item, i, ar) => ar.indexOf(item) === i,\n );\n }\n}\n","/* eslint-disable @typescript-eslint/class-methods-use-this */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\nimport type { Tokens } from '../authentification/types';\nimport type { AccountService, FullName } from './types';\n\n// https://api.slack.com/methods/users.identity\n\nexport default class UserAccountSlackService<ScopeKeys extends 'login'>\n implements AccountService<ScopeKeys>\n{\n scopeKeyToScope: Record<ScopeKeys, string>;\n\n constructor(scopeKeyToScope: Record<Exclude<'login', ScopeKeys>, string>) {\n this.scopeKeyToScope = {\n ...scopeKeyToScope,\n login: 'identity.basic identity.email identity.avatar',\n };\n }\n\n providerKey = 'google';\n\n getProfile(tokens: Tokens): Promise<any> {\n return fetch(\n `https://slack.com/api/users.identity?token=${tokens.accessToken}`,\n ).then((response) => response.json());\n }\n\n getId(profile: any): string | null {\n if (!profile?.team?.id || !profile.user?.id) {\n return null;\n }\n return `team:${profile.team.id as string};user:${\n profile.user.id as string\n }`;\n }\n\n getAccountName(profile: any): string | null | undefined {\n return profile.user.email;\n }\n\n getEmails(profile: any): string[] {\n return profile.user.email ? [profile.user.email] : [];\n }\n\n getDisplayName(profile: any): string | null | undefined {\n return profile.user.name;\n }\n\n getFullName(profile: any): FullName | null {\n return null;\n }\n\n getDefaultScope(newScope: string): string[] {\n return this.getScope(undefined, newScope);\n }\n\n getScope(oldScope: string[] | undefined, newScope: string): string[] {\n return !oldScope\n ? newScope.split(' ')\n : [...oldScope, ...newScope.split(' ')].filter(\n (item, i, ar) => ar.indexOf(item) === i,\n );\n }\n}\n","import type { NodeApplication } from 'alp-node';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type { User } from './types';\nimport { getTokenFromRequest } from './utils/cookies';\nimport { createFindLoggedInUser } from './utils/createFindLoggedInUser';\n\nconst logger = new Logger('alp:auth');\n\nexport const authSocketIO = <U extends User = User>(\n app: NodeApplication,\n usersManager: MongoUsersManager<U>,\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n io: any,\n jwtAudience?: string,\n): void => {\n const findLoggedInUser = createFindLoggedInUser(\n app.config.get<Map<string, string>>('authentication').get('secretKey')!,\n usersManager,\n logger,\n );\n\n const users = new Map();\n io.users = users;\n\n io.use(async (socket: any, next: any) => {\n const handshakeData = socket.request;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const token = getTokenFromRequest(handshakeData);\n\n if (!token) return next();\n\n const [loggedInUserId, loggedInUser] = await findLoggedInUser(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n jwtAudience || handshakeData.headers['user-agent'],\n token,\n );\n\n if (!loggedInUserId || !loggedInUser) return next();\n\n socket.user = loggedInUser;\n users.set(socket.client.id, loggedInUser);\n\n socket.on('disconnected', () => users.delete(socket.client.id));\n\n await next();\n });\n};\n","import type { IncomingMessage } from 'node:http';\nimport type { NodeConfig } from 'alp-node';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type { User } from './types';\nimport { getTokenFromRequest, COOKIE_NAME_TOKEN } from './utils/cookies';\nimport { createFindLoggedInUser } from './utils/createFindLoggedInUser';\n\nconst logger = new Logger('alp:auth');\n\nconst getTokenFromReq = (\n req: IncomingMessage & { cookies?: Record<string, string> },\n): string | undefined => {\n if (req.cookies) return req.cookies[COOKIE_NAME_TOKEN];\n return getTokenFromRequest(req);\n};\n\n/*\n * Not tested yet.\n * @internal\n */\nexport const createAuthApolloContext = <U extends User = User>(\n config: NodeConfig,\n usersManager: MongoUsersManager<U>,\n): any => {\n const findLoggedInUser = createFindLoggedInUser(\n config.get<Map<string, string>>('authentication').get('secretKey')!,\n usersManager,\n logger,\n );\n\n return async ({ req, connection }: { req: any; connection: any }) => {\n if (connection?.loggedInUser) {\n return { user: connection.loggedInUser };\n }\n\n if (!req) return null;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const token = getTokenFromReq(req);\n\n if (!token) return { user: undefined };\n\n const [, loggedInUser] = await findLoggedInUser(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n req.headers['user-agent'],\n token,\n );\n\n return { user: loggedInUser };\n };\n};\n","/* eslint-disable max-lines */\nimport type { IncomingMessage } from 'node:http';\nimport { promisify } from 'node:util';\nimport type { Context, ContextState, NodeApplication } from 'alp-node';\nimport jsonwebtoken from 'jsonwebtoken';\nimport { Logger } from 'nightingale-logger';\nimport type MongoUsersManager from './MongoUsersManager';\nimport type {\n AuthController as AuthControllerType,\n AuthHooks,\n} from './createAuthController';\nimport { createAuthController } from './createAuthController';\nimport type { AuthRoutes as AuthRoutesType } from './createRoutes';\nimport { createRoutes } from './createRoutes';\nimport type { Strategies } from './services/authentification/AuthenticationService';\nimport { AuthenticationService } from './services/authentification/AuthenticationService';\nimport type { AllowedStrategyKeys } from './services/authentification/types';\nimport UserAccountsService from './services/user/UserAccountsService';\nimport type { AccountService } from './services/user/types';\nimport type { User, UserSanitized } from './types';\nimport {\n getTokenFromRequest,\n COOKIE_NAME_TOKEN,\n COOKIE_NAME_STATE,\n} from './utils/cookies';\nimport { createFindLoggedInUser } from './utils/createFindLoggedInUser';\n\nexport { default as MongoUsersManager } from './MongoUsersManager';\nexport { default as UserAccountGoogleService } from './services/user/UserAccountGoogleService';\nexport { default as UserAccountSlackService } from './services/user/UserAccountSlackService';\nexport { authSocketIO } from './authSocketIO';\nexport { createAuthApolloContext } from './authApolloContext';\nexport { STATUSES } from './services/user/UserAccountsService';\n\nexport * from './types';\n\ndeclare module 'alp-node' {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n interface ContextState {\n loggedInUserId:\n | NonNullable<ContextState['loggedInUser']>['_id']\n | null\n | undefined;\n loggedInUser: User | null | undefined;\n }\n\n interface ContextSanitizedState {\n loggedInUserId:\n | NonNullable<ContextSanitizedState['loggedInUser']>['_id']\n | null\n | undefined;\n loggedInUser: UserSanitized | null | undefined;\n }\n\n interface BaseContext {\n setLoggedIn: (\n loggedInUserId: NonNullable<ContextState['loggedInUserId']>,\n loggedInUser: NonNullable<ContextState['loggedInUser']>,\n ) => Promise<void>;\n logout: () => void;\n }\n}\n\nconst logger = new Logger('alp:auth');\n\nconst signPromisified: any = promisify(jsonwebtoken.sign);\n\nexport type AuthController = AuthControllerType;\nexport type AuthRoutes = AuthRoutesType;\nexport { AuthenticationService } from './services/authentification/AuthenticationService';\n\nexport default function init<\n StrategyKeys extends AllowedStrategyKeys = 'google',\n U extends User = User,\n USanitized extends UserSanitized = UserSanitized,\n>({\n homeRouterKey,\n usersManager,\n strategies,\n defaultStrategy,\n strategyToService,\n authHooks,\n jwtAudience,\n}: {\n homeRouterKey?: string;\n usersManager: MongoUsersManager<U, USanitized>;\n strategies: Strategies<StrategyKeys>;\n defaultStrategy?: StrategyKeys;\n strategyToService: Record<StrategyKeys, AccountService<any>>;\n authHooks?: AuthHooks<StrategyKeys>;\n jwtAudience?: string;\n}) {\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n return (app: NodeApplication) => {\n const userAccountsService = new UserAccountsService(\n usersManager,\n strategyToService,\n );\n\n const authenticationService = new AuthenticationService(\n app.config,\n strategies,\n userAccountsService,\n );\n\n const controller = createAuthController({\n usersManager,\n authenticationService,\n homeRouterKey,\n defaultStrategy,\n authHooks,\n });\n\n app.context.setLoggedIn = async function (\n this: Context,\n loggedInUserId: NonNullable<ContextState['loggedInUser']>['_id'],\n loggedInUser: NonNullable<ContextState['loggedInUser']>,\n ): Promise<void> {\n logger.debug('setLoggedIn', { loggedInUser });\n if (!loggedInUserId) {\n throw new Error('Illegal value for setLoggedIn');\n }\n\n this.state.loggedInUserId = loggedInUserId;\n this.state.loggedInUser = loggedInUser;\n\n const token = await signPromisified(\n { loggedInUserId, time: Date.now() },\n this.config\n .get<Map<string, unknown>>('authentication')\n .get('secretKey'),\n {\n algorithm: 'HS512',\n audience: jwtAudience || this.request.headers['user-agent'],\n expiresIn: '30 days',\n },\n );\n\n const calcExpiresTime = (): number => {\n const date = new Date();\n date.setDate(date.getDate() + 30);\n return date.getTime();\n };\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.cookies.set(COOKIE_NAME_TOKEN, token, {\n httpOnly: true,\n secure: this.config.get('allowHttps'),\n });\n\n this.cookies.set(\n COOKIE_NAME_STATE,\n JSON.stringify({ loggedInUserId, expiresIn: calcExpiresTime() }),\n {\n httpOnly: false,\n secure: this.config.get('allowHttps'),\n },\n );\n };\n\n app.context.logout = function (this: Context): void {\n delete this.state.loggedInUserId;\n delete this.state.loggedInUser;\n this.cookies.set(COOKIE_NAME_TOKEN, '', { expires: new Date(1) });\n this.cookies.set(COOKIE_NAME_STATE, '', { expires: new Date(1) });\n };\n\n const findLoggedInUser = createFindLoggedInUser(\n app.config\n .get<Map<string, unknown>>('authentication')\n .get('secretKey') as string,\n usersManager,\n logger,\n );\n\n return {\n routes: createRoutes(controller),\n findLoggedInUserFromRequest: (\n req: IncomingMessage,\n ): ReturnType<typeof findLoggedInUser> => {\n const token = getTokenFromRequest(req);\n return findLoggedInUser(\n jwtAudience || req.headers['user-agent'],\n token,\n );\n },\n findLoggedInUser,\n middleware: async <T>(\n ctx: Context,\n next: () => Promise<T> | T,\n ): Promise<T> => {\n const token = ctx.cookies.get(COOKIE_NAME_TOKEN);\n const userAgent = ctx.request.headers['user-agent'];\n logger.debug('middleware', { token });\n\n const setState = (\n loggedInUserId: U['_id'] | null | undefined,\n loggedInUser: U | null | undefined,\n ): void => {\n ctx.state.loggedInUserId = loggedInUserId;\n ctx.state.user = loggedInUser;\n ctx.sanitizedState.loggedInUserId = loggedInUserId;\n ctx.sanitizedState.loggedInUser =\n loggedInUser && usersManager.sanitize(loggedInUser);\n };\n\n const [loggedInUserId, loggedInUser] = await findLoggedInUser(\n jwtAudience || userAgent,\n token,\n );\n logger.debug('middleware', { loggedInUserId });\n\n if (loggedInUserId == null || loggedInUser == null) {\n if (token) {\n ctx.cookies.set(COOKIE_NAME_TOKEN, '', { expires: new Date(1) });\n ctx.cookies.set(COOKIE_NAME_STATE, '', { expires: new Date(1) });\n }\n setState(null, null);\n return next();\n }\n\n setState(loggedInUserId, loggedInUser);\n return next();\n },\n };\n };\n}\n"],"names":["createAuthController","usersManager","authenticationService","homeRouterKey","defaultStrategy","authHooks","login","ctx","strategy","namedParam","Error","params","paramsForLogin","redirectAuthUrl","addScope","state","loggedInUser","redirectTo","scopeKey","response","assert","accessResponse","afterLoginSuccess","afterScopeUpdate","keyPath","store","setLoggedIn","logout","createRoutes","controller","segment","add","defaultRoute","randomBytesPromisified","promisify","randomBytes","randomHex","size","buffer","toString","logger","Logger","AuthenticationService","EventEmitter","constructor","config","strategies","userAccountsService","generateAuthUrl","debug","strategyInstance","type","oauth2","authorizationCode","authorizeURL","getTokens","options","result","getToken","code","redirect_uri","redirectUri","tokens","token","accessToken","access_token","refreshToken","refresh_token","tokenType","token_type","expiresIn","expires_in","expireDate","d","Date","setTime","getTime","idToken","id_token","tokensParam","clientCredentials","createToken","refresh","host","get","request","urlGenerator","user","accountId","scope","getScope","cookies","set","JSON","stringify","isLoginAccess","maxAge","httpOnly","secure","access_type","redirect","isLoggedIn","hooks","errorParam","queryParam","notEmpty","isValid","throw","value","validParams","cookieName","cookie","expires","parsedCookie","parse","findOrCreateFromStrategy","account","update","refreshAccountTokens","tokenExpireDate","now","Promise","resolve","provider","then","updateAccount","STATUSES","VALIDATED","DELETED","UserAccountsService","strategyToService","userId","_id","service","newScope","scopeKeyToScope","accounts","find","join","subservice","profile","getProfile","getId","status","undefined","subservices","includes","push","replaceOne","emails","getEmails","findOneByAccountOrEmails","providerKey","info","Object","assign","displayName","getDisplayName","fullName","getFullName","name","getAccountName","userEmails","forEach","email","emailDomains","reduce","domains","split","Set","insertOne","COOKIE_NAME_TOKEN","COOKIE_NAME_STATE","getTokenFromRequest","req","headers","authorization","startsWith","slice","Cookies","verifyPromisified","jsonwebtoken","verify","createDecodeJWT","secretKey","jwtAudience","algorithms","audience","loggedInUserId","createFindLoggedInUser","decodeJwt","error","err","findById","MongoUsersManager","findConnected","connected","findByKey","sanitize","sanitizeBaseUser","query","length","$or","$in","findOne","accountIndex","indexOf","partialUpdateOne","$set","created","updated","map","UserAccountGoogleService","fetch","json","id","givenName","given_name","familyName","family_name","getDefaultScope","oldScope","filter","item","i","ar","UserAccountSlackService","team","authSocketIO","app","io","findLoggedInUser","users","Map","use","socket","next","handshakeData","client","on","delete","getTokenFromReq","createAuthApolloContext","connection","signPromisified","sign","init","context","time","algorithm","date","setDate","getDate","routes","findLoggedInUserFromRequest","middleware","userAgent","setState","sanitizedState"],"mappings":";;;;;;;AA8CO,SAASA,oBAAoBA,CAIlC;EACAC,YAAY;EACZC,qBAAqB;AACrBC,EAAAA,aAAa,GAAG,GAAG;EACnBC,eAAe;AACfC,EAAAA,SAAS,GAAG,EAAC;AAC0C,CAAC,EAAkB;EAC1E,OAAO;IACL,MAAMC,KAAKA,CAACC,GAAY,EAAiB;MACvC,MAAMC,QAAsB,GAAID,GAAG,CAACE,UAAU,CAAC,UAAU,CAAC,IACxDL,eAAgC,CAAA;MAClC,IAAI,CAACI,QAAQ,EAAE,MAAM,IAAIE,KAAK,CAAC,kBAAkB,CAAC,CAAA;AAClD,MAAA,MAAMC,MAAM,GACTN,SAAS,CAACO,cAAc,KACtB,MAAMP,SAAS,CAACO,cAAc,CAACJ,QAAQ,EAAED,GAAG,CAAC,CAAC,IACjD,EAAE,CAAA;AACJ,MAAA,MAAML,qBAAqB,CAACW,eAAe,CAACN,GAAG,EAAEC,QAAQ,EAAE,EAAE,EAAEG,MAAM,CAAC,CAAA;KACvE;AAED;AACJ;AACA;AACA;IACI,MAAMG,QAAQA,CAACP,GAAY,EAAiB;AAC1C,MAAA,IAAI,CAACA,GAAG,CAACQ,KAAK,CAACC,YAAY,EAAE;AAC3BT,QAAAA,GAAG,CAACU,UAAU,CAACd,aAAa,CAAC,CAAA;AAC7B,QAAA,OAAA;AACF,OAAA;MAEA,MAAMK,QAAsB,GAAID,GAAG,CAACE,UAAU,CAAC,UAAU,CAAC,IACxDL,eAAgC,CAAA;MAClC,IAAI,CAACI,QAAQ,EAAE,MAAM,IAAIE,KAAK,CAAC,kBAAkB,CAAC,CAAA;AAClD,MAAA,MAAMQ,QAAQ,GAAGX,GAAG,CAACE,UAAU,CAAC,UA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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "alp-node-auth",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "10.0.0",
|
|
4
4
|
"description": "authentication with alp",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"alp"
|
|
@@ -119,15 +119,13 @@
|
|
|
119
119
|
},
|
|
120
120
|
"prettier": "@pob/root/prettier-config",
|
|
121
121
|
"peerDependencies": {
|
|
122
|
-
"alp-node": "^
|
|
123
|
-
"alp-router": "^7.1.1",
|
|
122
|
+
"alp-node": "^7.0.0",
|
|
124
123
|
"liwi-mongo": "^11.0.0",
|
|
125
124
|
"router-segments": "^9.1.0"
|
|
126
125
|
},
|
|
127
126
|
"dependencies": {
|
|
128
127
|
"@types/jsonwebtoken": "^9.0.1",
|
|
129
128
|
"@types/simple-oauth2": "^5.0.4",
|
|
130
|
-
"alp-types": "3.1.1",
|
|
131
129
|
"cookies": "~0.8.0",
|
|
132
130
|
"jsonwebtoken": "^9.0.0",
|
|
133
131
|
"nightingale-logger": "^15.0.0",
|
|
@@ -135,8 +133,7 @@
|
|
|
135
133
|
},
|
|
136
134
|
"devDependencies": {
|
|
137
135
|
"@babel/core": "7.23.7",
|
|
138
|
-
"alp-node": "
|
|
139
|
-
"alp-router": "7.2.0",
|
|
136
|
+
"alp-node": "7.0.0",
|
|
140
137
|
"liwi-mongo": "11.0.0",
|
|
141
138
|
"pob-babel": "38.0.2",
|
|
142
139
|
"router-segments": "9.1.0",
|
package/src/authApolloContext.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IncomingMessage } from 'node:http';
|
|
2
|
-
import type { NodeConfig } from 'alp-
|
|
2
|
+
import type { NodeConfig } from 'alp-node';
|
|
3
3
|
import { Logger } from 'nightingale-logger';
|
|
4
4
|
import type MongoUsersManager from './MongoUsersManager';
|
|
5
5
|
import type { User } from './types';
|
package/src/authSocketIO.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type { AlpRouteRef } from 'alp-
|
|
2
|
-
import type { Context } from 'alp-types';
|
|
1
|
+
import type { AlpRouteRef, Context } from 'alp-node';
|
|
3
2
|
import type MongoUsersManager from './MongoUsersManager';
|
|
4
3
|
import type {
|
|
5
4
|
AuthenticationService,
|
|
@@ -74,7 +73,7 @@ export function createAuthController<
|
|
|
74
73
|
*/
|
|
75
74
|
async addScope(ctx: Context): Promise<void> {
|
|
76
75
|
if (!ctx.state.loggedInUser) {
|
|
77
|
-
|
|
76
|
+
ctx.redirectTo(homeRouterKey);
|
|
78
77
|
return;
|
|
79
78
|
}
|
|
80
79
|
|
|
@@ -101,12 +100,12 @@ export function createAuthController<
|
|
|
101
100
|
);
|
|
102
101
|
const keyPath = usersManager.store.keyPath;
|
|
103
102
|
await ctx.setLoggedIn(loggedInUser[keyPath], loggedInUser);
|
|
104
|
-
|
|
103
|
+
ctx.redirectTo(homeRouterKey);
|
|
105
104
|
},
|
|
106
105
|
|
|
107
106
|
async logout(ctx: Context): Promise<void> {
|
|
108
107
|
ctx.logout();
|
|
109
|
-
|
|
108
|
+
ctx.redirectTo(homeRouterKey);
|
|
110
109
|
},
|
|
111
110
|
};
|
|
112
111
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
/* eslint-disable max-lines */
|
|
2
2
|
import type { IncomingMessage } from 'node:http';
|
|
3
3
|
import { promisify } from 'node:util';
|
|
4
|
-
import type { Context } from 'alp-node';
|
|
5
|
-
import type { ContextState, NodeApplication } from 'alp-types';
|
|
4
|
+
import type { Context, ContextState, NodeApplication } from 'alp-node';
|
|
6
5
|
import jsonwebtoken from 'jsonwebtoken';
|
|
7
6
|
import { Logger } from 'nightingale-logger';
|
|
8
7
|
import type MongoUsersManager from './MongoUsersManager';
|
|
@@ -35,7 +34,7 @@ export { STATUSES } from './services/user/UserAccountsService';
|
|
|
35
34
|
|
|
36
35
|
export * from './types';
|
|
37
36
|
|
|
38
|
-
declare module 'alp-
|
|
37
|
+
declare module 'alp-node' {
|
|
39
38
|
// eslint-disable-next-line @typescript-eslint/no-shadow
|
|
40
39
|
interface ContextState {
|
|
41
40
|
loggedInUserId:
|
|
@@ -3,8 +3,7 @@
|
|
|
3
3
|
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
|
4
4
|
/* eslint-disable camelcase, max-lines */
|
|
5
5
|
import { EventEmitter } from 'node:events';
|
|
6
|
-
import 'alp-
|
|
7
|
-
import type { Context, NodeConfig } from 'alp-types';
|
|
6
|
+
import type { Context, NodeConfig } from 'alp-node';
|
|
8
7
|
import { Logger } from 'nightingale-logger';
|
|
9
8
|
import type { Strategy as Oauth2Strategy } from '../../../strategies/strategies.d';
|
|
10
9
|
import type { AccountId, User, Account, UserSanitized } from '../../types';
|
|
@@ -216,7 +215,7 @@ export class AuthenticationService<
|
|
|
216
215
|
...params,
|
|
217
216
|
});
|
|
218
217
|
|
|
219
|
-
|
|
218
|
+
ctx.redirect(redirectUri);
|
|
220
219
|
}
|
|
221
220
|
|
|
222
221
|
async accessResponse<StrategyKey extends StrategyKeys>(
|
|
@@ -225,28 +224,27 @@ export class AuthenticationService<
|
|
|
225
224
|
isLoggedIn: boolean,
|
|
226
225
|
hooks: AccessResponseHooks<StrategyKeys, U>,
|
|
227
226
|
): Promise<U> {
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
error.expose = true;
|
|
232
|
-
throw error;
|
|
227
|
+
const errorParam = ctx.params.queryParam('error').notEmpty();
|
|
228
|
+
if (errorParam.isValid()) {
|
|
229
|
+
ctx.throw(errorParam.value, 403);
|
|
233
230
|
}
|
|
234
231
|
|
|
235
|
-
const code = ctx.
|
|
236
|
-
const state = ctx.
|
|
237
|
-
|
|
238
|
-
|
|
232
|
+
const code = ctx.validParams.queryParam('code').notEmpty().value;
|
|
233
|
+
const state = ctx.validParams.queryParam('state').notEmpty().value;
|
|
234
|
+
|
|
235
|
+
const cookieName = `auth_${strategy}_${state}`;
|
|
236
|
+
const cookie = ctx.cookies.get(cookieName);
|
|
239
237
|
ctx.cookies.set(cookieName, '', { expires: new Date(1) });
|
|
240
238
|
if (!cookie) {
|
|
241
239
|
throw new Error('No cookie for this state');
|
|
242
240
|
}
|
|
243
241
|
|
|
244
|
-
|
|
245
|
-
if (!
|
|
242
|
+
const parsedCookie = JSON.parse(cookie);
|
|
243
|
+
if (!parsedCookie?.scope) {
|
|
246
244
|
throw new Error('Unexpected cookie value');
|
|
247
245
|
}
|
|
248
246
|
|
|
249
|
-
if (!
|
|
247
|
+
if (!parsedCookie.isLoginAccess) {
|
|
250
248
|
if (!isLoggedIn) {
|
|
251
249
|
throw new Error('You are not connected');
|
|
252
250
|
}
|
|
@@ -257,12 +255,12 @@ export class AuthenticationService<
|
|
|
257
255
|
redirectUri: this.redirectUri(ctx, strategy),
|
|
258
256
|
});
|
|
259
257
|
|
|
260
|
-
if (
|
|
258
|
+
if (parsedCookie.isLoginAccess) {
|
|
261
259
|
const user = await this.userAccountsService.findOrCreateFromStrategy(
|
|
262
260
|
strategy,
|
|
263
261
|
tokens,
|
|
264
|
-
|
|
265
|
-
|
|
262
|
+
parsedCookie.scope,
|
|
263
|
+
parsedCookie.scopeKey,
|
|
266
264
|
);
|
|
267
265
|
|
|
268
266
|
if (hooks.afterLoginSuccess) {
|
|
@@ -277,12 +275,17 @@ export class AuthenticationService<
|
|
|
277
275
|
loggedInUser,
|
|
278
276
|
strategy,
|
|
279
277
|
tokens,
|
|
280
|
-
|
|
281
|
-
|
|
278
|
+
parsedCookie.scope,
|
|
279
|
+
parsedCookie.scopeKey,
|
|
282
280
|
);
|
|
283
281
|
|
|
284
282
|
if (hooks.afterScopeUpdate) {
|
|
285
|
-
await hooks.afterScopeUpdate(
|
|
283
|
+
await hooks.afterScopeUpdate(
|
|
284
|
+
strategy,
|
|
285
|
+
parsedCookie.scopeKey,
|
|
286
|
+
account,
|
|
287
|
+
user,
|
|
288
|
+
);
|
|
286
289
|
}
|
|
287
290
|
|
|
288
291
|
return loggedInUser;
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
export type GoogleParams =
|
|
2
|
+
| 'access_type'
|
|
3
|
+
| 'include_granted_scopes'
|
|
4
|
+
| 'login_hint'
|
|
5
|
+
| 'prompt';
|
|
6
|
+
export type SlackParams = 'client_id' | 'team';
|
|
2
7
|
|
|
3
8
|
export type AllowedStrategyKeys = 'google' | 'slack';
|
|
4
9
|
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
import { Config, SlackParams } from 'alp-types';
|
|
2
1
|
import { ClientCredentials, AuthorizationCode } from 'simple-oauth2';
|
|
2
|
+
export type GoogleParams =
|
|
3
|
+
| 'access_type'
|
|
4
|
+
| 'include_granted_scopes'
|
|
5
|
+
| 'login_hint'
|
|
6
|
+
| 'prompt';
|
|
7
|
+
export type SlackParams = 'client_id' | 'team';
|
|
3
8
|
|
|
4
9
|
export interface Strategy<Params = SlackParams> {
|
|
5
10
|
type: 'oauth2';
|