@authup/server-core 1.0.0-beta.61 → 1.0.0-beta.63

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.
Files changed (216) hide show
  1. package/dist/adapters/database/domains/client-scope/entity.d.ts.map +1 -1
  2. package/dist/adapters/database/domains/client-scope/entity.mjs +16 -8
  3. package/dist/adapters/database/domains/client-scope/entity.mjs.map +1 -1
  4. package/dist/adapters/database/domains/identity-provider-account/entity.d.ts.map +1 -1
  5. package/dist/adapters/database/domains/identity-provider-account/entity.mjs +1 -1
  6. package/dist/adapters/database/domains/identity-provider-account/entity.mjs.map +1 -1
  7. package/dist/adapters/database/domains/identity-provider-attribute/subscriber.d.ts +8 -1
  8. package/dist/adapters/database/domains/identity-provider-attribute/subscriber.d.ts.map +1 -1
  9. package/dist/adapters/database/domains/identity-provider-attribute/subscriber.mjs +14 -0
  10. package/dist/adapters/database/domains/identity-provider-attribute/subscriber.mjs.map +1 -1
  11. package/dist/adapters/database/migrations/mysql/1786631686318-SortIndexesAndAccountUniqueness.d.ts +50 -0
  12. package/dist/adapters/database/migrations/mysql/1786631686318-SortIndexesAndAccountUniqueness.d.ts.map +1 -0
  13. package/dist/adapters/database/migrations/mysql/1786631686318-SortIndexesAndAccountUniqueness.mjs +86 -0
  14. package/dist/adapters/database/migrations/mysql/1786631686318-SortIndexesAndAccountUniqueness.mjs.map +1 -0
  15. package/dist/adapters/database/migrations/postgres/1786631686318-SortIndexesAndAccountUniqueness.d.ts +42 -0
  16. package/dist/adapters/database/migrations/postgres/1786631686318-SortIndexesAndAccountUniqueness.d.ts.map +1 -0
  17. package/dist/adapters/database/migrations/postgres/1786631686318-SortIndexesAndAccountUniqueness.mjs +80 -0
  18. package/dist/adapters/database/migrations/postgres/1786631686318-SortIndexesAndAccountUniqueness.mjs.map +1 -0
  19. package/dist/adapters/http/adapters/oauth2/grant-types/refresh_token.d.ts.map +1 -1
  20. package/dist/adapters/http/adapters/oauth2/grant-types/refresh_token.mjs +8 -2
  21. package/dist/adapters/http/adapters/oauth2/grant-types/refresh_token.mjs.map +1 -1
  22. package/dist/adapters/http/adapters/oauth2/grant-types/utils/credentials.mjs +1 -1
  23. package/dist/adapters/http/adapters/oauth2/grant-types/utils/guess.mjs +1 -1
  24. package/dist/adapters/http/controllers/entities/client/module.mjs +2 -2
  25. package/dist/adapters/http/controllers/entities/identity-provider/module.d.ts +24 -4
  26. package/dist/adapters/http/controllers/entities/identity-provider/module.d.ts.map +1 -1
  27. package/dist/adapters/http/controllers/entities/identity-provider/module.mjs +117 -106
  28. package/dist/adapters/http/controllers/entities/identity-provider/module.mjs.map +1 -1
  29. package/dist/adapters/http/controllers/entities/identity-provider/types.d.ts +6 -4
  30. package/dist/adapters/http/controllers/entities/identity-provider/types.d.ts.map +1 -1
  31. package/dist/adapters/http/controllers/entities/realm/module.mjs +2 -2
  32. package/dist/adapters/http/controllers/entities/session/module.mjs +2 -2
  33. package/dist/adapters/http/controllers/entities/user/module.mjs +2 -2
  34. package/dist/adapters/http/controllers/entities/user-authenticator/module.mjs +2 -2
  35. package/dist/adapters/http/controllers/workflows/authenticator-challenge/module.d.ts +2 -0
  36. package/dist/adapters/http/controllers/workflows/authenticator-challenge/module.d.ts.map +1 -1
  37. package/dist/adapters/http/controllers/workflows/authenticator-challenge/module.mjs +21 -3
  38. package/dist/adapters/http/controllers/workflows/authenticator-challenge/module.mjs.map +1 -1
  39. package/dist/adapters/http/controllers/workflows/authorize/module.d.ts.map +1 -1
  40. package/dist/adapters/http/controllers/workflows/authorize/module.mjs +14 -5
  41. package/dist/adapters/http/controllers/workflows/authorize/module.mjs.map +1 -1
  42. package/dist/adapters/http/controllers/workflows/token/module.d.ts.map +1 -1
  43. package/dist/adapters/http/controllers/workflows/token/module.mjs +22 -9
  44. package/dist/adapters/http/controllers/workflows/token/module.mjs.map +1 -1
  45. package/dist/adapters/http/controllers/workflows/token/utils/extract.mjs +2 -1
  46. package/dist/adapters/http/controllers/workflows/token/utils/extract.mjs.map +1 -1
  47. package/dist/adapters/http/middleware/built-in/assets.mjs +1 -1
  48. package/dist/adapters/http/middleware/built-in/cors.d.ts.map +1 -1
  49. package/dist/adapters/http/middleware/built-in/cors.mjs.map +1 -1
  50. package/dist/adapters/http/middleware/built-in/error.d.ts.map +1 -1
  51. package/dist/adapters/http/middleware/built-in/error.mjs +10 -1
  52. package/dist/adapters/http/middleware/built-in/error.mjs.map +1 -1
  53. package/dist/adapters/http/request/helpers/param-id.d.ts.map +1 -1
  54. package/dist/adapters/http/request/helpers/param-id.mjs +2 -1
  55. package/dist/adapters/http/request/helpers/param-id.mjs.map +1 -1
  56. package/dist/adapters/http/ui/account-console/module.mjs +1 -1
  57. package/dist/adapters/http/ui/auth-console/http-client.mjs +1 -1
  58. package/dist/adapters/http/ui/auth-console/module.mjs +1 -1
  59. package/dist/adapters/http/ui/console-packages/module.d.ts +1 -1
  60. package/dist/adapters/http/ui/console-packages/module.mjs +2 -2
  61. package/dist/adapters/http/ui/console-packages/module.mjs.map +1 -1
  62. package/dist/adapters/http/ui/shared/html.d.ts.map +1 -1
  63. package/dist/adapters/http/ui/shared/html.mjs +1 -0
  64. package/dist/adapters/http/ui/shared/html.mjs.map +1 -1
  65. package/dist/app/modules/config/normalize.d.ts.map +1 -1
  66. package/dist/app/modules/config/normalize.mjs +2 -2
  67. package/dist/app/modules/config/normalize.mjs.map +1 -1
  68. package/dist/app/modules/config/read/env.mjs +1 -1
  69. package/dist/app/modules/config/types.d.ts +8 -0
  70. package/dist/app/modules/config/types.d.ts.map +1 -1
  71. package/dist/app/modules/database/repositories/event/repository.d.ts +2 -2
  72. package/dist/app/modules/database/repositories/event/repository.d.ts.map +1 -1
  73. package/dist/app/modules/database/repositories/event/repository.mjs +23 -6
  74. package/dist/app/modules/database/repositories/event/repository.mjs.map +1 -1
  75. package/dist/app/modules/database/repositories/identity-provider/repository.d.ts +3 -1
  76. package/dist/app/modules/database/repositories/identity-provider/repository.d.ts.map +1 -1
  77. package/dist/app/modules/database/repositories/identity-provider/repository.mjs +2 -2
  78. package/dist/app/modules/database/repositories/identity-provider/repository.mjs.map +1 -1
  79. package/dist/app/modules/database/repositories/identity-provider-account/repository.d.ts.map +1 -1
  80. package/dist/app/modules/database/repositories/identity-provider-account/repository.mjs +9 -1
  81. package/dist/app/modules/database/repositories/identity-provider-account/repository.mjs.map +1 -1
  82. package/dist/app/modules/http/modules/controller.d.ts.map +1 -1
  83. package/dist/app/modules/http/modules/controller.mjs +20 -6
  84. package/dist/app/modules/http/modules/controller.mjs.map +1 -1
  85. package/dist/app/modules/identity/module.d.ts.map +1 -1
  86. package/dist/app/modules/identity/module.mjs +6 -3
  87. package/dist/app/modules/identity/module.mjs.map +1 -1
  88. package/dist/app/modules/identity/repositories/user.d.ts +1 -0
  89. package/dist/app/modules/identity/repositories/user.d.ts.map +1 -1
  90. package/dist/app/modules/identity/repositories/user.mjs +3 -0
  91. package/dist/app/modules/identity/repositories/user.mjs.map +1 -1
  92. package/dist/app/modules/oauth2/constants.d.ts +2 -1
  93. package/dist/app/modules/oauth2/constants.d.ts.map +1 -1
  94. package/dist/app/modules/oauth2/constants.mjs +1 -0
  95. package/dist/app/modules/oauth2/constants.mjs.map +1 -1
  96. package/dist/app/modules/oauth2/module.d.ts.map +1 -1
  97. package/dist/app/modules/oauth2/module.mjs +5 -0
  98. package/dist/app/modules/oauth2/module.mjs.map +1 -1
  99. package/dist/app/modules/oauth2/repositories/authorize/state/repository.d.ts +1 -2
  100. package/dist/app/modules/oauth2/repositories/authorize/state/repository.d.ts.map +1 -1
  101. package/dist/app/modules/oauth2/repositories/authorize/state/repository.mjs +7 -16
  102. package/dist/app/modules/oauth2/repositories/authorize/state/repository.mjs.map +1 -1
  103. package/dist/app/modules/oauth2/repositories/constants.d.ts +1 -0
  104. package/dist/app/modules/oauth2/repositories/constants.d.ts.map +1 -1
  105. package/dist/app/modules/oauth2/repositories/constants.mjs +1 -0
  106. package/dist/app/modules/oauth2/repositories/constants.mjs.map +1 -1
  107. package/dist/app/modules/oauth2/repositories/federated-login/index.d.ts +2 -0
  108. package/dist/app/modules/oauth2/repositories/federated-login/index.d.ts.map +1 -0
  109. package/dist/app/modules/oauth2/repositories/federated-login/index.mjs +5 -0
  110. package/dist/app/modules/oauth2/repositories/federated-login/store.d.ts +9 -0
  111. package/dist/app/modules/oauth2/repositories/federated-login/store.d.ts.map +1 -0
  112. package/dist/app/modules/oauth2/repositories/federated-login/store.mjs +33 -0
  113. package/dist/app/modules/oauth2/repositories/federated-login/store.mjs.map +1 -0
  114. package/dist/app/modules/oauth2/repositories/index.d.ts +1 -0
  115. package/dist/app/modules/oauth2/repositories/index.d.ts.map +1 -1
  116. package/dist/app/modules/oauth2/repositories/index.mjs +3 -1
  117. package/dist/app/modules/runtime/module.mjs +2 -2
  118. package/dist/cli/commands/migration.mjs +1 -1
  119. package/dist/core/entities/client-scope/schema.d.ts.map +1 -1
  120. package/dist/core/entities/client-scope/schema.mjs +16 -1
  121. package/dist/core/entities/client-scope/schema.mjs.map +1 -1
  122. package/dist/core/entities/event/constants.d.ts +9 -0
  123. package/dist/core/entities/event/constants.d.ts.map +1 -1
  124. package/dist/core/entities/event/constants.mjs +9 -1
  125. package/dist/core/entities/event/constants.mjs.map +1 -1
  126. package/dist/core/entities/event/entity-event-handler.d.ts.map +1 -1
  127. package/dist/core/entities/event/entity-event-handler.mjs +14 -1
  128. package/dist/core/entities/event/entity-event-handler.mjs.map +1 -1
  129. package/dist/core/entities/event/index.mjs +2 -2
  130. package/dist/core/entities/event/types.d.ts +11 -2
  131. package/dist/core/entities/event/types.d.ts.map +1 -1
  132. package/dist/core/entities/identity-provider/types.d.ts +9 -1
  133. package/dist/core/entities/identity-provider/types.d.ts.map +1 -1
  134. package/dist/core/entities/identity-provider-account/types.d.ts +6 -0
  135. package/dist/core/entities/identity-provider-account/types.d.ts.map +1 -1
  136. package/dist/core/entities/identity-provider-account/types.mjs.map +1 -1
  137. package/dist/core/entities/index.mjs +2 -2
  138. package/dist/core/identity/entities/user/types.d.ts +1 -0
  139. package/dist/core/identity/entities/user/types.d.ts.map +1 -1
  140. package/dist/core/identity/index.mjs +12 -11
  141. package/dist/core/identity/provider/account/module.d.ts +3 -0
  142. package/dist/core/identity/provider/account/module.d.ts.map +1 -1
  143. package/dist/core/identity/provider/account/module.mjs +54 -27
  144. package/dist/core/identity/provider/account/module.mjs.map +1 -1
  145. package/dist/core/identity/provider/account/types.d.ts +7 -0
  146. package/dist/core/identity/provider/account/types.d.ts.map +1 -1
  147. package/dist/core/identity/provider/authentication/index.mjs +3 -2
  148. package/dist/core/identity/provider/authentication/protocols/index.mjs +2 -1
  149. package/dist/core/identity/provider/authentication/protocols/oauth2/assurance.d.ts +46 -0
  150. package/dist/core/identity/provider/authentication/protocols/oauth2/assurance.d.ts.map +1 -0
  151. package/dist/core/identity/provider/authentication/protocols/oauth2/assurance.mjs +89 -0
  152. package/dist/core/identity/provider/authentication/protocols/oauth2/assurance.mjs.map +1 -0
  153. package/dist/core/identity/provider/authentication/protocols/oauth2/index.d.ts +1 -0
  154. package/dist/core/identity/provider/authentication/protocols/oauth2/index.d.ts.map +1 -1
  155. package/dist/core/identity/provider/authentication/protocols/oauth2/index.mjs +2 -1
  156. package/dist/core/identity/provider/authentication/protocols/oauth2/module.d.ts.map +1 -1
  157. package/dist/core/identity/provider/authentication/protocols/oauth2/module.mjs +9 -2
  158. package/dist/core/identity/provider/authentication/protocols/oauth2/module.mjs.map +1 -1
  159. package/dist/core/identity/provider/index.mjs +12 -11
  160. package/dist/core/index.mjs +16 -12
  161. package/dist/core/oauth2/authorization/code-request/verifier/module.d.ts.map +1 -1
  162. package/dist/core/oauth2/authorization/code-request/verifier/module.mjs +7 -1
  163. package/dist/core/oauth2/authorization/code-request/verifier/module.mjs.map +1 -1
  164. package/dist/core/oauth2/authorization/helpers.d.ts.map +1 -1
  165. package/dist/core/oauth2/authorization/helpers.mjs +6 -1
  166. package/dist/core/oauth2/authorization/helpers.mjs.map +1 -1
  167. package/dist/core/oauth2/authorization/module.d.ts.map +1 -1
  168. package/dist/core/oauth2/authorization/module.mjs +5 -3
  169. package/dist/core/oauth2/authorization/module.mjs.map +1 -1
  170. package/dist/core/oauth2/authorization/state/module.mjs +1 -2
  171. package/dist/core/oauth2/authorization/state/module.mjs.map +1 -1
  172. package/dist/core/oauth2/authorization/state/types.d.ts +13 -2
  173. package/dist/core/oauth2/authorization/state/types.d.ts.map +1 -1
  174. package/dist/core/oauth2/end-session/service.d.ts.map +1 -1
  175. package/dist/core/oauth2/end-session/service.mjs +1 -0
  176. package/dist/core/oauth2/end-session/service.mjs.map +1 -1
  177. package/dist/core/oauth2/federated-login/constants.d.ts +22 -0
  178. package/dist/core/oauth2/federated-login/constants.d.ts.map +1 -0
  179. package/dist/core/oauth2/federated-login/constants.mjs +27 -0
  180. package/dist/core/oauth2/federated-login/constants.mjs.map +1 -0
  181. package/dist/core/oauth2/federated-login/index.d.ts +4 -0
  182. package/dist/core/oauth2/federated-login/index.d.ts.map +1 -0
  183. package/dist/core/oauth2/federated-login/index.mjs +7 -0
  184. package/dist/core/oauth2/federated-login/module.d.ts +29 -0
  185. package/dist/core/oauth2/federated-login/module.d.ts.map +1 -0
  186. package/dist/core/oauth2/federated-login/module.mjs +193 -0
  187. package/dist/core/oauth2/federated-login/module.mjs.map +1 -0
  188. package/dist/core/oauth2/federated-login/types.d.ts +196 -0
  189. package/dist/core/oauth2/federated-login/types.d.ts.map +1 -0
  190. package/dist/core/oauth2/federated-login/types.mjs +36 -0
  191. package/dist/core/oauth2/federated-login/types.mjs.map +1 -0
  192. package/dist/core/oauth2/grant-types/authorize.mjs +1 -1
  193. package/dist/core/oauth2/grant-types/client-credentials.mjs +1 -1
  194. package/dist/core/oauth2/grant-types/identity.mjs +1 -1
  195. package/dist/core/oauth2/grant-types/password.mjs +1 -1
  196. package/dist/core/oauth2/grant-types/refresh-token.mjs +1 -1
  197. package/dist/core/oauth2/index.d.ts +1 -0
  198. package/dist/core/oauth2/index.d.ts.map +1 -1
  199. package/dist/core/oauth2/index.mjs +5 -1
  200. package/dist/core/oauth2/token/verifier/module.d.ts.map +1 -1
  201. package/dist/core/oauth2/token/verifier/module.mjs +3 -3
  202. package/dist/core/oauth2/token/verifier/module.mjs.map +1 -1
  203. package/dist/core/provisioning/entities/policy/validator.d.ts.map +1 -1
  204. package/dist/core/provisioning/entities/policy/validator.mjs +2 -1
  205. package/dist/core/provisioning/entities/policy/validator.mjs.map +1 -1
  206. package/dist/core/provisioning/entities/realm/wildcard-validator.d.ts.map +1 -1
  207. package/dist/core/provisioning/entities/realm/wildcard-validator.mjs +2 -1
  208. package/dist/core/provisioning/entities/realm/wildcard-validator.mjs.map +1 -1
  209. package/dist/core/security/policy/evaluator.mjs.map +1 -1
  210. package/dist/node_modules/@ebec/core/dist/index.mjs +130 -0
  211. package/dist/node_modules/@ebec/core/dist/index.mjs.map +1 -0
  212. package/dist/swagger.json +119 -43
  213. package/dist/utils/error.d.ts.map +1 -1
  214. package/dist/utils/error.mjs +5 -6
  215. package/dist/utils/error.mjs.map +1 -1
  216. package/package.json +29 -29
