alepha 0.13.7 → 0.14.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/README.md +5 -2
- package/assets/swagger-ui/swagger-ui-bundle.js +1 -1
- package/assets/swagger-ui/swagger-ui-standalone-preset.js +1 -1
- package/assets/swagger-ui/swagger-ui.css +1 -1
- package/dist/{api-audits → api/audits}/index.browser.js +4 -4
- package/dist/api/audits/index.browser.js.map +1 -0
- package/dist/{api-audits → api/audits}/index.d.ts +10 -9
- package/dist/api/audits/index.d.ts.map +1 -0
- package/dist/{api-audits → api/audits}/index.js +8 -8
- package/dist/api/audits/index.js.map +1 -0
- package/dist/{api-files → api/files}/index.browser.js +5 -5
- package/dist/api/files/index.browser.js.map +1 -0
- package/dist/{api-files → api/files}/index.d.ts +18 -10
- package/dist/api/files/index.d.ts.map +1 -0
- package/dist/{api-files → api/files}/index.js +10 -10
- package/dist/api/files/index.js.map +1 -0
- package/dist/{api-jobs → api/jobs}/index.browser.js +5 -5
- package/dist/api/jobs/index.browser.js.map +1 -0
- package/dist/{api-jobs → api/jobs}/index.d.ts +168 -167
- package/dist/api/jobs/index.d.ts.map +1 -0
- package/dist/{api-jobs → api/jobs}/index.js +9 -9
- package/dist/api/jobs/index.js.map +1 -0
- package/dist/{api-notifications → api/notifications}/index.browser.js +11 -11
- package/dist/api/notifications/index.browser.js.map +1 -0
- package/dist/api/notifications/index.d.ts +327 -0
- package/dist/api/notifications/index.d.ts.map +1 -0
- package/dist/{api-notifications → api/notifications}/index.js +11 -11
- package/dist/api/notifications/index.js.map +1 -0
- package/dist/{api-parameters → api/parameters}/index.browser.js +2 -2
- package/dist/api/parameters/index.browser.js.map +1 -0
- package/dist/{api-parameters → api/parameters}/index.d.ts +11 -11
- package/dist/api/parameters/index.d.ts.map +1 -0
- package/dist/{api-parameters → api/parameters}/index.js +7 -7
- package/dist/api/parameters/index.js.map +1 -0
- package/dist/{api-users → api/users}/index.browser.js +6 -6
- package/dist/api/users/index.browser.js.map +1 -0
- package/dist/{api-users → api/users}/index.d.ts +836 -836
- package/dist/api/users/index.d.ts.map +1 -0
- package/dist/{api-users → api/users}/index.js +99 -766
- package/dist/api/users/index.js.map +1 -0
- package/dist/{api-verifications → api/verifications}/index.browser.js +5 -5
- package/dist/api/verifications/index.browser.js.map +1 -0
- package/dist/api/verifications/index.d.ts +248 -0
- package/dist/api/verifications/index.d.ts.map +1 -0
- package/dist/{api-verifications → api/verifications}/index.js +11 -11
- package/dist/api/verifications/index.js.map +1 -0
- package/dist/batch/index.d.ts.map +1 -0
- package/dist/bucket/index.d.ts.map +1 -0
- package/dist/cache/{index.d.ts → core/index.d.ts} +4 -4
- package/dist/cache/core/index.d.ts.map +1 -0
- package/dist/cache/{index.js → core/index.js} +5 -5
- package/dist/cache/core/index.js.map +1 -0
- package/dist/{cache-redis → cache/redis}/index.d.ts +2 -2
- package/dist/cache/redis/index.d.ts.map +1 -0
- package/dist/{cache-redis → cache/redis}/index.js +2 -2
- package/dist/cache/redis/index.js.map +1 -0
- package/dist/cli/index.d.ts +78 -58
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +454 -154
- package/dist/cli/index.js.map +1 -1
- package/dist/command/index.d.ts +15 -5
- package/dist/command/index.d.ts.map +1 -0
- package/dist/command/index.js +45 -6
- package/dist/command/index.js.map +1 -1
- package/dist/core/index.browser.js +1334 -1318
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.d.ts +75 -71
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +1337 -1321
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js +1337 -1321
- package/dist/core/index.native.js.map +1 -1
- package/dist/datetime/index.d.ts.map +1 -0
- package/dist/email/index.d.ts.map +1 -0
- package/dist/fake/index.d.ts.map +1 -0
- package/dist/file/index.d.ts.map +1 -0
- package/dist/lock/{index.d.ts → core/index.d.ts} +5 -5
- package/dist/lock/core/index.d.ts.map +1 -0
- package/dist/lock/{index.js → core/index.js} +5 -5
- package/dist/lock/core/index.js.map +1 -0
- package/dist/{lock-redis → lock/redis}/index.d.ts +2 -2
- package/dist/lock/redis/index.d.ts.map +1 -0
- package/dist/{lock-redis → lock/redis}/index.js +2 -2
- package/dist/lock/redis/index.js.map +1 -0
- package/dist/logger/index.d.ts +1 -0
- package/dist/logger/index.d.ts.map +1 -0
- package/dist/mcp/index.d.ts +820 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +978 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/orm/index.d.ts +180 -107
- package/dist/orm/index.d.ts.map +1 -0
- package/dist/orm/index.js +260 -174
- package/dist/orm/index.js.map +1 -1
- package/dist/queue/core/index.d.ts +548 -0
- package/dist/queue/core/index.d.ts.map +1 -0
- package/dist/queue/core/index.js +391 -0
- package/dist/queue/core/index.js.map +1 -0
- package/dist/queue/redis/index.d.ts +28 -0
- package/dist/queue/redis/index.d.ts.map +1 -0
- package/dist/queue/redis/index.js +43 -0
- package/dist/queue/redis/index.js.map +1 -0
- package/dist/redis/index.d.ts.map +1 -0
- package/dist/retry/index.d.ts.map +1 -0
- package/dist/router/index.d.ts.map +1 -0
- package/dist/scheduler/index.d.ts +1 -1
- package/dist/scheduler/index.d.ts.map +1 -0
- package/dist/scheduler/index.js +1 -393
- package/dist/scheduler/index.js.map +1 -1
- package/dist/security/index.d.ts +1 -1
- package/dist/security/index.d.ts.map +1 -0
- package/dist/security/index.js +2 -1413
- package/dist/security/index.js.map +1 -1
- package/dist/{server-auth → server/auth}/index.browser.js +6 -6
- package/dist/server/auth/index.browser.js.map +1 -0
- package/dist/{server-auth → server/auth}/index.d.ts +167 -167
- package/dist/server/auth/index.d.ts.map +1 -0
- package/dist/server/auth/index.js +742 -0
- package/dist/server/auth/index.js.map +1 -0
- package/dist/{server-cache → server/cache}/index.d.ts +2 -2
- package/dist/server/cache/index.d.ts.map +1 -0
- package/dist/{server-cache → server/cache}/index.js +2 -2
- package/dist/server/cache/index.js.map +1 -0
- package/dist/{server-compress → server/compress}/index.d.ts +2 -2
- package/dist/server/compress/index.d.ts.map +1 -0
- package/dist/{server-compress → server/compress}/index.js +2 -2
- package/dist/server/compress/index.js.map +1 -0
- package/dist/{server-cookies → server/cookies}/index.browser.js +3 -3
- package/dist/server/cookies/index.browser.js.map +1 -0
- package/dist/{server-cookies → server/cookies}/index.d.ts +4 -4
- package/dist/server/cookies/index.d.ts.map +1 -0
- package/dist/{server-cookies → server/cookies}/index.js +4 -4
- package/dist/server/cookies/index.js.map +1 -0
- package/dist/server/{index.browser.js → core/index.browser.js} +14 -14
- package/dist/server/core/index.browser.js.map +1 -0
- package/dist/server/{index.d.ts → core/index.d.ts} +36 -36
- package/dist/server/core/index.d.ts.map +1 -0
- package/dist/server/{index.js → core/index.js} +27 -27
- package/dist/server/core/index.js.map +1 -0
- package/dist/{server-cors → server/cors}/index.d.ts +3 -3
- package/dist/server/cors/index.d.ts.map +1 -0
- package/dist/{server-cors → server/cors}/index.js +3 -3
- package/dist/server/cors/index.js.map +1 -0
- package/dist/{server-health → server/health}/index.d.ts +3 -3
- package/dist/server/health/index.d.ts.map +1 -0
- package/dist/{server-health → server/health}/index.js +3 -3
- package/dist/server/health/index.js.map +1 -0
- package/dist/{server-helmet → server/helmet}/index.d.ts +2 -2
- package/dist/server/helmet/index.d.ts.map +1 -0
- package/dist/{server-helmet → server/helmet}/index.js +2 -2
- package/dist/server/helmet/index.js.map +1 -0
- package/dist/{server-links → server/links}/index.browser.js +5 -5
- package/dist/server/links/index.browser.js.map +1 -0
- package/dist/{server-links → server/links}/index.d.ts +40 -40
- package/dist/server/links/index.d.ts.map +1 -0
- package/dist/{server-links → server/links}/index.js +7 -7
- package/dist/server/links/index.js.map +1 -0
- package/dist/{server-metrics → server/metrics}/index.d.ts +2 -2
- package/dist/server/metrics/index.d.ts.map +1 -0
- package/dist/server/metrics/index.js +74 -0
- package/dist/server/metrics/index.js.map +1 -0
- package/dist/{server-multipart → server/multipart}/index.d.ts +2 -2
- package/dist/server/multipart/index.d.ts.map +1 -0
- package/dist/{server-multipart → server/multipart}/index.js +2 -2
- package/dist/server/multipart/index.js.map +1 -0
- package/dist/{server-proxy → server/proxy}/index.d.ts +3 -3
- package/dist/server/proxy/index.d.ts.map +1 -0
- package/dist/{server-proxy → server/proxy}/index.js +3 -3
- package/dist/server/proxy/index.js.map +1 -0
- package/dist/{server-rate-limit → server/rate-limit}/index.d.ts +4 -4
- package/dist/server/rate-limit/index.d.ts.map +1 -0
- package/dist/{server-rate-limit → server/rate-limit}/index.js +4 -4
- package/dist/server/rate-limit/index.js.map +1 -0
- package/dist/{server-security → server/security}/index.browser.js +1 -1
- package/dist/server/security/index.browser.js.map +1 -0
- package/dist/{server-security → server/security}/index.d.ts +4 -4
- package/dist/server/security/index.d.ts.map +1 -0
- package/dist/{server-security → server/security}/index.js +4 -4
- package/dist/server/security/index.js.map +1 -0
- package/dist/{server-static → server/static}/index.d.ts +3 -3
- package/dist/server/static/index.d.ts.map +1 -0
- package/dist/{server-static → server/static}/index.js +3 -3
- package/dist/server/static/index.js.map +1 -0
- package/dist/{server-swagger → server/swagger}/index.d.ts +3 -3
- package/dist/server/swagger/index.d.ts.map +1 -0
- package/dist/{server-swagger → server/swagger}/index.js +4 -4
- package/dist/server/swagger/index.js.map +1 -0
- package/dist/sms/index.d.ts.map +1 -0
- package/dist/thread/index.d.ts.map +1 -0
- package/dist/topic/{index.d.ts → core/index.d.ts} +6 -6
- package/dist/topic/core/index.d.ts.map +1 -0
- package/dist/topic/{index.js → core/index.js} +6 -6
- package/dist/topic/core/index.js.map +1 -0
- package/dist/{topic-redis → topic/redis}/index.d.ts +2 -2
- package/dist/topic/redis/index.d.ts.map +1 -0
- package/dist/{topic-redis → topic/redis}/index.js +2 -2
- package/dist/topic/redis/index.js.map +1 -0
- package/dist/vite/index.d.ts +21 -2
- package/dist/vite/index.d.ts.map +1 -0
- package/dist/vite/index.js +48 -19
- package/dist/vite/index.js.map +1 -1
- package/dist/websocket/index.d.ts.map +1 -0
- package/package.json +162 -158
- package/src/{api-files → api/files}/index.ts +1 -0
- package/src/{api-parameters → api/parameters}/index.ts +1 -1
- package/src/{api-users → api/users}/primitives/$userRealm.ts +1 -1
- package/src/{api-users → api/users}/providers/UserRealmProvider.ts +6 -7
- package/src/{api-verifications → api/verifications}/index.ts +2 -0
- package/src/cli/apps/AlephaCli.ts +2 -0
- package/src/cli/apps/AlephaPackageBuilderCli.ts +83 -54
- package/src/cli/assets/appRouterTs.ts +1 -1
- package/src/cli/assets/biomeJson.ts +1 -1
- package/src/cli/assets/indexHtml.ts +1 -1
- package/src/cli/assets/mainBrowserTs.ts +1 -1
- package/src/cli/assets/mainTs.ts +9 -10
- package/src/cli/assets/viteConfigTs.ts +1 -1
- package/src/cli/commands/ChangelogCommands.ts +389 -0
- package/src/cli/commands/CoreCommands.ts +10 -6
- package/src/cli/commands/DrizzleCommands.ts +204 -4
- package/src/cli/commands/VerifyCommands.ts +4 -1
- package/src/cli/commands/ViteCommands.ts +46 -25
- package/src/cli/services/AlephaCliUtils.ts +52 -164
- package/src/command/providers/CliProvider.ts +76 -5
- package/src/core/providers/SchemaValidator.ts +24 -2
- package/src/mcp/errors/McpError.ts +72 -0
- package/src/mcp/helpers/jsonrpc.ts +163 -0
- package/src/mcp/index.ts +132 -0
- package/src/mcp/interfaces/McpTypes.ts +248 -0
- package/src/mcp/primitives/$prompt.ts +188 -0
- package/src/mcp/primitives/$resource.ts +171 -0
- package/src/mcp/primitives/$tool.ts +285 -0
- package/src/mcp/providers/McpServerProvider.ts +382 -0
- package/src/mcp/transports/SseMcpTransport.ts +172 -0
- package/src/mcp/transports/StdioMcpTransport.ts +126 -0
- package/src/orm/index.ts +12 -0
- package/src/orm/providers/drivers/CloudflareD1Provider.ts +164 -0
- package/src/orm/providers/drivers/NodeSqliteProvider.ts +3 -1
- package/src/queue/{index.ts → core/index.ts} +2 -3
- package/src/queue/{primitives → core/primitives}/$queue.ts +17 -162
- package/src/queue/core/providers/MemoryQueueProvider.ts +19 -0
- package/src/queue/core/providers/QueueProvider.ts +23 -0
- package/src/queue/core/providers/WorkerProvider.ts +244 -0
- package/src/queue/redis/providers/RedisQueueProvider.ts +31 -0
- package/src/server/{index.ts → core/index.ts} +1 -0
- package/src/{server-rate-limit → server/rate-limit}/index.ts +1 -1
- package/src/{server-swagger → server/swagger}/providers/ServerSwaggerProvider.ts +1 -0
- package/src/vite/plugins/viteAlephaBuild.ts +8 -2
- package/src/vite/plugins/viteAlephaDev.ts +6 -2
- package/src/vite/tasks/buildServer.ts +1 -1
- package/src/vite/tasks/copyAssets.ts +32 -8
- package/src/vite/tasks/generateCloudflare.ts +43 -15
- package/src/vite/tasks/runAlepha.ts +1 -0
- package/dist/api-audits/index.browser.js.map +0 -1
- package/dist/api-audits/index.js.map +0 -1
- package/dist/api-files/index.browser.js.map +0 -1
- package/dist/api-files/index.js.map +0 -1
- package/dist/api-jobs/index.browser.js.map +0 -1
- package/dist/api-jobs/index.js.map +0 -1
- package/dist/api-notifications/index.browser.js.map +0 -1
- package/dist/api-notifications/index.d.ts +0 -327
- package/dist/api-notifications/index.js.map +0 -1
- package/dist/api-parameters/index.browser.js.map +0 -1
- package/dist/api-parameters/index.js.map +0 -1
- package/dist/api-users/index.browser.js.map +0 -1
- package/dist/api-users/index.js.map +0 -1
- package/dist/api-verifications/index.browser.js.map +0 -1
- package/dist/api-verifications/index.d.ts +0 -229
- package/dist/api-verifications/index.js.map +0 -1
- package/dist/cache/index.js.map +0 -1
- package/dist/cache-redis/index.js.map +0 -1
- package/dist/lock/index.js.map +0 -1
- package/dist/lock-redis/index.js.map +0 -1
- package/dist/queue/index.d.ts +0 -1265
- package/dist/queue/index.js +0 -1037
- package/dist/queue/index.js.map +0 -1
- package/dist/queue-redis/index.d.ts +0 -82
- package/dist/queue-redis/index.js +0 -872
- package/dist/queue-redis/index.js.map +0 -1
- package/dist/server/index.browser.js.map +0 -1
- package/dist/server/index.js.map +0 -1
- package/dist/server-auth/index.browser.js.map +0 -1
- package/dist/server-auth/index.js +0 -1973
- package/dist/server-auth/index.js.map +0 -1
- package/dist/server-cache/index.js.map +0 -1
- package/dist/server-compress/index.js.map +0 -1
- package/dist/server-cookies/index.browser.js.map +0 -1
- package/dist/server-cookies/index.js.map +0 -1
- package/dist/server-cors/index.js.map +0 -1
- package/dist/server-health/index.js.map +0 -1
- package/dist/server-helmet/index.js.map +0 -1
- package/dist/server-links/index.browser.js.map +0 -1
- package/dist/server-links/index.js.map +0 -1
- package/dist/server-metrics/index.js +0 -4532
- package/dist/server-metrics/index.js.map +0 -1
- package/dist/server-multipart/index.js.map +0 -1
- package/dist/server-proxy/index.js.map +0 -1
- package/dist/server-rate-limit/index.js.map +0 -1
- package/dist/server-security/index.browser.js.map +0 -1
- package/dist/server-security/index.js.map +0 -1
- package/dist/server-static/index.js.map +0 -1
- package/dist/server-swagger/index.js.map +0 -1
- package/dist/topic/index.js.map +0 -1
- package/dist/topic-redis/index.js.map +0 -1
- package/src/queue/interfaces/QueueJob.ts +0 -459
- package/src/queue/providers/MemoryQueueProvider.ts +0 -850
- package/src/queue/providers/QueueProvider.ts +0 -319
- package/src/queue/providers/WorkerProvider.ts +0 -344
- package/src/queue-redis/providers/RedisQueueProvider.ts +0 -1209
- /package/src/{api-audits → api/audits}/controllers/AuditController.ts +0 -0
- /package/src/{api-audits → api/audits}/entities/audits.ts +0 -0
- /package/src/{api-audits → api/audits}/index.browser.ts +0 -0
- /package/src/{api-audits → api/audits}/index.ts +0 -0
- /package/src/{api-audits → api/audits}/primitives/$audit.ts +0 -0
- /package/src/{api-audits → api/audits}/schemas/auditQuerySchema.ts +0 -0
- /package/src/{api-audits → api/audits}/schemas/auditResourceSchema.ts +0 -0
- /package/src/{api-audits → api/audits}/schemas/createAuditSchema.ts +0 -0
- /package/src/{api-audits → api/audits}/services/AuditService.ts +0 -0
- /package/src/{api-files → api/files}/controllers/FileController.ts +0 -0
- /package/src/{api-files → api/files}/controllers/StorageStatsController.ts +0 -0
- /package/src/{api-files → api/files}/entities/files.ts +0 -0
- /package/src/{api-files → api/files}/index.browser.ts +0 -0
- /package/src/{api-files → api/files}/jobs/FileJobs.ts +0 -0
- /package/src/{api-files → api/files}/schemas/fileQuerySchema.ts +0 -0
- /package/src/{api-files → api/files}/schemas/fileResourceSchema.ts +0 -0
- /package/src/{api-files → api/files}/schemas/storageStatsSchema.ts +0 -0
- /package/src/{api-files → api/files}/services/FileService.ts +0 -0
- /package/src/{api-jobs → api/jobs}/controllers/JobController.ts +0 -0
- /package/src/{api-jobs → api/jobs}/entities/jobExecutions.ts +0 -0
- /package/src/{api-jobs → api/jobs}/index.browser.ts +0 -0
- /package/src/{api-jobs → api/jobs}/index.ts +0 -0
- /package/src/{api-jobs → api/jobs}/primitives/$job.ts +0 -0
- /package/src/{api-jobs → api/jobs}/providers/JobProvider.ts +0 -0
- /package/src/{api-jobs → api/jobs}/schemas/jobExecutionQuerySchema.ts +0 -0
- /package/src/{api-jobs → api/jobs}/schemas/jobExecutionResourceSchema.ts +0 -0
- /package/src/{api-jobs → api/jobs}/schemas/triggerJobSchema.ts +0 -0
- /package/src/{api-jobs → api/jobs}/services/JobService.ts +0 -0
- /package/src/{api-notifications → api/notifications}/controllers/NotificationController.ts +0 -0
- /package/src/{api-notifications → api/notifications}/entities/notifications.ts +0 -0
- /package/src/{api-notifications → api/notifications}/index.browser.ts +0 -0
- /package/src/{api-notifications → api/notifications}/index.ts +0 -0
- /package/src/{api-notifications → api/notifications}/jobs/NotificationJobs.ts +0 -0
- /package/src/{api-notifications → api/notifications}/primitives/$notification.ts +0 -0
- /package/src/{api-notifications → api/notifications}/queues/NotificationQueues.ts +0 -0
- /package/src/{api-notifications → api/notifications}/schemas/notificationContactPreferencesSchema.ts +0 -0
- /package/src/{api-notifications → api/notifications}/schemas/notificationContactSchema.ts +0 -0
- /package/src/{api-notifications → api/notifications}/schemas/notificationCreateSchema.ts +0 -0
- /package/src/{api-notifications → api/notifications}/schemas/notificationQuerySchema.ts +0 -0
- /package/src/{api-notifications → api/notifications}/services/NotificationSenderService.ts +0 -0
- /package/src/{api-notifications → api/notifications}/services/NotificationService.ts +0 -0
- /package/src/{api-parameters → api/parameters}/controllers/ConfigController.ts +0 -0
- /package/src/{api-parameters → api/parameters}/entities/parameters.ts +0 -0
- /package/src/{api-parameters → api/parameters}/index.browser.ts +0 -0
- /package/src/{api-parameters → api/parameters}/primitives/$config.ts +0 -0
- /package/src/{api-parameters → api/parameters}/schedulers/ConfigActivationScheduler.ts +0 -0
- /package/src/{api-parameters → api/parameters}/services/ConfigStore.ts +0 -0
- /package/src/{api-users → api/users}/atoms/realmAuthSettingsAtom.ts +0 -0
- /package/src/{api-users → api/users}/controllers/IdentityController.ts +0 -0
- /package/src/{api-users → api/users}/controllers/SessionController.ts +0 -0
- /package/src/{api-users → api/users}/controllers/UserController.ts +0 -0
- /package/src/{api-users → api/users}/controllers/UserRealmController.ts +0 -0
- /package/src/{api-users → api/users}/entities/identities.ts +0 -0
- /package/src/{api-users → api/users}/entities/sessions.ts +0 -0
- /package/src/{api-users → api/users}/entities/users.ts +0 -0
- /package/src/{api-users → api/users}/index.browser.ts +0 -0
- /package/src/{api-users → api/users}/index.ts +0 -0
- /package/src/{api-users → api/users}/notifications/UserNotifications.ts +0 -0
- /package/src/{api-users → api/users}/schemas/completePasswordResetRequestSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/completeRegistrationRequestSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/createUserSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/identityQuerySchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/identityResourceSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/loginSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/passwordResetIntentResponseSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/registerQuerySchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/registerRequestSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/registerResponseSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/registerSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/registrationIntentResponseSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/resetPasswordSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/sessionQuerySchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/sessionResourceSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/updateUserSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/userQuerySchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/userRealmConfigSchema.ts +0 -0
- /package/src/{api-users → api/users}/schemas/userResourceSchema.ts +0 -0
- /package/src/{api-users → api/users}/services/CredentialService.ts +0 -0
- /package/src/{api-users → api/users}/services/IdentityService.ts +0 -0
- /package/src/{api-users → api/users}/services/RegistrationService.ts +0 -0
- /package/src/{api-users → api/users}/services/SessionCrudService.ts +0 -0
- /package/src/{api-users → api/users}/services/SessionService.ts +0 -0
- /package/src/{api-users → api/users}/services/UserService.ts +0 -0
- /package/src/{api-verifications → api/verifications}/controllers/VerificationController.ts +0 -0
- /package/src/{api-verifications → api/verifications}/entities/verifications.ts +0 -0
- /package/src/{api-verifications → api/verifications}/index.browser.ts +0 -0
- /package/src/{api-verifications → api/verifications}/jobs/VerificationJobs.ts +0 -0
- /package/src/{api-verifications → api/verifications}/parameters/VerificationParameters.ts +0 -0
- /package/src/{api-verifications → api/verifications}/schemas/requestVerificationCodeResponseSchema.ts +0 -0
- /package/src/{api-verifications → api/verifications}/schemas/validateVerificationCodeResponseSchema.ts +0 -0
- /package/src/{api-verifications → api/verifications}/schemas/verificationSettingsSchema.ts +0 -0
- /package/src/{api-verifications → api/verifications}/schemas/verificationTypeEnumSchema.ts +0 -0
- /package/src/{api-verifications → api/verifications}/services/VerificationService.ts +0 -0
- /package/src/cache/{errors → core/errors}/CacheError.ts +0 -0
- /package/src/cache/{index.ts → core/index.ts} +0 -0
- /package/src/cache/{primitives → core/primitives}/$cache.ts +0 -0
- /package/src/cache/{providers → core/providers}/CacheProvider.ts +0 -0
- /package/src/cache/{providers → core/providers}/MemoryCacheProvider.ts +0 -0
- /package/src/{cache-redis → cache/redis}/index.ts +0 -0
- /package/src/{cache-redis → cache/redis}/providers/RedisCacheProvider.ts +0 -0
- /package/src/lock/{index.ts → core/index.ts} +0 -0
- /package/src/lock/{primitives → core/primitives}/$lock.ts +0 -0
- /package/src/lock/{providers → core/providers}/LockProvider.ts +0 -0
- /package/src/lock/{providers → core/providers}/LockTopicProvider.ts +0 -0
- /package/src/lock/{providers → core/providers}/MemoryLockProvider.ts +0 -0
- /package/src/{lock-redis → lock/redis}/index.ts +0 -0
- /package/src/{lock-redis → lock/redis}/providers/RedisLockProvider.ts +0 -0
- /package/src/queue/{primitives → core/primitives}/$consumer.ts +0 -0
- /package/src/{queue-redis → queue/redis}/index.ts +0 -0
- /package/src/{server-auth → server/auth}/constants/routes.ts +0 -0
- /package/src/{server-auth → server/auth}/index.browser.ts +0 -0
- /package/src/{server-auth → server/auth}/index.shared.ts +0 -0
- /package/src/{server-auth → server/auth}/index.ts +0 -0
- /package/src/{server-auth → server/auth}/primitives/$auth.ts +0 -0
- /package/src/{server-auth → server/auth}/primitives/$authApple.ts +0 -0
- /package/src/{server-auth → server/auth}/primitives/$authCredentials.ts +0 -0
- /package/src/{server-auth → server/auth}/primitives/$authGithub.ts +0 -0
- /package/src/{server-auth → server/auth}/primitives/$authGoogle.ts +0 -0
- /package/src/{server-auth → server/auth}/providers/ServerAuthProvider.ts +0 -0
- /package/src/{server-auth → server/auth}/schemas/authenticationProviderSchema.ts +0 -0
- /package/src/{server-auth → server/auth}/schemas/tokenResponseSchema.ts +0 -0
- /package/src/{server-auth → server/auth}/schemas/tokensSchema.ts +0 -0
- /package/src/{server-auth → server/auth}/schemas/userinfoResponseSchema.ts +0 -0
- /package/src/{server-cache → server/cache}/index.ts +0 -0
- /package/src/{server-cache → server/cache}/providers/ServerCacheProvider.ts +0 -0
- /package/src/{server-compress → server/compress}/index.ts +0 -0
- /package/src/{server-compress → server/compress}/providers/ServerCompressProvider.ts +0 -0
- /package/src/{server-cookies → server/cookies}/index.browser.ts +0 -0
- /package/src/{server-cookies → server/cookies}/index.ts +0 -0
- /package/src/{server-cookies → server/cookies}/primitives/$cookie.browser.ts +0 -0
- /package/src/{server-cookies → server/cookies}/primitives/$cookie.ts +0 -0
- /package/src/{server-cookies → server/cookies}/providers/ServerCookiesProvider.ts +0 -0
- /package/src/{server-cookies → server/cookies}/services/CookieParser.ts +0 -0
- /package/src/server/{constants → core/constants}/routeMethods.ts +0 -0
- /package/src/server/{errors → core/errors}/BadRequestError.ts +0 -0
- /package/src/server/{errors → core/errors}/ConflictError.ts +0 -0
- /package/src/server/{errors → core/errors}/ForbiddenError.ts +0 -0
- /package/src/server/{errors → core/errors}/HttpError.ts +0 -0
- /package/src/server/{errors → core/errors}/NotFoundError.ts +0 -0
- /package/src/server/{errors → core/errors}/UnauthorizedError.ts +0 -0
- /package/src/server/{errors → core/errors}/ValidationError.ts +0 -0
- /package/src/server/{helpers → core/helpers}/ServerReply.ts +0 -0
- /package/src/server/{helpers → core/helpers}/isMultipart.ts +0 -0
- /package/src/server/{index.browser.ts → core/index.browser.ts} +0 -0
- /package/src/server/{index.shared.ts → core/index.shared.ts} +0 -0
- /package/src/server/{interfaces → core/interfaces}/ServerRequest.ts +0 -0
- /package/src/server/{primitives → core/primitives}/$action.ts +0 -0
- /package/src/server/{primitives → core/primitives}/$route.ts +0 -0
- /package/src/server/{providers → core/providers}/BunHttpServerProvider.ts +0 -0
- /package/src/server/{providers → core/providers}/NodeHttpServerProvider.ts +0 -0
- /package/src/server/{providers → core/providers}/ServerBodyParserProvider.ts +0 -0
- /package/src/server/{providers → core/providers}/ServerLoggerProvider.ts +0 -0
- /package/src/server/{providers → core/providers}/ServerNotReadyProvider.ts +0 -0
- /package/src/server/{providers → core/providers}/ServerProvider.ts +0 -0
- /package/src/server/{providers → core/providers}/ServerRouterProvider.ts +0 -0
- /package/src/server/{providers → core/providers}/ServerTimingProvider.ts +0 -0
- /package/src/server/{schemas → core/schemas}/errorSchema.ts +0 -0
- /package/src/server/{schemas → core/schemas}/okSchema.ts +0 -0
- /package/src/server/{services → core/services}/HttpClient.ts +0 -0
- /package/src/server/{services → core/services}/ServerRequestParser.ts +0 -0
- /package/src/server/{services → core/services}/UserAgentParser.ts +0 -0
- /package/src/{server-cors → server/cors}/index.ts +0 -0
- /package/src/{server-cors → server/cors}/primitives/$cors.ts +0 -0
- /package/src/{server-cors → server/cors}/providers/ServerCorsProvider.ts +0 -0
- /package/src/{server-health → server/health}/index.ts +0 -0
- /package/src/{server-health → server/health}/providers/ServerHealthProvider.ts +0 -0
- /package/src/{server-health → server/health}/schemas/healthSchema.ts +0 -0
- /package/src/{server-helmet → server/helmet}/index.ts +0 -0
- /package/src/{server-helmet → server/helmet}/providers/ServerHelmetProvider.ts +0 -0
- /package/src/{server-links → server/links}/index.browser.ts +0 -0
- /package/src/{server-links → server/links}/index.ts +0 -0
- /package/src/{server-links → server/links}/primitives/$client.ts +0 -0
- /package/src/{server-links → server/links}/primitives/$remote.ts +0 -0
- /package/src/{server-links → server/links}/providers/LinkProvider.ts +0 -0
- /package/src/{server-links → server/links}/providers/RemotePrimitiveProvider.ts +0 -0
- /package/src/{server-links → server/links}/providers/ServerLinksProvider.ts +0 -0
- /package/src/{server-links → server/links}/schemas/apiLinksResponseSchema.ts +0 -0
- /package/src/{server-metrics → server/metrics}/index.ts +0 -0
- /package/src/{server-metrics → server/metrics}/providers/ServerMetricsProvider.ts +0 -0
- /package/src/{server-multipart → server/multipart}/index.ts +0 -0
- /package/src/{server-multipart → server/multipart}/providers/ServerMultipartProvider.ts +0 -0
- /package/src/{server-proxy → server/proxy}/index.ts +0 -0
- /package/src/{server-proxy → server/proxy}/primitives/$proxy.ts +0 -0
- /package/src/{server-proxy → server/proxy}/providers/ServerProxyProvider.ts +0 -0
- /package/src/{server-rate-limit → server/rate-limit}/primitives/$rateLimit.ts +0 -0
- /package/src/{server-rate-limit → server/rate-limit}/providers/ServerRateLimitProvider.ts +0 -0
- /package/src/{server-security → server/security}/index.browser.ts +0 -0
- /package/src/{server-security → server/security}/index.ts +0 -0
- /package/src/{server-security → server/security}/primitives/$basicAuth.ts +0 -0
- /package/src/{server-security → server/security}/providers/ServerBasicAuthProvider.ts +0 -0
- /package/src/{server-security → server/security}/providers/ServerSecurityProvider.ts +0 -0
- /package/src/{server-static → server/static}/index.ts +0 -0
- /package/src/{server-static → server/static}/primitives/$serve.ts +0 -0
- /package/src/{server-static → server/static}/providers/ServerStaticProvider.ts +0 -0
- /package/src/{server-swagger → server/swagger}/index.ts +0 -0
- /package/src/{server-swagger → server/swagger}/primitives/$swagger.ts +0 -0
- /package/src/topic/{errors → core/errors}/TopicTimeoutError.ts +0 -0
- /package/src/topic/{index.ts → core/index.ts} +0 -0
- /package/src/topic/{primitives → core/primitives}/$subscriber.ts +0 -0
- /package/src/topic/{primitives → core/primitives}/$topic.ts +0 -0
- /package/src/topic/{providers → core/providers}/MemoryTopicProvider.ts +0 -0
- /package/src/topic/{providers → core/providers}/TopicProvider.ts +0 -0
- /package/src/{topic-redis → topic/redis}/index.ts +0 -0
- /package/src/{topic-redis → topic/redis}/providers/RedisTopicProvider.ts +0 -0
|
@@ -1,1973 +0,0 @@
|
|
|
1
|
-
import { $context, $hook, $inject, $module, Alepha, AlephaError, KIND, Primitive, createPrimitive, t } from "alepha";
|
|
2
|
-
import { $cookie, AlephaServerCookies, ServerCookiesProvider } from "alepha/server/cookies";
|
|
3
|
-
import { DateTimeProvider } from "alepha/datetime";
|
|
4
|
-
import { InvalidCredentialsError, SecurityError, SecurityProvider, userAccountInfoSchema } from "alepha/security";
|
|
5
|
-
import { $logger } from "alepha/logger";
|
|
6
|
-
import { $route, BadRequestError } from "alepha/server";
|
|
7
|
-
import { ServerLinksProvider, apiLinksResponseSchema } from "alepha/server/links";
|
|
8
|
-
|
|
9
|
-
//#region ../../../../node_modules/oauth4webapi/build/index.js
|
|
10
|
-
let USER_AGENT$1;
|
|
11
|
-
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT$1 = `oauth4webapi/v3.8.3`;
|
|
12
|
-
function looseInstanceOf(input, expected) {
|
|
13
|
-
if (input == null) return false;
|
|
14
|
-
try {
|
|
15
|
-
return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
|
|
16
|
-
} catch {
|
|
17
|
-
return false;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
const ERR_INVALID_ARG_VALUE$1 = "ERR_INVALID_ARG_VALUE";
|
|
21
|
-
const ERR_INVALID_ARG_TYPE$1 = "ERR_INVALID_ARG_TYPE";
|
|
22
|
-
function CodedTypeError$1(message, code, cause) {
|
|
23
|
-
const err = new TypeError(message, { cause });
|
|
24
|
-
Object.assign(err, { code });
|
|
25
|
-
return err;
|
|
26
|
-
}
|
|
27
|
-
const allowInsecureRequests$1 = Symbol();
|
|
28
|
-
const clockSkew$1 = Symbol();
|
|
29
|
-
const clockTolerance$1 = Symbol();
|
|
30
|
-
const customFetch$1 = Symbol();
|
|
31
|
-
const modifyAssertion$1 = Symbol();
|
|
32
|
-
const jweDecrypt = Symbol();
|
|
33
|
-
const encoder = new TextEncoder();
|
|
34
|
-
const decoder$1 = new TextDecoder();
|
|
35
|
-
function buf(input) {
|
|
36
|
-
if (typeof input === "string") return encoder.encode(input);
|
|
37
|
-
return decoder$1.decode(input);
|
|
38
|
-
}
|
|
39
|
-
let encodeBase64Url;
|
|
40
|
-
if (Uint8Array.prototype.toBase64) encodeBase64Url = (input) => {
|
|
41
|
-
if (input instanceof ArrayBuffer) input = new Uint8Array(input);
|
|
42
|
-
return input.toBase64({
|
|
43
|
-
alphabet: "base64url",
|
|
44
|
-
omitPadding: true
|
|
45
|
-
});
|
|
46
|
-
};
|
|
47
|
-
else {
|
|
48
|
-
const CHUNK_SIZE = 32768;
|
|
49
|
-
encodeBase64Url = (input) => {
|
|
50
|
-
if (input instanceof ArrayBuffer) input = new Uint8Array(input);
|
|
51
|
-
const arr = [];
|
|
52
|
-
for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
53
|
-
return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
let decodeBase64Url;
|
|
57
|
-
if (Uint8Array.fromBase64) decodeBase64Url = (input) => {
|
|
58
|
-
try {
|
|
59
|
-
return Uint8Array.fromBase64(input, { alphabet: "base64url" });
|
|
60
|
-
} catch (cause) {
|
|
61
|
-
throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
|
|
62
|
-
}
|
|
63
|
-
};
|
|
64
|
-
else decodeBase64Url = (input) => {
|
|
65
|
-
try {
|
|
66
|
-
const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
|
|
67
|
-
const bytes = new Uint8Array(binary.length);
|
|
68
|
-
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
69
|
-
return bytes;
|
|
70
|
-
} catch (cause) {
|
|
71
|
-
throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
function b64u(input) {
|
|
75
|
-
if (typeof input === "string") return decodeBase64Url(input);
|
|
76
|
-
return encodeBase64Url(input);
|
|
77
|
-
}
|
|
78
|
-
var UnsupportedOperationError = class extends Error {
|
|
79
|
-
code;
|
|
80
|
-
constructor(message, options) {
|
|
81
|
-
super(message, options);
|
|
82
|
-
this.name = this.constructor.name;
|
|
83
|
-
this.code = UNSUPPORTED_OPERATION;
|
|
84
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
var OperationProcessingError = class extends Error {
|
|
88
|
-
code;
|
|
89
|
-
constructor(message, options) {
|
|
90
|
-
super(message, options);
|
|
91
|
-
this.name = this.constructor.name;
|
|
92
|
-
if (options?.code) this.code = options?.code;
|
|
93
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
94
|
-
}
|
|
95
|
-
};
|
|
96
|
-
function OPE(message, code, cause) {
|
|
97
|
-
return new OperationProcessingError(message, {
|
|
98
|
-
code,
|
|
99
|
-
cause
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
function isJsonObject(input) {
|
|
103
|
-
if (input === null || typeof input !== "object" || Array.isArray(input)) return false;
|
|
104
|
-
return true;
|
|
105
|
-
}
|
|
106
|
-
function prepareHeaders(input) {
|
|
107
|
-
if (looseInstanceOf(input, Headers)) input = Object.fromEntries(input.entries());
|
|
108
|
-
const headers$1 = new Headers(input ?? {});
|
|
109
|
-
if (USER_AGENT$1 && !headers$1.has("user-agent")) headers$1.set("user-agent", USER_AGENT$1);
|
|
110
|
-
if (headers$1.has("authorization")) throw CodedTypeError$1("\"options.headers\" must not include the \"authorization\" header name", ERR_INVALID_ARG_VALUE$1);
|
|
111
|
-
return headers$1;
|
|
112
|
-
}
|
|
113
|
-
function signal$1(url, value) {
|
|
114
|
-
if (value !== void 0) {
|
|
115
|
-
if (typeof value === "function") value = value(url.href);
|
|
116
|
-
if (!(value instanceof AbortSignal)) throw CodedTypeError$1("\"options.signal\" must return or be an instance of AbortSignal", ERR_INVALID_ARG_TYPE$1);
|
|
117
|
-
return value;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
function replaceDoubleSlash(pathname) {
|
|
121
|
-
if (pathname.includes("//")) return pathname.replace("//", "/");
|
|
122
|
-
return pathname;
|
|
123
|
-
}
|
|
124
|
-
function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
|
|
125
|
-
if (url.pathname === "/") url.pathname = wellKnown;
|
|
126
|
-
else url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")}`);
|
|
127
|
-
return url;
|
|
128
|
-
}
|
|
129
|
-
function appendWellKnown(url, wellKnown) {
|
|
130
|
-
url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
|
|
131
|
-
return url;
|
|
132
|
-
}
|
|
133
|
-
async function performDiscovery$1(input, urlName, transform, options) {
|
|
134
|
-
if (!(input instanceof URL)) throw CodedTypeError$1(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE$1);
|
|
135
|
-
checkProtocol(input, options?.[allowInsecureRequests$1] !== true);
|
|
136
|
-
const url = transform(new URL(input.href));
|
|
137
|
-
const headers$1 = prepareHeaders(options?.headers);
|
|
138
|
-
headers$1.set("accept", "application/json");
|
|
139
|
-
return (options?.[customFetch$1] || fetch)(url.href, {
|
|
140
|
-
body: void 0,
|
|
141
|
-
headers: Object.fromEntries(headers$1.entries()),
|
|
142
|
-
method: "GET",
|
|
143
|
-
redirect: "manual",
|
|
144
|
-
signal: signal$1(url, options?.signal)
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
async function discoveryRequest(issuerIdentifier, options) {
|
|
148
|
-
return performDiscovery$1(issuerIdentifier, "issuerIdentifier", (url) => {
|
|
149
|
-
switch (options?.algorithm) {
|
|
150
|
-
case void 0:
|
|
151
|
-
case "oidc":
|
|
152
|
-
appendWellKnown(url, ".well-known/openid-configuration");
|
|
153
|
-
break;
|
|
154
|
-
case "oauth2":
|
|
155
|
-
prependWellKnown(url, ".well-known/oauth-authorization-server");
|
|
156
|
-
break;
|
|
157
|
-
default: throw CodedTypeError$1("\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"", ERR_INVALID_ARG_VALUE$1);
|
|
158
|
-
}
|
|
159
|
-
return url;
|
|
160
|
-
}, options);
|
|
161
|
-
}
|
|
162
|
-
function assertNumber(input, allow0, it, code, cause) {
|
|
163
|
-
try {
|
|
164
|
-
if (typeof input !== "number" || !Number.isFinite(input)) throw CodedTypeError$1(`${it} must be a number`, ERR_INVALID_ARG_TYPE$1, cause);
|
|
165
|
-
if (input > 0) return;
|
|
166
|
-
if (allow0) {
|
|
167
|
-
if (input !== 0) throw CodedTypeError$1(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
throw CodedTypeError$1(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
171
|
-
} catch (err) {
|
|
172
|
-
if (code) throw OPE(err.message, code, cause);
|
|
173
|
-
throw err;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
function assertString$1(input, it, code, cause) {
|
|
177
|
-
try {
|
|
178
|
-
if (typeof input !== "string") throw CodedTypeError$1(`${it} must be a string`, ERR_INVALID_ARG_TYPE$1, cause);
|
|
179
|
-
if (input.length === 0) throw CodedTypeError$1(`${it} must not be empty`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
180
|
-
} catch (err) {
|
|
181
|
-
if (code) throw OPE(err.message, code, cause);
|
|
182
|
-
throw err;
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
|
|
186
|
-
const expected = expectedIssuerIdentifier;
|
|
187
|
-
if (!(expected instanceof URL) && expected !== _nodiscoverycheck) throw CodedTypeError$1("\"expectedIssuerIdentifier\" must be an instance of URL", ERR_INVALID_ARG_TYPE$1);
|
|
188
|
-
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
189
|
-
if (response.status !== 200) throw OPE("\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)", RESPONSE_IS_NOT_CONFORM, response);
|
|
190
|
-
assertReadableResponse(response);
|
|
191
|
-
const json = await getResponseJsonBody(response);
|
|
192
|
-
assertString$1(json.issuer, "\"response\" body \"issuer\" property", INVALID_RESPONSE, { body: json });
|
|
193
|
-
if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) throw OPE("\"response\" body \"issuer\" property does not match the expected value", JSON_ATTRIBUTE_COMPARISON, {
|
|
194
|
-
expected: expected.href,
|
|
195
|
-
body: json,
|
|
196
|
-
attribute: "issuer"
|
|
197
|
-
});
|
|
198
|
-
return json;
|
|
199
|
-
}
|
|
200
|
-
function assertApplicationJson(response) {
|
|
201
|
-
assertContentType(response, "application/json");
|
|
202
|
-
}
|
|
203
|
-
function notJson(response, ...types) {
|
|
204
|
-
let msg = "\"response\" content-type must be ";
|
|
205
|
-
if (types.length > 2) {
|
|
206
|
-
const last = types.pop();
|
|
207
|
-
msg += `${types.join(", ")}, or ${last}`;
|
|
208
|
-
} else if (types.length === 2) msg += `${types[0]} or ${types[1]}`;
|
|
209
|
-
else msg += types[0];
|
|
210
|
-
return OPE(msg, RESPONSE_IS_NOT_JSON, response);
|
|
211
|
-
}
|
|
212
|
-
function assertContentType(response, contentType) {
|
|
213
|
-
if (getContentType(response) !== contentType) throw notJson(response, contentType);
|
|
214
|
-
}
|
|
215
|
-
function randomBytes() {
|
|
216
|
-
return b64u(crypto.getRandomValues(new Uint8Array(32)));
|
|
217
|
-
}
|
|
218
|
-
function generateRandomCodeVerifier() {
|
|
219
|
-
return randomBytes();
|
|
220
|
-
}
|
|
221
|
-
function generateRandomState() {
|
|
222
|
-
return randomBytes();
|
|
223
|
-
}
|
|
224
|
-
async function calculatePKCECodeChallenge$1(codeVerifier) {
|
|
225
|
-
assertString$1(codeVerifier, "codeVerifier");
|
|
226
|
-
return b64u(await crypto.subtle.digest("SHA-256", buf(codeVerifier)));
|
|
227
|
-
}
|
|
228
|
-
function getClockSkew(client) {
|
|
229
|
-
const skew = client?.[clockSkew$1];
|
|
230
|
-
return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
|
|
231
|
-
}
|
|
232
|
-
function getClockTolerance(client) {
|
|
233
|
-
const tolerance = client?.[clockTolerance$1];
|
|
234
|
-
return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
|
|
235
|
-
}
|
|
236
|
-
function epochTime() {
|
|
237
|
-
return Math.floor(Date.now() / 1e3);
|
|
238
|
-
}
|
|
239
|
-
function assertAs(as) {
|
|
240
|
-
if (typeof as !== "object" || as === null) throw CodedTypeError$1("\"as\" must be an object", ERR_INVALID_ARG_TYPE$1);
|
|
241
|
-
assertString$1(as.issuer, "\"as.issuer\"");
|
|
242
|
-
}
|
|
243
|
-
function assertClient(client) {
|
|
244
|
-
if (typeof client !== "object" || client === null) throw CodedTypeError$1("\"client\" must be an object", ERR_INVALID_ARG_TYPE$1);
|
|
245
|
-
assertString$1(client.client_id, "\"client.client_id\"");
|
|
246
|
-
}
|
|
247
|
-
function ClientSecretPost$1(clientSecret) {
|
|
248
|
-
assertString$1(clientSecret, "\"clientSecret\"");
|
|
249
|
-
return (_as, client, body, _headers) => {
|
|
250
|
-
body.set("client_id", client.client_id);
|
|
251
|
-
body.set("client_secret", clientSecret);
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
function None$1() {
|
|
255
|
-
return (_as, client, body, _headers) => {
|
|
256
|
-
body.set("client_id", client.client_id);
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
const URLParse = URL.parse ? (url, base) => URL.parse(url, base) : (url, base) => {
|
|
260
|
-
try {
|
|
261
|
-
return new URL(url, base);
|
|
262
|
-
} catch {
|
|
263
|
-
return null;
|
|
264
|
-
}
|
|
265
|
-
};
|
|
266
|
-
function checkProtocol(url, enforceHttps) {
|
|
267
|
-
if (enforceHttps && url.protocol !== "https:") throw OPE("only requests to HTTPS are allowed", HTTP_REQUEST_FORBIDDEN, url);
|
|
268
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") throw OPE("only HTTP and HTTPS requests are allowed", REQUEST_PROTOCOL_FORBIDDEN, url);
|
|
269
|
-
}
|
|
270
|
-
function validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {
|
|
271
|
-
let url;
|
|
272
|
-
if (typeof value !== "string" || !(url = URLParse(value))) throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `"as.mtls_endpoint_aliases.${endpoint}"` : `"as.${endpoint}"`}`, value === void 0 ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });
|
|
273
|
-
checkProtocol(url, enforceHttps);
|
|
274
|
-
return url;
|
|
275
|
-
}
|
|
276
|
-
function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {
|
|
277
|
-
if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
278
|
-
return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
279
|
-
}
|
|
280
|
-
function isDPoPNonceError(err) {
|
|
281
|
-
if (err instanceof WWWAuthenticateChallengeError) {
|
|
282
|
-
const { 0: challenge, length } = err.cause;
|
|
283
|
-
return length === 1 && challenge.scheme === "dpop" && challenge.parameters.error === "use_dpop_nonce";
|
|
284
|
-
}
|
|
285
|
-
if (err instanceof ResponseBodyError) return err.error === "use_dpop_nonce";
|
|
286
|
-
return false;
|
|
287
|
-
}
|
|
288
|
-
var ResponseBodyError = class extends Error {
|
|
289
|
-
cause;
|
|
290
|
-
code;
|
|
291
|
-
error;
|
|
292
|
-
status;
|
|
293
|
-
error_description;
|
|
294
|
-
response;
|
|
295
|
-
constructor(message, options) {
|
|
296
|
-
super(message, options);
|
|
297
|
-
this.name = this.constructor.name;
|
|
298
|
-
this.code = RESPONSE_BODY_ERROR;
|
|
299
|
-
this.cause = options.cause;
|
|
300
|
-
this.error = options.cause.error;
|
|
301
|
-
this.status = options.response.status;
|
|
302
|
-
this.error_description = options.cause.error_description;
|
|
303
|
-
Object.defineProperty(this, "response", {
|
|
304
|
-
enumerable: false,
|
|
305
|
-
value: options.response
|
|
306
|
-
});
|
|
307
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
308
|
-
}
|
|
309
|
-
};
|
|
310
|
-
var AuthorizationResponseError = class extends Error {
|
|
311
|
-
cause;
|
|
312
|
-
code;
|
|
313
|
-
error;
|
|
314
|
-
error_description;
|
|
315
|
-
constructor(message, options) {
|
|
316
|
-
super(message, options);
|
|
317
|
-
this.name = this.constructor.name;
|
|
318
|
-
this.code = AUTHORIZATION_RESPONSE_ERROR;
|
|
319
|
-
this.cause = options.cause;
|
|
320
|
-
this.error = options.cause.get("error");
|
|
321
|
-
this.error_description = options.cause.get("error_description") ?? void 0;
|
|
322
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
323
|
-
}
|
|
324
|
-
};
|
|
325
|
-
var WWWAuthenticateChallengeError = class extends Error {
|
|
326
|
-
cause;
|
|
327
|
-
code;
|
|
328
|
-
response;
|
|
329
|
-
status;
|
|
330
|
-
constructor(message, options) {
|
|
331
|
-
super(message, options);
|
|
332
|
-
this.name = this.constructor.name;
|
|
333
|
-
this.code = WWW_AUTHENTICATE_CHALLENGE;
|
|
334
|
-
this.cause = options.cause;
|
|
335
|
-
this.status = options.response.status;
|
|
336
|
-
this.response = options.response;
|
|
337
|
-
Object.defineProperty(this, "response", { enumerable: false });
|
|
338
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
339
|
-
}
|
|
340
|
-
};
|
|
341
|
-
const tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";
|
|
342
|
-
const token68Match = "[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}";
|
|
343
|
-
const quotedParamMatcher = "(" + tokenMatch + ")\\s*=\\s*\"((?:[^\"\\\\]|\\\\[\\s\\S])*)\"";
|
|
344
|
-
const paramMatcher = "(" + tokenMatch + ")\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)";
|
|
345
|
-
const schemeRE = /* @__PURE__ */ new RegExp("^[,\\s]*(" + tokenMatch + ")");
|
|
346
|
-
const quotedParamRE = /* @__PURE__ */ new RegExp("^[,\\s]*" + quotedParamMatcher + "[,\\s]*(.*)");
|
|
347
|
-
const unquotedParamRE = /* @__PURE__ */ new RegExp("^[,\\s]*" + paramMatcher + "[,\\s]*(.*)");
|
|
348
|
-
const token68ParamRE = /* @__PURE__ */ new RegExp("^(" + token68Match + ")(?:$|[,\\s])(.*)");
|
|
349
|
-
function parseWwwAuthenticateChallenges(response) {
|
|
350
|
-
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
351
|
-
const header = response.headers.get("www-authenticate");
|
|
352
|
-
if (header === null) return;
|
|
353
|
-
const challenges = [];
|
|
354
|
-
let rest = header;
|
|
355
|
-
while (rest) {
|
|
356
|
-
let match = rest.match(schemeRE);
|
|
357
|
-
const scheme = match?.["1"].toLowerCase();
|
|
358
|
-
if (!scheme) return;
|
|
359
|
-
const afterScheme = rest.substring(match[0].length);
|
|
360
|
-
if (afterScheme && !afterScheme.match(/^[\s,]/)) return;
|
|
361
|
-
const spaceMatch = afterScheme.match(/^\s+(.*)$/);
|
|
362
|
-
const hasParameters = !!spaceMatch;
|
|
363
|
-
rest = spaceMatch ? spaceMatch[1] : void 0;
|
|
364
|
-
const parameters = {};
|
|
365
|
-
let token68;
|
|
366
|
-
if (hasParameters) while (rest) {
|
|
367
|
-
let key;
|
|
368
|
-
let value;
|
|
369
|
-
if (match = rest.match(quotedParamRE)) {
|
|
370
|
-
[, key, value, rest] = match;
|
|
371
|
-
if (value.includes("\\")) try {
|
|
372
|
-
value = JSON.parse(`"${value}"`);
|
|
373
|
-
} catch {}
|
|
374
|
-
parameters[key.toLowerCase()] = value;
|
|
375
|
-
continue;
|
|
376
|
-
}
|
|
377
|
-
if (match = rest.match(unquotedParamRE)) {
|
|
378
|
-
[, key, value, rest] = match;
|
|
379
|
-
parameters[key.toLowerCase()] = value;
|
|
380
|
-
continue;
|
|
381
|
-
}
|
|
382
|
-
if (match = rest.match(token68ParamRE)) {
|
|
383
|
-
if (Object.keys(parameters).length) break;
|
|
384
|
-
[, token68, rest] = match;
|
|
385
|
-
break;
|
|
386
|
-
}
|
|
387
|
-
return;
|
|
388
|
-
}
|
|
389
|
-
else rest = afterScheme || void 0;
|
|
390
|
-
const challenge = {
|
|
391
|
-
scheme,
|
|
392
|
-
parameters
|
|
393
|
-
};
|
|
394
|
-
if (token68) challenge.token68 = token68;
|
|
395
|
-
challenges.push(challenge);
|
|
396
|
-
}
|
|
397
|
-
if (!challenges.length) return;
|
|
398
|
-
return challenges;
|
|
399
|
-
}
|
|
400
|
-
async function parseOAuthResponseErrorBody(response) {
|
|
401
|
-
if (response.status > 399 && response.status < 500) {
|
|
402
|
-
assertReadableResponse(response);
|
|
403
|
-
assertApplicationJson(response);
|
|
404
|
-
try {
|
|
405
|
-
const json = await response.clone().json();
|
|
406
|
-
if (isJsonObject(json) && typeof json.error === "string" && json.error.length) return json;
|
|
407
|
-
} catch {}
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
async function checkOAuthBodyError(response, expected, label) {
|
|
411
|
-
if (response.status !== expected) {
|
|
412
|
-
checkAuthenticationChallenges(response);
|
|
413
|
-
let err;
|
|
414
|
-
if (err = await parseOAuthResponseErrorBody(response)) {
|
|
415
|
-
await response.body?.cancel();
|
|
416
|
-
throw new ResponseBodyError("server responded with an error in the response body", {
|
|
417
|
-
cause: err,
|
|
418
|
-
response
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
throw OPE(`"response" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
function assertDPoP(option) {
|
|
425
|
-
if (!branded.has(option)) throw CodedTypeError$1("\"options.DPoP\" is not a valid DPoPHandle", ERR_INVALID_ARG_VALUE$1);
|
|
426
|
-
}
|
|
427
|
-
const skipSubjectCheck$1 = Symbol();
|
|
428
|
-
function getContentType(input) {
|
|
429
|
-
return input.headers.get("content-type")?.split(";")[0];
|
|
430
|
-
}
|
|
431
|
-
async function authenticatedRequest(as, client, clientAuthentication, url, body, headers$1, options) {
|
|
432
|
-
await clientAuthentication(as, client, body, headers$1);
|
|
433
|
-
headers$1.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
|
|
434
|
-
return (options?.[customFetch$1] || fetch)(url.href, {
|
|
435
|
-
body,
|
|
436
|
-
headers: Object.fromEntries(headers$1.entries()),
|
|
437
|
-
method: "POST",
|
|
438
|
-
redirect: "manual",
|
|
439
|
-
signal: signal$1(url, options?.signal)
|
|
440
|
-
});
|
|
441
|
-
}
|
|
442
|
-
async function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
|
|
443
|
-
const url = resolveEndpoint(as, "token_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests$1] !== true);
|
|
444
|
-
parameters.set("grant_type", grantType);
|
|
445
|
-
const headers$1 = prepareHeaders(options?.headers);
|
|
446
|
-
headers$1.set("accept", "application/json");
|
|
447
|
-
if (options?.DPoP !== void 0) {
|
|
448
|
-
assertDPoP(options.DPoP);
|
|
449
|
-
await options.DPoP.addProof(url, headers$1, "POST");
|
|
450
|
-
}
|
|
451
|
-
const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers$1, options);
|
|
452
|
-
options?.DPoP?.cacheNonce(response, url);
|
|
453
|
-
return response;
|
|
454
|
-
}
|
|
455
|
-
async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
|
|
456
|
-
assertAs(as);
|
|
457
|
-
assertClient(client);
|
|
458
|
-
assertString$1(refreshToken, "\"refreshToken\"");
|
|
459
|
-
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
460
|
-
parameters.set("refresh_token", refreshToken);
|
|
461
|
-
return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
|
|
462
|
-
}
|
|
463
|
-
const idTokenClaims = /* @__PURE__ */ new WeakMap();
|
|
464
|
-
const jwtRefs = /* @__PURE__ */ new WeakMap();
|
|
465
|
-
function getValidatedIdTokenClaims(ref) {
|
|
466
|
-
if (!ref.id_token) return;
|
|
467
|
-
const claims = idTokenClaims.get(ref);
|
|
468
|
-
if (!claims) throw CodedTypeError$1("\"ref\" was already garbage collected or did not resolve from the proper sources", ERR_INVALID_ARG_VALUE$1);
|
|
469
|
-
return claims;
|
|
470
|
-
}
|
|
471
|
-
async function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {
|
|
472
|
-
assertAs(as);
|
|
473
|
-
assertClient(client);
|
|
474
|
-
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
475
|
-
await checkOAuthBodyError(response, 200, "Token Endpoint");
|
|
476
|
-
assertReadableResponse(response);
|
|
477
|
-
const json = await getResponseJsonBody(response);
|
|
478
|
-
assertString$1(json.access_token, "\"response\" body \"access_token\" property", INVALID_RESPONSE, { body: json });
|
|
479
|
-
assertString$1(json.token_type, "\"response\" body \"token_type\" property", INVALID_RESPONSE, { body: json });
|
|
480
|
-
json.token_type = json.token_type.toLowerCase();
|
|
481
|
-
if (json.expires_in !== void 0) {
|
|
482
|
-
let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
|
|
483
|
-
assertNumber(expiresIn, true, "\"response\" body \"expires_in\" property", INVALID_RESPONSE, { body: json });
|
|
484
|
-
json.expires_in = expiresIn;
|
|
485
|
-
}
|
|
486
|
-
if (json.refresh_token !== void 0) assertString$1(json.refresh_token, "\"response\" body \"refresh_token\" property", INVALID_RESPONSE, { body: json });
|
|
487
|
-
if (json.scope !== void 0 && typeof json.scope !== "string") throw OPE("\"response\" body \"scope\" property must be a string", INVALID_RESPONSE, { body: json });
|
|
488
|
-
if (json.id_token !== void 0) {
|
|
489
|
-
assertString$1(json.id_token, "\"response\" body \"id_token\" property", INVALID_RESPONSE, { body: json });
|
|
490
|
-
const requiredClaims = [
|
|
491
|
-
"aud",
|
|
492
|
-
"exp",
|
|
493
|
-
"iat",
|
|
494
|
-
"iss",
|
|
495
|
-
"sub"
|
|
496
|
-
];
|
|
497
|
-
if (client.require_auth_time === true) requiredClaims.push("auth_time");
|
|
498
|
-
if (client.default_max_age !== void 0) {
|
|
499
|
-
assertNumber(client.default_max_age, true, "\"client.default_max_age\"");
|
|
500
|
-
requiredClaims.push("auth_time");
|
|
501
|
-
}
|
|
502
|
-
if (additionalRequiredIdTokenClaims?.length) requiredClaims.push(...additionalRequiredIdTokenClaims);
|
|
503
|
-
const { claims, jwt } = await validateJwt(json.id_token, checkSigningAlgorithm.bind(void 0, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, "RS256"), getClockSkew(client), getClockTolerance(client), decryptFn).then(validatePresence.bind(void 0, requiredClaims)).then(validateIssuer.bind(void 0, as)).then(validateAudience.bind(void 0, client.client_id));
|
|
504
|
-
if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
|
|
505
|
-
if (claims.azp === void 0) throw OPE("ID Token \"aud\" (audience) claim includes additional untrusted audiences", JWT_CLAIM_COMPARISON, {
|
|
506
|
-
claims,
|
|
507
|
-
claim: "aud"
|
|
508
|
-
});
|
|
509
|
-
if (claims.azp !== client.client_id) throw OPE("unexpected ID Token \"azp\" (authorized party) claim value", JWT_CLAIM_COMPARISON, {
|
|
510
|
-
expected: client.client_id,
|
|
511
|
-
claims,
|
|
512
|
-
claim: "azp"
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
if (claims.auth_time !== void 0) assertNumber(claims.auth_time, true, "ID Token \"auth_time\" (authentication time)", INVALID_RESPONSE, { claims });
|
|
516
|
-
jwtRefs.set(response, jwt);
|
|
517
|
-
idTokenClaims.set(json, claims);
|
|
518
|
-
}
|
|
519
|
-
if (recognizedTokenTypes?.[json.token_type] !== void 0) recognizedTokenTypes[json.token_type](response, json);
|
|
520
|
-
else if (json.token_type !== "dpop" && json.token_type !== "bearer") throw new UnsupportedOperationError("unsupported `token_type` value", { cause: { body: json } });
|
|
521
|
-
return json;
|
|
522
|
-
}
|
|
523
|
-
function checkAuthenticationChallenges(response) {
|
|
524
|
-
let challenges;
|
|
525
|
-
if (challenges = parseWwwAuthenticateChallenges(response)) throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", {
|
|
526
|
-
cause: challenges,
|
|
527
|
-
response
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
async function processRefreshTokenResponse(as, client, response, options) {
|
|
531
|
-
return processGenericAccessTokenResponse(as, client, response, void 0, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
532
|
-
}
|
|
533
|
-
function validateAudience(expected, result) {
|
|
534
|
-
if (Array.isArray(result.claims.aud)) {
|
|
535
|
-
if (!result.claims.aud.includes(expected)) throw OPE("unexpected JWT \"aud\" (audience) claim value", JWT_CLAIM_COMPARISON, {
|
|
536
|
-
expected,
|
|
537
|
-
claims: result.claims,
|
|
538
|
-
claim: "aud"
|
|
539
|
-
});
|
|
540
|
-
} else if (result.claims.aud !== expected) throw OPE("unexpected JWT \"aud\" (audience) claim value", JWT_CLAIM_COMPARISON, {
|
|
541
|
-
expected,
|
|
542
|
-
claims: result.claims,
|
|
543
|
-
claim: "aud"
|
|
544
|
-
});
|
|
545
|
-
return result;
|
|
546
|
-
}
|
|
547
|
-
function validateIssuer(as, result) {
|
|
548
|
-
const expected = as[_expectedIssuer]?.(result) ?? as.issuer;
|
|
549
|
-
if (result.claims.iss !== expected) throw OPE("unexpected JWT \"iss\" (issuer) claim value", JWT_CLAIM_COMPARISON, {
|
|
550
|
-
expected,
|
|
551
|
-
claims: result.claims,
|
|
552
|
-
claim: "iss"
|
|
553
|
-
});
|
|
554
|
-
return result;
|
|
555
|
-
}
|
|
556
|
-
const branded = /* @__PURE__ */ new WeakSet();
|
|
557
|
-
function brand(searchParams) {
|
|
558
|
-
branded.add(searchParams);
|
|
559
|
-
return searchParams;
|
|
560
|
-
}
|
|
561
|
-
const nopkce = Symbol();
|
|
562
|
-
async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {
|
|
563
|
-
assertAs(as);
|
|
564
|
-
assertClient(client);
|
|
565
|
-
if (!branded.has(callbackParameters)) throw CodedTypeError$1("\"callbackParameters\" must be an instance of URLSearchParams obtained from \"validateAuthResponse()\", or \"validateJwtAuthResponse()", ERR_INVALID_ARG_VALUE$1);
|
|
566
|
-
assertString$1(redirectUri, "\"redirectUri\"");
|
|
567
|
-
const code = getURLSearchParameter(callbackParameters, "code");
|
|
568
|
-
if (!code) throw OPE("no authorization code in \"callbackParameters\"", INVALID_RESPONSE);
|
|
569
|
-
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
570
|
-
parameters.set("redirect_uri", redirectUri);
|
|
571
|
-
parameters.set("code", code);
|
|
572
|
-
if (codeVerifier !== nopkce) {
|
|
573
|
-
assertString$1(codeVerifier, "\"codeVerifier\"");
|
|
574
|
-
parameters.set("code_verifier", codeVerifier);
|
|
575
|
-
}
|
|
576
|
-
return tokenEndpointRequest(as, client, clientAuthentication, "authorization_code", parameters, options);
|
|
577
|
-
}
|
|
578
|
-
const jwtClaimNames = {
|
|
579
|
-
aud: "audience",
|
|
580
|
-
c_hash: "code hash",
|
|
581
|
-
client_id: "client id",
|
|
582
|
-
exp: "expiration time",
|
|
583
|
-
iat: "issued at",
|
|
584
|
-
iss: "issuer",
|
|
585
|
-
jti: "jwt id",
|
|
586
|
-
nonce: "nonce",
|
|
587
|
-
s_hash: "state hash",
|
|
588
|
-
sub: "subject",
|
|
589
|
-
ath: "access token hash",
|
|
590
|
-
htm: "http method",
|
|
591
|
-
htu: "http uri",
|
|
592
|
-
cnf: "confirmation",
|
|
593
|
-
auth_time: "authentication time"
|
|
594
|
-
};
|
|
595
|
-
function validatePresence(required, result) {
|
|
596
|
-
for (const claim of required) if (result.claims[claim] === void 0) throw OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, { claims: result.claims });
|
|
597
|
-
return result;
|
|
598
|
-
}
|
|
599
|
-
const expectNoNonce = Symbol();
|
|
600
|
-
const skipAuthTimeCheck = Symbol();
|
|
601
|
-
async function processAuthorizationCodeResponse(as, client, response, options) {
|
|
602
|
-
if (typeof options?.expectedNonce === "string" || typeof options?.maxAge === "number" || options?.requireIdToken) return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);
|
|
603
|
-
return processAuthorizationCodeOAuth2Response(as, client, response, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
604
|
-
}
|
|
605
|
-
async function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {
|
|
606
|
-
const additionalRequiredClaims = [];
|
|
607
|
-
switch (expectedNonce) {
|
|
608
|
-
case void 0:
|
|
609
|
-
expectedNonce = expectNoNonce;
|
|
610
|
-
break;
|
|
611
|
-
case expectNoNonce: break;
|
|
612
|
-
default:
|
|
613
|
-
assertString$1(expectedNonce, "\"expectedNonce\" argument");
|
|
614
|
-
additionalRequiredClaims.push("nonce");
|
|
615
|
-
}
|
|
616
|
-
maxAge ??= client.default_max_age;
|
|
617
|
-
switch (maxAge) {
|
|
618
|
-
case void 0:
|
|
619
|
-
maxAge = skipAuthTimeCheck;
|
|
620
|
-
break;
|
|
621
|
-
case skipAuthTimeCheck: break;
|
|
622
|
-
default:
|
|
623
|
-
assertNumber(maxAge, true, "\"maxAge\" argument");
|
|
624
|
-
additionalRequiredClaims.push("auth_time");
|
|
625
|
-
}
|
|
626
|
-
const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);
|
|
627
|
-
assertString$1(result.id_token, "\"response\" body \"id_token\" property", INVALID_RESPONSE, { body: result });
|
|
628
|
-
const claims = getValidatedIdTokenClaims(result);
|
|
629
|
-
if (maxAge !== skipAuthTimeCheck) {
|
|
630
|
-
const now = epochTime() + getClockSkew(client);
|
|
631
|
-
const tolerance = getClockTolerance(client);
|
|
632
|
-
if (claims.auth_time + maxAge < now - tolerance) throw OPE("too much time has elapsed since the last End-User authentication", JWT_TIMESTAMP_CHECK, {
|
|
633
|
-
claims,
|
|
634
|
-
now,
|
|
635
|
-
tolerance,
|
|
636
|
-
claim: "auth_time"
|
|
637
|
-
});
|
|
638
|
-
}
|
|
639
|
-
if (expectedNonce === expectNoNonce) {
|
|
640
|
-
if (claims.nonce !== void 0) throw OPE("unexpected ID Token \"nonce\" claim value", JWT_CLAIM_COMPARISON, {
|
|
641
|
-
expected: void 0,
|
|
642
|
-
claims,
|
|
643
|
-
claim: "nonce"
|
|
644
|
-
});
|
|
645
|
-
} else if (claims.nonce !== expectedNonce) throw OPE("unexpected ID Token \"nonce\" claim value", JWT_CLAIM_COMPARISON, {
|
|
646
|
-
expected: expectedNonce,
|
|
647
|
-
claims,
|
|
648
|
-
claim: "nonce"
|
|
649
|
-
});
|
|
650
|
-
return result;
|
|
651
|
-
}
|
|
652
|
-
async function processAuthorizationCodeOAuth2Response(as, client, response, decryptFn, recognizedTokenTypes) {
|
|
653
|
-
const result = await processGenericAccessTokenResponse(as, client, response, void 0, decryptFn, recognizedTokenTypes);
|
|
654
|
-
const claims = getValidatedIdTokenClaims(result);
|
|
655
|
-
if (claims) {
|
|
656
|
-
if (client.default_max_age !== void 0) {
|
|
657
|
-
assertNumber(client.default_max_age, true, "\"client.default_max_age\"");
|
|
658
|
-
const now = epochTime() + getClockSkew(client);
|
|
659
|
-
const tolerance = getClockTolerance(client);
|
|
660
|
-
if (claims.auth_time + client.default_max_age < now - tolerance) throw OPE("too much time has elapsed since the last End-User authentication", JWT_TIMESTAMP_CHECK, {
|
|
661
|
-
claims,
|
|
662
|
-
now,
|
|
663
|
-
tolerance,
|
|
664
|
-
claim: "auth_time"
|
|
665
|
-
});
|
|
666
|
-
}
|
|
667
|
-
if (claims.nonce !== void 0) throw OPE("unexpected ID Token \"nonce\" claim value", JWT_CLAIM_COMPARISON, {
|
|
668
|
-
expected: void 0,
|
|
669
|
-
claims,
|
|
670
|
-
claim: "nonce"
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
return result;
|
|
674
|
-
}
|
|
675
|
-
const WWW_AUTHENTICATE_CHALLENGE = "OAUTH_WWW_AUTHENTICATE_CHALLENGE";
|
|
676
|
-
const RESPONSE_BODY_ERROR = "OAUTH_RESPONSE_BODY_ERROR";
|
|
677
|
-
const UNSUPPORTED_OPERATION = "OAUTH_UNSUPPORTED_OPERATION";
|
|
678
|
-
const AUTHORIZATION_RESPONSE_ERROR = "OAUTH_AUTHORIZATION_RESPONSE_ERROR";
|
|
679
|
-
const PARSE_ERROR = "OAUTH_PARSE_ERROR";
|
|
680
|
-
const INVALID_RESPONSE = "OAUTH_INVALID_RESPONSE";
|
|
681
|
-
const RESPONSE_IS_NOT_JSON = "OAUTH_RESPONSE_IS_NOT_JSON";
|
|
682
|
-
const RESPONSE_IS_NOT_CONFORM = "OAUTH_RESPONSE_IS_NOT_CONFORM";
|
|
683
|
-
const HTTP_REQUEST_FORBIDDEN = "OAUTH_HTTP_REQUEST_FORBIDDEN";
|
|
684
|
-
const REQUEST_PROTOCOL_FORBIDDEN = "OAUTH_REQUEST_PROTOCOL_FORBIDDEN";
|
|
685
|
-
const JWT_TIMESTAMP_CHECK = "OAUTH_JWT_TIMESTAMP_CHECK_FAILED";
|
|
686
|
-
const JWT_CLAIM_COMPARISON = "OAUTH_JWT_CLAIM_COMPARISON_FAILED";
|
|
687
|
-
const JSON_ATTRIBUTE_COMPARISON = "OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";
|
|
688
|
-
const MISSING_SERVER_METADATA = "OAUTH_MISSING_SERVER_METADATA";
|
|
689
|
-
const INVALID_SERVER_METADATA = "OAUTH_INVALID_SERVER_METADATA";
|
|
690
|
-
function assertReadableResponse(response) {
|
|
691
|
-
if (response.bodyUsed) throw CodedTypeError$1("\"response\" body has been used already", ERR_INVALID_ARG_VALUE$1);
|
|
692
|
-
}
|
|
693
|
-
async function validateJwt(jws, checkAlg, clockSkew$2, clockTolerance$2, decryptJwt) {
|
|
694
|
-
let { 0: protectedHeader, 1: payload, length } = jws.split(".");
|
|
695
|
-
if (length === 5) if (decryptJwt !== void 0) {
|
|
696
|
-
jws = await decryptJwt(jws);
|
|
697
|
-
({0: protectedHeader, 1: payload, length} = jws.split("."));
|
|
698
|
-
} else throw new UnsupportedOperationError("JWE decryption is not configured", { cause: jws });
|
|
699
|
-
if (length !== 3) throw OPE("Invalid JWT", INVALID_RESPONSE, jws);
|
|
700
|
-
let header;
|
|
701
|
-
try {
|
|
702
|
-
header = JSON.parse(buf(b64u(protectedHeader)));
|
|
703
|
-
} catch (cause) {
|
|
704
|
-
throw OPE("failed to parse JWT Header body as base64url encoded JSON", PARSE_ERROR, cause);
|
|
705
|
-
}
|
|
706
|
-
if (!isJsonObject(header)) throw OPE("JWT Header must be a top level object", INVALID_RESPONSE, jws);
|
|
707
|
-
checkAlg(header);
|
|
708
|
-
if (header.crit !== void 0) throw new UnsupportedOperationError("no JWT \"crit\" header parameter extensions are supported", { cause: { header } });
|
|
709
|
-
let claims;
|
|
710
|
-
try {
|
|
711
|
-
claims = JSON.parse(buf(b64u(payload)));
|
|
712
|
-
} catch (cause) {
|
|
713
|
-
throw OPE("failed to parse JWT Payload body as base64url encoded JSON", PARSE_ERROR, cause);
|
|
714
|
-
}
|
|
715
|
-
if (!isJsonObject(claims)) throw OPE("JWT Payload must be a top level object", INVALID_RESPONSE, jws);
|
|
716
|
-
const now = epochTime() + clockSkew$2;
|
|
717
|
-
if (claims.exp !== void 0) {
|
|
718
|
-
if (typeof claims.exp !== "number") throw OPE("unexpected JWT \"exp\" (expiration time) claim type", INVALID_RESPONSE, { claims });
|
|
719
|
-
if (claims.exp <= now - clockTolerance$2) throw OPE("unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp", JWT_TIMESTAMP_CHECK, {
|
|
720
|
-
claims,
|
|
721
|
-
now,
|
|
722
|
-
tolerance: clockTolerance$2,
|
|
723
|
-
claim: "exp"
|
|
724
|
-
});
|
|
725
|
-
}
|
|
726
|
-
if (claims.iat !== void 0) {
|
|
727
|
-
if (typeof claims.iat !== "number") throw OPE("unexpected JWT \"iat\" (issued at) claim type", INVALID_RESPONSE, { claims });
|
|
728
|
-
}
|
|
729
|
-
if (claims.iss !== void 0) {
|
|
730
|
-
if (typeof claims.iss !== "string") throw OPE("unexpected JWT \"iss\" (issuer) claim type", INVALID_RESPONSE, { claims });
|
|
731
|
-
}
|
|
732
|
-
if (claims.nbf !== void 0) {
|
|
733
|
-
if (typeof claims.nbf !== "number") throw OPE("unexpected JWT \"nbf\" (not before) claim type", INVALID_RESPONSE, { claims });
|
|
734
|
-
if (claims.nbf > now + clockTolerance$2) throw OPE("unexpected JWT \"nbf\" (not before) claim value", JWT_TIMESTAMP_CHECK, {
|
|
735
|
-
claims,
|
|
736
|
-
now,
|
|
737
|
-
tolerance: clockTolerance$2,
|
|
738
|
-
claim: "nbf"
|
|
739
|
-
});
|
|
740
|
-
}
|
|
741
|
-
if (claims.aud !== void 0) {
|
|
742
|
-
if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) throw OPE("unexpected JWT \"aud\" (audience) claim type", INVALID_RESPONSE, { claims });
|
|
743
|
-
}
|
|
744
|
-
return {
|
|
745
|
-
header,
|
|
746
|
-
claims,
|
|
747
|
-
jwt: jws
|
|
748
|
-
};
|
|
749
|
-
}
|
|
750
|
-
async function consumeStream(request) {
|
|
751
|
-
if (request.bodyUsed) throw CodedTypeError$1("form_post Request instances must contain a readable body", ERR_INVALID_ARG_VALUE$1, { cause: request });
|
|
752
|
-
return request.text();
|
|
753
|
-
}
|
|
754
|
-
async function formPostResponse(request) {
|
|
755
|
-
if (request.method !== "POST") throw CodedTypeError$1("form_post responses are expected to use the POST method", ERR_INVALID_ARG_VALUE$1, { cause: request });
|
|
756
|
-
if (getContentType(request) !== "application/x-www-form-urlencoded") throw CodedTypeError$1("form_post responses are expected to use the application/x-www-form-urlencoded content-type", ERR_INVALID_ARG_VALUE$1, { cause: request });
|
|
757
|
-
return consumeStream(request);
|
|
758
|
-
}
|
|
759
|
-
function checkSigningAlgorithm(client, issuer, fallback, header) {
|
|
760
|
-
if (client !== void 0) {
|
|
761
|
-
if (typeof client === "string" ? header.alg !== client : !client.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
762
|
-
header,
|
|
763
|
-
expected: client,
|
|
764
|
-
reason: "client configuration"
|
|
765
|
-
});
|
|
766
|
-
return;
|
|
767
|
-
}
|
|
768
|
-
if (Array.isArray(issuer)) {
|
|
769
|
-
if (!issuer.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
770
|
-
header,
|
|
771
|
-
expected: issuer,
|
|
772
|
-
reason: "authorization server metadata"
|
|
773
|
-
});
|
|
774
|
-
return;
|
|
775
|
-
}
|
|
776
|
-
if (fallback !== void 0) {
|
|
777
|
-
if (typeof fallback === "string" ? header.alg !== fallback : typeof fallback === "function" ? !fallback(header.alg) : !fallback.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
778
|
-
header,
|
|
779
|
-
expected: fallback,
|
|
780
|
-
reason: "default value"
|
|
781
|
-
});
|
|
782
|
-
return;
|
|
783
|
-
}
|
|
784
|
-
throw OPE("missing client or server configuration to verify used JWT \"alg\" header parameter", void 0, {
|
|
785
|
-
client,
|
|
786
|
-
issuer,
|
|
787
|
-
fallback
|
|
788
|
-
});
|
|
789
|
-
}
|
|
790
|
-
function getURLSearchParameter(parameters, name) {
|
|
791
|
-
const { 0: value, length } = parameters.getAll(name);
|
|
792
|
-
if (length > 1) throw OPE(`"${name}" parameter must be provided only once`, INVALID_RESPONSE);
|
|
793
|
-
return value;
|
|
794
|
-
}
|
|
795
|
-
const skipStateCheck$1 = Symbol();
|
|
796
|
-
const expectNoState = Symbol();
|
|
797
|
-
function validateAuthResponse(as, client, parameters, expectedState) {
|
|
798
|
-
assertAs(as);
|
|
799
|
-
assertClient(client);
|
|
800
|
-
if (parameters instanceof URL) parameters = parameters.searchParams;
|
|
801
|
-
if (!(parameters instanceof URLSearchParams)) throw CodedTypeError$1("\"parameters\" must be an instance of URLSearchParams, or URL", ERR_INVALID_ARG_TYPE$1);
|
|
802
|
-
if (getURLSearchParameter(parameters, "response")) throw OPE("\"parameters\" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()", INVALID_RESPONSE, { parameters });
|
|
803
|
-
const iss = getURLSearchParameter(parameters, "iss");
|
|
804
|
-
const state = getURLSearchParameter(parameters, "state");
|
|
805
|
-
if (!iss && as.authorization_response_iss_parameter_supported) throw OPE("response parameter \"iss\" (issuer) missing", INVALID_RESPONSE, { parameters });
|
|
806
|
-
if (iss && iss !== as.issuer) throw OPE("unexpected \"iss\" (issuer) response parameter value", INVALID_RESPONSE, {
|
|
807
|
-
expected: as.issuer,
|
|
808
|
-
parameters
|
|
809
|
-
});
|
|
810
|
-
switch (expectedState) {
|
|
811
|
-
case void 0:
|
|
812
|
-
case expectNoState:
|
|
813
|
-
if (state !== void 0) throw OPE("unexpected \"state\" response parameter encountered", INVALID_RESPONSE, {
|
|
814
|
-
expected: void 0,
|
|
815
|
-
parameters
|
|
816
|
-
});
|
|
817
|
-
break;
|
|
818
|
-
case skipStateCheck$1: break;
|
|
819
|
-
default:
|
|
820
|
-
assertString$1(expectedState, "\"expectedState\" argument");
|
|
821
|
-
if (state !== expectedState) throw OPE(state === void 0 ? "response parameter \"state\" missing" : "unexpected \"state\" response parameter value", INVALID_RESPONSE, {
|
|
822
|
-
expected: expectedState,
|
|
823
|
-
parameters
|
|
824
|
-
});
|
|
825
|
-
}
|
|
826
|
-
if (getURLSearchParameter(parameters, "error")) throw new AuthorizationResponseError("authorization response from the server is an error", { cause: parameters });
|
|
827
|
-
const id_token = getURLSearchParameter(parameters, "id_token");
|
|
828
|
-
const token = getURLSearchParameter(parameters, "token");
|
|
829
|
-
if (id_token !== void 0 || token !== void 0) throw new UnsupportedOperationError("implicit and hybrid flows are not supported");
|
|
830
|
-
return brand(new URLSearchParams(parameters));
|
|
831
|
-
}
|
|
832
|
-
async function getResponseJsonBody(response, check = assertApplicationJson) {
|
|
833
|
-
let json;
|
|
834
|
-
try {
|
|
835
|
-
json = await response.json();
|
|
836
|
-
} catch (cause) {
|
|
837
|
-
check(response);
|
|
838
|
-
throw OPE("failed to parse \"response\" body as JSON", PARSE_ERROR, cause);
|
|
839
|
-
}
|
|
840
|
-
if (!isJsonObject(json)) throw OPE("\"response\" body must be a top level object", INVALID_RESPONSE, { body: json });
|
|
841
|
-
return json;
|
|
842
|
-
}
|
|
843
|
-
const _nodiscoverycheck = Symbol();
|
|
844
|
-
const _expectedIssuer = Symbol();
|
|
845
|
-
|
|
846
|
-
//#endregion
|
|
847
|
-
//#region ../../../../node_modules/openid-client/build/index.js
|
|
848
|
-
let headers;
|
|
849
|
-
let USER_AGENT;
|
|
850
|
-
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
|
|
851
|
-
USER_AGENT = `openid-client/v6.8.1`;
|
|
852
|
-
headers = { "user-agent": USER_AGENT };
|
|
853
|
-
}
|
|
854
|
-
const int = (config) => {
|
|
855
|
-
return props.get(config);
|
|
856
|
-
};
|
|
857
|
-
let props;
|
|
858
|
-
let tbi;
|
|
859
|
-
function ClientSecretPost(clientSecret) {
|
|
860
|
-
if (clientSecret !== void 0) return ClientSecretPost$1(clientSecret);
|
|
861
|
-
tbi ||= /* @__PURE__ */ new WeakMap();
|
|
862
|
-
return (as, client, body, headers$1) => {
|
|
863
|
-
let auth;
|
|
864
|
-
if (!(auth = tbi.get(client))) {
|
|
865
|
-
assertString(client.client_secret, "\"metadata.client_secret\"");
|
|
866
|
-
auth = ClientSecretPost$1(client.client_secret);
|
|
867
|
-
tbi.set(client, auth);
|
|
868
|
-
}
|
|
869
|
-
return auth(as, client, body, headers$1);
|
|
870
|
-
};
|
|
871
|
-
}
|
|
872
|
-
function assertString(input, it) {
|
|
873
|
-
if (typeof input !== "string") throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE);
|
|
874
|
-
if (input.length === 0) throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE);
|
|
875
|
-
}
|
|
876
|
-
function None() {
|
|
877
|
-
return None$1();
|
|
878
|
-
}
|
|
879
|
-
const skipStateCheck = skipStateCheck$1;
|
|
880
|
-
const skipSubjectCheck = skipSubjectCheck$1;
|
|
881
|
-
const customFetch = customFetch$1;
|
|
882
|
-
const modifyAssertion = modifyAssertion$1;
|
|
883
|
-
const clockSkew = clockSkew$1;
|
|
884
|
-
const clockTolerance = clockTolerance$1;
|
|
885
|
-
const ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
|
|
886
|
-
const ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
|
|
887
|
-
function CodedTypeError(message, code, cause) {
|
|
888
|
-
const err = new TypeError(message, { cause });
|
|
889
|
-
Object.assign(err, { code });
|
|
890
|
-
return err;
|
|
891
|
-
}
|
|
892
|
-
function calculatePKCECodeChallenge(codeVerifier) {
|
|
893
|
-
return calculatePKCECodeChallenge$1(codeVerifier);
|
|
894
|
-
}
|
|
895
|
-
function randomPKCECodeVerifier() {
|
|
896
|
-
return generateRandomCodeVerifier();
|
|
897
|
-
}
|
|
898
|
-
function randomState() {
|
|
899
|
-
return generateRandomState();
|
|
900
|
-
}
|
|
901
|
-
var ClientError = class extends Error {
|
|
902
|
-
code;
|
|
903
|
-
constructor(message, options) {
|
|
904
|
-
super(message, options);
|
|
905
|
-
this.name = this.constructor.name;
|
|
906
|
-
this.code = options?.code;
|
|
907
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
908
|
-
}
|
|
909
|
-
};
|
|
910
|
-
const decoder = new TextDecoder();
|
|
911
|
-
function e(msg, cause, code) {
|
|
912
|
-
return new ClientError(msg, {
|
|
913
|
-
cause,
|
|
914
|
-
code
|
|
915
|
-
});
|
|
916
|
-
}
|
|
917
|
-
function errorHandler(err) {
|
|
918
|
-
if (err instanceof TypeError || err instanceof ClientError || err instanceof ResponseBodyError || err instanceof AuthorizationResponseError || err instanceof WWWAuthenticateChallengeError) throw err;
|
|
919
|
-
if (err instanceof OperationProcessingError) switch (err.code) {
|
|
920
|
-
case HTTP_REQUEST_FORBIDDEN: throw e("only requests to HTTPS are allowed", err, err.code);
|
|
921
|
-
case REQUEST_PROTOCOL_FORBIDDEN: throw e("only requests to HTTP or HTTPS are allowed", err, err.code);
|
|
922
|
-
case RESPONSE_IS_NOT_CONFORM: throw e("unexpected HTTP response status code", err.cause, err.code);
|
|
923
|
-
case RESPONSE_IS_NOT_JSON: throw e("unexpected response content-type", err.cause, err.code);
|
|
924
|
-
case PARSE_ERROR: throw e("parsing error occured", err, err.code);
|
|
925
|
-
case INVALID_RESPONSE: throw e("invalid response encountered", err, err.code);
|
|
926
|
-
case JWT_CLAIM_COMPARISON: throw e("unexpected JWT claim value encountered", err, err.code);
|
|
927
|
-
case JSON_ATTRIBUTE_COMPARISON: throw e("unexpected JSON attribute value encountered", err, err.code);
|
|
928
|
-
case JWT_TIMESTAMP_CHECK: throw e("JWT timestamp claim value failed validation", err, err.code);
|
|
929
|
-
default: throw e(err.message, err, err.code);
|
|
930
|
-
}
|
|
931
|
-
if (err instanceof UnsupportedOperationError) throw e("unsupported operation", err, err.code);
|
|
932
|
-
if (err instanceof DOMException) switch (err.name) {
|
|
933
|
-
case "OperationError": throw e("runtime operation error", err, UNSUPPORTED_OPERATION);
|
|
934
|
-
case "NotSupportedError": throw e("runtime unsupported operation", err, UNSUPPORTED_OPERATION);
|
|
935
|
-
case "TimeoutError": throw e("operation timed out", err, "OAUTH_TIMEOUT");
|
|
936
|
-
case "AbortError": throw e("operation aborted", err, "OAUTH_ABORT");
|
|
937
|
-
}
|
|
938
|
-
throw new ClientError("something went wrong", { cause: err });
|
|
939
|
-
}
|
|
940
|
-
function handleEntraId(server, as, options) {
|
|
941
|
-
if (server.origin === "https://login.microsoftonline.com" && (!options?.algorithm || options.algorithm === "oidc")) {
|
|
942
|
-
as[kEntraId] = true;
|
|
943
|
-
return true;
|
|
944
|
-
}
|
|
945
|
-
return false;
|
|
946
|
-
}
|
|
947
|
-
function handleB2Clogin(server, options) {
|
|
948
|
-
if (server.hostname.endsWith(".b2clogin.com") && (!options?.algorithm || options.algorithm === "oidc")) return true;
|
|
949
|
-
return false;
|
|
950
|
-
}
|
|
951
|
-
async function discovery(server, clientId, metadata, clientAuthentication, options) {
|
|
952
|
-
const instance = new Configuration(await performDiscovery(server, options), clientId, metadata, clientAuthentication);
|
|
953
|
-
let internals = int(instance);
|
|
954
|
-
if (options?.[customFetch]) internals.fetch = options[customFetch];
|
|
955
|
-
if (options?.timeout) internals.timeout = options.timeout;
|
|
956
|
-
if (options?.execute) for (const extension of options.execute) extension(instance);
|
|
957
|
-
return instance;
|
|
958
|
-
}
|
|
959
|
-
async function performDiscovery(server, options) {
|
|
960
|
-
if (!(server instanceof URL)) throw CodedTypeError("\"server\" must be an instance of URL", ERR_INVALID_ARG_TYPE);
|
|
961
|
-
const resolve = !server.href.includes("/.well-known/");
|
|
962
|
-
const timeout = options?.timeout ?? 30;
|
|
963
|
-
const signal$2 = AbortSignal.timeout(timeout * 1e3);
|
|
964
|
-
const as = await (resolve ? discoveryRequest(server, {
|
|
965
|
-
algorithm: options?.algorithm,
|
|
966
|
-
[customFetch$1]: options?.[customFetch],
|
|
967
|
-
[allowInsecureRequests$1]: options?.execute?.includes(allowInsecureRequests),
|
|
968
|
-
signal: signal$2,
|
|
969
|
-
headers: new Headers(headers)
|
|
970
|
-
}) : (options?.[customFetch] || fetch)((() => {
|
|
971
|
-
checkProtocol(server, options?.execute?.includes(allowInsecureRequests) ? false : true);
|
|
972
|
-
return server.href;
|
|
973
|
-
})(), {
|
|
974
|
-
headers: Object.fromEntries(new Headers({
|
|
975
|
-
accept: "application/json",
|
|
976
|
-
...headers
|
|
977
|
-
}).entries()),
|
|
978
|
-
body: void 0,
|
|
979
|
-
method: "GET",
|
|
980
|
-
redirect: "manual",
|
|
981
|
-
signal: signal$2
|
|
982
|
-
})).then((response) => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
|
|
983
|
-
if (resolve && new URL(as.issuer).href !== server.href) handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
|
|
984
|
-
throw new ClientError("discovered metadata issuer does not match the expected issuer", {
|
|
985
|
-
code: JSON_ATTRIBUTE_COMPARISON,
|
|
986
|
-
cause: {
|
|
987
|
-
expected: server.href,
|
|
988
|
-
body: as,
|
|
989
|
-
attribute: "issuer"
|
|
990
|
-
}
|
|
991
|
-
});
|
|
992
|
-
})();
|
|
993
|
-
return as;
|
|
994
|
-
}
|
|
995
|
-
function getServerHelpers(metadata) {
|
|
996
|
-
return { supportsPKCE: {
|
|
997
|
-
__proto__: null,
|
|
998
|
-
value(method = "S256") {
|
|
999
|
-
return metadata.code_challenge_methods_supported?.includes(method) === true;
|
|
1000
|
-
}
|
|
1001
|
-
} };
|
|
1002
|
-
}
|
|
1003
|
-
function addServerHelpers(metadata) {
|
|
1004
|
-
Object.defineProperties(metadata, getServerHelpers(metadata));
|
|
1005
|
-
}
|
|
1006
|
-
const kEntraId = Symbol();
|
|
1007
|
-
var Configuration = class {
|
|
1008
|
-
constructor(server, clientId, metadata, clientAuthentication) {
|
|
1009
|
-
if (typeof clientId !== "string" || !clientId.length) throw CodedTypeError("\"clientId\" must be a non-empty string", ERR_INVALID_ARG_TYPE);
|
|
1010
|
-
if (typeof metadata === "string") metadata = { client_secret: metadata };
|
|
1011
|
-
if (metadata?.client_id !== void 0 && clientId !== metadata.client_id) throw CodedTypeError("\"clientId\" and \"metadata.client_id\" must be the same", ERR_INVALID_ARG_VALUE);
|
|
1012
|
-
const client = {
|
|
1013
|
-
...structuredClone(metadata),
|
|
1014
|
-
client_id: clientId
|
|
1015
|
-
};
|
|
1016
|
-
client[clockSkew$1] = metadata?.[clockSkew$1] ?? 0;
|
|
1017
|
-
client[clockTolerance$1] = metadata?.[clockTolerance$1] ?? 30;
|
|
1018
|
-
let auth;
|
|
1019
|
-
if (clientAuthentication) auth = clientAuthentication;
|
|
1020
|
-
else if (typeof client.client_secret === "string" && client.client_secret.length) auth = ClientSecretPost(client.client_secret);
|
|
1021
|
-
else auth = None();
|
|
1022
|
-
let c = Object.freeze(client);
|
|
1023
|
-
const clone = structuredClone(server);
|
|
1024
|
-
if (kEntraId in server) clone[_expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace("{tenantid}", tid);
|
|
1025
|
-
let as = Object.freeze(clone);
|
|
1026
|
-
props ||= /* @__PURE__ */ new WeakMap();
|
|
1027
|
-
props.set(this, {
|
|
1028
|
-
__proto__: null,
|
|
1029
|
-
as,
|
|
1030
|
-
c,
|
|
1031
|
-
auth,
|
|
1032
|
-
tlsOnly: true,
|
|
1033
|
-
jwksCache: {}
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
serverMetadata() {
|
|
1037
|
-
const metadata = structuredClone(int(this).as);
|
|
1038
|
-
addServerHelpers(metadata);
|
|
1039
|
-
return metadata;
|
|
1040
|
-
}
|
|
1041
|
-
clientMetadata() {
|
|
1042
|
-
return structuredClone(int(this).c);
|
|
1043
|
-
}
|
|
1044
|
-
get timeout() {
|
|
1045
|
-
return int(this).timeout;
|
|
1046
|
-
}
|
|
1047
|
-
set timeout(value) {
|
|
1048
|
-
int(this).timeout = value;
|
|
1049
|
-
}
|
|
1050
|
-
get [customFetch]() {
|
|
1051
|
-
return int(this).fetch;
|
|
1052
|
-
}
|
|
1053
|
-
set [customFetch](value) {
|
|
1054
|
-
int(this).fetch = value;
|
|
1055
|
-
}
|
|
1056
|
-
};
|
|
1057
|
-
Object.freeze(Configuration.prototype);
|
|
1058
|
-
function getHelpers(response) {
|
|
1059
|
-
let exp = void 0;
|
|
1060
|
-
if (response.expires_in !== void 0) {
|
|
1061
|
-
const now = /* @__PURE__ */ new Date();
|
|
1062
|
-
now.setSeconds(now.getSeconds() + response.expires_in);
|
|
1063
|
-
exp = now.getTime();
|
|
1064
|
-
}
|
|
1065
|
-
return {
|
|
1066
|
-
expiresIn: {
|
|
1067
|
-
__proto__: null,
|
|
1068
|
-
value() {
|
|
1069
|
-
if (exp) {
|
|
1070
|
-
const now = Date.now();
|
|
1071
|
-
if (exp > now) return Math.floor((exp - now) / 1e3);
|
|
1072
|
-
return 0;
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
},
|
|
1076
|
-
claims: {
|
|
1077
|
-
__proto__: null,
|
|
1078
|
-
value() {
|
|
1079
|
-
try {
|
|
1080
|
-
return getValidatedIdTokenClaims(this);
|
|
1081
|
-
} catch {
|
|
1082
|
-
return;
|
|
1083
|
-
}
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
};
|
|
1087
|
-
}
|
|
1088
|
-
function addHelpers(response) {
|
|
1089
|
-
Object.defineProperties(response, getHelpers(response));
|
|
1090
|
-
}
|
|
1091
|
-
function allowInsecureRequests(config) {
|
|
1092
|
-
int(config).tlsOnly = false;
|
|
1093
|
-
}
|
|
1094
|
-
function stripParams(url) {
|
|
1095
|
-
url = new URL(url);
|
|
1096
|
-
url.search = "";
|
|
1097
|
-
url.hash = "";
|
|
1098
|
-
return url.href;
|
|
1099
|
-
}
|
|
1100
|
-
function webInstanceOf(input, toStringTag) {
|
|
1101
|
-
try {
|
|
1102
|
-
return Object.getPrototypeOf(input)[Symbol.toStringTag] === toStringTag;
|
|
1103
|
-
} catch {
|
|
1104
|
-
return false;
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
async function authorizationCodeGrant(config, currentUrl, checks, tokenEndpointParameters, options) {
|
|
1108
|
-
checkConfig(config);
|
|
1109
|
-
if (options?.flag !== retry && !(currentUrl instanceof URL) && !webInstanceOf(currentUrl, "Request")) throw CodedTypeError("\"currentUrl\" must be an instance of URL, or Request", ERR_INVALID_ARG_TYPE);
|
|
1110
|
-
let authResponse;
|
|
1111
|
-
let redirectUri;
|
|
1112
|
-
const { as, c, auth, fetch: fetch$1, tlsOnly, jarm, hybrid, nonRepudiation, timeout, decrypt, implicit } = int(config);
|
|
1113
|
-
if (options?.flag === retry) {
|
|
1114
|
-
authResponse = options.authResponse;
|
|
1115
|
-
redirectUri = options.redirectUri;
|
|
1116
|
-
} else {
|
|
1117
|
-
if (!(currentUrl instanceof URL)) {
|
|
1118
|
-
const request = currentUrl;
|
|
1119
|
-
currentUrl = new URL(currentUrl.url);
|
|
1120
|
-
switch (request.method) {
|
|
1121
|
-
case "GET": break;
|
|
1122
|
-
case "POST":
|
|
1123
|
-
const params = new URLSearchParams(await formPostResponse(request));
|
|
1124
|
-
if (hybrid) currentUrl.hash = params.toString();
|
|
1125
|
-
else for (const [k, v] of params.entries()) currentUrl.searchParams.append(k, v);
|
|
1126
|
-
break;
|
|
1127
|
-
default: throw CodedTypeError("unexpected Request HTTP method", ERR_INVALID_ARG_VALUE);
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
redirectUri = stripParams(currentUrl);
|
|
1131
|
-
switch (true) {
|
|
1132
|
-
case !!jarm:
|
|
1133
|
-
authResponse = await jarm(currentUrl, checks?.expectedState);
|
|
1134
|
-
break;
|
|
1135
|
-
case !!hybrid:
|
|
1136
|
-
authResponse = await hybrid(currentUrl, checks?.expectedNonce, checks?.expectedState, checks?.maxAge);
|
|
1137
|
-
break;
|
|
1138
|
-
case !!implicit: throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");
|
|
1139
|
-
default: try {
|
|
1140
|
-
authResponse = validateAuthResponse(as, c, currentUrl.searchParams, checks?.expectedState);
|
|
1141
|
-
} catch (err) {
|
|
1142
|
-
errorHandler(err);
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
const response = await authorizationCodeGrantRequest(as, c, auth, authResponse, redirectUri, checks?.pkceCodeVerifier || nopkce, {
|
|
1147
|
-
additionalParameters: tokenEndpointParameters,
|
|
1148
|
-
[customFetch$1]: fetch$1,
|
|
1149
|
-
[allowInsecureRequests$1]: !tlsOnly,
|
|
1150
|
-
DPoP: options?.DPoP,
|
|
1151
|
-
headers: new Headers(headers),
|
|
1152
|
-
signal: signal(timeout)
|
|
1153
|
-
}).catch(errorHandler);
|
|
1154
|
-
if (typeof checks?.expectedNonce === "string" || typeof checks?.maxAge === "number") checks.idTokenExpected = true;
|
|
1155
|
-
const p = processAuthorizationCodeResponse(as, c, response, {
|
|
1156
|
-
expectedNonce: checks?.expectedNonce,
|
|
1157
|
-
maxAge: checks?.maxAge,
|
|
1158
|
-
requireIdToken: checks?.idTokenExpected,
|
|
1159
|
-
[jweDecrypt]: decrypt
|
|
1160
|
-
});
|
|
1161
|
-
let result;
|
|
1162
|
-
try {
|
|
1163
|
-
result = await p;
|
|
1164
|
-
} catch (err) {
|
|
1165
|
-
if (retryable(err, options)) return authorizationCodeGrant(config, void 0, checks, tokenEndpointParameters, {
|
|
1166
|
-
...options,
|
|
1167
|
-
flag: retry,
|
|
1168
|
-
authResponse,
|
|
1169
|
-
redirectUri
|
|
1170
|
-
});
|
|
1171
|
-
errorHandler(err);
|
|
1172
|
-
}
|
|
1173
|
-
result.id_token && await nonRepudiation?.(response);
|
|
1174
|
-
addHelpers(result);
|
|
1175
|
-
return result;
|
|
1176
|
-
}
|
|
1177
|
-
async function refreshTokenGrant(config, refreshToken, parameters, options) {
|
|
1178
|
-
checkConfig(config);
|
|
1179
|
-
parameters = new URLSearchParams(parameters);
|
|
1180
|
-
const { as, c, auth, fetch: fetch$1, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);
|
|
1181
|
-
const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
|
|
1182
|
-
[customFetch$1]: fetch$1,
|
|
1183
|
-
[allowInsecureRequests$1]: !tlsOnly,
|
|
1184
|
-
additionalParameters: parameters,
|
|
1185
|
-
DPoP: options?.DPoP,
|
|
1186
|
-
headers: new Headers(headers),
|
|
1187
|
-
signal: signal(timeout)
|
|
1188
|
-
}).catch(errorHandler);
|
|
1189
|
-
const p = processRefreshTokenResponse(as, c, response, { [jweDecrypt]: decrypt });
|
|
1190
|
-
let result;
|
|
1191
|
-
try {
|
|
1192
|
-
result = await p;
|
|
1193
|
-
} catch (err) {
|
|
1194
|
-
if (retryable(err, options)) return refreshTokenGrant(config, refreshToken, parameters, {
|
|
1195
|
-
...options,
|
|
1196
|
-
flag: retry
|
|
1197
|
-
});
|
|
1198
|
-
errorHandler(err);
|
|
1199
|
-
}
|
|
1200
|
-
result.id_token && await nonRepudiation?.(response);
|
|
1201
|
-
addHelpers(result);
|
|
1202
|
-
return result;
|
|
1203
|
-
}
|
|
1204
|
-
function buildAuthorizationUrl(config, parameters) {
|
|
1205
|
-
checkConfig(config);
|
|
1206
|
-
const { as, c, tlsOnly, hybrid, jarm, implicit } = int(config);
|
|
1207
|
-
const authorizationEndpoint = resolveEndpoint(as, "authorization_endpoint", false, tlsOnly);
|
|
1208
|
-
parameters = new URLSearchParams(parameters);
|
|
1209
|
-
if (!parameters.has("client_id")) parameters.set("client_id", c.client_id);
|
|
1210
|
-
if (!parameters.has("request_uri") && !parameters.has("request")) {
|
|
1211
|
-
if (!parameters.has("response_type")) parameters.set("response_type", hybrid ? "code id_token" : implicit ? "id_token" : "code");
|
|
1212
|
-
if (implicit && !parameters.has("nonce")) throw CodedTypeError("response_type=id_token clients must provide a nonce parameter in their authorization request parameters", ERR_INVALID_ARG_VALUE);
|
|
1213
|
-
if (jarm) parameters.set("response_mode", "jwt");
|
|
1214
|
-
}
|
|
1215
|
-
for (const [k, v] of parameters.entries()) authorizationEndpoint.searchParams.append(k, v);
|
|
1216
|
-
return authorizationEndpoint;
|
|
1217
|
-
}
|
|
1218
|
-
function buildEndSessionUrl(config, parameters) {
|
|
1219
|
-
checkConfig(config);
|
|
1220
|
-
const { as, c, tlsOnly } = int(config);
|
|
1221
|
-
const endSessionEndpoint = resolveEndpoint(as, "end_session_endpoint", false, tlsOnly);
|
|
1222
|
-
parameters = new URLSearchParams(parameters);
|
|
1223
|
-
if (!parameters.has("client_id")) parameters.set("client_id", c.client_id);
|
|
1224
|
-
for (const [k, v] of parameters.entries()) endSessionEndpoint.searchParams.append(k, v);
|
|
1225
|
-
return endSessionEndpoint;
|
|
1226
|
-
}
|
|
1227
|
-
function checkConfig(input) {
|
|
1228
|
-
if (!(input instanceof Configuration)) throw CodedTypeError("\"config\" must be an instance of Configuration", ERR_INVALID_ARG_TYPE);
|
|
1229
|
-
if (Object.getPrototypeOf(input) !== Configuration.prototype) throw CodedTypeError("subclassing Configuration is not allowed", ERR_INVALID_ARG_VALUE);
|
|
1230
|
-
}
|
|
1231
|
-
function signal(timeout) {
|
|
1232
|
-
return timeout ? AbortSignal.timeout(timeout * 1e3) : void 0;
|
|
1233
|
-
}
|
|
1234
|
-
function retryable(err, options) {
|
|
1235
|
-
if (options?.DPoP && options.flag !== retry) return isDPoPNonceError(err);
|
|
1236
|
-
return false;
|
|
1237
|
-
}
|
|
1238
|
-
const retry = Symbol();
|
|
1239
|
-
|
|
1240
|
-
//#endregion
|
|
1241
|
-
//#region ../../src/server-auth/primitives/$auth.ts
|
|
1242
|
-
/**
|
|
1243
|
-
* Creates an authentication provider primitive for handling user login flows.
|
|
1244
|
-
*
|
|
1245
|
-
* Supports multiple authentication strategies: credentials (username/password), OAuth2,
|
|
1246
|
-
* and OIDC (OpenID Connect). Handles token management, user profile retrieval, and
|
|
1247
|
-
* integration with both external identity providers (Auth0, Keycloak) and internal realms.
|
|
1248
|
-
*
|
|
1249
|
-
* **Authentication Types**: Credentials, OAuth2 (Google, GitHub), OIDC, External providers
|
|
1250
|
-
*
|
|
1251
|
-
* @example
|
|
1252
|
-
* ```ts
|
|
1253
|
-
* class AuthProviders {
|
|
1254
|
-
* // Internal credentials-based auth
|
|
1255
|
-
* credentials = $auth({
|
|
1256
|
-
* realm: this.userRealm,
|
|
1257
|
-
* credentials: {
|
|
1258
|
-
* account: async ({ username, password }) => {
|
|
1259
|
-
* return await this.validateUser(username, password);
|
|
1260
|
-
* }
|
|
1261
|
-
* }
|
|
1262
|
-
* });
|
|
1263
|
-
*
|
|
1264
|
-
* // External OIDC provider
|
|
1265
|
-
* keycloak = $auth({
|
|
1266
|
-
* oidc: {
|
|
1267
|
-
* issuer: "https://auth.example.com",
|
|
1268
|
-
* clientId: "my-app",
|
|
1269
|
-
* clientSecret: "secret",
|
|
1270
|
-
* redirectUri: "/auth/callback"
|
|
1271
|
-
* }
|
|
1272
|
-
* });
|
|
1273
|
-
* }
|
|
1274
|
-
* ```
|
|
1275
|
-
*/
|
|
1276
|
-
const $auth = (options) => {
|
|
1277
|
-
return createPrimitive(AuthPrimitive, options);
|
|
1278
|
-
};
|
|
1279
|
-
var AuthPrimitive = class extends Primitive {
|
|
1280
|
-
securityProvider = $inject(SecurityProvider);
|
|
1281
|
-
dateTimeProvider = $inject(DateTimeProvider);
|
|
1282
|
-
oauth;
|
|
1283
|
-
get name() {
|
|
1284
|
-
return this.options.name ?? this.config.propertyKey;
|
|
1285
|
-
}
|
|
1286
|
-
get realm() {
|
|
1287
|
-
if ("realm" in this.options) return this.options.realm;
|
|
1288
|
-
}
|
|
1289
|
-
get jwks_uri() {
|
|
1290
|
-
const jwks = this.oauth?.serverMetadata().jwks_uri;
|
|
1291
|
-
if (!jwks) throw new AlephaError("No JWKS URI available for the auth provider");
|
|
1292
|
-
return jwks;
|
|
1293
|
-
}
|
|
1294
|
-
get scope() {
|
|
1295
|
-
if ("oauth" in this.options) return this.options.oauth.scope;
|
|
1296
|
-
if ("oidc" in this.options) return this.options.oidc.scope || "openid profile email";
|
|
1297
|
-
throw new AlephaError("No OAuth2 or OIDC configuration available for the auth provider");
|
|
1298
|
-
}
|
|
1299
|
-
get redirect_uri() {
|
|
1300
|
-
if ("oauth" in this.options) return this.options.oauth.redirectUri;
|
|
1301
|
-
if ("oidc" in this.options) return this.options.oidc.redirectUri;
|
|
1302
|
-
throw new AlephaError("No OAuth2 or OIDC configuration available for the auth provider");
|
|
1303
|
-
}
|
|
1304
|
-
/**
|
|
1305
|
-
* Refreshes the access token using the refresh token.
|
|
1306
|
-
* Can be used on oauth2, oidc or credentials auth providers.
|
|
1307
|
-
*/
|
|
1308
|
-
async refresh(refreshToken, accessToken) {
|
|
1309
|
-
if ("realm" in this.options) return this.options.realm.refreshToken(refreshToken, accessToken).then((it) => it.tokens).catch((error) => {
|
|
1310
|
-
throw new SecurityError("Failed to refresh access token using the refresh token (realm)", { cause: error });
|
|
1311
|
-
});
|
|
1312
|
-
else if (this.oauth) try {
|
|
1313
|
-
return {
|
|
1314
|
-
...await refreshTokenGrant(this.oauth, refreshToken),
|
|
1315
|
-
issued_at: this.dateTimeProvider.now().unix()
|
|
1316
|
-
};
|
|
1317
|
-
} catch (error) {
|
|
1318
|
-
throw new SecurityError("Failed to refresh access token using the refresh token (oauth2)", { cause: error });
|
|
1319
|
-
}
|
|
1320
|
-
throw new AlephaError("No realm or OAuth2 configuration available for refreshing the access token");
|
|
1321
|
-
}
|
|
1322
|
-
/**
|
|
1323
|
-
* Extracts user information from the access token.
|
|
1324
|
-
* This is used to create a user account from the access token.
|
|
1325
|
-
*/
|
|
1326
|
-
async user(tokens) {
|
|
1327
|
-
try {
|
|
1328
|
-
if ("oauth" in this.options) {
|
|
1329
|
-
const profile = await this.options.oauth.userinfo(tokens);
|
|
1330
|
-
if (this.options.oauth.account) return this.options.oauth.account({
|
|
1331
|
-
...tokens,
|
|
1332
|
-
user: profile
|
|
1333
|
-
});
|
|
1334
|
-
return this.securityProvider.createUserFromPayload(profile);
|
|
1335
|
-
}
|
|
1336
|
-
if ("oidc" in this.options) {
|
|
1337
|
-
const payload = this.getUserFromIdToken(tokens.id_token || "");
|
|
1338
|
-
if (this.options.oidc.account) return this.options.oidc.account({
|
|
1339
|
-
...tokens,
|
|
1340
|
-
user: payload
|
|
1341
|
-
});
|
|
1342
|
-
return this.securityProvider.createUserFromPayload(payload);
|
|
1343
|
-
}
|
|
1344
|
-
} catch (error) {
|
|
1345
|
-
throw new SecurityError("Failed to extract user from identity provider tokens", { cause: error });
|
|
1346
|
-
}
|
|
1347
|
-
throw new AlephaError("This authentication does not support user extraction from tokens");
|
|
1348
|
-
}
|
|
1349
|
-
getUserFromIdToken(idToken) {
|
|
1350
|
-
try {
|
|
1351
|
-
return JSON.parse(Buffer.from(idToken.split(".")[1], "base64").toString("utf8"));
|
|
1352
|
-
} catch (error) {
|
|
1353
|
-
throw new AlephaError("Failed to parse ID Token payload", { cause: error });
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
async prepare() {
|
|
1357
|
-
const addons = [];
|
|
1358
|
-
addons.push(allowInsecureRequests);
|
|
1359
|
-
if ("oidc" in this.options) {
|
|
1360
|
-
const { oidc } = this.options;
|
|
1361
|
-
this.oauth = await discovery(new URL(oidc.issuer), oidc.clientId, { client_secret: oidc.clientSecret }, void 0, { execute: addons });
|
|
1362
|
-
}
|
|
1363
|
-
if ("oauth" in this.options) {
|
|
1364
|
-
const { oauth } = this.options;
|
|
1365
|
-
this.oauth = new Configuration({
|
|
1366
|
-
authorization_endpoint: oauth.authorization,
|
|
1367
|
-
token_endpoint: oauth.token,
|
|
1368
|
-
issuer: oauth.authorization,
|
|
1369
|
-
jwks_uri: void 0,
|
|
1370
|
-
end_session_endpoint: void 0
|
|
1371
|
-
}, oauth.clientId, { client_secret: oauth.clientSecret });
|
|
1372
|
-
}
|
|
1373
|
-
}
|
|
1374
|
-
};
|
|
1375
|
-
$auth[KIND] = AuthPrimitive;
|
|
1376
|
-
|
|
1377
|
-
//#endregion
|
|
1378
|
-
//#region ../../src/server-auth/constants/routes.ts
|
|
1379
|
-
const alephaServerAuthRoutes = {
|
|
1380
|
-
login: "/oauth/login",
|
|
1381
|
-
callback: "/oauth/callback",
|
|
1382
|
-
logout: "/oauth/logout",
|
|
1383
|
-
token: "/_auth/token",
|
|
1384
|
-
refresh: "/_auth/refresh",
|
|
1385
|
-
userinfo: "/_auth/userinfo"
|
|
1386
|
-
};
|
|
1387
|
-
|
|
1388
|
-
//#endregion
|
|
1389
|
-
//#region ../../src/server-auth/schemas/tokensSchema.ts
|
|
1390
|
-
const tokensSchema = t.object({
|
|
1391
|
-
provider: t.text(),
|
|
1392
|
-
access_token: t.text({ size: "rich" }),
|
|
1393
|
-
issued_at: t.number(),
|
|
1394
|
-
expires_in: t.optional(t.number()),
|
|
1395
|
-
refresh_token: t.optional(t.text({ size: "rich" })),
|
|
1396
|
-
refresh_token_expires_in: t.optional(t.number()),
|
|
1397
|
-
refresh_expires_in: t.optional(t.number({ description: "Alias of `refresh_token_expires_in` for compatibility with some providers." })),
|
|
1398
|
-
id_token: t.optional(t.text({ size: "rich" })),
|
|
1399
|
-
scope: t.optional(t.text())
|
|
1400
|
-
});
|
|
1401
|
-
|
|
1402
|
-
//#endregion
|
|
1403
|
-
//#region ../../src/server-auth/schemas/tokenResponseSchema.ts
|
|
1404
|
-
const tokenResponseSchema = t.extend(tokensSchema, {
|
|
1405
|
-
user: userAccountInfoSchema,
|
|
1406
|
-
api: apiLinksResponseSchema
|
|
1407
|
-
});
|
|
1408
|
-
|
|
1409
|
-
//#endregion
|
|
1410
|
-
//#region ../../src/server-auth/schemas/userinfoResponseSchema.ts
|
|
1411
|
-
const userinfoResponseSchema = t.object({
|
|
1412
|
-
user: t.optional(userAccountInfoSchema),
|
|
1413
|
-
api: apiLinksResponseSchema
|
|
1414
|
-
});
|
|
1415
|
-
|
|
1416
|
-
//#endregion
|
|
1417
|
-
//#region ../../src/server-auth/providers/ServerAuthProvider.ts
|
|
1418
|
-
var ServerAuthProvider = class {
|
|
1419
|
-
log = $logger();
|
|
1420
|
-
alepha = $inject(Alepha);
|
|
1421
|
-
serverCookiesProvider = $inject(ServerCookiesProvider);
|
|
1422
|
-
dateTimeProvider = $inject(DateTimeProvider);
|
|
1423
|
-
serverLinksProvider = $inject(ServerLinksProvider);
|
|
1424
|
-
authorizationCode = $cookie({
|
|
1425
|
-
name: "authorizationCode",
|
|
1426
|
-
ttl: [15, "minutes"],
|
|
1427
|
-
httpOnly: true,
|
|
1428
|
-
schema: t.object({
|
|
1429
|
-
provider: t.text(),
|
|
1430
|
-
realm: t.optional(t.text()),
|
|
1431
|
-
codeVerifier: t.optional(t.text({ size: "long" })),
|
|
1432
|
-
redirectUri: t.optional(t.text({ size: "long" })),
|
|
1433
|
-
state: t.optional(t.text()),
|
|
1434
|
-
nonce: t.optional(t.text())
|
|
1435
|
-
})
|
|
1436
|
-
});
|
|
1437
|
-
tokens = $cookie({
|
|
1438
|
-
name: "tokens",
|
|
1439
|
-
ttl: [30, "days"],
|
|
1440
|
-
httpOnly: true,
|
|
1441
|
-
compress: true,
|
|
1442
|
-
encrypt: true,
|
|
1443
|
-
schema: tokensSchema
|
|
1444
|
-
});
|
|
1445
|
-
get identities() {
|
|
1446
|
-
return this.alepha.primitives($auth).filter((auth) => !auth.options.disabled);
|
|
1447
|
-
}
|
|
1448
|
-
getAuthenticationProviders(filters = {}) {
|
|
1449
|
-
const providers = [];
|
|
1450
|
-
for (const identity of this.identities) {
|
|
1451
|
-
if (filters.realmName) {
|
|
1452
|
-
const realm = "realm" in identity.options && identity.options.realm;
|
|
1453
|
-
if (!realm || realm.name !== filters.realmName) continue;
|
|
1454
|
-
}
|
|
1455
|
-
const type = "oidc" in identity.options ? "OIDC" : "oauth" in identity.options ? "OAUTH2" : "credentials" in identity.options ? "CREDENTIALS" : void 0;
|
|
1456
|
-
if (!type) continue;
|
|
1457
|
-
providers.push({
|
|
1458
|
-
name: identity.name,
|
|
1459
|
-
type
|
|
1460
|
-
});
|
|
1461
|
-
}
|
|
1462
|
-
return providers;
|
|
1463
|
-
}
|
|
1464
|
-
configure = $hook({
|
|
1465
|
-
on: "configure",
|
|
1466
|
-
handler: async () => {
|
|
1467
|
-
for (const identity of this.identities) await identity.prepare();
|
|
1468
|
-
}
|
|
1469
|
-
});
|
|
1470
|
-
getAccessTokens(tokens) {
|
|
1471
|
-
const idp = this.provider(tokens.provider);
|
|
1472
|
-
if ("oidc" in idp.options && !("realm" in idp.options) && idp.options.oidc?.useIdToken) return tokens.id_token;
|
|
1473
|
-
return tokens.access_token;
|
|
1474
|
-
}
|
|
1475
|
-
/**
|
|
1476
|
-
* Fill request headers with access token from cookies or fallback to provider's fallback function.
|
|
1477
|
-
*/
|
|
1478
|
-
onRequest = $hook({
|
|
1479
|
-
on: "server:onRequest",
|
|
1480
|
-
after: this.serverCookiesProvider,
|
|
1481
|
-
handler: async ({ request }) => {
|
|
1482
|
-
const cookies = request.cookies;
|
|
1483
|
-
if (cookies) {
|
|
1484
|
-
const tokens = await this.cookiesToTokens(cookies);
|
|
1485
|
-
if (tokens) {
|
|
1486
|
-
request.headers.authorization = `Bearer ${this.getAccessTokens(tokens)}`;
|
|
1487
|
-
this.log.trace("Access token set in request headers", { provider: tokens.provider });
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
if (!request.headers.authorization) {
|
|
1491
|
-
for (const provider of this.identities) if (!("realm" in provider.options) && !!provider.options.fallback) {
|
|
1492
|
-
const token = await provider.options.fallback();
|
|
1493
|
-
if (token) {
|
|
1494
|
-
request.headers.authorization = `Bearer ${token}`;
|
|
1495
|
-
break;
|
|
1496
|
-
}
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
});
|
|
1501
|
-
/**
|
|
1502
|
-
* Convert cookies to tokens.
|
|
1503
|
-
* If the tokens are expired, try to refresh them using the refresh token.
|
|
1504
|
-
*/
|
|
1505
|
-
async cookiesToTokens(cookies) {
|
|
1506
|
-
const tokens = this.getTokens(cookies);
|
|
1507
|
-
if (!tokens) {
|
|
1508
|
-
this.log.trace("No tokens found in cookies");
|
|
1509
|
-
return;
|
|
1510
|
-
}
|
|
1511
|
-
this.log.trace("Tokens found in cookies", {
|
|
1512
|
-
expires_in: tokens.expires_in,
|
|
1513
|
-
issued_at: tokens.issued_at
|
|
1514
|
-
});
|
|
1515
|
-
const refreshedTokens = await this.refreshTokens(tokens);
|
|
1516
|
-
if (!refreshedTokens) {
|
|
1517
|
-
this.tokens.del({ cookies });
|
|
1518
|
-
return;
|
|
1519
|
-
}
|
|
1520
|
-
if (refreshedTokens.access_token !== tokens.access_token) this.setTokens(refreshedTokens, cookies);
|
|
1521
|
-
return refreshedTokens;
|
|
1522
|
-
}
|
|
1523
|
-
async refreshTokens(tokens) {
|
|
1524
|
-
if (tokens.expires_in && tokens.issued_at) {
|
|
1525
|
-
if (tokens.issued_at + (tokens.expires_in - 10) < this.dateTimeProvider.now().unix()) {
|
|
1526
|
-
this.log.trace("Tokens are expired");
|
|
1527
|
-
if (tokens.refresh_token) {
|
|
1528
|
-
this.log.trace("Trying to refresh tokens using refresh token");
|
|
1529
|
-
try {
|
|
1530
|
-
const newTokens = {
|
|
1531
|
-
...await this.provider(tokens).refresh(tokens.refresh_token, tokens.access_token),
|
|
1532
|
-
provider: tokens.provider,
|
|
1533
|
-
issued_at: this.dateTimeProvider.now().unix()
|
|
1534
|
-
};
|
|
1535
|
-
this.log.debug("Tokens refreshed successfully");
|
|
1536
|
-
return newTokens;
|
|
1537
|
-
} catch (e$1) {
|
|
1538
|
-
this.log.warn("Failed to refresh token", e$1);
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
return;
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
if (!tokens.issued_at && tokens.access_token) return;
|
|
1545
|
-
return tokens;
|
|
1546
|
-
}
|
|
1547
|
-
/**
|
|
1548
|
-
* Get user information.
|
|
1549
|
-
*/
|
|
1550
|
-
userinfo = $route({
|
|
1551
|
-
path: alephaServerAuthRoutes.userinfo,
|
|
1552
|
-
schema: { response: userinfoResponseSchema },
|
|
1553
|
-
handler: async ({ user, headers: headers$1, cookies }) => {
|
|
1554
|
-
const tokens = this.getTokens(cookies);
|
|
1555
|
-
if (tokens) {
|
|
1556
|
-
const provider = this.provider(tokens);
|
|
1557
|
-
if (!("realm" in provider.options)) {
|
|
1558
|
-
const user$1 = await provider.user(tokens);
|
|
1559
|
-
return {
|
|
1560
|
-
api: await this.serverLinksProvider.getUserApiLinks({
|
|
1561
|
-
authorization: headers$1.authorization,
|
|
1562
|
-
user: user$1
|
|
1563
|
-
}),
|
|
1564
|
-
user: user$1
|
|
1565
|
-
};
|
|
1566
|
-
}
|
|
1567
|
-
}
|
|
1568
|
-
return {
|
|
1569
|
-
api: await this.serverLinksProvider.getUserApiLinks({
|
|
1570
|
-
authorization: headers$1.authorization,
|
|
1571
|
-
user
|
|
1572
|
-
}),
|
|
1573
|
-
user
|
|
1574
|
-
};
|
|
1575
|
-
}
|
|
1576
|
-
});
|
|
1577
|
-
/**
|
|
1578
|
-
* Refresh a token for internal providers.
|
|
1579
|
-
*/
|
|
1580
|
-
refresh = $route({
|
|
1581
|
-
path: alephaServerAuthRoutes.refresh,
|
|
1582
|
-
method: "POST",
|
|
1583
|
-
schema: {
|
|
1584
|
-
query: t.object({ provider: t.text() }),
|
|
1585
|
-
body: t.object({
|
|
1586
|
-
refresh_token: t.text({ size: "rich" }),
|
|
1587
|
-
access_token: t.optional(t.text({
|
|
1588
|
-
size: "rich",
|
|
1589
|
-
description: "Required if provider has stateless refresh token on credentials mode"
|
|
1590
|
-
}))
|
|
1591
|
-
}),
|
|
1592
|
-
response: tokensSchema
|
|
1593
|
-
},
|
|
1594
|
-
handler: async ({ query, body, cookies }) => {
|
|
1595
|
-
const provider = this.provider(query);
|
|
1596
|
-
const tokens = {
|
|
1597
|
-
provider: query.provider,
|
|
1598
|
-
...await provider.refresh(body.refresh_token, body.access_token)
|
|
1599
|
-
};
|
|
1600
|
-
this.setTokens(tokens, cookies);
|
|
1601
|
-
return tokens;
|
|
1602
|
-
}
|
|
1603
|
-
});
|
|
1604
|
-
/**
|
|
1605
|
-
* Login for local password-based authentication.
|
|
1606
|
-
*/
|
|
1607
|
-
token = $route({
|
|
1608
|
-
path: alephaServerAuthRoutes.token,
|
|
1609
|
-
method: "POST",
|
|
1610
|
-
schema: {
|
|
1611
|
-
query: t.object({
|
|
1612
|
-
provider: t.text(),
|
|
1613
|
-
realm: t.optional(t.text({ description: "Realm name for multi-realm setups" }))
|
|
1614
|
-
}),
|
|
1615
|
-
body: t.object({
|
|
1616
|
-
username: t.text(),
|
|
1617
|
-
password: t.text()
|
|
1618
|
-
}),
|
|
1619
|
-
response: tokenResponseSchema
|
|
1620
|
-
},
|
|
1621
|
-
handler: async ({ query, body, cookies }) => {
|
|
1622
|
-
const provider = this.provider({
|
|
1623
|
-
provider: query.provider,
|
|
1624
|
-
realm: query.realm
|
|
1625
|
-
});
|
|
1626
|
-
const realm = "realm" in provider.options && provider.options.realm;
|
|
1627
|
-
if (!realm) throw new SecurityError(`Auth provider '${query.provider}' does not support password grant`);
|
|
1628
|
-
const credentials = "credentials" in provider.options && provider.options.credentials;
|
|
1629
|
-
if (!credentials) throw new SecurityError(`Auth provider '${query.provider}' does not support password grant`);
|
|
1630
|
-
console.log("->", body);
|
|
1631
|
-
let user;
|
|
1632
|
-
try {
|
|
1633
|
-
user = await credentials.account(body);
|
|
1634
|
-
} catch (e$1) {
|
|
1635
|
-
if (e$1 instanceof InvalidCredentialsError) throw e$1;
|
|
1636
|
-
this.log.error("Failed to authenticate user", e$1);
|
|
1637
|
-
throw new InvalidCredentialsError();
|
|
1638
|
-
}
|
|
1639
|
-
if (!user) throw new InvalidCredentialsError();
|
|
1640
|
-
const tokens = {
|
|
1641
|
-
provider: query.provider,
|
|
1642
|
-
...await realm.createToken(user)
|
|
1643
|
-
};
|
|
1644
|
-
this.setTokens(tokens, cookies);
|
|
1645
|
-
const api = await this.serverLinksProvider.getUserApiLinks({ user });
|
|
1646
|
-
return {
|
|
1647
|
-
...tokens,
|
|
1648
|
-
user,
|
|
1649
|
-
api
|
|
1650
|
-
};
|
|
1651
|
-
}
|
|
1652
|
-
});
|
|
1653
|
-
/**
|
|
1654
|
-
* Oauth2/OIDC login route.
|
|
1655
|
-
*/
|
|
1656
|
-
login = $route({
|
|
1657
|
-
path: alephaServerAuthRoutes.login,
|
|
1658
|
-
schema: { query: t.object({
|
|
1659
|
-
provider: t.text(),
|
|
1660
|
-
realm: t.optional(t.text({ description: "Realm name for multi-realm setups" })),
|
|
1661
|
-
redirect_uri: t.optional(t.text({ size: "rich" }))
|
|
1662
|
-
}) },
|
|
1663
|
-
handler: async ({ query, url, reply }) => {
|
|
1664
|
-
const provider = this.provider({
|
|
1665
|
-
provider: query.provider,
|
|
1666
|
-
realm: query.realm
|
|
1667
|
-
});
|
|
1668
|
-
const oauth = provider.oauth;
|
|
1669
|
-
if (!oauth) throw new SecurityError(`Auth provider '${query.provider}' does not support OAuth2`);
|
|
1670
|
-
const scope = provider.scope;
|
|
1671
|
-
let redirect_uri = provider.redirect_uri || alephaServerAuthRoutes.callback;
|
|
1672
|
-
if (redirect_uri.startsWith("/")) redirect_uri = `${url.protocol}//${url.host}${redirect_uri}`;
|
|
1673
|
-
const oidc = "oidc" in provider.options && provider.options.oidc;
|
|
1674
|
-
if (!oauth.serverMetadata().supportsPKCE()) {
|
|
1675
|
-
const state = randomState();
|
|
1676
|
-
const parameters$1 = {
|
|
1677
|
-
redirect_uri,
|
|
1678
|
-
state
|
|
1679
|
-
};
|
|
1680
|
-
if (oidc) parameters$1.nonce = randomState();
|
|
1681
|
-
if (scope) parameters$1.scope = scope;
|
|
1682
|
-
this.authorizationCode.set({
|
|
1683
|
-
state,
|
|
1684
|
-
nonce: parameters$1.nonce,
|
|
1685
|
-
redirectUri: query.redirect_uri ?? "/",
|
|
1686
|
-
provider: query.provider,
|
|
1687
|
-
realm: query.realm
|
|
1688
|
-
});
|
|
1689
|
-
reply.redirect(buildAuthorizationUrl(oauth, parameters$1).toString());
|
|
1690
|
-
return;
|
|
1691
|
-
}
|
|
1692
|
-
const codeVerifier = randomPKCECodeVerifier();
|
|
1693
|
-
const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
|
|
1694
|
-
const parameters = {
|
|
1695
|
-
redirect_uri,
|
|
1696
|
-
code_challenge: codeChallenge,
|
|
1697
|
-
code_challenge_method: "S256"
|
|
1698
|
-
};
|
|
1699
|
-
if (scope) parameters.scope = scope;
|
|
1700
|
-
this.authorizationCode.set({
|
|
1701
|
-
codeVerifier,
|
|
1702
|
-
redirectUri: query.redirect_uri ?? "/",
|
|
1703
|
-
provider: query.provider,
|
|
1704
|
-
realm: query.realm
|
|
1705
|
-
});
|
|
1706
|
-
reply.redirect(buildAuthorizationUrl(oauth, parameters).toString());
|
|
1707
|
-
}
|
|
1708
|
-
});
|
|
1709
|
-
/**
|
|
1710
|
-
* Callback for OAuth2/OIDC providers.
|
|
1711
|
-
* It handles the authorization code flow and retrieves the access token.
|
|
1712
|
-
*/
|
|
1713
|
-
callback = $route({
|
|
1714
|
-
path: alephaServerAuthRoutes.callback,
|
|
1715
|
-
handler: async ({ url, reply, cookies }) => {
|
|
1716
|
-
const authorizationCode = this.authorizationCode.get({ cookies });
|
|
1717
|
-
if (!authorizationCode) throw new BadRequestError("Missing code verifier");
|
|
1718
|
-
const provider = this.provider(authorizationCode);
|
|
1719
|
-
const oauth = provider.oauth;
|
|
1720
|
-
if (!oauth) throw new SecurityError(`Auth provider '${provider.name}' does not support OAuth2`);
|
|
1721
|
-
const redirectUri = authorizationCode.redirectUri ?? "/";
|
|
1722
|
-
const externalTokens = await authorizationCodeGrant(oauth, url, {
|
|
1723
|
-
pkceCodeVerifier: authorizationCode.codeVerifier,
|
|
1724
|
-
expectedState: authorizationCode.state,
|
|
1725
|
-
expectedNonce: authorizationCode.nonce
|
|
1726
|
-
}).then((tokens$1) => ({
|
|
1727
|
-
issued_at: this.dateTimeProvider.now().unix(),
|
|
1728
|
-
provider: provider.name,
|
|
1729
|
-
...tokens$1
|
|
1730
|
-
})).catch((e$1) => {
|
|
1731
|
-
this.log.error("Failed to get access token", e$1);
|
|
1732
|
-
throw new SecurityError("Failed to get access token", { cause: e$1 });
|
|
1733
|
-
});
|
|
1734
|
-
this.authorizationCode.del({ cookies });
|
|
1735
|
-
const realm = "realm" in provider.options && provider.options.realm;
|
|
1736
|
-
if (!realm) {
|
|
1737
|
-
this.setTokens(externalTokens, cookies);
|
|
1738
|
-
reply.redirect(redirectUri);
|
|
1739
|
-
return;
|
|
1740
|
-
}
|
|
1741
|
-
const user = await provider.user(externalTokens);
|
|
1742
|
-
const tokens = await realm.createToken(user);
|
|
1743
|
-
this.setTokens({
|
|
1744
|
-
...tokens,
|
|
1745
|
-
issued_at: this.dateTimeProvider.now().unix(),
|
|
1746
|
-
provider: provider.name
|
|
1747
|
-
}, cookies);
|
|
1748
|
-
reply.redirect(redirectUri);
|
|
1749
|
-
}
|
|
1750
|
-
});
|
|
1751
|
-
/**
|
|
1752
|
-
* Logout route for OAuth2/OIDC providers.
|
|
1753
|
-
*/
|
|
1754
|
-
logout = $route({
|
|
1755
|
-
path: alephaServerAuthRoutes.logout,
|
|
1756
|
-
method: "GET",
|
|
1757
|
-
schema: { query: t.object({ post_logout_redirect_uri: t.optional(t.text()) }) },
|
|
1758
|
-
handler: async ({ query, reply, cookies }) => {
|
|
1759
|
-
const redirect = query.post_logout_redirect_uri ?? "/";
|
|
1760
|
-
const tokens = this.getTokens(cookies);
|
|
1761
|
-
if (!tokens) {
|
|
1762
|
-
reply.redirect(redirect);
|
|
1763
|
-
return;
|
|
1764
|
-
}
|
|
1765
|
-
const provider = this.provider(tokens.provider);
|
|
1766
|
-
this.tokens.del({ cookies });
|
|
1767
|
-
if ("realm" in provider.options && tokens.refresh_token) {
|
|
1768
|
-
const onDeleteSession = provider.options.realm.options.settings?.onDeleteSession;
|
|
1769
|
-
if (onDeleteSession) try {
|
|
1770
|
-
await onDeleteSession(tokens.refresh_token);
|
|
1771
|
-
} catch (e$1) {
|
|
1772
|
-
this.log.error("Failed to delete session", e$1);
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
const oauth = provider.oauth;
|
|
1776
|
-
if (!oauth) {
|
|
1777
|
-
reply.redirect(redirect);
|
|
1778
|
-
return;
|
|
1779
|
-
}
|
|
1780
|
-
const params = new URLSearchParams();
|
|
1781
|
-
const idToken = tokens?.id_token;
|
|
1782
|
-
params.set("post_logout_redirect_uri", redirect);
|
|
1783
|
-
if (idToken) params.set("id_token_hint", idToken);
|
|
1784
|
-
const customLogoutUri = "oidc" in provider.options ? provider.options.oidc?.logoutUri : void 0;
|
|
1785
|
-
if (customLogoutUri) {
|
|
1786
|
-
reply.redirect(`${customLogoutUri}?${params}`);
|
|
1787
|
-
return;
|
|
1788
|
-
}
|
|
1789
|
-
if (!oauth.serverMetadata().end_session_endpoint) {
|
|
1790
|
-
reply.redirect(redirect);
|
|
1791
|
-
return;
|
|
1792
|
-
}
|
|
1793
|
-
reply.redirect(buildEndSessionUrl(oauth, params).toString());
|
|
1794
|
-
}
|
|
1795
|
-
});
|
|
1796
|
-
/**
|
|
1797
|
-
* Find an auth provider by name and optionally by realm.
|
|
1798
|
-
* When realm is specified, it filters providers by both name and realm.
|
|
1799
|
-
* This enables multi-realm setups where multiple providers share the same name (e.g., "credentials").
|
|
1800
|
-
*/
|
|
1801
|
-
provider(opts) {
|
|
1802
|
-
const name = typeof opts === "string" ? opts : opts.provider;
|
|
1803
|
-
const realmName = typeof opts === "string" ? void 0 : opts.realm;
|
|
1804
|
-
const identity = this.identities.find((identity$1) => {
|
|
1805
|
-
if (identity$1.name !== name) return false;
|
|
1806
|
-
if (realmName && identity$1.realm?.name !== realmName) return false;
|
|
1807
|
-
return true;
|
|
1808
|
-
});
|
|
1809
|
-
if (!identity) throw new SecurityError(`Auth provider '${name}'${realmName ? ` for realm '${realmName}'` : ""} not found`);
|
|
1810
|
-
return identity;
|
|
1811
|
-
}
|
|
1812
|
-
getTokens(cookies) {
|
|
1813
|
-
return this.tokens.get({ cookies });
|
|
1814
|
-
}
|
|
1815
|
-
setTokens(tokens, cookies) {
|
|
1816
|
-
const exp = tokens.refresh_token_expires_in || tokens.refresh_expires_in || tokens.expires_in;
|
|
1817
|
-
const ttl = exp ? this.dateTimeProvider.duration(exp, "seconds") : void 0;
|
|
1818
|
-
this.tokens.set(tokens, {
|
|
1819
|
-
cookies,
|
|
1820
|
-
ttl
|
|
1821
|
-
});
|
|
1822
|
-
}
|
|
1823
|
-
};
|
|
1824
|
-
|
|
1825
|
-
//#endregion
|
|
1826
|
-
//#region ../../src/server-auth/schemas/authenticationProviderSchema.ts
|
|
1827
|
-
const authenticationProviderSchema = t.object({
|
|
1828
|
-
name: t.text({ description: "Name of the authentication provider." }),
|
|
1829
|
-
type: t.enum([
|
|
1830
|
-
"OAUTH2",
|
|
1831
|
-
"OIDC",
|
|
1832
|
-
"CREDENTIALS"
|
|
1833
|
-
], { description: "Type of the authentication provider." })
|
|
1834
|
-
}, { title: "AuthenticationProvider" });
|
|
1835
|
-
|
|
1836
|
-
//#endregion
|
|
1837
|
-
//#region ../../src/server-auth/primitives/$authCredentials.ts
|
|
1838
|
-
/**
|
|
1839
|
-
* Already configured Credentials authentication primitive.
|
|
1840
|
-
*
|
|
1841
|
-
* Uses username and password to authenticate users.
|
|
1842
|
-
*/
|
|
1843
|
-
const $authCredentials = (realm, options = {}) => {
|
|
1844
|
-
const name = "credentials";
|
|
1845
|
-
const account = realm.login ? realm.login(name) : options.account;
|
|
1846
|
-
if (!account) throw new AlephaError("Credentials authentication requires a login function in the realm primitive.");
|
|
1847
|
-
return $auth({
|
|
1848
|
-
realm,
|
|
1849
|
-
name,
|
|
1850
|
-
credentials: { account }
|
|
1851
|
-
});
|
|
1852
|
-
};
|
|
1853
|
-
|
|
1854
|
-
//#endregion
|
|
1855
|
-
//#region ../../src/server-auth/primitives/$authGithub.ts
|
|
1856
|
-
/**
|
|
1857
|
-
* Already configured GitHub authentication primitive.
|
|
1858
|
-
*
|
|
1859
|
-
* Uses OAuth2 to authenticate users via their GitHub accounts.
|
|
1860
|
-
* Upon successful authentication, it links the GitHub account to a user session.
|
|
1861
|
-
*
|
|
1862
|
-
* Environment Variables:
|
|
1863
|
-
* - `GITHUB_CLIENT_ID`: The client ID obtained from the GitHub Developer Settings.
|
|
1864
|
-
* - `GITHUB_CLIENT_SECRET`: The client secret obtained from the GitHub Developer Settings.
|
|
1865
|
-
*/
|
|
1866
|
-
const $authGithub = (realm, options = {}) => {
|
|
1867
|
-
const { alepha } = $context();
|
|
1868
|
-
const env = alepha.parseEnv(t.object({
|
|
1869
|
-
GITHUB_CLIENT_ID: t.optional(t.text()),
|
|
1870
|
-
GITHUB_CLIENT_SECRET: t.optional(t.text())
|
|
1871
|
-
}));
|
|
1872
|
-
const disabled = !env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET;
|
|
1873
|
-
const name = "github";
|
|
1874
|
-
const account = options.account ?? (realm.link ? realm.link(name) : void 0);
|
|
1875
|
-
if (!account) throw new AlephaError("Authentication requires a link function in the realm primitive.");
|
|
1876
|
-
return $auth({
|
|
1877
|
-
realm,
|
|
1878
|
-
name,
|
|
1879
|
-
oauth: {
|
|
1880
|
-
clientId: env.GITHUB_CLIENT_ID,
|
|
1881
|
-
clientSecret: env.GITHUB_CLIENT_SECRET,
|
|
1882
|
-
authorization: "https://github.com/login/oauth/authorize",
|
|
1883
|
-
token: "https://github.com/login/oauth/access_token",
|
|
1884
|
-
scope: "read:user user:email",
|
|
1885
|
-
userinfo: async (tokens) => {
|
|
1886
|
-
const BASE_URL = "https://api.github.com";
|
|
1887
|
-
const res = await fetch(`${BASE_URL}/user`, { headers: {
|
|
1888
|
-
Authorization: `Bearer ${tokens.access_token}`,
|
|
1889
|
-
"User-Agent": "Alepha"
|
|
1890
|
-
} }).then((res$1) => res$1.json());
|
|
1891
|
-
const user = { sub: res.id.toString() };
|
|
1892
|
-
if (res.email) user.email = res.email;
|
|
1893
|
-
if (res.name) user.name = res.name.trim();
|
|
1894
|
-
if (res.avatar_url) user.picture = res.avatar_url;
|
|
1895
|
-
if (!user.email) {
|
|
1896
|
-
const res$1 = await fetch(`${BASE_URL}/user/emails`, { headers: {
|
|
1897
|
-
Authorization: `Bearer ${tokens.access_token}`,
|
|
1898
|
-
"User-Agent": "Alepha"
|
|
1899
|
-
} });
|
|
1900
|
-
if (res$1.ok) {
|
|
1901
|
-
const emails = await res$1.json();
|
|
1902
|
-
user.email = (emails.find((e$1) => e$1.primary) ?? emails[0]).email;
|
|
1903
|
-
}
|
|
1904
|
-
}
|
|
1905
|
-
return user;
|
|
1906
|
-
},
|
|
1907
|
-
...options,
|
|
1908
|
-
account
|
|
1909
|
-
},
|
|
1910
|
-
disabled
|
|
1911
|
-
});
|
|
1912
|
-
};
|
|
1913
|
-
|
|
1914
|
-
//#endregion
|
|
1915
|
-
//#region ../../src/server-auth/primitives/$authGoogle.ts
|
|
1916
|
-
/**
|
|
1917
|
-
* Already configured Google authentication primitive.
|
|
1918
|
-
*
|
|
1919
|
-
* Uses OpenID Connect (OIDC) to authenticate users via their Google accounts.
|
|
1920
|
-
* Upon successful authentication, it links the Google account to a user session.
|
|
1921
|
-
*
|
|
1922
|
-
* Environment Variables:
|
|
1923
|
-
* - `GOOGLE_CLIENT_ID`: The client ID obtained from the Google Developer Console.
|
|
1924
|
-
* - `GOOGLE_CLIENT_SECRET`: The client secret obtained from the Google Developer Console.
|
|
1925
|
-
*/
|
|
1926
|
-
const $authGoogle = (realm, options = {}) => {
|
|
1927
|
-
const { alepha } = $context();
|
|
1928
|
-
const env = alepha.parseEnv(t.object({
|
|
1929
|
-
GOOGLE_CLIENT_ID: t.optional(t.text()),
|
|
1930
|
-
GOOGLE_CLIENT_SECRET: t.optional(t.text())
|
|
1931
|
-
}));
|
|
1932
|
-
const disabled = !env.GOOGLE_CLIENT_ID || !env.GOOGLE_CLIENT_SECRET;
|
|
1933
|
-
const name = "google";
|
|
1934
|
-
const account = options.account ?? (realm.link ? realm.link(name) : void 0);
|
|
1935
|
-
if (!account) throw new AlephaError("Authentication requires a link function in the realm primitive.");
|
|
1936
|
-
return $auth({
|
|
1937
|
-
realm,
|
|
1938
|
-
name,
|
|
1939
|
-
oidc: {
|
|
1940
|
-
issuer: "https://accounts.google.com",
|
|
1941
|
-
clientId: env.GOOGLE_CLIENT_ID,
|
|
1942
|
-
clientSecret: env.GOOGLE_CLIENT_SECRET,
|
|
1943
|
-
...options,
|
|
1944
|
-
account
|
|
1945
|
-
},
|
|
1946
|
-
disabled
|
|
1947
|
-
});
|
|
1948
|
-
};
|
|
1949
|
-
|
|
1950
|
-
//#endregion
|
|
1951
|
-
//#region ../../src/server-auth/index.ts
|
|
1952
|
-
/**
|
|
1953
|
-
* Allow authentication services for server applications.
|
|
1954
|
-
* It provides login and logout functionalities.
|
|
1955
|
-
*
|
|
1956
|
-
* There are multiple authentication providers available (e.g., Google, GitHub).
|
|
1957
|
-
* You can also delegate authentication to your own OIDC/OAuth2, for example using Keycloak or Auth0.
|
|
1958
|
-
*
|
|
1959
|
-
* It's cookie-based and SSR friendly.
|
|
1960
|
-
*
|
|
1961
|
-
* @see {@link $auth}
|
|
1962
|
-
* @see {@link ServerAuthProvider}
|
|
1963
|
-
* @module alepha.server.auth
|
|
1964
|
-
*/
|
|
1965
|
-
const AlephaServerAuth = $module({
|
|
1966
|
-
name: "alepha.server.auth",
|
|
1967
|
-
primitives: [$auth],
|
|
1968
|
-
services: [AlephaServerCookies, ServerAuthProvider]
|
|
1969
|
-
});
|
|
1970
|
-
|
|
1971
|
-
//#endregion
|
|
1972
|
-
export { $auth, $authCredentials, $authGithub, $authGoogle, AlephaServerAuth, AuthPrimitive, ServerAuthProvider, alephaServerAuthRoutes, authenticationProviderSchema, tokenResponseSchema, tokensSchema, userinfoResponseSchema };
|
|
1973
|
-
//# sourceMappingURL=index.js.map
|