alp-node-auth 9.3.0 → 11.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 +42 -0
- package/README.md +13 -13
- package/dist/definitions/MongoUsersManager.d.ts +2 -2
- package/dist/definitions/MongoUsersManager.d.ts.map +1 -1
- package/dist/definitions/authApolloContext.d.ts +4 -4
- package/dist/definitions/authApolloContext.d.ts.map +1 -1
- package/dist/definitions/authSocketIO.d.ts +4 -4
- package/dist/definitions/authSocketIO.d.ts.map +1 -1
- package/dist/definitions/createAuthController.d.ts +6 -9
- package/dist/definitions/createAuthController.d.ts.map +1 -1
- package/dist/definitions/createRoutes.d.ts +3 -3
- package/dist/definitions/createRoutes.d.ts.map +1 -1
- package/dist/definitions/index.d.ts +24 -26
- package/dist/definitions/index.d.ts.map +1 -1
- package/dist/definitions/services/authentification/AuthenticationService.d.ts +6 -8
- package/dist/definitions/services/authentification/AuthenticationService.d.ts.map +1 -1
- package/dist/definitions/services/authentification/types.d.ts +3 -2
- package/dist/definitions/services/authentification/types.d.ts.map +1 -1
- package/dist/definitions/services/user/UserAccountGoogleService.d.ts +4 -4
- package/dist/definitions/services/user/UserAccountGoogleService.d.ts.map +1 -1
- package/dist/definitions/services/user/UserAccountSlackService.d.ts +4 -4
- package/dist/definitions/services/user/UserAccountSlackService.d.ts.map +1 -1
- package/dist/definitions/services/user/UserAccountsService.d.ts +6 -7
- package/dist/definitions/services/user/UserAccountsService.d.ts.map +1 -1
- package/dist/definitions/services/user/types.d.ts +1 -1
- package/dist/definitions/types.d.ts +1 -1
- package/dist/definitions/utils/cookies.d.ts +3 -4
- package/dist/definitions/utils/cookies.d.ts.map +1 -1
- package/dist/definitions/utils/createFindLoggedInUser.d.ts +4 -4
- package/dist/definitions/utils/createFindLoggedInUser.d.ts.map +1 -1
- package/dist/{index-node18.mjs → index-node20.mjs} +115 -124
- package/dist/index-node20.mjs.map +1 -0
- package/package.json +24 -26
- package/src/MongoUsersManager.ts +5 -6
- package/src/authApolloContext.ts +10 -10
- package/src/authSocketIO.ts +10 -10
- package/src/createAuthController.ts +22 -20
- package/src/createRoutes.ts +8 -8
- package/src/index.ts +58 -64
- package/src/services/authentification/AuthenticationService.ts +56 -53
- package/src/services/authentification/types.ts +7 -2
- package/src/services/user/UserAccountGoogleService.ts +9 -9
- package/src/services/user/UserAccountSlackService.ts +9 -9
- package/src/services/user/UserAccountsService.ts +23 -25
- package/src/services/user/types.ts +1 -1
- package/src/types.ts +1 -1
- package/src/utils/cookies.ts +8 -8
- package/src/utils/createFindLoggedInUser.ts +9 -9
- package/src/utils/generators.ts +4 -4
- package/strategies/dropbox.js +7 -7
- package/strategies/facebook.js +7 -7
- package/strategies/foursquare.js +7 -7
- package/strategies/github.js +7 -7
- package/strategies/google.js +7 -7
- package/strategies/slack.js +7 -7
- package/strategies/strategies.d.ts +8 -3
- package/dist/index-node18.mjs.map +0 -1
- package/src/.eslintrc.json +0 -38
- package/strategies/.eslintrc.json +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-node20.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 AccessResponseHooks,\n AuthenticationService,\n} from \"./services/authentification/AuthenticationService\";\nimport type {\n AllowedMapParamsStrategy,\n AllowedStrategyKeys,\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> = Partial<Record<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.namedRouteParam(\"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.namedRouteParam(\"strategy\") ||\n defaultStrategy) as StrategyKeys;\n if (!strategy) throw new Error(\"Strategy missing\");\n const scopeKey = ctx.namedRouteParam(\"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.namedRouteParam(\n \"strategy\",\n ) 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 // eslint-disable-next-line @typescript-eslint/require-await -- keep async in case i later need await in this method\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 */\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 { Account, AccountId, User, 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(403, errorParam.value);\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","import { EventEmitter } from \"node:events\";\nimport { Logger } from \"nightingale-logger\";\nimport type MongoUsersManager from \"../../MongoUsersManager\";\nimport type { Account, AccountId, User, 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 user.accounts.push(account as 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 { Account, User, 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 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/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 // eslint-disable-next-line n/no-unsupported-features/node-builtins\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/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 // eslint-disable-next-line n/no-unsupported-features/node-builtins\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<{ secretKey: string }>(\"authentication\").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 { COOKIE_NAME_TOKEN, getTokenFromRequest } 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<{ secretKey: string }>(\"authentication\").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","import 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 COOKIE_NAME_STATE,\n COOKIE_NAME_TOKEN,\n getTokenFromRequest,\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 type * from \"./types\";\n\ndeclare module \"alp-node\" {\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 setLoggedIn(\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 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 logout(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.get<{ secretKey: string }>(\"authentication\").secretKey,\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","namedRouteParam","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;AAC2C,CAAC,EAAkB;EAC1E,OAAO;IACL,MAAMC,KAAKA,CAACC,GAAY,EAAiB;MACvC,MAAMC,QAAsB,GAAID,GAAG,CAACE,eAAe,CAAC,UAAU,CAAC,IAC7DL,eAAgC;MAClC,IAAI,CAACI,QAAQ,EAAE,MAAM,IAAIE,KAAK,CAAC,kBAAkB,CAAC;AAClD,MAAA,MAAMC,MAAM,GACTN,SAAS,CAACO,cAAc,KACtB,MAAMP,SAAS,CAACO,cAAc,CAACJ,QAAQ,EAAED,GAAG,CAAC,CAAC,IACjD,EAAE;AACJ,MAAA,MAAML,qBAAqB,CAACW,eAAe,CAACN,GAAG,EAAEC,QAAQ,EAAE,EAAE,EAAEG,MAAM,CAAC;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;AAC7B,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AAQ,CAACrE,cAAc,EAAE5K,YAAY,CAAC;QACtC,OAAO4N,IAAI,EAAE;AACf;KACD;GACF;AACH;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "alp-node-auth",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "11.0.0",
|
|
4
4
|
"description": "authentication with alp",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"alp"
|
|
@@ -15,10 +15,10 @@
|
|
|
15
15
|
"homepage": "https://github.com/christophehurpeau/alp",
|
|
16
16
|
"type": "module",
|
|
17
17
|
"engines": {
|
|
18
|
-
"node": ">=
|
|
18
|
+
"node": ">=20.11.0"
|
|
19
19
|
},
|
|
20
20
|
"sideEffects": false,
|
|
21
|
-
"main": "./dist/index-
|
|
21
|
+
"main": "./dist/index-node20.mjs",
|
|
22
22
|
"types": "./dist/definitions/index.d.ts",
|
|
23
23
|
"typesVersions": {
|
|
24
24
|
">=3.1": {
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
".": {
|
|
33
33
|
"types": "./dist/definitions/index.d.ts",
|
|
34
34
|
"node": {
|
|
35
|
-
"import": "./dist/index-
|
|
35
|
+
"import": "./dist/index-node20.mjs"
|
|
36
36
|
}
|
|
37
37
|
},
|
|
38
38
|
"./strategies/dropbox": {
|
|
@@ -71,19 +71,20 @@
|
|
|
71
71
|
"clean": "yarn clean:build",
|
|
72
72
|
"clean:build": "pob-babel-clean-out dist",
|
|
73
73
|
"lint": "yarn run lint:eslint",
|
|
74
|
-
"lint:eslint": "yarn ../.. run eslint --
|
|
74
|
+
"lint:eslint": "yarn ../.. run eslint --quiet packages/alp-node-auth",
|
|
75
75
|
"watch": "yarn clean:build && rollup --config rollup.config.mjs --watch"
|
|
76
76
|
},
|
|
77
77
|
"pob": {
|
|
78
|
-
"
|
|
78
|
+
"bundler": "rollup-babel",
|
|
79
|
+
"entries": [
|
|
80
|
+
"index"
|
|
81
|
+
],
|
|
82
|
+
"envs": [
|
|
79
83
|
{
|
|
80
84
|
"target": "node",
|
|
81
|
-
"version": "
|
|
85
|
+
"version": "20"
|
|
82
86
|
}
|
|
83
87
|
],
|
|
84
|
-
"entries": [
|
|
85
|
-
"index"
|
|
86
|
-
],
|
|
87
88
|
"extraEntries": [
|
|
88
89
|
{
|
|
89
90
|
"directory": "strategies",
|
|
@@ -119,27 +120,24 @@
|
|
|
119
120
|
},
|
|
120
121
|
"prettier": "@pob/root/prettier-config",
|
|
121
122
|
"peerDependencies": {
|
|
122
|
-
"alp-node": "^
|
|
123
|
-
"
|
|
124
|
-
"
|
|
125
|
-
"router-segments": "^9.1.0"
|
|
123
|
+
"alp-node": "^8.0.0",
|
|
124
|
+
"liwi-mongo": "^12.0.0",
|
|
125
|
+
"router-segments": "^11.0.0"
|
|
126
126
|
},
|
|
127
127
|
"dependencies": {
|
|
128
|
-
"@types/jsonwebtoken": "^9.0.
|
|
129
|
-
"@types/simple-oauth2": "^5.0.
|
|
130
|
-
"
|
|
131
|
-
"
|
|
132
|
-
"jsonwebtoken": "^9.0.0",
|
|
128
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
129
|
+
"@types/simple-oauth2": "^5.0.7",
|
|
130
|
+
"cookies": "~0.9.1",
|
|
131
|
+
"jsonwebtoken": "^9.0.2",
|
|
133
132
|
"nightingale-logger": "^15.0.0",
|
|
134
133
|
"simple-oauth2": "^5.0.0"
|
|
135
134
|
},
|
|
136
135
|
"devDependencies": {
|
|
137
|
-
"@babel/core": "7.
|
|
138
|
-
"alp-node": "
|
|
139
|
-
"
|
|
140
|
-
"
|
|
141
|
-
"
|
|
142
|
-
"
|
|
143
|
-
"typescript": "5.3.3"
|
|
136
|
+
"@babel/core": "7.28.0",
|
|
137
|
+
"alp-node": "8.0.0",
|
|
138
|
+
"liwi-mongo": "12.0.0",
|
|
139
|
+
"pob-babel": "43.7.0",
|
|
140
|
+
"router-segments": "11.0.0",
|
|
141
|
+
"typescript": "5.8.3"
|
|
144
142
|
}
|
|
145
143
|
}
|
package/src/MongoUsersManager.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { MongoInsertType, MongoStore, Update } from
|
|
2
|
-
import type {
|
|
1
|
+
import type { MongoInsertType, MongoStore, Update } from "liwi-mongo";
|
|
2
|
+
import type { Account, User, UserSanitized } from "./types";
|
|
3
3
|
|
|
4
4
|
export default class MongoUsersManager<
|
|
5
5
|
U extends User = User,
|
|
@@ -42,8 +42,8 @@ export default class MongoUsersManager<
|
|
|
42
42
|
provider: string;
|
|
43
43
|
}): Promise<U | undefined> {
|
|
44
44
|
let query: any = {
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
"accounts.provider": provider,
|
|
46
|
+
"accounts.accountId": accountId,
|
|
47
47
|
};
|
|
48
48
|
|
|
49
49
|
if (emails && emails.length > 0) {
|
|
@@ -64,7 +64,7 @@ export default class MongoUsersManager<
|
|
|
64
64
|
updateAccount(user: U, account: Account): Promise<U> {
|
|
65
65
|
const accountIndex = user.accounts.indexOf(account);
|
|
66
66
|
if (accountIndex === -1) {
|
|
67
|
-
throw new Error(
|
|
67
|
+
throw new Error("Invalid account");
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
return this.store.partialUpdateOne(user, {
|
|
@@ -74,7 +74,6 @@ export default class MongoUsersManager<
|
|
|
74
74
|
} as Update<U>);
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
// eslint-disable-next-line @typescript-eslint/class-methods-use-this
|
|
78
77
|
sanitizeBaseUser(user: U): UserSanitized {
|
|
79
78
|
return {
|
|
80
79
|
_id: user._id,
|
package/src/authApolloContext.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import type { IncomingMessage } from
|
|
2
|
-
import type { NodeConfig } from
|
|
3
|
-
import { Logger } from
|
|
4
|
-
import type MongoUsersManager from
|
|
5
|
-
import type { User } from
|
|
6
|
-
import {
|
|
7
|
-
import { createFindLoggedInUser } from
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import type { NodeConfig } from "alp-node";
|
|
3
|
+
import { Logger } from "nightingale-logger";
|
|
4
|
+
import type MongoUsersManager from "./MongoUsersManager";
|
|
5
|
+
import type { User } from "./types";
|
|
6
|
+
import { COOKIE_NAME_TOKEN, getTokenFromRequest } from "./utils/cookies";
|
|
7
|
+
import { createFindLoggedInUser } from "./utils/createFindLoggedInUser";
|
|
8
8
|
|
|
9
|
-
const logger = new Logger(
|
|
9
|
+
const logger = new Logger("alp:auth");
|
|
10
10
|
|
|
11
11
|
const getTokenFromReq = (
|
|
12
12
|
req: IncomingMessage & { cookies?: Record<string, string> },
|
|
@@ -24,7 +24,7 @@ export const createAuthApolloContext = <U extends User = User>(
|
|
|
24
24
|
usersManager: MongoUsersManager<U>,
|
|
25
25
|
): any => {
|
|
26
26
|
const findLoggedInUser = createFindLoggedInUser(
|
|
27
|
-
config.get<
|
|
27
|
+
config.get<{ secretKey: string }>("authentication").secretKey,
|
|
28
28
|
usersManager,
|
|
29
29
|
logger,
|
|
30
30
|
);
|
|
@@ -43,7 +43,7 @@ export const createAuthApolloContext = <U extends User = User>(
|
|
|
43
43
|
|
|
44
44
|
const [, loggedInUser] = await findLoggedInUser(
|
|
45
45
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
46
|
-
req.headers[
|
|
46
|
+
req.headers["user-agent"],
|
|
47
47
|
token,
|
|
48
48
|
);
|
|
49
49
|
|
package/src/authSocketIO.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type { NodeApplication } from
|
|
2
|
-
import { Logger } from
|
|
3
|
-
import type MongoUsersManager from
|
|
4
|
-
import type { User } from
|
|
5
|
-
import { getTokenFromRequest } from
|
|
6
|
-
import { createFindLoggedInUser } from
|
|
1
|
+
import type { NodeApplication } from "alp-node";
|
|
2
|
+
import { Logger } from "nightingale-logger";
|
|
3
|
+
import type MongoUsersManager from "./MongoUsersManager";
|
|
4
|
+
import type { User } from "./types";
|
|
5
|
+
import { getTokenFromRequest } from "./utils/cookies";
|
|
6
|
+
import { createFindLoggedInUser } from "./utils/createFindLoggedInUser";
|
|
7
7
|
|
|
8
|
-
const logger = new Logger(
|
|
8
|
+
const logger = new Logger("alp:auth");
|
|
9
9
|
|
|
10
10
|
export const authSocketIO = <U extends User = User>(
|
|
11
11
|
app: NodeApplication,
|
|
@@ -15,7 +15,7 @@ export const authSocketIO = <U extends User = User>(
|
|
|
15
15
|
jwtAudience?: string,
|
|
16
16
|
): void => {
|
|
17
17
|
const findLoggedInUser = createFindLoggedInUser(
|
|
18
|
-
app.config.get<
|
|
18
|
+
app.config.get<{ secretKey: string }>("authentication").secretKey,
|
|
19
19
|
usersManager,
|
|
20
20
|
logger,
|
|
21
21
|
);
|
|
@@ -32,7 +32,7 @@ export const authSocketIO = <U extends User = User>(
|
|
|
32
32
|
|
|
33
33
|
const [loggedInUserId, loggedInUser] = await findLoggedInUser(
|
|
34
34
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
35
|
-
jwtAudience || handshakeData.headers[
|
|
35
|
+
jwtAudience || handshakeData.headers["user-agent"],
|
|
36
36
|
token,
|
|
37
37
|
);
|
|
38
38
|
|
|
@@ -41,7 +41,7 @@ export const authSocketIO = <U extends User = User>(
|
|
|
41
41
|
socket.user = loggedInUser;
|
|
42
42
|
users.set(socket.client.id, loggedInUser);
|
|
43
43
|
|
|
44
|
-
socket.on(
|
|
44
|
+
socket.on("disconnected", () => users.delete(socket.client.id));
|
|
45
45
|
|
|
46
46
|
await next();
|
|
47
47
|
});
|
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
import type { AlpRouteRef } from
|
|
2
|
-
import type
|
|
3
|
-
import type MongoUsersManager from './MongoUsersManager';
|
|
1
|
+
import type { AlpRouteRef, Context } from "alp-node";
|
|
2
|
+
import type MongoUsersManager from "./MongoUsersManager";
|
|
4
3
|
import type {
|
|
5
|
-
AuthenticationService,
|
|
6
4
|
AccessResponseHooks,
|
|
7
|
-
|
|
5
|
+
AuthenticationService,
|
|
6
|
+
} from "./services/authentification/AuthenticationService";
|
|
8
7
|
import type {
|
|
9
|
-
AllowedStrategyKeys,
|
|
10
8
|
AllowedMapParamsStrategy,
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
AllowedStrategyKeys,
|
|
10
|
+
} from "./services/authentification/types";
|
|
11
|
+
import type { User, UserSanitized } from "./types";
|
|
13
12
|
|
|
14
13
|
export interface CreateAuthControllerParams<
|
|
15
14
|
StrategyKeys extends AllowedStrategyKeys,
|
|
@@ -30,7 +29,7 @@ export interface AuthController {
|
|
|
30
29
|
logout: AlpRouteRef;
|
|
31
30
|
}
|
|
32
31
|
|
|
33
|
-
type OptionalRecord<K extends keyof any, T> =
|
|
32
|
+
type OptionalRecord<K extends keyof any, T> = Partial<Record<K, T>>;
|
|
34
33
|
|
|
35
34
|
export interface AuthHooks<StrategyKeys extends AllowedStrategyKeys>
|
|
36
35
|
extends AccessResponseHooks<StrategyKeys> {
|
|
@@ -52,15 +51,15 @@ export function createAuthController<
|
|
|
52
51
|
>({
|
|
53
52
|
usersManager,
|
|
54
53
|
authenticationService,
|
|
55
|
-
homeRouterKey =
|
|
54
|
+
homeRouterKey = "/",
|
|
56
55
|
defaultStrategy,
|
|
57
56
|
authHooks = {},
|
|
58
57
|
}: CreateAuthControllerParams<StrategyKeys, U, USanitized>): AuthController {
|
|
59
58
|
return {
|
|
60
59
|
async login(ctx: Context): Promise<void> {
|
|
61
|
-
const strategy: StrategyKeys = (ctx.
|
|
60
|
+
const strategy: StrategyKeys = (ctx.namedRouteParam("strategy") ||
|
|
62
61
|
defaultStrategy) as StrategyKeys;
|
|
63
|
-
if (!strategy) throw new Error(
|
|
62
|
+
if (!strategy) throw new Error("Strategy missing");
|
|
64
63
|
const params =
|
|
65
64
|
(authHooks.paramsForLogin &&
|
|
66
65
|
(await authHooks.paramsForLogin(strategy, ctx))) ||
|
|
@@ -74,20 +73,22 @@ 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
|
|
|
81
|
-
const strategy: StrategyKeys = (ctx.
|
|
80
|
+
const strategy: StrategyKeys = (ctx.namedRouteParam("strategy") ||
|
|
82
81
|
defaultStrategy) as StrategyKeys;
|
|
83
|
-
if (!strategy) throw new Error(
|
|
84
|
-
const scopeKey = ctx.
|
|
85
|
-
if (!scopeKey) throw new Error(
|
|
82
|
+
if (!strategy) throw new Error("Strategy missing");
|
|
83
|
+
const scopeKey = ctx.namedRouteParam("scopeKey");
|
|
84
|
+
if (!scopeKey) throw new Error("Scope missing");
|
|
86
85
|
await authenticationService.redirectAuthUrl(ctx, strategy, { scopeKey });
|
|
87
86
|
},
|
|
88
87
|
|
|
89
88
|
async response(ctx: Context): Promise<void> {
|
|
90
|
-
const strategy: StrategyKeys = ctx.
|
|
89
|
+
const strategy: StrategyKeys = ctx.namedRouteParam(
|
|
90
|
+
"strategy",
|
|
91
|
+
) as StrategyKeys;
|
|
91
92
|
ctx.assert(strategy);
|
|
92
93
|
|
|
93
94
|
const loggedInUser = await authenticationService.accessResponse(
|
|
@@ -101,12 +102,13 @@ export function createAuthController<
|
|
|
101
102
|
);
|
|
102
103
|
const keyPath = usersManager.store.keyPath;
|
|
103
104
|
await ctx.setLoggedIn(loggedInUser[keyPath], loggedInUser);
|
|
104
|
-
|
|
105
|
+
ctx.redirectTo(homeRouterKey);
|
|
105
106
|
},
|
|
106
107
|
|
|
108
|
+
// eslint-disable-next-line @typescript-eslint/require-await -- keep async in case i later need await in this method
|
|
107
109
|
async logout(ctx: Context): Promise<void> {
|
|
108
110
|
ctx.logout();
|
|
109
|
-
|
|
111
|
+
ctx.redirectTo(homeRouterKey);
|
|
110
112
|
},
|
|
111
113
|
};
|
|
112
114
|
}
|
package/src/createRoutes.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import type { AuthController } from
|
|
1
|
+
import type { AuthController } from "./createAuthController";
|
|
2
2
|
|
|
3
3
|
export interface AuthRoutes {
|
|
4
4
|
login: [string, (segment: any) => void];
|
|
5
|
-
addScope: [string, AuthController[
|
|
6
|
-
logout: [string, AuthController[
|
|
5
|
+
addScope: [string, AuthController["addScope"]];
|
|
6
|
+
logout: [string, AuthController["logout"]];
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
export const createRoutes = (controller: AuthController): AuthRoutes => ({
|
|
10
10
|
login: [
|
|
11
|
-
|
|
11
|
+
"/login/:strategy?",
|
|
12
12
|
(segment: any) => {
|
|
13
|
-
segment.add(
|
|
14
|
-
segment.defaultRoute(controller.login,
|
|
13
|
+
segment.add("/response", controller.response, "authResponse");
|
|
14
|
+
segment.defaultRoute(controller.login, "login");
|
|
15
15
|
},
|
|
16
16
|
],
|
|
17
|
-
addScope: [
|
|
18
|
-
logout: [
|
|
17
|
+
addScope: ["/add-scope/:strategy/:scopeKey", controller.addScope],
|
|
18
|
+
logout: ["/logout", controller.logout],
|
|
19
19
|
});
|