@@ -1 +1 @@
1
- {"version":3,"file":"module.mjs","names":["EventName","EventRefType","EventScope","IdentityType","hasInstanceof","OAUTH2_ACCESS_DENIED_ERROR_INSTANCE","OAUTH2_LOGIN_REQUIRED_ERROR_INSTANCE","OAUTH2_MFA_REQUIRED_ERROR_INSTANCE","OAuth2AccessDeniedError","OAuth2AuthenticationContextClass","OAuth2AuthorizationPrompt","OAuth2AuthorizationResponseType","OAuth2GrantError","OAuth2LoginRequiredError","OAuth2MfaRequiredError","OAuth2RequestError","OAuth2ResponseTypeError","toIdentityPolicyData","DEFAULT_PROMPT_LOGIN_MAX_AGE","DEFAULT_MFA_FRESHNESS_MAX_AGE","OAuth2Authorization","codeIssuer","sessionManager","eventService","metrics","promptLoginMaxAge","mfaFreshnessMaxAge","mfaChallengeProvider","accessPolicyEvaluator","ctx","authorize","data","identity","options","result","authorizeInner","record","scope","OAUTH2","name","AUTHORIZE","refType","CLIENT","refId","client","id","client_id","clientId","sessionId","actorType","type","actorId","actorName","realmId","realm_id","reason","builtIn","recordAuthorize","e","AUTHORIZE_FAILED","responseTypes","response_type","Array","isArray","split","responseType","CODE","unsupported","includes","redirect_uri","redirectUriMismatch","output","redirectUri","state","identityInvalid","realmMismatch","nowSeconds","Math","floor","Date","now","authTime","session","findOneById","createdAt","getTime","USER","challenge","issueMaterial","required","mfaAt","challengeRequired","enrollmentRequired","acr_values","acrValues","MFA","mfaAtSeconds","stepUpRequired","prompts","prompt","LOGIN","reauthenticationRequired","max_age","maxAge","Number","isFinite","accessPolicyId","allowed","subject","evaluate","forClient","redirectUriVerified","undefined","codeEntity","issue","authMethod","authorizationCode"],"sources":["../../../../src/core/oauth2/authorization/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type {\n Identity, \n OAuth2AuthorizationCode, \n OAuth2AuthorizationCodeRequest, \n Session,\n} from '@authup/core-kit';\nimport {\n EventName, \n EventRefType, \n EventScope, \n IdentityType,\n} from '@authup/core-kit';\nimport { hasInstanceof } from '@authup/errors';\nimport {\n OAUTH2_ACCESS_DENIED_ERROR_INSTANCE,\n OAUTH2_LOGIN_REQUIRED_ERROR_INSTANCE,\n OAUTH2_MFA_REQUIRED_ERROR_INSTANCE,\n OAuth2AccessDeniedError,\n OAuth2AuthenticationContextClass,\n OAuth2AuthorizationPrompt,\n OAuth2AuthorizationResponseType,\n OAuth2GrantError,\n OAuth2LoginRequiredError,\n OAuth2MfaRequiredError,\n OAuth2RequestError,\n OAuth2ResponseTypeError,\n} from '@authup/specs';\nimport type { IOAuth2AuthorizationCodeIssuer } from './code/index.ts';\nimport type { IOAuth2AccessPolicyEvaluator } from '../access-policy/index.ts';\nimport { toIdentityPolicyData } from '../../identity/permission/identity-policy-data.ts';\nimport type {\n OAuth2AuthorizationManagerContext,\n OAuth2AuthorizationOptions,\n OAuth2AuthorizationResult,\n} from './types.ts';\nimport type { ISessionManager } from '../../authentication/index.ts';\nimport type { IEventService, IUserAuthenticatorChallengeProvider } from '../../entities/index.ts';\nimport type { IAuthFlowMetrics } from '../../metrics/index.ts';\n\nconst DEFAULT_PROMPT_LOGIN_MAX_AGE = 60;\n\n// Deliberately 60 (not 0, deviating from the plan-050 sketch): the hosted\n// challenge round-trip (stamp mfa_at → retry POST /authorize) takes seconds,\n// so a 0-window step-up could never be satisfied and would loop the ladder.\nconst DEFAULT_MFA_FRESHNESS_MAX_AGE = 60;\n\nexport class OAuth2Authorization {\n protected codeIssuer : IOAuth2AuthorizationCodeIssuer;\n\n protected sessionManager : ISessionManager;\n\n protected eventService? : IEventService;\n\n protected metrics? : IAuthFlowMetrics;\n\n protected promptLoginMaxAge : number;\n\n protected mfaFreshnessMaxAge : number;\n\n protected mfaChallengeProvider? : IUserAuthenticatorChallengeProvider;\n\n protected accessPolicyEvaluator? : IOAuth2AccessPolicyEvaluator;\n\n constructor(ctx: OAuth2AuthorizationManagerContext) {\n this.codeIssuer = ctx.codeIssuer;\n this.sessionManager = ctx.sessionManager;\n this.eventService = ctx.eventService;\n this.metrics = ctx.metrics;\n this.accessPolicyEvaluator = ctx.accessPolicyEvaluator;\n this.promptLoginMaxAge = ctx.promptLoginMaxAge ?? DEFAULT_PROMPT_LOGIN_MAX_AGE;\n this.mfaFreshnessMaxAge = ctx.mfaFreshnessMaxAge ?? DEFAULT_MFA_FRESHNESS_MAX_AGE;\n this.mfaChallengeProvider = ctx.mfaChallengeProvider;\n }\n\n /**\n * Authorize with validated codeRequest.\n *\n * @param data\n * @param identity\n * @param options\n */\n async authorize(\n data: OAuth2AuthorizationCodeRequest,\n identity: Identity,\n options: OAuth2AuthorizationOptions = {},\n ) : Promise<OAuth2AuthorizationResult> {\n try {\n const result = await this.authorizeInner(data, identity, options);\n\n await this.eventService?.record({\n scope: EventScope.OAUTH2,\n name: EventName.AUTHORIZE,\n refType: EventRefType.CLIENT,\n refId: options.client?.id ?? data.client_id ?? null,\n clientId: options.client?.id ?? data.client_id ?? null,\n sessionId: options.sessionId ?? null,\n actorType: identity.type,\n actorId: identity.data.id,\n actorName: identity.data.name,\n realmId: data.realm_id ?? null,\n data: {\n reason: options.client?.builtIn ? 'autoConsent' : 'consent',\n ...(data.scope ? { scope: data.scope } : {}),\n },\n });\n this.metrics?.recordAuthorize('issued');\n\n return result;\n } catch (e) {\n if (hasInstanceof(e, OAUTH2_ACCESS_DENIED_ERROR_INSTANCE)) {\n await this.eventService?.record({\n scope: EventScope.OAUTH2,\n name: EventName.AUTHORIZE_FAILED,\n refType: EventRefType.CLIENT,\n refId: options.client?.id ?? data.client_id ?? null,\n clientId: options.client?.id ?? data.client_id ?? null,\n sessionId: options.sessionId ?? null,\n actorType: identity.type,\n actorId: identity.data.id,\n actorName: identity.data.name,\n realmId: data.realm_id ?? null,\n data: { reason: 'accessPolicy' },\n });\n this.metrics?.recordAuthorize('denied');\n } else if (hasInstanceof(e, OAUTH2_LOGIN_REQUIRED_ERROR_INSTANCE)) {\n this.metrics?.recordAuthorize('login_required');\n } else if (hasInstanceof(e, OAUTH2_MFA_REQUIRED_ERROR_INSTANCE)) {\n this.metrics?.recordAuthorize('mfa_required');\n } else {\n this.metrics?.recordAuthorize('error');\n }\n\n throw e;\n }\n }\n\n protected async authorizeInner(\n data: OAuth2AuthorizationCodeRequest,\n identity: Identity,\n options: OAuth2AuthorizationOptions = {},\n ) : Promise<OAuth2AuthorizationResult> {\n // OAuth 2.1 posture: only the authorization-code response type is\n // supported — implicit/hybrid (token, id_token, none) were dropped\n // (plan 042 item 3). Defense in depth behind the request validator.\n let responseTypes : string[] = [];\n if (data.response_type) {\n responseTypes = Array.isArray(data.response_type) ?\n data.response_type :\n data.response_type.split(' ');\n }\n\n for (const responseType of responseTypes) {\n if (responseType !== OAuth2AuthorizationResponseType.CODE) {\n throw OAuth2ResponseTypeError.unsupported();\n }\n }\n\n if (!responseTypes.includes(OAuth2AuthorizationResponseType.CODE)) {\n throw OAuth2ResponseTypeError.unsupported();\n }\n\n if (!data.redirect_uri) {\n throw OAuth2GrantError.redirectUriMismatch();\n }\n\n const output : OAuth2AuthorizationResult = {\n redirectUri: data.redirect_uri,\n ...(data.state ? { state: data.state } : {}),\n };\n\n if (!identity) {\n throw OAuth2RequestError.identityInvalid();\n }\n\n // Realm binding: the code-request verifier stamped data.realm_id with the\n // resolved client's realm. The authenticated identity must belong to that\n // same realm — otherwise a lingering session for realm A could silently\n // mint a code/token for realm B's client (confused deputy). The error body\n // deliberately carries no identity data (no realm-enumeration oracle).\n // The comparison reads the scalar realmId column, NOT the realm\n // relation — the relation may simply not be loaded on the resolved\n // identity. An identity without a realmId fails closed the same way —\n // clean login_required, never a TypeError.\n if (\n data.realm_id &&\n identity.data.realmId !== data.realm_id\n ) {\n throw OAuth2LoginRequiredError.realmMismatch();\n }\n\n // Authentication time = the backing session's creation instant (NOT\n // refreshed_at — a token refresh must not reset it). Session-less flows\n // (e.g. HTTP Basic authorize) present live credentials on this request,\n // so the authentication time is \"now\".\n const nowSeconds = Math.floor(Date.now() / 1000);\n let authTime = nowSeconds;\n let session : Session | null = null;\n if (options.sessionId) {\n session = await this.sessionManager.findOneById(options.sessionId);\n if (session && session.createdAt) {\n authTime = Math.floor(new Date(session.createdAt).getTime() / 1000);\n }\n }\n\n // MFA backstop (plan 049) — the authoritative server-side gate; the\n // hosted UI's challenge step is convenience. The proof is session-bound\n // (mfa_at — stamped by the challenge endpoint or the password grant's\n // otp param), so a session-less flow (HTTP Basic) cannot carry one and\n // fails closed while the user holds a confirmed device. A user without\n // a device under mfaRequired is routed to inline enrollment.\n if (this.mfaChallengeProvider && identity.type === IdentityType.USER) {\n // requirement flags only — the interactive challenge material (the\n // webauthn nonce) is issued by the status endpoint, not this backstop.\n const challenge = await this.mfaChallengeProvider.challenge(\n identity.data.id,\n { issueMaterial: false },\n );\n if (challenge.required && !session?.mfaAt) {\n throw OAuth2MfaRequiredError.challengeRequired();\n }\n\n if (challenge.enrollmentRequired) {\n throw OAuth2MfaRequiredError.enrollmentRequired();\n }\n\n // Step-up (plan 050 stage 3): a requested `acr_values` containing\n // urn:authup:mfa is a TRIGGER (Auth0/Keycloak stance) — the proof\n // must additionally be FRESH (mfaFreshnessMaxAge window, mirroring\n // promptLoginMaxAge's absorb-the-round-trip semantics). Enforced\n // only while the user actually holds a factor — per OIDC Core\n // §5.5.1.1 acr is voluntary, so an unsatisfiable request degrades\n // to the achieved acr instead of bricking the RP.\n if (challenge.required && data.acr_values) {\n const acrValues = data.acr_values.split(' ');\n if (acrValues.includes(OAuth2AuthenticationContextClass.MFA)) {\n const mfaAtSeconds = session?.mfaAt ?\n Math.floor(new Date(session.mfaAt).getTime() / 1000) :\n null;\n if (mfaAtSeconds === null || nowSeconds - mfaAtSeconds > this.mfaFreshnessMaxAge) {\n throw OAuth2MfaRequiredError.stepUpRequired();\n }\n }\n }\n }\n\n // OIDC §3.1.2.1 prompt=login / max_age freshness (enforced only when\n // requested — a plain authorize never throws here). The hosted page\n // renders the login form for prompt=login; this is the server backstop.\n const prompts = data.prompt ? data.prompt.split(' ') : [];\n if (\n prompts.includes(OAuth2AuthorizationPrompt.LOGIN) &&\n nowSeconds - authTime > this.promptLoginMaxAge\n ) {\n throw OAuth2LoginRequiredError.reauthenticationRequired();\n }\n\n if (\n typeof data.max_age !== 'undefined' &&\n data.max_age !== null\n ) {\n const maxAge = Number(data.max_age);\n if (\n Number.isFinite(maxAge) &&\n nowSeconds - authTime > maxAge\n ) {\n throw OAuth2LoginRequiredError.reauthenticationRequired();\n }\n }\n\n // Application access policy (plan 052) — the last gate before\n // issuance: a denial is only revealed to a fully-authenticated\n // (incl. second-factor) identity. A client carrying a policy id with\n // no wired evaluator denies too (never silently allow a configured\n // gate). The redirect target rides the error only when the\n // redirect_uri was pattern-verified (RFC 6749 §4.1.2.1).\n if (options.client?.accessPolicyId) {\n let allowed = false;\n\n const subject = toIdentityPolicyData(identity);\n if (this.accessPolicyEvaluator && subject) {\n allowed = await this.accessPolicyEvaluator.evaluate(\n options.client.accessPolicyId,\n subject,\n );\n }\n\n if (!allowed) {\n throw OAuth2AccessDeniedError.forClient(\n options.redirectUriVerified && data.redirect_uri ?\n { redirectUri: data.redirect_uri, state: data.state ?? null } :\n undefined,\n );\n }\n }\n\n // The id_token is NOT minted here — the /token exchange mints it after\n // resolving the real backing session, so its `sid` is authoritative\n // (plan 042 item 6). The code carries the authentication instant.\n const codeEntity : OAuth2AuthorizationCode = await this.codeIssuer.issue(\n data,\n identity,\n {\n sessionId: options.sessionId,\n authTime,\n authMethod: session?.authMethod ?? null,\n },\n );\n\n output.authorizationCode = codeEntity.id;\n\n return output;\n }\n}\n"],"mappings":";;;;;;;;AA8CA,MAAMkB,+BAA+B;AAKrC,MAAMC,gCAAgC;AAEtC,IAAaC,sBAAb,MAAaA;CACCC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEV,YAAYC,KAAwC;EAChD,KAAKR,aAAaQ,IAAIR;EACtB,KAAKC,iBAAiBO,IAAIP;EAC1B,KAAKC,eAAeM,IAAIN;EACxB,KAAKC,UAAUK,IAAIL;EACnB,KAAKI,wBAAwBC,IAAID;EACjC,KAAKH,oBAAoBI,IAAIJ,qBAAqBP;EAClD,KAAKQ,qBAAqBG,IAAIH,sBAAsBP;EACpD,KAAKQ,uBAAuBE,IAAIF;CACpC;;;;;;;IASA,MAAMG,UACFC,MACAC,UACAC,UAAsC,CAAC,GACJ;EACnC,IAAI;GACA,MAAMC,SAAS,MAAM,KAAKC,eAAeJ,MAAMC,UAAUC,OAAAA;GAEzD,MAAM,KAAKV,cAAca,OAAO;IAC5BC,OAAOnC,WAAWoC;IAClBC,MAAMvC,UAAUwC;IAChBC,SAASxC,aAAayC;IACtBC,OAAOV,QAAQW,QAAQC,MAAMd,KAAKe,aAAa;IAC/CC,UAAUd,QAAQW,QAAQC,MAAMd,KAAKe,aAAa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ventRefType","EventScope","IdentityType","SessionAuthMethod","hasInstanceof","OAUTH2_ACCESS_DENIED_ERROR_INSTANCE","OAUTH2_LOGIN_REQUIRED_ERROR_INSTANCE","OAUTH2_MFA_REQUIRED_ERROR_INSTANCE","OAuth2AccessDeniedError","OAuth2AuthenticationContextClass","OAuth2AuthorizationPrompt","OAuth2AuthorizationResponseType","OAuth2GrantError","OAuth2LoginRequiredError","OAuth2MfaRequiredError","OAuth2RequestError","OAuth2ResponseTypeError","toIdentityPolicyData","DEFAULT_PROMPT_LOGIN_MAX_AGE","DEFAULT_MFA_FRESHNESS_MAX_AGE","OAuth2Authorization","codeIssuer","sessionManager","eventService","metrics","promptLoginMaxAge","mfaFreshnessMaxAge","mfaChallengeProvider","accessPolicyEvaluator","ctx","authorize","data","identity","options","result","authorizeInner","record","scope","OAUTH2","name","AUTHORIZE","refType","CLIENT","refId","client","id","client_id","clientId","sessionId","actorType","type","actorId","actorName","realmId","realm_id","reason","builtIn","recordAuthorize","e","AUTHORIZE_FAILED","responseTypes","response_type","Array","isArray","split","responseType","CODE","unsupported","includes","redirect_uri","redirectUriMismatch","output","redirectUri","state","identityInvalid","realmMismatch","nowSeconds","Math","floor","Date","now","authTime","session","findOneById","createdAt","getTime","USER","challenge","issueMaterial","externallyAuthenticated","authMethod","EXTERNAL","required","mfaAt","challengeRequired","enrollmentRequired","acr_values","acrValues","MFA","mfaAtSeconds","stepUpRequired","prompts","prompt","LOGIN","reauthenticationRequired","max_age","maxAge","Number","isFinite","accessPolicyId","allowed","subject","evaluate","forClient","redirectUriVerified","undefined","codeEntity","issue","authorizationCode"],"sources":["../../../../src/core/oauth2/authorization/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2024.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport type {\n Identity, \n OAuth2AuthorizationCode, \n OAuth2AuthorizationCodeRequest, \n Session,\n} from '@authup/core-kit';\nimport {\n EventName, \n EventRefType, \n EventScope, \n IdentityType,\n SessionAuthMethod,\n} from '@authup/core-kit';\nimport { hasInstanceof } from '@authup/errors';\nimport {\n OAUTH2_ACCESS_DENIED_ERROR_INSTANCE,\n OAUTH2_LOGIN_REQUIRED_ERROR_INSTANCE,\n OAUTH2_MFA_REQUIRED_ERROR_INSTANCE,\n OAuth2AccessDeniedError,\n OAuth2AuthenticationContextClass,\n OAuth2AuthorizationPrompt,\n OAuth2AuthorizationResponseType,\n OAuth2GrantError,\n OAuth2LoginRequiredError,\n OAuth2MfaRequiredError,\n OAuth2RequestError,\n OAuth2ResponseTypeError,\n} from '@authup/specs';\nimport type { IOAuth2AuthorizationCodeIssuer } from './code/index.ts';\nimport type { IOAuth2AccessPolicyEvaluator } from '../access-policy/index.ts';\nimport { toIdentityPolicyData } from '../../identity/permission/identity-policy-data.ts';\nimport type {\n OAuth2AuthorizationManagerContext,\n OAuth2AuthorizationOptions,\n OAuth2AuthorizationResult,\n} from './types.ts';\nimport type { ISessionManager } from '../../authentication/index.ts';\nimport type { IEventService, IUserAuthenticatorChallengeProvider } from '../../entities/index.ts';\nimport type { IAuthFlowMetrics } from '../../metrics/index.ts';\n\nconst DEFAULT_PROMPT_LOGIN_MAX_AGE = 60;\n\n// Deliberately 60 (not 0, deviating from the plan-050 sketch): the hosted\n// challenge round-trip (stamp mfa_at → retry POST /authorize) takes seconds,\n// so a 0-window step-up could never be satisfied and would loop the ladder.\nconst DEFAULT_MFA_FRESHNESS_MAX_AGE = 60;\n\nexport class OAuth2Authorization {\n protected codeIssuer : IOAuth2AuthorizationCodeIssuer;\n\n protected sessionManager : ISessionManager;\n\n protected eventService? : IEventService;\n\n protected metrics? : IAuthFlowMetrics;\n\n protected promptLoginMaxAge : number;\n\n protected mfaFreshnessMaxAge : number;\n\n protected mfaChallengeProvider? : IUserAuthenticatorChallengeProvider;\n\n protected accessPolicyEvaluator? : IOAuth2AccessPolicyEvaluator;\n\n constructor(ctx: OAuth2AuthorizationManagerContext) {\n this.codeIssuer = ctx.codeIssuer;\n this.sessionManager = ctx.sessionManager;\n this.eventService = ctx.eventService;\n this.metrics = ctx.metrics;\n this.accessPolicyEvaluator = ctx.accessPolicyEvaluator;\n this.promptLoginMaxAge = ctx.promptLoginMaxAge ?? DEFAULT_PROMPT_LOGIN_MAX_AGE;\n this.mfaFreshnessMaxAge = ctx.mfaFreshnessMaxAge ?? DEFAULT_MFA_FRESHNESS_MAX_AGE;\n this.mfaChallengeProvider = ctx.mfaChallengeProvider;\n }\n\n /**\n * Authorize with validated codeRequest.\n *\n * @param data\n * @param identity\n * @param options\n */\n async authorize(\n data: OAuth2AuthorizationCodeRequest,\n identity: Identity,\n options: OAuth2AuthorizationOptions = {},\n ) : Promise<OAuth2AuthorizationResult> {\n try {\n const result = await this.authorizeInner(data, identity, options);\n\n await this.eventService?.record({\n scope: EventScope.OAUTH2,\n name: EventName.AUTHORIZE,\n refType: EventRefType.CLIENT,\n refId: options.client?.id ?? data.client_id ?? null,\n clientId: options.client?.id ?? data.client_id ?? null,\n sessionId: options.sessionId ?? null,\n actorType: identity.type,\n actorId: identity.data.id,\n actorName: identity.data.name,\n realmId: data.realm_id ?? null,\n data: {\n reason: options.client?.builtIn ? 'autoConsent' : 'consent',\n ...(data.scope ? { scope: data.scope } : {}),\n },\n });\n this.metrics?.recordAuthorize('issued');\n\n return result;\n } catch (e) {\n if (hasInstanceof(e, OAUTH2_ACCESS_DENIED_ERROR_INSTANCE)) {\n await this.eventService?.record({\n scope: EventScope.OAUTH2,\n name: EventName.AUTHORIZE_FAILED,\n refType: EventRefType.CLIENT,\n refId: options.client?.id ?? data.client_id ?? null,\n clientId: options.client?.id ?? data.client_id ?? null,\n sessionId: options.sessionId ?? null,\n actorType: identity.type,\n actorId: identity.data.id,\n actorName: identity.data.name,\n realmId: data.realm_id ?? null,\n data: { reason: 'accessPolicy' },\n });\n this.metrics?.recordAuthorize('denied');\n } else if (hasInstanceof(e, OAUTH2_LOGIN_REQUIRED_ERROR_INSTANCE)) {\n this.metrics?.recordAuthorize('login_required');\n } else if (hasInstanceof(e, OAUTH2_MFA_REQUIRED_ERROR_INSTANCE)) {\n this.metrics?.recordAuthorize('mfa_required');\n } else {\n this.metrics?.recordAuthorize('error');\n }\n\n throw e;\n }\n }\n\n protected async authorizeInner(\n data: OAuth2AuthorizationCodeRequest,\n identity: Identity,\n options: OAuth2AuthorizationOptions = {},\n ) : Promise<OAuth2AuthorizationResult> {\n // OAuth 2.1 posture: only the authorization-code response type is\n // supported — implicit/hybrid (token, id_token, none) were dropped\n // (plan 042 item 3). Defense in depth behind the request validator.\n let responseTypes : string[] = [];\n if (data.response_type) {\n responseTypes = Array.isArray(data.response_type) ?\n data.response_type :\n data.response_type.split(' ');\n }\n\n for (const responseType of responseTypes) {\n if (responseType !== OAuth2AuthorizationResponseType.CODE) {\n throw OAuth2ResponseTypeError.unsupported();\n }\n }\n\n if (!responseTypes.includes(OAuth2AuthorizationResponseType.CODE)) {\n throw OAuth2ResponseTypeError.unsupported();\n }\n\n if (!data.redirect_uri) {\n throw OAuth2GrantError.redirectUriMismatch();\n }\n\n const output : OAuth2AuthorizationResult = {\n redirectUri: data.redirect_uri,\n ...(data.state ? { state: data.state } : {}),\n };\n\n if (!identity) {\n throw OAuth2RequestError.identityInvalid();\n }\n\n // Realm binding: the code-request verifier stamped data.realm_id with the\n // resolved client's realm. The authenticated identity must belong to that\n // same realm — otherwise a lingering session for realm A could silently\n // mint a code/token for realm B's client (confused deputy). The error body\n // deliberately carries no identity data (no realm-enumeration oracle).\n // The comparison reads the scalar realmId column, NOT the realm\n // relation — the relation may simply not be loaded on the resolved\n // identity. An identity without a realmId fails closed the same way —\n // clean login_required, never a TypeError.\n if (\n data.realm_id &&\n identity.data.realmId !== data.realm_id\n ) {\n throw OAuth2LoginRequiredError.realmMismatch();\n }\n\n // Authentication time = the backing session's creation instant (NOT\n // refreshed_at — a token refresh must not reset it). Session-less flows\n // (e.g. HTTP Basic authorize) present live credentials on this request,\n // so the authentication time is \"now\".\n const nowSeconds = Math.floor(Date.now() / 1000);\n let authTime = nowSeconds;\n let session : Session | null = null;\n if (options.sessionId) {\n session = await this.sessionManager.findOneById(options.sessionId);\n if (session && session.createdAt) {\n authTime = Math.floor(new Date(session.createdAt).getTime() / 1000);\n }\n }\n\n // MFA backstop (plan 049) — the authoritative server-side gate; the\n // hosted UI's challenge step is convenience. The proof is session-bound\n // (mfa_at — stamped by the challenge endpoint or the password grant's\n // otp param), so a session-less flow (HTTP Basic) cannot carry one and\n // fails closed while the user holds a confirmed device. A user without\n // a device under mfaRequired is routed to inline enrollment.\n if (this.mfaChallengeProvider && identity.type === IdentityType.USER) {\n // requirement flags only — the interactive challenge material (the\n // webauthn nonce) is issued by the status endpoint, not this backstop.\n const challenge = await this.mfaChallengeProvider.challenge(\n identity.data.id,\n { issueMaterial: false },\n );\n // The local second factor belongs to a local credential. A\n // session established by an external identity provider was\n // authenticated THERE, which is where MFA is configured and\n // enforced for it, so authup does not stack a factor of its own\n // on top and `mfaRequired` does not force local enrollment on\n // those users. The route is opt-in either way: an external\n // identity reaches an existing account only through the\n // bearer-authenticated link flow, since a first login provisions\n // a NEW user (plan 091). A session-less authorize (HTTP Basic) is\n // not external and keeps the gate.\n const externallyAuthenticated = session?.authMethod === SessionAuthMethod.EXTERNAL;\n\n if (!externallyAuthenticated) {\n if (challenge.required && !session?.mfaAt) {\n throw OAuth2MfaRequiredError.challengeRequired();\n }\n\n if (challenge.enrollmentRequired) {\n throw OAuth2MfaRequiredError.enrollmentRequired();\n }\n }\n\n // Step-up (plan 050 stage 3): a requested `acr_values` containing\n // urn:authup:mfa is a TRIGGER (Auth0/Keycloak stance) — the proof\n // must additionally be FRESH (mfaFreshnessMaxAge window, mirroring\n // promptLoginMaxAge's absorb-the-round-trip semantics). Enforced\n // only while the user actually holds a factor — per OIDC Core\n // §5.5.1.1 acr is voluntary, so an unsatisfiable request degrades\n // to the achieved acr instead of bricking the RP.\n //\n // This one DOES apply to an externally authenticated session: the\n // application asked for MFA explicitly, and a local factor the\n // user holds is the only way authup can answer that. Trusting the\n // upstream is the default, not a refusal to prove anything.\n if (challenge.required && data.acr_values) {\n const acrValues = data.acr_values.split(' ');\n if (acrValues.includes(OAuth2AuthenticationContextClass.MFA)) {\n const mfaAtSeconds = session?.mfaAt ?\n Math.floor(new Date(session.mfaAt).getTime() / 1000) :\n null;\n if (mfaAtSeconds === null || nowSeconds - mfaAtSeconds > this.mfaFreshnessMaxAge) {\n throw OAuth2MfaRequiredError.stepUpRequired();\n }\n }\n }\n }\n\n // OIDC §3.1.2.1 prompt=login / max_age freshness (enforced only when\n // requested — a plain authorize never throws here). The hosted page\n // renders the login form for prompt=login; this is the server backstop.\n const prompts = data.prompt ? data.prompt.split(' ') : [];\n if (\n prompts.includes(OAuth2AuthorizationPrompt.LOGIN) &&\n nowSeconds - authTime > this.promptLoginMaxAge\n ) {\n throw OAuth2LoginRequiredError.reauthenticationRequired();\n }\n\n if (\n typeof data.max_age !== 'undefined' &&\n data.max_age !== null\n ) {\n const maxAge = Number(data.max_age);\n if (\n Number.isFinite(maxAge) &&\n nowSeconds - authTime > maxAge\n ) {\n throw OAuth2LoginRequiredError.reauthenticationRequired();\n }\n }\n\n // Application access policy (plan 052) — the last gate before\n // issuance: a denial is only revealed to a fully-authenticated\n // (incl. second-factor) identity. A client carrying a policy id with\n // no wired evaluator denies too (never silently allow a configured\n // gate). The redirect target rides the error only when the\n // redirect_uri was pattern-verified (RFC 6749 §4.1.2.1).\n if (options.client?.accessPolicyId) {\n let allowed = false;\n\n const subject = toIdentityPolicyData(identity);\n if (this.accessPolicyEvaluator && subject) {\n allowed = await this.accessPolicyEvaluator.evaluate(\n options.client.accessPolicyId,\n subject,\n );\n }\n\n if (!allowed) {\n throw OAuth2AccessDeniedError.forClient(\n options.redirectUriVerified && data.redirect_uri ?\n { redirectUri: data.redirect_uri, state: data.state ?? null } :\n undefined,\n );\n }\n }\n\n // The id_token is NOT minted here — the /token exchange mints it after\n // resolving the real backing session, so its `sid` is authoritative\n // (plan 042 item 6). The code carries the authentication instant.\n const codeEntity : OAuth2AuthorizationCode = await this.codeIssuer.issue(\n data,\n identity,\n {\n sessionId: options.sessionId,\n authTime,\n authMethod: session?.authMethod ?? null,\n },\n );\n\n output.authorizationCode = codeEntity.id;\n\n return output;\n }\n}\n"],"mappings":";;;;;;;;AA+CA,MAAMmB,+BAA+B;AAKrC,MAAMC,gCAAgC;AAEtC,IAAaC,sBAAb,MAAaA;CACCC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEV,YAAYC,KAAwC;EAChD,KAAKR,aAAaQ,IAAIR;EACtB,KAAKC,iBAAiBO,IAAIP;EAC1B,KAAKC,eAAeM,IAAIN;EACxB,KAAKC,UAAUK,IAAIL;EACnB,KAAKI,wBAAwBC,IAAID;EACjC,KAAKH,oBAAoBI,IAAIJ,qBAAqBP;EAClD,KAAKQ,qBAAqBG,IAAIH,sBAAsBP;EACpD,KAAKQ,uBAAuBE,IAAIF;CACpC;;;;;;;IASA,MAAMG,UACFC,MACAC,UACAC,UAAsC,CAAC,GACJ;EACnC,IAAI;GACA,MAAMC,SAAS,MAAM,KAAKC,eAAeJ,MAAMC,UAAUC,OAAAA;GAEzD,MAAM,KAAKV,cAAca,OAAO;IAC5BC,OAAOpC,WAAWqC;IAClBC,MAAMxC,UAAUyC;IAChBC,SAASzC,aAAa0C;IACtBC,OAAOV,QAAQW,QAAQC,MAAMd,KAAKe,aAAa;IAC/CC,UAAUd,QAAQW,QAAQC,MAAMd,KAAKe,aAAa;IAClDE,WAAWf,QAAQe,aAAa;IAChCC,WAAWjB,SAASkB;IACpBC,SAASnB,SAASD,KAAKc;IACvBO,WAAWpB,SAASD,KAAKQ;IACzBc,SAAStB,KAAKuB,YAAY;IAC1BvB,MAAM;KACFwB,QAAQtB,QAAQW,QAAQY,UAAU,gBAAgB;KAClD,GAAIzB,KAAKM,QAAQ,EAAEA,OAAON,KAAKM,MAAM,IAAI,CAAC;IA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,MAAMZ,uBAAuBsF,eAAc;IAEnD;;EAER;EAMA,KADgBrE,KAAKuE,SAASvE,KAAKuE,OAAOtC,MAAM,GAAA,IAAO,CAAA,EAAA,CAE3CI,SAAS1D,0BAA0B6F,KAAK,KAChD3B,aAAaK,WAAW,KAAKxD,mBAE7B,MAAMZ,yBAAyB2F,yBAAwB;EAG3D,IACI,OAAOzE,KAAK0E,YAAY,eACxB1E,KAAK0E,YAAY,MACnB;GACE,MAAMC,SAASC,OAAO5E,KAAK0E,OAAO;GAClC,IACIE,OAAOC,SAASF,MAAAA,KAChB9B,aAAaK,WAAWyB,QAExB,MAAM7F,yBAAyB2F,yBAAwB;EAE/D;EAQA,IAAIvE,QAAQW,QAAQiE,gBAAgB;GAChC,IAAIC,UAAU;GAEd,MAAMC,UAAU9F,qBAAqBe,QAAAA;GACrC,IAAI,KAAKJ,yBAAyBmF,SAC9BD,UAAU,MAAM,KAAKlF,sBAAsBoF,SACvC/E,QAAQW,OAAOiE,gBACfE,OAAAA;GAIR,IAAI,CAACD,SACD,MAAMtG,wBAAwByG,UAC1BhF,QAAQiF,uBAAuBnF,KAAKsC,eAChC;IAAEG,aAAazC,KAAKsC;IAAcI,OAAO1C,KAAK0C,SAAS;GAAK,IAC5D0C,KAAAA,CAAAA;EAGhB;EAeA5C,OAAO+C,qBAAoBF,MAVwB,KAAK/F,WAAWgG,MAC/DtF,MACAC,UACA;GACIgB,WAAWf,QAAQe;GACnBiC;GACAS,YAAYR,SAASQ,cAAc;EACvC,CAAA,EAAA,CAGkC7C;EAEtC,OAAO0B;CACX;AACJ"}
@@ -12,9 +12,8 @@ var OAuth2AuthorizationStateManager = class {
12
12
  return this.repository.insert(data);
13
13
  }
14
14
  async verify(state, input) {
15
- const payload = await this.repository.findOneById(state);
15
+ const payload = await this.repository.popOneById(state);
16
16
  if (!payload) throw OAuth2RequestError.stateInvalid();
17
- await this.repository.remove(state);
18
17
  if (payload.ip && input.ip !== payload.ip) throw OAuth2RequestError.stateInvalid();
19
18
  if (payload.userAgent && input.userAgent !== payload.userAgent) throw OAuth2RequestError.stateInvalid();
20
19
  return payload;
@@ -1 +1 @@
1
- {"version":3,"file":"module.mjs","names":["OAuth2RequestError","OAuth2AuthorizationStateManager","repository","save","data","insert","verify","state","input","payload","findOneById","stateInvalid","remove","ip","userAgent"],"sources":["../../../../../src/core/oauth2/authorization/state/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { OAuth2RequestError } from '@authup/specs';\nimport type {\n IOAuth2AuthorizationStateManager,\n IOAuth2AuthorizeStateRepository,\n OAuth2AuthorizationState,\n} from './types.ts';\n\nexport class OAuth2AuthorizationStateManager implements IOAuth2AuthorizationStateManager {\n protected repository: IOAuth2AuthorizeStateRepository;\n\n constructor(repository: IOAuth2AuthorizeStateRepository) {\n this.repository = repository;\n }\n\n async save(data: OAuth2AuthorizationState) : Promise<string> {\n return this.repository.insert(data);\n }\n\n async verify(state: string, input: Partial<OAuth2AuthorizationState>): Promise<OAuth2AuthorizationState> {\n const payload = await this.repository.findOneById(state);\n if (!payload) {\n throw OAuth2RequestError.stateInvalid();\n }\n\n // avoid replay attacks\n await this.repository.remove(state);\n\n if (\n payload.ip &&\n input.ip !== payload.ip\n ) {\n throw OAuth2RequestError.stateInvalid();\n }\n\n if (\n payload.userAgent &&\n input.userAgent !== payload.userAgent\n ) {\n throw OAuth2RequestError.stateInvalid();\n }\n\n return payload;\n }\n}\n"],"mappings":";;;;;AAcA,IAAaC,kCAAb,MAAaA;CACCC;CAEV,YAAYA,YAA6C;EACrD,KAAKA,aAAaA;CACtB;CAEA,MAAMC,KAAKC,MAAkD;EACzD,OAAO,KAAKF,WAAWG,OAAOD,IAAAA;CAClC;CAEA,MAAME,OAAOC,OAAeC,OAA6E;EACrG,MAAMC,UAAU,MAAM,KAAKP,WAAWQ,YAAYH,KAAAA;EAClD,IAAI,CAACE,SACD,MAAMT,mBAAmBW,aAAY;EAIzC,MAAM,KAAKT,WAAWU,OAAOL,KAAAA;EAE7B,IACIE,QAAQI,MACRL,MAAMK,OAAOJ,QAAQI,IAErB,MAAMb,mBAAmBW,aAAY;EAGzC,IACIF,QAAQK,aACRN,MAAMM,cAAcL,QAAQK,WAE5B,MAAMd,mBAAmBW,aAAY;EAGzC,OAAOF;CACX;AACJ"}
1
+ {"version":3,"file":"module.mjs","names":["OAuth2RequestError","OAuth2AuthorizationStateManager","repository","save","data","insert","verify","state","input","payload","popOneById","stateInvalid","ip","userAgent"],"sources":["../../../../../src/core/oauth2/authorization/state/module.ts"],"sourcesContent":["/*\n * Copyright (c) 2025.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { OAuth2RequestError } from '@authup/specs';\nimport type {\n IOAuth2AuthorizationStateManager,\n IOAuth2AuthorizeStateRepository,\n OAuth2AuthorizationState,\n} from './types.ts';\n\nexport class OAuth2AuthorizationStateManager implements IOAuth2AuthorizationStateManager {\n protected repository: IOAuth2AuthorizeStateRepository;\n\n constructor(repository: IOAuth2AuthorizeStateRepository) {\n this.repository = repository;\n }\n\n async save(data: OAuth2AuthorizationState) : Promise<string> {\n return this.repository.insert(data);\n }\n\n async verify(state: string, input: Partial<OAuth2AuthorizationState>): Promise<OAuth2AuthorizationState> {\n // The pop is the replay guard: a state is consumed by whichever\n // callback presents it first, whether or not it then passes the\n // binding checks below.\n const payload = await this.repository.popOneById(state);\n if (!payload) {\n throw OAuth2RequestError.stateInvalid();\n }\n\n if (\n payload.ip &&\n input.ip !== payload.ip\n ) {\n throw OAuth2RequestError.stateInvalid();\n }\n\n if (\n payload.userAgent &&\n input.userAgent !== payload.userAgent\n ) {\n throw OAuth2RequestError.stateInvalid();\n }\n\n return payload;\n }\n}\n"],"mappings":";;;;;AAcA,IAAaC,kCAAb,MAAaA;CACCC;CAEV,YAAYA,YAA6C;EACrD,KAAKA,aAAaA;CACtB;CAEA,MAAMC,KAAKC,MAAkD;EACzD,OAAO,KAAKF,WAAWG,OAAOD,IAAAA;CAClC;CAEA,MAAME,OAAOC,OAAeC,OAA6E;EAIrG,MAAMC,UAAU,MAAM,KAAKP,WAAWQ,WAAWH,KAAAA;EACjD,IAAI,CAACE,SACD,MAAMT,mBAAmBW,aAAY;EAGzC,IACIF,QAAQG,MACRJ,MAAMI,OAAOH,QAAQG,IAErB,MAAMZ,mBAAmBW,aAAY;EAGzC,IACIF,QAAQI,aACRL,MAAMK,cAAcJ,QAAQI,WAE5B,MAAMb,mBAAmBW,aAAY;EAGzC,OAAOF;CACX;AACJ"}
@@ -12,13 +12,24 @@ export type OAuth2AuthorizationState = {
12
12
  * endpoint, never from client input.
13
13
  */
14
14
  link?: OAuth2AuthorizationStateLink;
15
+ /**
16
+ * Ties a federated login to the browser that started it (plan 094). The
17
+ * value is set as a cookie when the login starts and required to match
18
+ * when the provider sends the browser back, so a crafted callback URL
19
+ * opened elsewhere establishes nothing. The state's own ip / user agent
20
+ * cannot do this: both are chosen by whoever mints the state (#3439).
21
+ */
22
+ browserNonce?: string;
15
23
  ip: string;
16
24
  userAgent?: string | null;
17
25
  };
18
26
  export interface IOAuth2AuthorizeStateRepository {
19
- findOneById(id: string): Promise<OAuth2AuthorizationState | null>;
20
27
  insert(data: OAuth2AuthorizationState): Promise<string>;
21
- remove(id: string): Promise<void>;
28
+ /**
29
+ * Read and delete in one step, so two callbacks presenting the same
30
+ * state cannot both obtain the payload.
31
+ */
32
+ popOneById(id: string): Promise<OAuth2AuthorizationState | null>;
22
33
  }
23
34
  export interface IOAuth2AuthorizationStateManager {
24
35
  save(data: OAuth2AuthorizationState): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../../src/core/oauth2/authorization/state/types.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAEvE,MAAM,MA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AAE,gBAAgB,CAAC;IAE5C,SAAS,CAAC,YAAY,CAAC,EAAE,aAAa,CAAC;IAEvC,SAAS,CAAC,eAAe,EAAE,MAAM,CAAC;gBAEtB,GAAG,EAAE,8BAA8B;IASzC,MAAM,CAAC,IAAI,EAAE,uBAAuB,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAgHtE,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IA2B/E;;;;;OAKG;IACH,SAAS,CAAC,uBAAuB,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO;IAcvE;;;;OAIG;IACH,SAAS,CAAC,yBAAyB,CAC/B,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACrC,SAAS,EAAE,MAAM,GAClB,OAAO;CA6Bb"}
@@ -120,6 +120,7 @@ var OAuth2EndSessionService = class {
120
120
  return false;
121
121
  }
122
122
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
123
+ if (parsed.username || parsed.password) return false;
123
124
  if (!registered) return false;
124
125
  return isSimpleURLMatch(candidate, registered.split(","));
125
126
  }
@@ -1 +1 @@
1
- {"version":3,"file":"service.mjs","names":["isSimpleURLMatch","isUUID","EventName","EventRefType","EventScope","OAuth2TokenKind","OAuth2EndSessionService","tokenVerifier","sessionManager","clientRepository","realmRepository","eventService","hintGracePeriod","ctx","verify","data","hintVerified","sub","subKind","sessionId","hintRealmId","audiences","id_token_hint","payload","ignoreExpiry","skipActiveCheck","kind","ID_TOKEN","isWithinHintGraceWindow","sub_kind","sid","session_id","undefined","realm_id","aud","Array","isArray","filter","entry","clientId","client_id","length","client","realmKey","realm_name","realm","resolve","findOneByIdOrName","id","expected","includes","clientName","redirectUri","name","post_logout_redirect_uri","isValidPostLogoutRedirect","postLogoutRedirectUri","state","revoke","session","findOneById","record","scope","OAUTH2","LOGOUT","refType","SESSION","refId","actorType","actorId","realmId","exp","nowSeconds","Math","floor","Date","now","registered","candidate","parsed","URL","protocol","split"],"sources":["../../../../src/core/oauth2/end-session/service.ts"],"sourcesContent":["/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isSimpleURLMatch, isUUID } from '@authup/kit';\nimport type { Client, IdentityType } from '@authup/core-kit';\nimport { EventName, EventRefType, EventScope } from '@authup/core-kit';\nimport type { OAuth2TokenPayload } from '@authup/specs';\nimport { OAuth2TokenKind } from '@authup/specs';\nimport type { IEventService, IRealmRepository } from '../../entities/index.ts';\nimport type { ISessionManager } from '../../authentication/index.ts';\nimport type { IOAuth2ClientRepository } from '../client/index.ts';\nimport type { IOAuth2TokenVerifier } from '../token/index.ts';\nimport type {\n IOAuth2EndSessionService,\n OAuth2EndSessionRequest,\n OAuth2EndSessionResult,\n OAuth2EndSessionServiceContext,\n} from './types.ts';\n\nexport class OAuth2EndSessionService implements IOAuth2EndSessionService {\n protected tokenVerifier: IOAuth2TokenVerifier;\n\n protected sessionManager: ISessionManager;\n\n protected clientRepository: IOAuth2ClientRepository;\n\n protected realmRepository: IRealmRepository;\n\n protected eventService?: IEventService;\n\n protected hintGracePeriod: number;\n\n constructor(ctx: OAuth2EndSessionServiceContext) {\n this.tokenVerifier = ctx.tokenVerifier;\n this.sessionManager = ctx.sessionManager;\n this.clientRepository = ctx.clientRepository;\n this.realmRepository = ctx.realmRepository;\n this.eventService = ctx.eventService;\n this.hintGracePeriod = ctx.hintGracePeriod ?? 0;\n }\n\n async verify(data: OAuth2EndSessionRequest): Promise<OAuth2EndSessionResult> {\n let hintVerified = false;\n let sub: string | undefined;\n let subKind: string | undefined;\n let sessionId: string | undefined;\n let hintRealmId: string | undefined;\n let audiences: string[] = [];\n\n if (data.id_token_hint) {\n try {\n // Signature + kind are the anchors; exp is skipped (a logout hint\n // is routinely expired) and the cache blocklist is irrelevant.\n const payload = await this.tokenVerifier.verify(data.id_token_hint, {\n ignoreExpiry: true,\n skipActiveCheck: true,\n });\n\n // MUST be an id_token — access/refresh tokens also carry\n // session_id, so accepting them would let a leaked access token\n // act as a logout weapon.\n if (payload.kind === OAuth2TokenKind.ID_TOKEN && this.isWithinHintGraceWindow(payload)) {\n hintVerified = true;\n sub = payload.sub;\n subKind = payload.sub_kind;\n sessionId = payload.sid ?? payload.session_id ?? undefined;\n hintRealmId = payload.realm_id ?? undefined;\n // aud may be a single string or an array (JWT spec).\n const { aud } = payload;\n if (Array.isArray(aud)) {\n audiences = aud.filter((entry): entry is string => typeof entry === 'string');\n } else if (typeof aud === 'string') {\n audiences = [aud];\n }\n }\n } catch {\n // forged / unverifiable hint → stays unverified (no revoke)\n }\n }\n\n // Resolve a single client for the aud cross-check and redirect\n // validation: the request's client_id, else the hint's sole audience\n // (ambiguous for a multi-aud hint).\n const clientId = data.client_id ?? (audiences.length === 1 ? audiences[0] : undefined);\n\n let client: Client | null = null;\n if (clientId) {\n // Scope a name-identified client to the request's realm hint; a\n // VERIFIED hint's own realm claim serves as fallback (claims from an\n // unverified hint are never trusted). No master fallback here\n // (unlike /token): a bogus hint must NOT silently resolve a\n // same-named client in master → null realm.\n const realmKey = data.realm_id ?? data.realm_name ?? (hintVerified ? hintRealmId : undefined);\n const realm = await this.realmRepository.resolve(realmKey, false);\n\n // Fail closed instead of dropping the realm predicate: a supplied\n // realm key that does not resolve never degrades to an unscoped\n // lookup, and a NAME-form client_id without any realm key is\n // ambiguous (client names are only unique per realm, and every\n // realm carries the same-named system clients — same rule as the\n // /authorize verifier). A UUID is globally unique and needs no\n // scope; the sole-aud-derived clientId is always a UUID.\n if (realm) {\n client = await this.clientRepository.findOneByIdOrName(clientId, realm.id);\n } else if (!realmKey && isUUID(clientId)) {\n client = await this.clientRepository.findOneByIdOrName(clientId);\n }\n }\n\n // aud/client_id cross-check: when the request supplies a client_id on a\n // verified hint, it MUST denote one of the hint's audiences. The aud is\n // the client UUID, so a name-form client_id is compared via its resolved\n // client's id. Fail closed: an aud-less hint, or a name that did not\n // resolve, counts as unverified.\n if (hintVerified && data.client_id) {\n const expected = isUUID(data.client_id) ? data.client_id : client?.id;\n if (audiences.length === 0 || !expected || !audiences.includes(expected)) {\n hintVerified = false;\n sub = undefined;\n subKind = undefined;\n sessionId = undefined;\n }\n }\n\n let clientName: string | undefined;\n let redirectUri: string | undefined;\n\n // Redirect validation is independent of hint verification — the\n // click-gated confirm page (unverified hint / hint-less request) still\n // honors a registered post-logout redirect.\n if (client) {\n clientName = client.name;\n if (\n data.post_logout_redirect_uri &&\n this.isValidPostLogoutRedirect(client.postLogoutRedirectUri, data.post_logout_redirect_uri)\n ) {\n redirectUri = data.post_logout_redirect_uri;\n }\n }\n\n return {\n hintVerified,\n ...(hintVerified ? {\n sub,\n subKind,\n sessionId,\n } : {}),\n ...(clientId ? { clientId } : {}),\n ...(clientName ? { clientName } : {}),\n ...(redirectUri ? { redirectUri, ...(data.state ? { state: data.state } : {}) } : {}),\n };\n }\n\n async revoke(sessionId: string, sub: string, subKind: string): Promise<boolean> {\n const session = await this.sessionManager.findOneById(sessionId);\n if (!session) {\n return false;\n }\n\n // Never revoke a session that does not belong to the hint's subject.\n if (session.sub !== sub || session.subKind !== subKind) {\n return false;\n }\n\n await this.sessionManager.revoke(sessionId);\n\n await this.eventService?.record({\n scope: EventScope.OAUTH2,\n name: EventName.LOGOUT,\n refType: EventRefType.SESSION,\n refId: sessionId,\n sessionId,\n actorType: session.subKind as `${IdentityType}`,\n actorId: session.sub,\n realmId: session.realmId,\n });\n\n return true;\n }\n\n /**\n * With a positive `hintGracePeriod`, an expired hint is honored only within\n * the window past `exp` — beyond it a leaked id_token stops being a\n * replayable remote logout (the hint counts as unverified; the click-gated\n * confirm page still works). 0 keeps spec/Keycloak parity: any expired hint.\n */\n protected isWithinHintGraceWindow(payload: OAuth2TokenPayload): boolean {\n if (this.hintGracePeriod <= 0) {\n return true;\n }\n\n // a bounded window without an exp claim to judge against fails closed\n if (typeof payload.exp !== 'number') {\n return false;\n }\n\n const nowSeconds = Math.floor(Date.now() / 1000);\n return nowSeconds - payload.exp <= this.hintGracePeriod;\n }\n\n /**\n * A post-logout redirect is honored only when it is an absolute http(s) URL\n * that matches a registered client redirect pattern (defense against open\n * redirects to attacker-controlled URLs).\n */\n protected isValidPostLogoutRedirect(\n registered: string | null | undefined,\n candidate: string,\n ): boolean {\n let parsed: URL;\n try {\n parsed = new URL(candidate);\n } catch {\n return false;\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return false;\n }\n\n if (!registered) {\n return false;\n }\n\n // isSimpleURLMatch, never isSimpleMatch: matched against the raw\n // string, a `*` in a registered pattern's host absorbs a `?`, `#` or\n // `\\`, which would turn this endpoint into a server-issued open\n // redirect carrying `state`.\n return isSimpleURLMatch(candidate, registered.split(','));\n }\n}\n"],"mappings":";;;;;;;AAuBA,IAAaM,0BAAb,MAAaA;CACCC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEV,YAAYC,KAAqC;EAC7C,KAAKN,gBAAgBM,IAAIN;EACzB,KAAKC,iBAAiBK,IAAIL;EAC1B,KAAKC,mBAAmBI,IAAIJ;EAC5B,KAAKC,kBAAkBG,IAAIH;EAC3B,KAAKC,eAAeE,IAAIF;EACxB,KAAKC,kBAAkBC,IAAID,mBAAmB;CAClD;CAEA,MAAME,OAAOC,MAAgE;EACzE,IAAIC,eAAe;EACnB,IAAIC;EACJ,IAAIC;EACJ,IAAIC;EACJ,IAAIC;EACJ,IAAIC,YAAsB,CAAA;EAE1B,IAAIN,KAAKO,eACL,IAAI;GAGA,MAAMC,UAAU,MAAM,KAAKhB,cAAcO,OAAOC,KAAKO,eAAe;IAChEE,cAAc;IACdC,iBAAiB;GACrB,CAAA;GAKA,IAAIF,QAAQG,SAASrB,gBAAgBsB,YAAY,KAAKC,wBAAwBL,OAAAA,GAAU;IACpFP,eAAe;IACfC,MAAMM,QAAQN;IACdC,UAAUK,QAAQM;IAClBV,YAAYI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","names":["isSimpleURLMatch","isUUID","EventName","EventRefType","EventScope","OAuth2TokenKind","OAuth2EndSessionService","tokenVerifier","sessionManager","clientRepository","realmRepository","eventService","hintGracePeriod","ctx","verify","data","hintVerified","sub","subKind","sessionId","hintRealmId","audiences","id_token_hint","payload","ignoreExpiry","skipActiveCheck","kind","ID_TOKEN","isWithinHintGraceWindow","sub_kind","sid","session_id","undefined","realm_id","aud","Array","isArray","filter","entry","clientId","client_id","length","client","realmKey","realm_name","realm","resolve","findOneByIdOrName","id","expected","includes","clientName","redirectUri","name","post_logout_redirect_uri","isValidPostLogoutRedirect","postLogoutRedirectUri","state","revoke","session","findOneById","record","scope","OAUTH2","LOGOUT","refType","SESSION","refId","actorType","actorId","realmId","exp","nowSeconds","Math","floor","Date","now","registered","candidate","parsed","URL","protocol","username","password","split"],"sources":["../../../../src/core/oauth2/end-session/service.ts"],"sourcesContent":["/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\nimport { isSimpleURLMatch, isUUID } from '@authup/kit';\nimport type { Client, IdentityType } from '@authup/core-kit';\nimport { EventName, EventRefType, EventScope } from '@authup/core-kit';\nimport type { OAuth2TokenPayload } from '@authup/specs';\nimport { OAuth2TokenKind } from '@authup/specs';\nimport type { IEventService, IRealmRepository } from '../../entities/index.ts';\nimport type { ISessionManager } from '../../authentication/index.ts';\nimport type { IOAuth2ClientRepository } from '../client/index.ts';\nimport type { IOAuth2TokenVerifier } from '../token/index.ts';\nimport type {\n IOAuth2EndSessionService,\n OAuth2EndSessionRequest,\n OAuth2EndSessionResult,\n OAuth2EndSessionServiceContext,\n} from './types.ts';\n\nexport class OAuth2EndSessionService implements IOAuth2EndSessionService {\n protected tokenVerifier: IOAuth2TokenVerifier;\n\n protected sessionManager: ISessionManager;\n\n protected clientRepository: IOAuth2ClientRepository;\n\n protected realmRepository: IRealmRepository;\n\n protected eventService?: IEventService;\n\n protected hintGracePeriod: number;\n\n constructor(ctx: OAuth2EndSessionServiceContext) {\n this.tokenVerifier = ctx.tokenVerifier;\n this.sessionManager = ctx.sessionManager;\n this.clientRepository = ctx.clientRepository;\n this.realmRepository = ctx.realmRepository;\n this.eventService = ctx.eventService;\n this.hintGracePeriod = ctx.hintGracePeriod ?? 0;\n }\n\n async verify(data: OAuth2EndSessionRequest): Promise<OAuth2EndSessionResult> {\n let hintVerified = false;\n let sub: string | undefined;\n let subKind: string | undefined;\n let sessionId: string | undefined;\n let hintRealmId: string | undefined;\n let audiences: string[] = [];\n\n if (data.id_token_hint) {\n try {\n // Signature + kind are the anchors; exp is skipped (a logout hint\n // is routinely expired) and the cache blocklist is irrelevant.\n const payload = await this.tokenVerifier.verify(data.id_token_hint, {\n ignoreExpiry: true,\n skipActiveCheck: true,\n });\n\n // MUST be an id_token — access/refresh tokens also carry\n // session_id, so accepting them would let a leaked access token\n // act as a logout weapon.\n if (payload.kind === OAuth2TokenKind.ID_TOKEN && this.isWithinHintGraceWindow(payload)) {\n hintVerified = true;\n sub = payload.sub;\n subKind = payload.sub_kind;\n sessionId = payload.sid ?? payload.session_id ?? undefined;\n hintRealmId = payload.realm_id ?? undefined;\n // aud may be a single string or an array (JWT spec).\n const { aud } = payload;\n if (Array.isArray(aud)) {\n audiences = aud.filter((entry): entry is string => typeof entry === 'string');\n } else if (typeof aud === 'string') {\n audiences = [aud];\n }\n }\n } catch {\n // forged / unverifiable hint → stays unverified (no revoke)\n }\n }\n\n // Resolve a single client for the aud cross-check and redirect\n // validation: the request's client_id, else the hint's sole audience\n // (ambiguous for a multi-aud hint).\n const clientId = data.client_id ?? (audiences.length === 1 ? audiences[0] : undefined);\n\n let client: Client | null = null;\n if (clientId) {\n // Scope a name-identified client to the request's realm hint; a\n // VERIFIED hint's own realm claim serves as fallback (claims from an\n // unverified hint are never trusted). No master fallback here\n // (unlike /token): a bogus hint must NOT silently resolve a\n // same-named client in master → null realm.\n const realmKey = data.realm_id ?? data.realm_name ?? (hintVerified ? hintRealmId : undefined);\n const realm = await this.realmRepository.resolve(realmKey, false);\n\n // Fail closed instead of dropping the realm predicate: a supplied\n // realm key that does not resolve never degrades to an unscoped\n // lookup, and a NAME-form client_id without any realm key is\n // ambiguous (client names are only unique per realm, and every\n // realm carries the same-named system clients — same rule as the\n // /authorize verifier). A UUID is globally unique and needs no\n // scope; the sole-aud-derived clientId is always a UUID.\n if (realm) {\n client = await this.clientRepository.findOneByIdOrName(clientId, realm.id);\n } else if (!realmKey && isUUID(clientId)) {\n client = await this.clientRepository.findOneByIdOrName(clientId);\n }\n }\n\n // aud/client_id cross-check: when the request supplies a client_id on a\n // verified hint, it MUST denote one of the hint's audiences. The aud is\n // the client UUID, so a name-form client_id is compared via its resolved\n // client's id. Fail closed: an aud-less hint, or a name that did not\n // resolve, counts as unverified.\n if (hintVerified && data.client_id) {\n const expected = isUUID(data.client_id) ? data.client_id : client?.id;\n if (audiences.length === 0 || !expected || !audiences.includes(expected)) {\n hintVerified = false;\n sub = undefined;\n subKind = undefined;\n sessionId = undefined;\n }\n }\n\n let clientName: string | undefined;\n let redirectUri: string | undefined;\n\n // Redirect validation is independent of hint verification — the\n // click-gated confirm page (unverified hint / hint-less request) still\n // honors a registered post-logout redirect.\n if (client) {\n clientName = client.name;\n if (\n data.post_logout_redirect_uri &&\n this.isValidPostLogoutRedirect(client.postLogoutRedirectUri, data.post_logout_redirect_uri)\n ) {\n redirectUri = data.post_logout_redirect_uri;\n }\n }\n\n return {\n hintVerified,\n ...(hintVerified ? {\n sub,\n subKind,\n sessionId,\n } : {}),\n ...(clientId ? { clientId } : {}),\n ...(clientName ? { clientName } : {}),\n ...(redirectUri ? { redirectUri, ...(data.state ? { state: data.state } : {}) } : {}),\n };\n }\n\n async revoke(sessionId: string, sub: string, subKind: string): Promise<boolean> {\n const session = await this.sessionManager.findOneById(sessionId);\n if (!session) {\n return false;\n }\n\n // Never revoke a session that does not belong to the hint's subject.\n if (session.sub !== sub || session.subKind !== subKind) {\n return false;\n }\n\n await this.sessionManager.revoke(sessionId);\n\n await this.eventService?.record({\n scope: EventScope.OAUTH2,\n name: EventName.LOGOUT,\n refType: EventRefType.SESSION,\n refId: sessionId,\n sessionId,\n actorType: session.subKind as `${IdentityType}`,\n actorId: session.sub,\n realmId: session.realmId,\n });\n\n return true;\n }\n\n /**\n * With a positive `hintGracePeriod`, an expired hint is honored only within\n * the window past `exp` — beyond it a leaked id_token stops being a\n * replayable remote logout (the hint counts as unverified; the click-gated\n * confirm page still works). 0 keeps spec/Keycloak parity: any expired hint.\n */\n protected isWithinHintGraceWindow(payload: OAuth2TokenPayload): boolean {\n if (this.hintGracePeriod <= 0) {\n return true;\n }\n\n // a bounded window without an exp claim to judge against fails closed\n if (typeof payload.exp !== 'number') {\n return false;\n }\n\n const nowSeconds = Math.floor(Date.now() / 1000);\n return nowSeconds - payload.exp <= this.hintGracePeriod;\n }\n\n /**\n * A post-logout redirect is honored only when it is an absolute http(s) URL\n * that matches a registered client redirect pattern (defense against open\n * redirects to attacker-controlled URLs).\n */\n protected isValidPostLogoutRedirect(\n registered: string | null | undefined,\n candidate: string,\n ): boolean {\n let parsed: URL;\n try {\n parsed = new URL(candidate);\n } catch {\n return false;\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n return false;\n }\n\n // The matcher canonicalizes the candidate (userinfo dropped) while the\n // redirect is built from the raw value, so a credential blob would\n // ride the Location header (#3455).\n if (parsed.username || parsed.password) {\n return false;\n }\n\n if (!registered) {\n return false;\n }\n\n // isSimpleURLMatch, never isSimpleMatch: matched against the raw\n // string, a `*` in a registered pattern's host absorbs a `?`, `#` or\n // `\\`, which would turn this endpoint into a server-issued open\n // redirect carrying `state`.\n return isSimpleURLMatch(candidate, registered.split(','));\n }\n}\n"],"mappings":";;;;;;;AAuBA,IAAaM,0BAAb,MAAaA;CACCC;CAEAC;CAEAC;CAEAC;CAEAC;CAEAC;CAEV,YAAYC,KAAqC;EAC7C,KAAKN,gBAAgBM,IAAIN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Q1C;GACjBqD,SAASX,QAAQW;EACrB,CAAA;EAEA,OAAO;CACX;;;;;;IAQA,wBAAkC/C,SAAsC;EACpE,IAAI,KAAKX,mBAAmB,GACxB,OAAO;EAIX,IAAI,OAAOW,QAAQgD,QAAQ,UACvB,OAAO;EAIX,OADmBE,KAAKC,MAAMC,KAAKC,IAAG,IAAK,GACpCJ,IAAajD,QAAQgD,OAAO,KAAK3D;CAC5C;;;;;IAOA,0BACIiE,YACAC,WACO;EACP,IAAIC;EACJ,IAAI;GACAA,SAAS,IAAIC,IAAIF,SAAAA;EACrB,QAAQ;GACJ,OAAO;EACX;EAEA,IAAIC,OAAOE,aAAa,WAAWF,OAAOE,aAAa,UACnD,OAAO;EAMX,IAAIF,OAAOG,YAAYH,OAAOI,UAC1B,OAAO;EAGX,IAAI,CAACN,YACD,OAAO;EAOX,OAAO7E,iBAAiB8E,WAAWD,WAAWO,MAAM,GAAA,CAAA;CACxD;AACJ"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Lifetime of a pending federated login (plan 094).
3
+ *
4
+ * It is completed by the very next page load, so it needs to cover a redirect
5
+ * and a bootstrap, not a user's attention span. It is also the lifetime of the
6
+ * session the callback creates, so an abandoned login self-expires and is
7
+ * swept with the regular session sweep; completion extends it to the full
8
+ * session lifetime.
9
+ */
10
+ export declare const OAUTH2_FEDERATED_LOGIN_TTL: number;
11
+ /**
12
+ * The cookie carrying the pending login between the provider callback and the
13
+ * hosted page that completes it.
14
+ *
15
+ * A cookie rather than a query parameter, which is what Keycloak and Authentik
16
+ * both do: the browser that STARTED the login is the only one that can present
17
+ * it, no other origin can set it, and nothing redeemable travels in a URL that
18
+ * reaches history, logs or a referrer. `SameSite=Lax` keeps it off cross-site
19
+ * requests, so a page on another origin cannot drive the completion.
20
+ */
21
+ export declare const OAUTH2_FEDERATED_LOGIN_COOKIE = "authup_federated_login";
22
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../../src/core/oauth2/federated-login/constants.ts"],"names":[],"mappings":"AAOA;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,QAAgB,CAAC;AAExD;;;;;;;;;GASG;AACH,eAAO,MAAM,6BAA6B,2BAA2B,CAAC"}
@@ -0,0 +1,27 @@
1
+ import "node:path";
2
+ import "node:url";
3
+ import.meta.url;
4
+ //#region src/core/oauth2/federated-login/constants.ts
5
+ /**
6
+ * Lifetime of a pending federated login (plan 094).
7
+ *
8
+ * It is completed by the very next page load, so it needs to cover a redirect
9
+ * and a bootstrap, not a user's attention span. It is also the lifetime of the
10
+ * session the callback creates, so an abandoned login self-expires and is
11
+ * swept with the regular session sweep; completion extends it to the full
12
+ * session lifetime.
13
+ */ const OAUTH2_FEDERATED_LOGIN_TTL = 3e5;
14
+ /**
15
+ * The cookie carrying the pending login between the provider callback and the
16
+ * hosted page that completes it.
17
+ *
18
+ * A cookie rather than a query parameter, which is what Keycloak and Authentik
19
+ * both do: the browser that STARTED the login is the only one that can present
20
+ * it, no other origin can set it, and nothing redeemable travels in a URL that
21
+ * reaches history, logs or a referrer. `SameSite=Lax` keeps it off cross-site
22
+ * requests, so a page on another origin cannot drive the completion.
23
+ */ const OAUTH2_FEDERATED_LOGIN_COOKIE = "authup_federated_login";
24
+ //#endregion
25
+ export { OAUTH2_FEDERATED_LOGIN_COOKIE, OAUTH2_FEDERATED_LOGIN_TTL };
26
+
27
+ //# sourceMappingURL=constants.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.mjs","names":["OAUTH2_FEDERATED_LOGIN_TTL","OAUTH2_FEDERATED_LOGIN_COOKIE"],"sources":["../../../../src/core/oauth2/federated-login/constants.ts"],"sourcesContent":["/*\n * Copyright (c) 2026.\n * Author Peter Placzek (tada5hi)\n * For the full copyright and license information,\n * view the LICENSE file that was distributed with this source code.\n */\n\n/**\n * Lifetime of a pending federated login (plan 094).\n *\n * It is completed by the very next page load, so it needs to cover a redirect\n * and a bootstrap, not a user's attention span. It is also the lifetime of the\n * session the callback creates, so an abandoned login self-expires and is\n * swept with the regular session sweep; completion extends it to the full\n * session lifetime.\n */\nexport const OAUTH2_FEDERATED_LOGIN_TTL = 1000 * 60 * 5;\n\n/**\n * The cookie carrying the pending login between the provider callback and the\n * hosted page that completes it.\n *\n * A cookie rather than a query parameter, which is what Keycloak and Authentik\n * both do: the browser that STARTED the login is the only one that can present\n * it, no other origin can set it, and nothing redeemable travels in a URL that\n * reaches history, logs or a referrer. `SameSite=Lax` keeps it off cross-site\n * requests, so a page on another origin cannot drive the completion.\n */\nexport const OAUTH2_FEDERATED_LOGIN_COOKIE = 'authup_federated_login';\n"],"mappings":";;;;;;;;;;;;GAgBA,MAAaA,6BAA6B;;;;;;;;;;GAY1C,MAAaC,gCAAgC"}
@@ -0,0 +1,4 @@
1
+ export * from './constants.ts';
2
+ export * from './module.ts';
3
+ export * from './types.ts';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/core/oauth2/federated-login/index.ts"],"names":[],"mappings":"AAOA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,7 @@
1
+ import "node:path";
2
+ import "node:url";
3
+ import.meta.url;
4
+ import { OAUTH2_FEDERATED_LOGIN_COOKIE, OAUTH2_FEDERATED_LOGIN_TTL } from "./constants.mjs";
5
+ import { OAuth2FederatedLoginRefusal } from "./types.mjs";
6
+ import { OAuth2FederatedLoginService } from "./module.mjs";
7
+ export { OAUTH2_FEDERATED_LOGIN_COOKIE, OAUTH2_FEDERATED_LOGIN_TTL, OAuth2FederatedLoginRefusal, OAuth2FederatedLoginService };
@@ -0,0 +1,29 @@
1
+ import type { Logger } from '@authup/server-kit';
2
+ import type { OAuth2TokenGrantResponse } from '@authup/specs';
3
+ import type { IEventService, IRealmRepository } from '../../entities/index.ts';
4
+ import type { IAuthFlowMetrics } from '../../metrics/index.ts';
5
+ import type { ISessionManager } from '../../authentication/index.ts';
6
+ import type { IIdentityProviderAccountManager } from '../../identity/provider/account/types.ts';
7
+ import type { IOAuth2AccessPolicyEvaluator } from '../access-policy/index.ts';
8
+ import type { IOAuth2AuthorizationCodeRequestVerifier } from '../authorization/index.ts';
9
+ import type { IOAuth2TokenIssuer } from '../token/index.ts';
10
+ import type { IOAuth2FederatedLoginService, IOAuth2FederatedLoginStore, OAuth2FederatedLoginAuthenticatorFactory, OAuth2FederatedLoginCompleteHandoffInput, OAuth2FederatedLoginCompleteInput, OAuth2FederatedLoginCompleteResult, OAuth2FederatedLoginServiceContext, OAuth2FederatedLoginServiceOptions } from './types.ts';
11
+ export declare class OAuth2FederatedLoginService implements IOAuth2FederatedLoginService {
12
+ protected options: OAuth2FederatedLoginServiceOptions;
13
+ protected accountManager: IIdentityProviderAccountManager;
14
+ protected realmRepository: IRealmRepository;
15
+ protected codeRequestVerifier: IOAuth2AuthorizationCodeRequestVerifier;
16
+ protected sessionManager: ISessionManager;
17
+ protected pendingLoginStore: IOAuth2FederatedLoginStore;
18
+ protected accessTokenIssuer: IOAuth2TokenIssuer;
19
+ protected refreshTokenIssuer: IOAuth2TokenIssuer;
20
+ protected accessPolicyEvaluator?: IOAuth2AccessPolicyEvaluator;
21
+ protected eventService?: IEventService;
22
+ protected metrics?: IAuthFlowMetrics;
23
+ protected logger?: Logger;
24
+ protected authenticatorFactory: OAuth2FederatedLoginAuthenticatorFactory;
25
+ constructor(ctx: OAuth2FederatedLoginServiceContext);
26
+ complete(input: OAuth2FederatedLoginCompleteInput): Promise<OAuth2FederatedLoginCompleteResult>;
27
+ completeHandoff(input: OAuth2FederatedLoginCompleteHandoffInput): Promise<OAuth2TokenGrantResponse>;
28
+ }
29
+ //# sourceMappingURL=module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.d.ts","sourceRoot":"","sources":["../../../../src/core/oauth2/federated-login/module.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AC;IAExC,SAAS,CAAC,OAAO,CAAC,EAAG,gBAAgB,CAAC;IAEtC,SAAS,CAAC,MAAM,CAAC,EAAG,MAAM,CAAC;IAE3B,SAAS,CAAC,oBAAoB,EAAG,wCAAwC,CAAC;gBAE9D,GAAG,EAAE,kCAAkC;IAyB7C,QAAQ,CAAC,KAAK,EAAE,iCAAiC,GAAG,OAAO,CAAC,kCAAkC,CAAC;IA4L/F,eAAe,CAAC,KAAK,EAAE,wCAAwC,GAAG,OAAO,CAAC,wBAAwB,CAAC;CAqF5G"}
@@ -0,0 +1,193 @@
1
+ import "node:path";
2
+ import "node:url";
3
+ import.meta.url;
4
+ import { deriveAmrAcr } from "../authorization/helpers.mjs";
5
+ import { toIdentityPolicyData } from "../../identity/permission/identity-policy-data.mjs";
6
+ import { OAUTH2_FEDERATED_LOGIN_TTL } from "./constants.mjs";
7
+ import { describeError } from "../../../utils/error.mjs";
8
+ import "../../../utils/index.mjs";
9
+ import { isIdentityProviderAssuranceError } from "../../identity/provider/authentication/protocols/oauth2/assurance.mjs";
10
+ import { createIdentityProviderOAuth2Authenticator } from "../../identity/provider/authentication/factory.mjs";
11
+ import { buildOAuth2BearerTokenResponse } from "../response/bearer.mjs";
12
+ import { OAuth2FederatedLoginRefusal } from "./types.mjs";
13
+ import { isSafeRedirectURLScheme } from "@authup/kit";
14
+ import { EventName, EventRefType, EventScope, IdentityType, ScopeName, SessionAuthMethod } from "@authup/core-kit";
15
+ import { BadRequestError, InternalError } from "@authup/errors";
16
+ import { OAuth2ErrorCode, OAuth2RequestError, OAuth2SubKind, isOAuth2Error } from "@authup/specs";
17
+ //#region src/core/oauth2/federated-login/module.ts
18
+ var OAuth2FederatedLoginService = class {
19
+ options;
20
+ accountManager;
21
+ realmRepository;
22
+ codeRequestVerifier;
23
+ sessionManager;
24
+ pendingLoginStore;
25
+ accessTokenIssuer;
26
+ refreshTokenIssuer;
27
+ accessPolicyEvaluator;
28
+ eventService;
29
+ metrics;
30
+ logger;
31
+ authenticatorFactory;
32
+ constructor(ctx) {
33
+ this.options = ctx.options;
34
+ this.accountManager = ctx.accountManager;
35
+ this.realmRepository = ctx.realmRepository;
36
+ this.codeRequestVerifier = ctx.codeRequestVerifier;
37
+ this.sessionManager = ctx.sessionManager;
38
+ this.pendingLoginStore = ctx.pendingLoginStore;
39
+ this.accessTokenIssuer = ctx.accessTokenIssuer;
40
+ this.refreshTokenIssuer = ctx.refreshTokenIssuer;
41
+ this.accessPolicyEvaluator = ctx.accessPolicyEvaluator;
42
+ this.eventService = ctx.eventService;
43
+ this.metrics = ctx.metrics;
44
+ this.logger = ctx.logger;
45
+ this.authenticatorFactory = ctx.authenticatorFactory ?? ((provider, options) => createIdentityProviderOAuth2Authenticator({
46
+ accountManager: this.accountManager,
47
+ provider,
48
+ logger: options.logger,
49
+ options: {
50
+ baseURL: options.baseURL,
51
+ clientId: options.clientId
52
+ }
53
+ }));
54
+ }
55
+ async complete(input) {
56
+ const { code, codeRequest, provider } = input;
57
+ let verified;
58
+ try {
59
+ verified = await this.codeRequestVerifier.verify(codeRequest);
60
+ } catch (e) {
61
+ if (!isOAuth2Error(e)) throw e;
62
+ return {
63
+ kind: "refused",
64
+ refusal: OAuth2FederatedLoginRefusal.CODE_REQUEST,
65
+ codeRequest
66
+ };
67
+ }
68
+ if (provider.realmId && verified.client.realmId !== provider.realmId) throw OAuth2RequestError.malformed("The provider and client realm do not match.");
69
+ const redirectUri = verified.data.redirect_uri;
70
+ if (!verified.redirectUriVerified || !redirectUri) throw OAuth2RequestError.malformed("The redirect_uri was not verified.");
71
+ if (!isSafeRedirectURLScheme(redirectUri)) throw new InternalError("The redirect_uri scheme is not allowed.");
72
+ if (!provider.enabled) return {
73
+ kind: "refused",
74
+ refusal: OAuth2FederatedLoginRefusal.PROVIDER_DISABLED,
75
+ error: OAuth2ErrorCode.LOGIN_REQUIRED,
76
+ codeRequest: verified.data
77
+ };
78
+ const authenticator = this.authenticatorFactory(provider, {
79
+ baseURL: this.options.baseURL,
80
+ clientId: verified.data.client_id,
81
+ logger: this.logger
82
+ });
83
+ let user;
84
+ try {
85
+ user = await authenticator.authenticate({ code });
86
+ } catch (e) {
87
+ if (!isIdentityProviderAssuranceError(e)) throw e;
88
+ this.logger?.warn(describeError(e, `The identity provider (${provider.id}) login was refused.`));
89
+ return {
90
+ kind: "refused",
91
+ refusal: OAuth2FederatedLoginRefusal.ASSURANCE_INSUFFICIENT,
92
+ error: OAuth2ErrorCode.ACCESS_DENIED,
93
+ codeRequest: verified.data
94
+ };
95
+ }
96
+ if (!user.active) return {
97
+ kind: "refused",
98
+ refusal: OAuth2FederatedLoginRefusal.USER_INACTIVE,
99
+ error: OAuth2ErrorCode.ACCESS_DENIED,
100
+ codeRequest: verified.data
101
+ };
102
+ if (verified.client.accessPolicyId) {
103
+ const realm = await this.realmRepository.resolve(provider.realmId, true);
104
+ let allowed = false;
105
+ const subject = toIdentityPolicyData({
106
+ type: IdentityType.USER,
107
+ data: {
108
+ ...user,
109
+ realm
110
+ }
111
+ });
112
+ if (this.accessPolicyEvaluator && subject) allowed = await this.accessPolicyEvaluator.evaluate(verified.client.accessPolicyId, subject);
113
+ if (!allowed) return {
114
+ kind: "refused",
115
+ refusal: OAuth2FederatedLoginRefusal.ACCESS_DENIED,
116
+ error: OAuth2ErrorCode.ACCESS_DENIED,
117
+ codeRequest: verified.data
118
+ };
119
+ }
120
+ const session = await this.sessionManager.create({
121
+ userAgent: input.request?.userAgent ?? void 0,
122
+ ipAddress: input.request?.ipAddress ?? void 0,
123
+ realmId: user.realmId,
124
+ sub: user.id,
125
+ subKind: IdentityType.USER,
126
+ mfaAt: null,
127
+ authMethod: SessionAuthMethod.EXTERNAL,
128
+ expiresAt: new Date(Date.now() + OAUTH2_FEDERATED_LOGIN_TTL).toISOString()
129
+ });
130
+ return {
131
+ kind: "issued",
132
+ pendingLoginId: await this.pendingLoginStore.save({
133
+ sessionId: session.id,
134
+ providerId: provider.id,
135
+ userName: user.name
136
+ }),
137
+ codeRequest: verified.data
138
+ };
139
+ }
140
+ async completeHandoff(input) {
141
+ const refuse = () => new BadRequestError("The login request is unknown or expired.");
142
+ const pending = await this.pendingLoginStore.consume(input.pendingLoginId);
143
+ if (!pending) throw refuse();
144
+ if (pending.providerId !== input.providerId) throw refuse();
145
+ const existing = await this.sessionManager.findOneById(pending.sessionId);
146
+ if (!existing) throw refuse();
147
+ if (Date.parse(existing.expiresAt) <= Date.now()) throw refuse();
148
+ const realm = await this.realmRepository.resolve(existing.realmId, true);
149
+ const session = await this.sessionManager.refresh(existing);
150
+ const payload = {
151
+ session_id: session.id,
152
+ user_agent: session.userAgent,
153
+ remote_address: session.ipAddress,
154
+ scope: ScopeName.GLOBAL,
155
+ sub: session.sub,
156
+ sub_kind: OAuth2SubKind.USER,
157
+ realm_id: session.realmId,
158
+ realm_name: realm.name,
159
+ ...deriveAmrAcr(session)
160
+ };
161
+ const [accessToken, accessTokenPayload] = await this.accessTokenIssuer.issue(payload);
162
+ const [refreshToken, refreshTokenPayload] = await this.refreshTokenIssuer.issue(payload);
163
+ await this.eventService?.record({
164
+ scope: EventScope.OAUTH2,
165
+ name: EventName.LOGIN,
166
+ refType: EventRefType.SESSION,
167
+ refId: session.id,
168
+ clientId: null,
169
+ sessionId: session.id,
170
+ actorType: IdentityType.USER,
171
+ actorId: session.sub,
172
+ actorName: pending.userName ?? null,
173
+ realmId: session.realmId,
174
+ requestIpAddress: session.ipAddress ?? null,
175
+ requestUserAgent: session.userAgent ?? null,
176
+ data: {
177
+ reason: "federated",
178
+ providerId: pending.providerId
179
+ }
180
+ });
181
+ this.metrics?.recordLogin("success");
182
+ return buildOAuth2BearerTokenResponse({
183
+ accessToken,
184
+ accessTokenPayload,
185
+ refreshToken,
186
+ refreshTokenPayload
187
+ });
188
+ }
189
+ };
190
+ //#endregion
191
+ export { OAuth2FederatedLoginService };
192
+
193
+ //# sourceMappingURL=module.mjs.map