alepha 0.14.4 → 0.15.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 +1 -4
- package/dist/api/audits/index.d.ts +619 -731
- package/dist/api/audits/index.d.ts.map +1 -1
- package/dist/api/files/index.d.ts +185 -298
- package/dist/api/files/index.d.ts.map +1 -1
- package/dist/api/files/index.js +0 -1
- package/dist/api/files/index.js.map +1 -1
- package/dist/api/jobs/index.d.ts +245 -356
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/notifications/index.d.ts +238 -350
- package/dist/api/notifications/index.d.ts.map +1 -1
- package/dist/api/parameters/index.d.ts +499 -611
- package/dist/api/parameters/index.d.ts.map +1 -1
- package/dist/api/users/index.browser.js +1 -2
- package/dist/api/users/index.browser.js.map +1 -1
- package/dist/api/users/index.d.ts +1697 -1804
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/users/index.js +178 -151
- package/dist/api/users/index.js.map +1 -1
- package/dist/api/verifications/index.d.ts +132 -132
- package/dist/api/verifications/index.d.ts.map +1 -1
- package/dist/batch/index.d.ts +122 -122
- package/dist/batch/index.d.ts.map +1 -1
- package/dist/batch/index.js +1 -2
- package/dist/batch/index.js.map +1 -1
- package/dist/bucket/index.d.ts +163 -163
- package/dist/bucket/index.d.ts.map +1 -1
- package/dist/cache/core/index.d.ts +46 -46
- package/dist/cache/core/index.d.ts.map +1 -1
- package/dist/cache/redis/index.d.ts.map +1 -1
- package/dist/cli/index.d.ts +302 -299
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +966 -564
- package/dist/cli/index.js.map +1 -1
- package/dist/command/index.d.ts +303 -299
- package/dist/command/index.d.ts.map +1 -1
- package/dist/command/index.js +11 -7
- package/dist/command/index.js.map +1 -1
- package/dist/core/index.browser.js +419 -99
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.d.ts +718 -625
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +420 -99
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js +419 -99
- package/dist/core/index.native.js.map +1 -1
- package/dist/datetime/index.d.ts +44 -44
- package/dist/datetime/index.d.ts.map +1 -1
- package/dist/datetime/index.js +4 -4
- package/dist/datetime/index.js.map +1 -1
- package/dist/email/index.d.ts +97 -50
- package/dist/email/index.d.ts.map +1 -1
- package/dist/email/index.js +129 -33
- package/dist/email/index.js.map +1 -1
- package/dist/fake/index.d.ts +7981 -14
- package/dist/fake/index.d.ts.map +1 -1
- package/dist/file/index.d.ts +523 -390
- package/dist/file/index.d.ts.map +1 -1
- package/dist/file/index.js +253 -1
- package/dist/file/index.js.map +1 -1
- package/dist/lock/core/index.d.ts +208 -208
- package/dist/lock/core/index.d.ts.map +1 -1
- package/dist/lock/redis/index.d.ts.map +1 -1
- package/dist/logger/index.d.ts +25 -26
- package/dist/logger/index.d.ts.map +1 -1
- package/dist/mcp/index.d.ts +197 -197
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/orm/chunk-DtkW-qnP.js +38 -0
- package/dist/orm/index.browser.js.map +1 -1
- package/dist/orm/index.bun.js +2814 -0
- package/dist/orm/index.bun.js.map +1 -0
- package/dist/orm/index.d.ts +1205 -1057
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +2056 -1753
- package/dist/orm/index.js.map +1 -1
- package/dist/queue/core/index.d.ts +248 -248
- package/dist/queue/core/index.d.ts.map +1 -1
- package/dist/queue/redis/index.d.ts.map +1 -1
- package/dist/redis/index.bun.js +285 -0
- package/dist/redis/index.bun.js.map +1 -0
- package/dist/redis/index.d.ts +118 -136
- package/dist/redis/index.d.ts.map +1 -1
- package/dist/redis/index.js +18 -38
- package/dist/redis/index.js.map +1 -1
- package/dist/retry/index.d.ts +69 -69
- package/dist/retry/index.d.ts.map +1 -1
- package/dist/router/index.d.ts +6 -6
- package/dist/router/index.d.ts.map +1 -1
- package/dist/scheduler/index.d.ts +25 -25
- package/dist/scheduler/index.d.ts.map +1 -1
- package/dist/security/index.browser.js +5 -1
- package/dist/security/index.browser.js.map +1 -1
- package/dist/security/index.d.ts +417 -254
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/index.js +386 -86
- package/dist/security/index.js.map +1 -1
- package/dist/server/auth/index.d.ts +277 -277
- package/dist/server/auth/index.d.ts.map +1 -1
- package/dist/server/auth/index.js +20 -20
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/cache/index.d.ts +60 -57
- package/dist/server/cache/index.d.ts.map +1 -1
- package/dist/server/cache/index.js +1 -1
- package/dist/server/cache/index.js.map +1 -1
- package/dist/server/compress/index.d.ts +3 -3
- package/dist/server/compress/index.d.ts.map +1 -1
- package/dist/server/cookies/index.d.ts +6 -6
- package/dist/server/cookies/index.d.ts.map +1 -1
- package/dist/server/cookies/index.js +3 -3
- package/dist/server/cookies/index.js.map +1 -1
- package/dist/server/core/index.d.ts +242 -150
- package/dist/server/core/index.d.ts.map +1 -1
- package/dist/server/core/index.js +288 -122
- package/dist/server/core/index.js.map +1 -1
- package/dist/server/cors/index.d.ts +11 -12
- package/dist/server/cors/index.d.ts.map +1 -1
- package/dist/server/health/index.d.ts +0 -1
- package/dist/server/health/index.d.ts.map +1 -1
- package/dist/server/helmet/index.d.ts +2 -2
- package/dist/server/helmet/index.d.ts.map +1 -1
- package/dist/server/links/index.browser.js.map +1 -1
- package/dist/server/links/index.d.ts +84 -85
- package/dist/server/links/index.d.ts.map +1 -1
- package/dist/server/links/index.js +1 -2
- package/dist/server/links/index.js.map +1 -1
- package/dist/server/metrics/index.d.ts.map +1 -1
- package/dist/server/multipart/index.d.ts +6 -6
- package/dist/server/multipart/index.d.ts.map +1 -1
- package/dist/server/proxy/index.d.ts +102 -103
- package/dist/server/proxy/index.d.ts.map +1 -1
- package/dist/server/rate-limit/index.d.ts +16 -16
- package/dist/server/rate-limit/index.d.ts.map +1 -1
- package/dist/server/static/index.d.ts +44 -44
- package/dist/server/static/index.d.ts.map +1 -1
- package/dist/server/swagger/index.d.ts +48 -49
- package/dist/server/swagger/index.d.ts.map +1 -1
- package/dist/server/swagger/index.js +1 -2
- package/dist/server/swagger/index.js.map +1 -1
- package/dist/sms/index.d.ts +13 -11
- package/dist/sms/index.d.ts.map +1 -1
- package/dist/sms/index.js +7 -7
- package/dist/sms/index.js.map +1 -1
- package/dist/thread/index.d.ts +71 -72
- package/dist/thread/index.d.ts.map +1 -1
- package/dist/topic/core/index.d.ts +318 -318
- package/dist/topic/core/index.d.ts.map +1 -1
- package/dist/topic/redis/index.d.ts +6 -6
- package/dist/topic/redis/index.d.ts.map +1 -1
- package/dist/vite/index.d.ts +5720 -159
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +41 -18
- package/dist/vite/index.js.map +1 -1
- package/dist/websocket/index.browser.js +6 -6
- package/dist/websocket/index.browser.js.map +1 -1
- package/dist/websocket/index.d.ts +247 -247
- package/dist/websocket/index.d.ts.map +1 -1
- package/dist/websocket/index.js +6 -6
- package/dist/websocket/index.js.map +1 -1
- package/package.json +9 -14
- package/src/api/files/controllers/AdminFileStatsController.ts +0 -1
- package/src/api/users/atoms/realmAuthSettingsAtom.ts +5 -0
- package/src/api/users/controllers/{UserRealmController.ts → RealmController.ts} +11 -11
- package/src/api/users/entities/users.ts +1 -1
- package/src/api/users/index.ts +8 -8
- package/src/api/users/primitives/{$userRealm.ts → $realm.ts} +17 -19
- package/src/api/users/providers/{UserRealmProvider.ts → RealmProvider.ts} +26 -30
- package/src/api/users/schemas/{userRealmConfigSchema.ts → realmConfigSchema.ts} +2 -2
- package/src/api/users/services/CredentialService.ts +7 -7
- package/src/api/users/services/IdentityService.ts +4 -4
- package/src/api/users/services/RegistrationService.spec.ts +25 -27
- package/src/api/users/services/RegistrationService.ts +38 -27
- package/src/api/users/services/SessionCrudService.ts +3 -3
- package/src/api/users/services/SessionService.spec.ts +3 -3
- package/src/api/users/services/SessionService.ts +28 -9
- package/src/api/users/services/UserService.ts +7 -7
- package/src/batch/providers/BatchProvider.ts +1 -2
- package/src/cli/apps/AlephaPackageBuilderCli.ts +38 -19
- package/src/cli/assets/apiHelloControllerTs.ts +18 -0
- package/src/cli/assets/apiIndexTs.ts +16 -0
- package/src/cli/assets/claudeMd.ts +303 -0
- package/src/cli/assets/mainBrowserTs.ts +2 -2
- package/src/cli/assets/mainServerTs.ts +24 -0
- package/src/cli/assets/webAppRouterTs.ts +15 -0
- package/src/cli/assets/webHelloComponentTsx.ts +16 -0
- package/src/cli/assets/webIndexTs.ts +16 -0
- package/src/cli/commands/build.ts +41 -21
- package/src/cli/commands/db.ts +21 -18
- package/src/cli/commands/deploy.ts +17 -5
- package/src/cli/commands/dev.ts +13 -17
- package/src/cli/commands/format.ts +8 -2
- package/src/cli/commands/init.ts +74 -29
- package/src/cli/commands/lint.ts +8 -2
- package/src/cli/commands/test.ts +8 -2
- package/src/cli/commands/typecheck.ts +5 -1
- package/src/cli/commands/verify.ts +4 -2
- package/src/cli/services/AlephaCliUtils.ts +39 -600
- package/src/cli/services/PackageManagerUtils.ts +301 -0
- package/src/cli/services/ProjectScaffolder.ts +306 -0
- package/src/command/helpers/Runner.ts +15 -3
- package/src/core/__tests__/Alepha-graph.spec.ts +4 -0
- package/src/core/index.shared.ts +1 -0
- package/src/core/index.ts +2 -0
- package/src/core/primitives/$hook.ts +6 -2
- package/src/core/primitives/$module.spec.ts +4 -0
- package/src/core/providers/AlsProvider.ts +1 -1
- package/src/core/providers/CodecManager.spec.ts +12 -6
- package/src/core/providers/CodecManager.ts +26 -6
- package/src/core/providers/EventManager.ts +169 -13
- package/src/core/providers/KeylessJsonSchemaCodec.spec.ts +621 -0
- package/src/core/providers/KeylessJsonSchemaCodec.ts +407 -0
- package/src/core/providers/StateManager.spec.ts +27 -16
- package/src/email/providers/LocalEmailProvider.spec.ts +111 -87
- package/src/email/providers/LocalEmailProvider.ts +52 -15
- package/src/email/providers/NodemailerEmailProvider.ts +167 -56
- package/src/file/errors/FileError.ts +7 -0
- package/src/file/index.ts +9 -1
- package/src/file/providers/MemoryFileSystemProvider.ts +393 -0
- package/src/orm/index.browser.ts +1 -19
- package/src/orm/index.bun.ts +77 -0
- package/src/orm/index.shared-server.ts +22 -0
- package/src/orm/index.shared.ts +15 -0
- package/src/orm/index.ts +19 -39
- package/src/orm/providers/drivers/BunPostgresProvider.ts +3 -5
- package/src/orm/providers/drivers/BunSqliteProvider.ts +1 -1
- package/src/orm/providers/drivers/CloudflareD1Provider.ts +4 -0
- package/src/orm/providers/drivers/DatabaseProvider.ts +4 -0
- package/src/orm/providers/drivers/PglitePostgresProvider.ts +4 -0
- package/src/orm/services/Repository.ts +8 -0
- package/src/redis/index.bun.ts +35 -0
- package/src/redis/providers/BunRedisProvider.ts +12 -43
- package/src/redis/providers/BunRedisSubscriberProvider.ts +2 -3
- package/src/redis/providers/NodeRedisProvider.ts +16 -34
- package/src/{server/security → security}/__tests__/BasicAuth.spec.ts +11 -11
- package/src/{server/security → security}/__tests__/ServerSecurityProvider-realm.spec.ts +21 -16
- package/src/{server/security/providers → security/__tests__}/ServerSecurityProvider.spec.ts +5 -5
- package/src/security/index.browser.ts +5 -0
- package/src/security/index.ts +90 -7
- package/src/security/primitives/{$realm.spec.ts → $issuer.spec.ts} +11 -11
- package/src/security/primitives/{$realm.ts → $issuer.ts} +20 -17
- package/src/security/primitives/$role.ts +5 -5
- package/src/security/primitives/$serviceAccount.spec.ts +5 -5
- package/src/security/primitives/$serviceAccount.ts +3 -3
- package/src/{server/security → security}/providers/ServerSecurityProvider.ts +5 -7
- package/src/server/auth/primitives/$auth.ts +10 -10
- package/src/server/auth/primitives/$authCredentials.ts +3 -3
- package/src/server/auth/primitives/$authGithub.ts +3 -3
- package/src/server/auth/primitives/$authGoogle.ts +3 -3
- package/src/server/auth/providers/ServerAuthProvider.ts +13 -13
- package/src/server/cache/providers/ServerCacheProvider.ts +1 -1
- package/src/server/cookies/providers/ServerCookiesProvider.ts +3 -3
- package/src/server/core/providers/NodeHttpServerProvider.ts +25 -6
- package/src/server/core/providers/ServerBodyParserProvider.ts +19 -23
- package/src/server/core/providers/ServerLoggerProvider.ts +23 -19
- package/src/server/core/providers/ServerProvider.ts +144 -21
- package/src/server/core/providers/ServerRouterProvider.ts +259 -115
- package/src/server/core/providers/ServerTimingProvider.ts +2 -2
- package/src/server/links/index.ts +1 -1
- package/src/server/links/providers/LinkProvider.ts +1 -1
- package/src/server/swagger/index.ts +1 -1
- package/src/sms/providers/LocalSmsProvider.spec.ts +153 -111
- package/src/sms/providers/LocalSmsProvider.ts +8 -7
- package/src/vite/helpers/boot.ts +28 -17
- package/src/vite/tasks/buildServer.ts +12 -1
- package/src/vite/tasks/devServer.ts +3 -1
- package/src/vite/tasks/generateCloudflare.ts +7 -0
- package/dist/server/security/index.browser.js +0 -13
- package/dist/server/security/index.browser.js.map +0 -1
- package/dist/server/security/index.d.ts +0 -173
- package/dist/server/security/index.d.ts.map +0 -1
- package/dist/server/security/index.js +0 -311
- package/dist/server/security/index.js.map +0 -1
- package/src/cli/assets/appRouterTs.ts +0 -9
- package/src/cli/assets/mainTs.ts +0 -13
- package/src/server/security/index.browser.ts +0 -10
- package/src/server/security/index.ts +0 -94
- /package/src/{server/security → security}/primitives/$basicAuth.ts +0 -0
- /package/src/{server/security → security}/providers/ServerBasicAuthProvider.ts +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/auth/constants/routes.ts","../../../src/server/auth/schemas/authenticationProviderSchema.ts","../../../src/server/auth/schemas/tokenResponseSchema.ts","../../../src/server/auth/schemas/tokensSchema.ts","../../../src/server/auth/schemas/userinfoResponseSchema.ts","../../../src/server/auth/providers/ServerAuthProvider.ts","../../../src/server/auth/primitives/$auth.ts","../../../src/server/auth/primitives/$authCredentials.ts","../../../src/server/auth/primitives/$authGithub.ts","../../../src/server/auth/primitives/$authGoogle.ts","../../../src/server/auth/index.ts"],"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/auth/constants/routes.ts","../../../src/server/auth/schemas/authenticationProviderSchema.ts","../../../src/server/auth/schemas/tokenResponseSchema.ts","../../../src/server/auth/schemas/tokensSchema.ts","../../../src/server/auth/schemas/userinfoResponseSchema.ts","../../../src/server/auth/providers/ServerAuthProvider.ts","../../../src/server/auth/primitives/$auth.ts","../../../src/server/auth/primitives/$authCredentials.ts","../../../src/server/auth/primitives/$authGithub.ts","../../../src/server/auth/primitives/$authGoogle.ts","../../../src/server/auth/index.ts"],"mappings":";;;;;;;;;;;;cAAa,sBAAA;EAAA,KAAA;EAAA,QAAA;EAAA,MAAA;EAAA,KAAA;EAAA,OAAA;EAAA,QAAA;AAAA;;;cCEA,4BAAA,YAA4B,OAAA;EAAA,IAAA,EAYxC,SAAA,CAAA,OAAA;EAAA,IAAA;;KAEW,sBAAA,GAAyB,MAAA,QAC5B,4BAAA;;;cCZI,mBAAA,YAAmB,OAAA;EAAA,QAAA,EAG9B,SAAA,CAAA,OAAA;EAAA,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAEU,aAAA,GAAgB,MAAA,QAAc,mBAAA;;;cCP7B,YAAA,YAAY,OAAA;EAAA,QAAA,EAevB,SAAA,CAAA,OAAA;EAAA,YAAA;;;;;;;;;KAEU,MAAA,GAAS,MAAA,QAAc,YAAA;;;cChBtB,sBAAA,YAAsB,OAAA;EAAA,IAAA;QAGjC,SAAA,CAAA,OAAA;IAAA,IAAA;;;;;;;;;;;;;;;;;;;;;;;;KAEU,gBAAA,GAAmB,MAAA,QAAc,sBAAA;;;cCqBhC,kBAAA;EAAA,mBAAA,GAAA,EAAkB,cAAA,CACP,MAAA;EAAA,mBAAA,MAAA,EACG,MAAA;EAAA,mBAAA,qBAAA,EACe,qBAAA;EAAA,mBAAA,gBAAA,EACL,gBAAA;EAAA,mBAAA,mBAAA,EACG,mBAAA;EAAA,mBAAA,iBAAA,EAEF,sBAAA,CAAA,uBAAA,WAAA,OAAA;IAAA,QAAA,EAFE,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B,kBAAA,KAAuB,KAAA,CAAM,WAAA;AAAA;AAAA,UAG9C,WAAA;EAAA,KAAA,IAAA,QAAA,cAAA,KAAA,EAGF,WAAA,KAAgB,KAAA,CAAM,WAAA;AAAA;;;;ACzbrC;;;;cAAa,gBAAA,GAAA,KAAA,EACJ,eAAA,GAAkB,WAAA,EAAA,OAAA,GAChB,OAAA,CAAQ,kBAAA,MAAD,aAAA;;;;ACIlB;;;;;;;;;cAAa,WAAA,GAAA,KAAA,EACJ,eAAA,GAAkB,UAAA,EAAA,OAAA,GAChB,OAAA,CAAQ,WAAA,MAAD,aAAA;;;;ACHlB;;;;;;;;;cAAa,WAAA,GAAA,KAAA,EACJ,eAAA,GAAkB,UAAA,EAAA,OAAA,GAChB,OAAA,CAAQ,WAAA,MAAD,aAAA;;;;;;ACRgC;;;;mCAWf,WAAA;EAAA;AAAA;AAAA;;;AAmBnC;;;;;;;;;;AAnBmC,cAmBtB,gBAAA,EAAgB,SAAA,CAAA,OAAA,CAI3B,SAAA,CAJ2B,MAAA"}
|
|
@@ -52,8 +52,8 @@ var AuthPrimitive = class extends Primitive {
|
|
|
52
52
|
get name() {
|
|
53
53
|
return this.options.name ?? this.config.propertyKey;
|
|
54
54
|
}
|
|
55
|
-
get
|
|
56
|
-
if ("
|
|
55
|
+
get issuer() {
|
|
56
|
+
if ("issuer" in this.options) return this.options.issuer;
|
|
57
57
|
}
|
|
58
58
|
get jwks_uri() {
|
|
59
59
|
const jwks = this.oauth?.serverMetadata().jwks_uri;
|
|
@@ -75,8 +75,8 @@ var AuthPrimitive = class extends Primitive {
|
|
|
75
75
|
* Can be used on oauth2, oidc or credentials auth providers.
|
|
76
76
|
*/
|
|
77
77
|
async refresh(refreshToken, accessToken) {
|
|
78
|
-
if ("
|
|
79
|
-
throw new SecurityError("Failed to refresh access token using the refresh token (
|
|
78
|
+
if ("issuer" in this.options) return this.options.issuer.refreshToken(refreshToken, accessToken).then((it) => it.tokens).catch((error) => {
|
|
79
|
+
throw new SecurityError("Failed to refresh access token using the refresh token (issuer)", { cause: error });
|
|
80
80
|
});
|
|
81
81
|
else if (this.oauth) try {
|
|
82
82
|
return {
|
|
@@ -86,7 +86,7 @@ var AuthPrimitive = class extends Primitive {
|
|
|
86
86
|
} catch (error) {
|
|
87
87
|
throw new SecurityError("Failed to refresh access token using the refresh token (oauth2)", { cause: error });
|
|
88
88
|
}
|
|
89
|
-
throw new AlephaError("No
|
|
89
|
+
throw new AlephaError("No issuer or OAuth2 configuration available for refreshing the access token");
|
|
90
90
|
}
|
|
91
91
|
/**
|
|
92
92
|
* Extracts user information from the access token.
|
|
@@ -218,8 +218,8 @@ var ServerAuthProvider = class {
|
|
|
218
218
|
const providers = [];
|
|
219
219
|
for (const identity of this.identities) {
|
|
220
220
|
if (filters.realmName) {
|
|
221
|
-
const
|
|
222
|
-
if (!
|
|
221
|
+
const issuer = identity.issuer;
|
|
222
|
+
if (!issuer || issuer.name !== filters.realmName) continue;
|
|
223
223
|
}
|
|
224
224
|
const type = "oidc" in identity.options ? "OIDC" : "oauth" in identity.options ? "OAUTH2" : "credentials" in identity.options ? "CREDENTIALS" : void 0;
|
|
225
225
|
if (!type) continue;
|
|
@@ -257,7 +257,7 @@ var ServerAuthProvider = class {
|
|
|
257
257
|
}
|
|
258
258
|
}
|
|
259
259
|
if (!request.headers.authorization) {
|
|
260
|
-
for (const provider of this.identities) if (
|
|
260
|
+
for (const provider of this.identities) if ("fallback" in provider.options && !!provider.options.fallback) {
|
|
261
261
|
const token = await provider.options.fallback();
|
|
262
262
|
if (token) {
|
|
263
263
|
request.headers.authorization = `Bearer ${token}`;
|
|
@@ -392,8 +392,8 @@ var ServerAuthProvider = class {
|
|
|
392
392
|
provider: query.provider,
|
|
393
393
|
realm: query.realm
|
|
394
394
|
});
|
|
395
|
-
const
|
|
396
|
-
if (!
|
|
395
|
+
const issuer = provider.issuer;
|
|
396
|
+
if (!issuer) throw new SecurityError(`Auth provider '${query.provider}' does not support password grant`);
|
|
397
397
|
const credentials = "credentials" in provider.options && provider.options.credentials;
|
|
398
398
|
if (!credentials) throw new SecurityError(`Auth provider '${query.provider}' does not support password grant`);
|
|
399
399
|
let user;
|
|
@@ -407,7 +407,7 @@ var ServerAuthProvider = class {
|
|
|
407
407
|
if (!user) throw new InvalidCredentialsError();
|
|
408
408
|
const tokens = {
|
|
409
409
|
provider: query.provider,
|
|
410
|
-
...await
|
|
410
|
+
...await issuer.createToken(user)
|
|
411
411
|
};
|
|
412
412
|
this.setTokens(tokens, cookies);
|
|
413
413
|
const api = await this.serverLinksProvider.getUserApiLinks({ user });
|
|
@@ -500,14 +500,14 @@ var ServerAuthProvider = class {
|
|
|
500
500
|
throw new SecurityError("Failed to get access token", { cause: e });
|
|
501
501
|
});
|
|
502
502
|
this.authorizationCode.del({ cookies });
|
|
503
|
-
const
|
|
504
|
-
if (!
|
|
503
|
+
const issuer = provider.issuer;
|
|
504
|
+
if (!issuer) {
|
|
505
505
|
this.setTokens(externalTokens, cookies);
|
|
506
506
|
reply.redirect(redirectUri);
|
|
507
507
|
return;
|
|
508
508
|
}
|
|
509
509
|
const user = await provider.user(externalTokens);
|
|
510
|
-
const tokens = await
|
|
510
|
+
const tokens = await issuer.createToken(user);
|
|
511
511
|
this.setTokens({
|
|
512
512
|
...tokens,
|
|
513
513
|
issued_at: this.dateTimeProvider.now().unix(),
|
|
@@ -532,8 +532,8 @@ var ServerAuthProvider = class {
|
|
|
532
532
|
}
|
|
533
533
|
const provider = this.provider(tokens.provider);
|
|
534
534
|
this.tokens.del({ cookies });
|
|
535
|
-
if (
|
|
536
|
-
const onDeleteSession = provider.
|
|
535
|
+
if (provider.issuer && tokens.refresh_token) {
|
|
536
|
+
const onDeleteSession = provider.issuer.options.settings?.onDeleteSession;
|
|
537
537
|
if (onDeleteSession) try {
|
|
538
538
|
await onDeleteSession(tokens.refresh_token);
|
|
539
539
|
} catch (e) {
|
|
@@ -571,7 +571,7 @@ var ServerAuthProvider = class {
|
|
|
571
571
|
const realmName = typeof opts === "string" ? void 0 : opts.realm;
|
|
572
572
|
const identity = this.identities.find((identity$1) => {
|
|
573
573
|
if (identity$1.name !== name) return false;
|
|
574
|
-
if (realmName && identity$1.
|
|
574
|
+
if (realmName && identity$1.issuer?.name !== realmName) return false;
|
|
575
575
|
return true;
|
|
576
576
|
});
|
|
577
577
|
if (!identity) throw new SecurityError(`Auth provider '${name}'${realmName ? ` for realm '${realmName}'` : ""} not found`);
|
|
@@ -613,7 +613,7 @@ const $authCredentials = (realm, options = {}) => {
|
|
|
613
613
|
const account = realm.login ? realm.login(name) : options.account;
|
|
614
614
|
if (!account) throw new AlephaError("Credentials authentication requires a login function in the realm primitive.");
|
|
615
615
|
return $auth({
|
|
616
|
-
realm,
|
|
616
|
+
issuer: realm,
|
|
617
617
|
name,
|
|
618
618
|
credentials: { account }
|
|
619
619
|
});
|
|
@@ -642,7 +642,7 @@ const $authGithub = (realm, options = {}) => {
|
|
|
642
642
|
const account = options.account ?? (realm.link ? realm.link(name) : void 0);
|
|
643
643
|
if (!account) throw new AlephaError("Authentication requires a link function in the realm primitive.");
|
|
644
644
|
return $auth({
|
|
645
|
-
realm,
|
|
645
|
+
issuer: realm,
|
|
646
646
|
name,
|
|
647
647
|
oauth: {
|
|
648
648
|
clientId: env.GITHUB_CLIENT_ID,
|
|
@@ -702,7 +702,7 @@ const $authGoogle = (realm, options = {}) => {
|
|
|
702
702
|
const account = options.account ?? (realm.link ? realm.link(name) : void 0);
|
|
703
703
|
if (!account) throw new AlephaError("Authentication requires a link function in the realm primitive.");
|
|
704
704
|
return $auth({
|
|
705
|
-
realm,
|
|
705
|
+
issuer: realm,
|
|
706
706
|
name,
|
|
707
707
|
oidc: {
|
|
708
708
|
issuer: "https://accounts.google.com",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["user","parameters","tokens","identity","res"],"sources":["../../../src/server/auth/primitives/$auth.ts","../../../src/server/auth/constants/routes.ts","../../../src/server/auth/schemas/tokensSchema.ts","../../../src/server/auth/schemas/tokenResponseSchema.ts","../../../src/server/auth/schemas/userinfoResponseSchema.ts","../../../src/server/auth/providers/ServerAuthProvider.ts","../../../src/server/auth/schemas/authenticationProviderSchema.ts","../../../src/server/auth/primitives/$authCredentials.ts","../../../src/server/auth/primitives/$authGithub.ts","../../../src/server/auth/primitives/$authGoogle.ts","../../../src/server/auth/index.ts"],"sourcesContent":["import {\n $inject,\n AlephaError,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n} from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport {\n type AccessTokenResponse,\n type RealmPrimitive,\n SecurityError,\n SecurityProvider,\n type UserAccount,\n} from \"alepha/security\";\nimport {\n allowInsecureRequests,\n Configuration,\n discovery,\n refreshTokenGrant,\n} from \"openid-client\";\nimport type { OAuth2Profile } from \"../providers/ServerAuthProvider.ts\";\nimport type { Tokens } from \"../schemas/tokensSchema.ts\";\n\n/**\n * Creates an authentication provider primitive for handling user login flows.\n *\n * Supports multiple authentication strategies: credentials (username/password), OAuth2,\n * and OIDC (OpenID Connect). Handles token management, user profile retrieval, and\n * integration with both external identity providers (Auth0, Keycloak) and internal realms.\n *\n * **Authentication Types**: Credentials, OAuth2 (Google, GitHub), OIDC, External providers\n *\n * @example\n * ```ts\n * class AuthProviders {\n * // Internal credentials-based auth\n * credentials = $auth({\n * realm: this.userRealm,\n * credentials: {\n * account: async ({ username, password }) => {\n * return await this.validateUser(username, password);\n * }\n * }\n * });\n *\n * // External OIDC provider\n * keycloak = $auth({\n * oidc: {\n * issuer: \"https://auth.example.com\",\n * clientId: \"my-app\",\n * clientSecret: \"secret\",\n * redirectUri: \"/auth/callback\"\n * }\n * });\n * }\n * ```\n */\nexport const $auth = (options: AuthPrimitiveOptions): AuthPrimitive => {\n return createPrimitive(AuthPrimitive, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport type AuthPrimitiveOptions = {\n /**\n * Name of the identity provider.\n * If not provided, it will be derived from the property key.\n */\n name?: string;\n\n /**\n * If true, auth provider will be skipped.\n */\n disabled?: boolean;\n} & (AuthExternal | AuthInternal);\n\n/**\n * When you let an external service handle authentication. (e.g. Keycloak, Auth0, etc.)\n */\nexport type AuthExternal = {\n /**\n * Only OIDC is supported for external authentication.\n */\n oidc: OidcOptions;\n\n /**\n * For anonymous access, this will expect a service account access token.\n *\n * ```ts\n * class App {\n * anonymous = $serviceAccount(...);\n * auth = $auth({\n * // ... config ...\n * fallback: this.anonymous,\n * })\n * }\n * ```\n */\n fallback?: () => Async<AccessToken>;\n};\n\n/**\n * When using your own authentication system, e.g. using a database to store user accounts.\n * This is usually used with a custom login form.\n *\n * This relies on the `realm`, which is used to create/verify the access token.\n */\nexport type AuthInternal = {\n realm: RealmPrimitive;\n} & (\n | {\n /**\n * The common username/password authentication.\n *\n * - It uses the OAuth2 Client Credentials flow to obtain an access token.\n *\n * This is usually used with a custom login form on your website or mobile app.\n */\n credentials: CredentialsOptions;\n }\n | {\n /**\n * OAuth2 authentication. Delegates authentication to an OAuth2 provider. (e.g. Google, GitHub, etc.)\n *\n * - It uses the OAuth2 Authorization Code flow to obtain an access token and user information.\n *\n * This is usually used with a login button that redirects to the OAuth2 provider.\n */\n oauth: OAuth2Options;\n }\n | {\n /**\n * Like OAuth2, but uses OIDC (OpenID Connect) for authentication and user information retrieval.\n * OIDC is an identity layer on top of OAuth2, providing user authentication and profile information.\n *\n * - It uses the OAuth2 Authorization Code flow to obtain an access token and user information.\n * - PCKE (Proof Key for Code Exchange) is recommended for security.\n *\n * This is usually used with a login button that redirects to the OIDC provider.\n */\n oidc: OidcOptions;\n }\n);\n\nexport type CredentialsOptions = {\n account: CredentialsFn;\n};\n\nexport type CredentialsFn = (\n credentials: Credentials,\n) => Async<UserAccount | undefined>;\n\nexport interface Credentials {\n username: string;\n password: string;\n}\n\nexport interface OidcOptions {\n /**\n * URL of the OIDC issuer.\n */\n issuer: string;\n\n /**\n * Client ID for the OIDC client.\n */\n clientId: string;\n\n /**\n * Client secret for the OIDC client.\n * Optional if PKCE (Proof Key for Code Exchange) is used.\n */\n clientSecret?: string;\n\n /**\n * Redirect URI for the OIDC client.\n * This is where the user will be redirected after authentication.\n */\n redirectUri?: string;\n\n /**\n * For external auth providers only.\n * Take the ID token instead of the access token for validation.\n */\n useIdToken?: boolean;\n\n /**\n * URI to redirect the user after logout.\n */\n logoutUri?: string;\n\n /**\n * Optional scope for the OIDC client.\n * @default \"openid profile email\".\n */\n scope?: string;\n\n account?: LinkAccountFn;\n}\n\nexport interface LinkAccountOptions {\n access_token: string;\n user: OAuth2Profile;\n id_token?: string;\n expires_in?: number;\n scope?: string;\n}\n\nexport type LinkAccountFn = (tokens: LinkAccountOptions) => Async<UserAccount>;\n\nexport interface OAuth2Options {\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n clientId: string;\n\n /**\n * Client secret for the OAuth2 client.\n */\n clientSecret: string;\n\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n authorization: string;\n\n /**\n * URL of the OAuth2 token endpoint.\n */\n token: string;\n\n /**\n * Function to retrieve user profile information from the OAuth2 tokens.\n */\n userinfo: (tokens: Tokens) => Async<OAuth2Profile>;\n\n account?: LinkAccountFn;\n\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n redirectUri?: string;\n\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n scope?: string;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class AuthPrimitive extends Primitive<AuthPrimitiveOptions> {\n protected readonly securityProvider = $inject(SecurityProvider);\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n\n public oauth?: Configuration;\n\n public get name() {\n return this.options.name ?? this.config.propertyKey;\n }\n\n public get realm(): RealmPrimitive | undefined {\n if (\"realm\" in this.options) {\n return this.options.realm;\n }\n return undefined;\n }\n\n public get jwks_uri(): string {\n const jwks = this.oauth?.serverMetadata().jwks_uri;\n if (!jwks) {\n throw new AlephaError(\"No JWKS URI available for the auth provider\");\n }\n return jwks;\n }\n\n public get scope(): string | undefined {\n if (\"oauth\" in this.options) {\n return this.options.oauth.scope;\n }\n if (\"oidc\" in this.options) {\n return this.options.oidc.scope || \"openid profile email\";\n }\n throw new AlephaError(\n \"No OAuth2 or OIDC configuration available for the auth provider\",\n );\n }\n\n public get redirect_uri() {\n if (\"oauth\" in this.options) {\n return this.options.oauth.redirectUri;\n }\n if (\"oidc\" in this.options) {\n return this.options.oidc.redirectUri;\n }\n throw new AlephaError(\n \"No OAuth2 or OIDC configuration available for the auth provider\",\n );\n }\n\n /**\n * Refreshes the access token using the refresh token.\n * Can be used on oauth2, oidc or credentials auth providers.\n */\n public async refresh(\n refreshToken: string,\n accessToken?: string,\n ): Promise<AccessTokenResponse> {\n if (\"realm\" in this.options) {\n return this.options.realm\n .refreshToken(refreshToken, accessToken)\n .then((it) => it.tokens)\n .catch((error) => {\n throw new SecurityError(\n \"Failed to refresh access token using the refresh token (realm)\",\n {\n cause: error,\n },\n );\n });\n } else if (this.oauth) {\n try {\n return {\n ...(await refreshTokenGrant(this.oauth, refreshToken)),\n issued_at: this.dateTimeProvider.now().unix(),\n };\n } catch (error) {\n throw new SecurityError(\n \"Failed to refresh access token using the refresh token (oauth2)\",\n {\n cause: error,\n },\n );\n }\n }\n\n throw new AlephaError(\n \"No realm or OAuth2 configuration available for refreshing the access token\",\n );\n }\n\n /**\n * Extracts user information from the access token.\n * This is used to create a user account from the access token.\n */\n public async user(tokens: Tokens): Promise<UserAccount> {\n try {\n if (\"oauth\" in this.options) {\n const profile = await this.options.oauth.userinfo(tokens);\n\n if (this.options.oauth.account) {\n return this.options.oauth.account({\n ...tokens,\n user: profile,\n });\n }\n\n return this.securityProvider.createUserFromPayload(profile);\n }\n\n if (\"oidc\" in this.options) {\n const payload = this.getUserFromIdToken(tokens.id_token || \"\");\n\n if (this.options.oidc.account) {\n return this.options.oidc.account({\n ...tokens,\n user: payload,\n });\n }\n\n return this.securityProvider.createUserFromPayload(payload);\n }\n } catch (error) {\n throw new SecurityError(\n \"Failed to extract user from identity provider tokens\",\n {\n cause: error,\n },\n );\n }\n\n throw new AlephaError(\n \"This authentication does not support user extraction from tokens\",\n );\n }\n\n protected getUserFromIdToken(idToken: string): OAuth2Profile {\n try {\n return JSON.parse(\n Buffer.from(idToken.split(\".\")[1], \"base64\").toString(\"utf8\"),\n ) as OAuth2Profile;\n } catch (error) {\n throw new AlephaError(\"Failed to parse ID Token payload\", {\n cause: error,\n });\n }\n }\n\n public async prepare() {\n const addons: Array<(config: Configuration) => void> = [];\n\n addons.push(allowInsecureRequests);\n\n if (\"oidc\" in this.options) {\n const { oidc } = this.options;\n\n this.oauth = await discovery(\n new URL(oidc.issuer),\n oidc.clientId,\n {\n client_secret: oidc.clientSecret,\n },\n undefined,\n {\n execute: addons,\n },\n );\n }\n\n if (\"oauth\" in this.options) {\n const { oauth } = this.options;\n\n this.oauth = new Configuration(\n {\n authorization_endpoint: oauth.authorization,\n token_endpoint: oauth.token,\n issuer: oauth.authorization, // use authorization URL as a pseudo-issuer?\n // we don't need all of these endpoints\n jwks_uri: undefined,\n end_session_endpoint: undefined,\n },\n oauth.clientId,\n {\n client_secret: oauth.clientSecret,\n },\n );\n }\n }\n}\n\n$auth[KIND] = AuthPrimitive;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport type AccessToken = string | { token: () => Async<string> };\n\nexport interface WithLinkFn {\n link?: (name: string) => (opts: LinkAccountOptions) => Async<UserAccount>;\n}\n\nexport interface WithLoginFn {\n login?: (\n provider: string,\n ) => (creds: Credentials) => Async<UserAccount | undefined>;\n}\n","export const alephaServerAuthRoutes = {\n login: \"/oauth/login\",\n callback: \"/oauth/callback\",\n logout: \"/oauth/logout\",\n token: \"/_auth/token\",\n refresh: \"/_auth/refresh\",\n userinfo: \"/_auth/userinfo\",\n};\n","import type { Static } from \"alepha\";\nimport { t } from \"alepha\";\n\nexport const tokensSchema = t.object({\n provider: t.text(),\n access_token: t.text({ size: \"rich\" }),\n issued_at: t.number(),\n expires_in: t.optional(t.number()),\n refresh_token: t.optional(t.text({ size: \"rich\" })),\n refresh_token_expires_in: t.optional(t.number()),\n refresh_expires_in: t.optional(\n t.number({\n description:\n \"Alias of `refresh_token_expires_in` for compatibility with some providers.\",\n }),\n ),\n id_token: t.optional(t.text({ size: \"rich\" })),\n scope: t.optional(t.text()),\n});\n\nexport type Tokens = Static<typeof tokensSchema>;\n","import { type Static, t } from \"alepha\";\nimport { userAccountInfoSchema } from \"alepha/security\";\nimport { apiLinksResponseSchema } from \"alepha/server/links\";\nimport { tokensSchema } from \"./tokensSchema.ts\";\n\nexport const tokenResponseSchema = t.extend(tokensSchema, {\n user: userAccountInfoSchema,\n api: apiLinksResponseSchema,\n});\n\nexport type TokenResponse = Static<typeof tokenResponseSchema>;\n","import { type Static, t } from \"alepha\";\nimport { userAccountInfoSchema } from \"alepha/security\";\nimport { apiLinksResponseSchema } from \"alepha/server/links\";\n\nexport const userinfoResponseSchema = t.object({\n user: t.optional(userAccountInfoSchema),\n api: apiLinksResponseSchema,\n});\n\nexport type UserinfoResponse = Static<typeof userinfoResponseSchema>;\n","import { $hook, $inject, Alepha, t } from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport { $logger } from \"alepha/logger\";\nimport {\n InvalidCredentialsError,\n SecurityError,\n type UserAccount,\n} from \"alepha/security\";\nimport { $route, BadRequestError } from \"alepha/server\";\nimport {\n $cookie,\n type Cookies,\n ServerCookiesProvider,\n} from \"alepha/server/cookies\";\nimport { ServerLinksProvider } from \"alepha/server/links\";\nimport {\n authorizationCodeGrant,\n buildAuthorizationUrl,\n buildEndSessionUrl,\n calculatePKCECodeChallenge,\n randomPKCECodeVerifier,\n randomState,\n} from \"openid-client\";\nimport { alephaServerAuthRoutes } from \"../constants/routes.ts\";\nimport { $auth, type AuthPrimitive } from \"../primitives/$auth.ts\";\nimport type { AuthenticationProvider } from \"../schemas/authenticationProviderSchema.ts\";\nimport { tokenResponseSchema } from \"../schemas/tokenResponseSchema.ts\";\nimport { type Tokens, tokensSchema } from \"../schemas/tokensSchema.ts\";\nimport { userinfoResponseSchema } from \"../schemas/userinfoResponseSchema.ts\";\n\nexport class ServerAuthProvider {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n protected readonly serverCookiesProvider = $inject(ServerCookiesProvider);\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n protected readonly serverLinksProvider = $inject(ServerLinksProvider);\n\n protected readonly authorizationCode = $cookie({\n name: \"authorizationCode\",\n ttl: [15, \"minutes\"],\n httpOnly: true,\n schema: t.object({\n provider: t.text(),\n realm: t.optional(t.text()),\n codeVerifier: t.optional(t.text({ size: \"long\" })),\n redirectUri: t.optional(t.text({ size: \"long\" })),\n state: t.optional(t.text()),\n nonce: t.optional(t.text()),\n }),\n });\n\n public readonly tokens = $cookie({\n name: \"tokens\",\n ttl: [30, \"days\"],\n httpOnly: true,\n compress: true,\n encrypt: true,\n schema: tokensSchema,\n });\n\n public get identities(): Array<AuthPrimitive> {\n return this.alepha\n .primitives($auth)\n .filter((auth) => !auth.options.disabled);\n }\n\n public getAuthenticationProviders(\n filters: { realmName?: string } = {},\n ): AuthenticationProvider[] {\n const providers: AuthenticationProvider[] = [];\n\n for (const identity of this.identities) {\n if (filters.realmName) {\n const realm = \"realm\" in identity.options && identity.options.realm;\n if (!realm || realm.name !== filters.realmName) {\n continue;\n }\n }\n\n const type =\n \"oidc\" in identity.options\n ? \"OIDC\"\n : \"oauth\" in identity.options\n ? \"OAUTH2\"\n : \"credentials\" in identity.options\n ? \"CREDENTIALS\"\n : undefined;\n\n if (!type) {\n continue;\n }\n\n providers.push({\n name: identity.name,\n type,\n });\n }\n\n return providers;\n }\n\n protected readonly configure = $hook({\n on: \"configure\",\n handler: async () => {\n for (const identity of this.identities) {\n await identity.prepare();\n }\n },\n });\n\n protected getAccessTokens(tokens: Tokens) {\n const idp = this.provider(tokens.provider);\n\n if (\n \"oidc\" in idp.options &&\n !(\"realm\" in idp.options) &&\n idp.options.oidc?.useIdToken\n ) {\n return tokens.id_token;\n }\n\n return tokens.access_token;\n }\n\n /**\n * Fill request headers with access token from cookies or fallback to provider's fallback function.\n */\n protected readonly onRequest = $hook({\n on: \"server:onRequest\",\n after: this.serverCookiesProvider,\n handler: async ({ request }) => {\n const cookies = request.cookies;\n\n // [feature] forward cookies to request headers\n if (cookies) {\n const tokens = await this.cookiesToTokens(cookies);\n if (tokens) {\n request.headers.authorization = `Bearer ${this.getAccessTokens(tokens)}`;\n this.log.trace(\"Access token set in request headers\", {\n provider: tokens.provider,\n });\n }\n }\n\n // [feature] support for auth providers with fallback\n if (!request.headers.authorization) {\n for (const provider of this.identities) {\n if (!(\"realm\" in provider.options) && !!provider.options.fallback) {\n const token = await provider.options.fallback();\n if (token) {\n request.headers.authorization = `Bearer ${token}`;\n break;\n }\n }\n }\n }\n },\n });\n\n /**\n * Convert cookies to tokens.\n * If the tokens are expired, try to refresh them using the refresh token.\n */\n protected async cookiesToTokens(\n cookies: Cookies,\n ): Promise<Tokens | undefined> {\n const tokens = this.getTokens(cookies);\n if (!tokens) {\n // no cookie, no tokens\n this.log.trace(\"No tokens found in cookies\");\n return;\n }\n\n this.log.trace(\"Tokens found in cookies\", {\n expires_in: tokens.expires_in,\n issued_at: tokens.issued_at,\n });\n\n // check if tokens are expired\n const refreshedTokens = await this.refreshTokens(tokens);\n if (!refreshedTokens) {\n this.tokens.del({ cookies });\n // 08/25: exception here will go to Server error handler, not the React one\n // better to remove cookie & session and let the page handle 401 Unauthorized\n //throw new SessionExpiredError(\"Session expired. Please login again.\");\n return;\n }\n\n if (refreshedTokens.access_token !== tokens.access_token) {\n this.setTokens(refreshedTokens, cookies);\n }\n\n return refreshedTokens;\n }\n\n protected async refreshTokens(tokens: Tokens): Promise<Tokens | undefined> {\n if (tokens.expires_in && tokens.issued_at) {\n const gracePeriodSec = 10;\n const expiresAt = tokens.issued_at + (tokens.expires_in - gracePeriodSec);\n\n if (expiresAt < this.dateTimeProvider.now().unix()) {\n this.log.trace(\"Tokens are expired\");\n\n // oh no, it is expired\n if (tokens.refresh_token) {\n this.log.trace(\"Trying to refresh tokens using refresh token\");\n // but has refresh token!\n try {\n const provider = this.provider(tokens);\n const result = await provider.refresh(\n tokens.refresh_token,\n tokens.access_token,\n );\n const newTokens = {\n ...result,\n provider: tokens.provider,\n issued_at: this.dateTimeProvider.now().unix(),\n };\n\n this.log.debug(\"Tokens refreshed successfully\");\n\n return newTokens;\n } catch (e) {\n this.log.warn(\"Failed to refresh token\", e);\n }\n }\n\n // session expired and no (valid) refresh token\n return;\n }\n }\n\n if (!tokens.issued_at && tokens.access_token) {\n return;\n }\n\n return tokens;\n }\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Get user information.\n */\n public readonly userinfo = $route({\n path: alephaServerAuthRoutes.userinfo,\n schema: {\n response: userinfoResponseSchema,\n },\n handler: async ({ user, headers, cookies }) => {\n const tokens = this.getTokens(cookies);\n if (tokens) {\n const provider = this.provider(tokens);\n if (!(\"realm\" in provider.options)) {\n const user = await provider.user(tokens);\n const api = await this.serverLinksProvider.getUserApiLinks({\n authorization: headers.authorization,\n user,\n });\n return {\n api,\n user,\n };\n }\n }\n\n const api = await this.serverLinksProvider.getUserApiLinks({\n authorization: headers.authorization,\n user,\n });\n\n return {\n api,\n user,\n };\n },\n });\n\n /**\n * Refresh a token for internal providers.\n */\n public readonly refresh = $route({\n path: alephaServerAuthRoutes.refresh,\n method: \"POST\",\n schema: {\n query: t.object({\n provider: t.text(),\n }),\n body: t.object({\n refresh_token: t.text({\n size: \"rich\",\n }),\n access_token: t.optional(\n t.text({\n size: \"rich\",\n description:\n \"Required if provider has stateless refresh token on credentials mode\",\n }),\n ),\n }),\n response: tokensSchema,\n },\n handler: async ({ query, body, cookies }) => {\n const provider = this.provider(query);\n\n const tokens = {\n provider: query.provider,\n ...(await provider.refresh(body.refresh_token, body.access_token)),\n };\n\n // for web applications, we store tokens in cookies\n this.setTokens(tokens, cookies);\n\n return tokens;\n },\n });\n\n /**\n * Login for local password-based authentication.\n */\n public readonly token = $route({\n path: alephaServerAuthRoutes.token,\n method: \"POST\",\n schema: {\n query: t.object({\n provider: t.text(),\n realm: t.optional(\n t.text({ description: \"Realm name for multi-realm setups\" }),\n ),\n }),\n body: t.object({\n username: t.text(),\n password: t.text(),\n }),\n response: tokenResponseSchema,\n },\n handler: async ({ query, body, cookies }) => {\n const provider = this.provider({\n provider: query.provider,\n realm: query.realm,\n });\n\n const realm = \"realm\" in provider.options && provider.options.realm;\n if (!realm) {\n throw new SecurityError(\n `Auth provider '${query.provider}' does not support password grant`,\n );\n }\n\n const credentials =\n \"credentials\" in provider.options && provider.options.credentials;\n\n if (!credentials) {\n throw new SecurityError(\n `Auth provider '${query.provider}' does not support password grant`,\n );\n }\n\n let user: UserAccount | undefined;\n try {\n user = await credentials.account(body);\n } catch (e) {\n if (e instanceof InvalidCredentialsError) {\n throw e;\n }\n this.log.error(\"Failed to authenticate user\", e);\n throw new InvalidCredentialsError();\n }\n\n if (!user) {\n throw new InvalidCredentialsError();\n }\n\n const tokens = {\n provider: query.provider,\n ...(await realm.createToken(user)),\n };\n\n // for web applications, we store tokens in cookies\n this.setTokens(tokens, cookies);\n\n const api = await this.serverLinksProvider.getUserApiLinks({\n user,\n });\n\n // mobile apps require this\n return {\n ...tokens,\n user,\n api,\n };\n },\n });\n\n /**\n * Oauth2/OIDC login route.\n */\n public readonly login = $route({\n path: alephaServerAuthRoutes.login,\n schema: {\n query: t.object({\n provider: t.text(),\n realm: t.optional(\n t.text({ description: \"Realm name for multi-realm setups\" }),\n ),\n redirect_uri: t.optional(t.text({ size: \"rich\" })),\n }),\n },\n handler: async ({ query, url, reply }) => {\n const provider = this.provider({\n provider: query.provider,\n realm: query.realm,\n });\n const oauth = provider.oauth;\n if (!oauth) {\n throw new SecurityError(\n `Auth provider '${query.provider}' does not support OAuth2`,\n );\n }\n\n const scope = provider.scope;\n let redirect_uri =\n provider.redirect_uri || alephaServerAuthRoutes.callback;\n if (redirect_uri.startsWith(\"/\")) {\n redirect_uri = `${url.protocol}//${url.host}${redirect_uri}`;\n }\n\n const oidc = \"oidc\" in provider.options && provider.options.oidc;\n\n if (!oauth.serverMetadata().supportsPKCE()) {\n const state = randomState();\n const parameters: Record<string, string> = {\n redirect_uri,\n state,\n };\n\n if (oidc) {\n parameters.nonce = randomState();\n }\n\n if (scope) {\n parameters.scope = scope;\n }\n\n this.authorizationCode.set({\n state,\n nonce: parameters.nonce,\n redirectUri: query.redirect_uri ?? \"/\",\n provider: query.provider,\n realm: query.realm,\n });\n\n reply.redirect(buildAuthorizationUrl(oauth, parameters).toString());\n return;\n }\n\n const codeVerifier = randomPKCECodeVerifier();\n const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);\n\n const parameters: Record<string, string> = {\n redirect_uri,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n };\n\n if (scope) {\n parameters.scope = scope;\n }\n\n this.authorizationCode.set({\n codeVerifier,\n redirectUri: query.redirect_uri ?? \"/\",\n provider: query.provider,\n realm: query.realm,\n });\n\n reply.redirect(buildAuthorizationUrl(oauth, parameters).toString());\n },\n });\n\n /**\n * Callback for OAuth2/OIDC providers.\n * It handles the authorization code flow and retrieves the access token.\n */\n public readonly callback = $route({\n path: alephaServerAuthRoutes.callback,\n handler: async ({ url, reply, cookies }) => {\n const authorizationCode = this.authorizationCode.get({ cookies });\n if (!authorizationCode) {\n throw new BadRequestError(\"Missing code verifier\");\n }\n\n const provider = this.provider(authorizationCode);\n const oauth = provider.oauth;\n if (!oauth) {\n throw new SecurityError(\n `Auth provider '${provider.name}' does not support OAuth2`,\n );\n }\n\n const redirectUri = authorizationCode.redirectUri ?? \"/\";\n\n const externalTokens = await authorizationCodeGrant(oauth, url, {\n pkceCodeVerifier: authorizationCode.codeVerifier,\n expectedState: authorizationCode.state,\n expectedNonce: authorizationCode.nonce,\n })\n .then((tokens) => ({\n issued_at: this.dateTimeProvider.now().unix(),\n provider: provider.name,\n ...tokens,\n }))\n .catch((e) => {\n this.log.error(\"Failed to get access token\", e);\n throw new SecurityError(\"Failed to get access token\", {\n cause: e,\n });\n });\n\n this.authorizationCode.del({ cookies });\n\n const realm = \"realm\" in provider.options && provider.options.realm;\n\n // external, full OIDC System (e.g. Keycloak, Auth0)\n if (!realm) {\n this.setTokens(externalTokens, cookies);\n reply.redirect(redirectUri);\n return;\n }\n\n // internal, we need to create our own tokens\n\n const user = await provider.user(externalTokens);\n const tokens = await realm.createToken(user);\n\n this.setTokens(\n {\n ...tokens,\n issued_at: this.dateTimeProvider.now().unix(),\n provider: provider.name,\n },\n cookies,\n );\n\n reply.redirect(redirectUri);\n },\n });\n\n /**\n * Logout route for OAuth2/OIDC providers.\n */\n public readonly logout = $route({\n path: alephaServerAuthRoutes.logout,\n method: \"GET\",\n schema: {\n query: t.object({\n post_logout_redirect_uri: t.optional(t.text()),\n }),\n },\n handler: async ({ query, reply, cookies }) => {\n const redirect = query.post_logout_redirect_uri ?? \"/\";\n const tokens = this.getTokens(cookies);\n if (!tokens) {\n reply.redirect(redirect);\n return;\n }\n\n const provider = this.provider(tokens.provider);\n\n this.tokens.del({ cookies });\n\n // for internal providers, we can delete the session - if available\n if (\"realm\" in provider.options && tokens.refresh_token) {\n const onDeleteSession =\n provider.options.realm.options.settings?.onDeleteSession;\n if (onDeleteSession) {\n try {\n await onDeleteSession(tokens.refresh_token);\n } catch (e) {\n this.log.error(\"Failed to delete session\", e);\n }\n }\n }\n\n const oauth = provider.oauth;\n if (!oauth) {\n reply.redirect(redirect);\n return;\n }\n\n const params = new URLSearchParams();\n const idToken = tokens?.id_token;\n\n params.set(\"post_logout_redirect_uri\", redirect);\n if (idToken) {\n params.set(\"id_token_hint\", idToken);\n }\n\n const customLogoutUri =\n \"oidc\" in provider.options\n ? provider.options.oidc?.logoutUri\n : undefined;\n\n if (customLogoutUri) {\n reply.redirect(`${customLogoutUri}?${params}`);\n return;\n }\n\n if (!oauth.serverMetadata().end_session_endpoint) {\n // await tokenRevocation(\n // \toauth,\n // \ttokens?.refresh_token ?? tokens.access_token,\n // );\n reply.redirect(redirect);\n return;\n }\n\n reply.redirect(buildEndSessionUrl(oauth, params).toString());\n },\n });\n\n /**\n * Find an auth provider by name and optionally by realm.\n * When realm is specified, it filters providers by both name and realm.\n * This enables multi-realm setups where multiple providers share the same name (e.g., \"credentials\").\n */\n protected provider(\n opts: string | { provider: string; realm?: string },\n ): AuthPrimitive {\n const name = typeof opts === \"string\" ? opts : opts.provider;\n const realmName = typeof opts === \"string\" ? undefined : opts.realm;\n\n const identity = this.identities.find((identity) => {\n if (identity.name !== name) {\n return false;\n }\n\n // If realm filter is specified, match against provider's realm\n if (realmName && identity.realm?.name !== realmName) {\n return false;\n }\n\n return true;\n });\n\n if (!identity) {\n const realmInfo = realmName ? ` for realm '${realmName}'` : \"\";\n throw new SecurityError(`Auth provider '${name}'${realmInfo} not found`);\n }\n\n return identity;\n }\n\n protected getTokens(cookies?: Cookies): Tokens | undefined {\n return this.tokens.get({ cookies });\n }\n\n protected setTokens(tokens: Tokens, cookies?: Cookies): void {\n const exp =\n tokens.refresh_token_expires_in ||\n tokens.refresh_expires_in ||\n tokens.expires_in;\n\n const ttl = exp\n ? this.dateTimeProvider.duration(exp, \"seconds\")\n : undefined;\n\n this.tokens.set(tokens, {\n cookies,\n ttl,\n });\n }\n}\n\nexport interface OAuth2Profile {\n sub: string; // Subject - unique ID per user (required by OpenID)\n email?: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string; // ISO 8601: YYYY-MM-DD\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: {\n formatted?: string;\n street_address?: string;\n locality?: string;\n region?: string;\n postal_code?: string;\n country?: string;\n };\n updated_at?: number; // seconds since epoch\n // Allow additional fields (provider-specific)\n [key: string]: unknown;\n}\n","import { type Static, t } from \"alepha\";\n\nexport const authenticationProviderSchema = t.object(\n {\n name: t.text({\n description: \"Name of the authentication provider.\",\n }),\n type: t.enum([\"OAUTH2\", \"OIDC\", \"CREDENTIALS\"], {\n description: \"Type of the authentication provider.\",\n }),\n },\n {\n title: \"AuthenticationProvider\",\n },\n);\n\nexport type AuthenticationProvider = Static<\n typeof authenticationProviderSchema\n>;\n","import { AlephaError } from \"alepha\";\nimport type { RealmPrimitive } from \"alepha/security\";\nimport {\n $auth,\n type CredentialsFn,\n type CredentialsOptions,\n type WithLoginFn,\n} from \"./$auth.ts\";\n\n/**\n * Already configured Credentials authentication primitive.\n *\n * Uses username and password to authenticate users.\n */\nexport const $authCredentials = (\n realm: RealmPrimitive & WithLoginFn,\n options: Partial<CredentialsOptions> = {},\n) => {\n const name = \"credentials\";\n\n const account: CredentialsFn | undefined = realm.login\n ? realm.login(name)\n : options.account;\n\n if (!account) {\n throw new AlephaError(\n \"Credentials authentication requires a login function in the realm primitive.\",\n );\n }\n\n return $auth({\n realm,\n name,\n credentials: {\n account,\n },\n });\n};\n","import { $context, AlephaError, t } from \"alepha\";\nimport type { RealmPrimitive } from \"alepha/security\";\nimport type { OAuth2Profile } from \"../providers/ServerAuthProvider.ts\";\nimport {\n $auth,\n type LinkAccountFn,\n type OidcOptions,\n type WithLinkFn,\n} from \"./$auth.ts\";\n\n/**\n * Already configured GitHub authentication primitive.\n *\n * Uses OAuth2 to authenticate users via their GitHub accounts.\n * Upon successful authentication, it links the GitHub account to a user session.\n *\n * Environment Variables:\n * - `GITHUB_CLIENT_ID`: The client ID obtained from the GitHub Developer Settings.\n * - `GITHUB_CLIENT_SECRET`: The client secret obtained from the GitHub Developer Settings.\n */\nexport const $authGithub = (\n realm: RealmPrimitive & WithLinkFn,\n options: Partial<OidcOptions> = {},\n) => {\n const { alepha } = $context();\n\n const env = alepha.parseEnv(\n t.object({\n GITHUB_CLIENT_ID: t.optional(t.text()),\n GITHUB_CLIENT_SECRET: t.optional(t.text()),\n }),\n );\n\n const disabled = !env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET;\n\n const name = \"github\";\n\n const account: LinkAccountFn | undefined =\n options.account ?? (realm.link ? realm.link(name) : undefined);\n\n if (!account) {\n throw new AlephaError(\n \"Authentication requires a link function in the realm primitive.\",\n );\n }\n\n return $auth({\n realm,\n name,\n oauth: {\n clientId: env.GITHUB_CLIENT_ID!,\n clientSecret: env.GITHUB_CLIENT_SECRET!,\n authorization: \"https://github.com/login/oauth/authorize\",\n token: \"https://github.com/login/oauth/access_token\",\n scope: \"read:user user:email\",\n userinfo: async (tokens) => {\n const BASE_URL = \"https://api.github.com\";\n const res = await fetch(`${BASE_URL}/user`, {\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n \"User-Agent\": \"Alepha\",\n },\n }).then((res) => res.json());\n\n const user: OAuth2Profile = {\n sub: res.id.toString(),\n };\n\n if (res.email) {\n user.email = res.email;\n }\n\n if (res.name) {\n user.name = res.name.trim();\n }\n\n if (res.avatar_url) {\n user.picture = res.avatar_url;\n }\n\n if (!user.email) {\n const res = await fetch(`${BASE_URL}/user/emails`, {\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n \"User-Agent\": \"Alepha\",\n },\n });\n if (res.ok) {\n const emails: any[] = await res.json();\n user.email = (emails.find((e) => e.primary) ?? emails[0]).email;\n }\n }\n\n return user;\n },\n ...options,\n account,\n },\n disabled,\n });\n};\n","import { $context, AlephaError, t } from \"alepha\";\nimport type { RealmPrimitive } from \"alepha/security\";\nimport {\n $auth,\n type LinkAccountFn,\n type OidcOptions,\n type WithLinkFn,\n} from \"./$auth.ts\";\n\n/**\n * Already configured Google authentication primitive.\n *\n * Uses OpenID Connect (OIDC) to authenticate users via their Google accounts.\n * Upon successful authentication, it links the Google account to a user session.\n *\n * Environment Variables:\n * - `GOOGLE_CLIENT_ID`: The client ID obtained from the Google Developer Console.\n * - `GOOGLE_CLIENT_SECRET`: The client secret obtained from the Google Developer Console.\n */\nexport const $authGoogle = (\n realm: RealmPrimitive & WithLinkFn,\n options: Partial<OidcOptions> = {},\n) => {\n const { alepha } = $context();\n\n const env = alepha.parseEnv(\n t.object({\n GOOGLE_CLIENT_ID: t.optional(t.text()),\n GOOGLE_CLIENT_SECRET: t.optional(t.text()),\n }),\n );\n\n const disabled = !env.GOOGLE_CLIENT_ID || !env.GOOGLE_CLIENT_SECRET;\n\n const name = \"google\";\n\n const account: LinkAccountFn | undefined =\n options.account ?? (realm.link ? realm.link(name) : undefined);\n\n if (!account) {\n throw new AlephaError(\n \"Authentication requires a link function in the realm primitive.\",\n );\n }\n\n return $auth({\n realm,\n name,\n oidc: {\n issuer: \"https://accounts.google.com\",\n clientId: env.GOOGLE_CLIENT_ID!,\n clientSecret: env.GOOGLE_CLIENT_SECRET,\n ...options,\n account,\n },\n disabled,\n });\n};\n","import { $module } from \"alepha\";\nimport type { UserAccount } from \"alepha/security\";\nimport { AlephaServerCookies } from \"alepha/server/cookies\";\nimport { $auth } from \"./primitives/$auth.ts\";\nimport { ServerAuthProvider } from \"./providers/ServerAuthProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./index.shared.ts\";\nexport * from \"./primitives/$auth.ts\";\nexport * from \"./primitives/$authCredentials.ts\";\nexport * from \"./primitives/$authGithub.ts\";\nexport * from \"./primitives/$authGoogle.ts\";\nexport * from \"./providers/ServerAuthProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha\" {\n export interface State {\n /**\n * The authenticated user account attached to the server request state.\n *\n * @internal\n */\n \"alepha.server.request.user\"?: UserAccount;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Allow authentication services for server applications.\n * It provides login and logout functionalities.\n *\n * There are multiple authentication providers available (e.g., Google, GitHub).\n * You can also delegate authentication to your own OIDC/OAuth2, for example using Keycloak or Auth0.\n *\n * It's cookie-based and SSR friendly.\n *\n * @see {@link $auth}\n * @see {@link ServerAuthProvider}\n * @module alepha.server.auth\n */\nexport const AlephaServerAuth = $module({\n name: \"alepha.server.auth\",\n primitives: [$auth],\n services: [AlephaServerCookies, ServerAuthProvider],\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,MAAa,SAAS,YAAiD;AACrE,QAAO,gBAAgB,eAAe,QAAQ;;AAiMhD,IAAa,gBAAb,cAAmC,UAAgC;CACjE,AAAmB,mBAAmB,QAAQ,iBAAiB;CAC/D,AAAmB,mBAAmB,QAAQ,iBAAiB;CAE/D,AAAO;CAEP,IAAW,OAAO;AAChB,SAAO,KAAK,QAAQ,QAAQ,KAAK,OAAO;;CAG1C,IAAW,QAAoC;AAC7C,MAAI,WAAW,KAAK,QAClB,QAAO,KAAK,QAAQ;;CAKxB,IAAW,WAAmB;EAC5B,MAAM,OAAO,KAAK,OAAO,gBAAgB,CAAC;AAC1C,MAAI,CAAC,KACH,OAAM,IAAI,YAAY,8CAA8C;AAEtE,SAAO;;CAGT,IAAW,QAA4B;AACrC,MAAI,WAAW,KAAK,QAClB,QAAO,KAAK,QAAQ,MAAM;AAE5B,MAAI,UAAU,KAAK,QACjB,QAAO,KAAK,QAAQ,KAAK,SAAS;AAEpC,QAAM,IAAI,YACR,kEACD;;CAGH,IAAW,eAAe;AACxB,MAAI,WAAW,KAAK,QAClB,QAAO,KAAK,QAAQ,MAAM;AAE5B,MAAI,UAAU,KAAK,QACjB,QAAO,KAAK,QAAQ,KAAK;AAE3B,QAAM,IAAI,YACR,kEACD;;;;;;CAOH,MAAa,QACX,cACA,aAC8B;AAC9B,MAAI,WAAW,KAAK,QAClB,QAAO,KAAK,QAAQ,MACjB,aAAa,cAAc,YAAY,CACvC,MAAM,OAAO,GAAG,OAAO,CACvB,OAAO,UAAU;AAChB,SAAM,IAAI,cACR,kEACA,EACE,OAAO,OACR,CACF;IACD;WACK,KAAK,MACd,KAAI;AACF,UAAO;IACL,GAAI,MAAM,kBAAkB,KAAK,OAAO,aA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ACP,kBAAkB,EAAE,SAAS,EAAE,MAAM,CAAC;EACtC,sBAAsB,EAAE,SAAS,EAAE,MAAM,CAAC;EAC3C,CAAC,CACH;CAED,MAAM,WAAW,CAAC,IAAI,oBAAoB,CAAC,IAAI;CAE/C,MAAM,OAAO;CAEb,MAAM,UACJ,QAAQ,YAAY,MAAM,OAAO,MAAM,KAAK,KAAK,GAAG;AAEtD,KAAI,CAAC,QACH,OAAM,IAAI,YACR,kEACD;AAGH,QAAO,MAAM;EACX;EACA;EACA,MAAM;GACJ,QAAQ;GACR,UAAU,IAAI;GACd,cAAc,IAAI;GAClB,GAAG;GACH;GACD;EACD;EACD,CAAC;;;;;;;;;;;;;;;;;;ACbJ,MAAa,mBAAmB,QAAQ;CACtC,MAAM;CACN,YAAY,CAAC,MAAM;CACnB,UAAU,CAAC,qBAAqB,mBAAmB;CACpD,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["user","parameters","tokens","identity","res"],"sources":["../../../src/server/auth/primitives/$auth.ts","../../../src/server/auth/constants/routes.ts","../../../src/server/auth/schemas/tokensSchema.ts","../../../src/server/auth/schemas/tokenResponseSchema.ts","../../../src/server/auth/schemas/userinfoResponseSchema.ts","../../../src/server/auth/providers/ServerAuthProvider.ts","../../../src/server/auth/schemas/authenticationProviderSchema.ts","../../../src/server/auth/primitives/$authCredentials.ts","../../../src/server/auth/primitives/$authGithub.ts","../../../src/server/auth/primitives/$authGoogle.ts","../../../src/server/auth/index.ts"],"sourcesContent":["import {\n $inject,\n AlephaError,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n} from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport {\n type AccessTokenResponse,\n type IssuerPrimitive,\n SecurityError,\n SecurityProvider,\n type UserAccount,\n} from \"alepha/security\";\nimport {\n allowInsecureRequests,\n Configuration,\n discovery,\n refreshTokenGrant,\n} from \"openid-client\";\nimport type { OAuth2Profile } from \"../providers/ServerAuthProvider.ts\";\nimport type { Tokens } from \"../schemas/tokensSchema.ts\";\n\n/**\n * Creates an authentication provider primitive for handling user login flows.\n *\n * Supports multiple authentication strategies: credentials (username/password), OAuth2,\n * and OIDC (OpenID Connect). Handles token management, user profile retrieval, and\n * integration with both external identity providers (Auth0, Keycloak) and internal realms.\n *\n * **Authentication Types**: Credentials, OAuth2 (Google, GitHub), OIDC, External providers\n *\n * @example\n * ```ts\n * class AuthProviders {\n * // Internal credentials-based auth\n * credentials = $auth({\n * realm: this.userRealm,\n * credentials: {\n * account: async ({ username, password }) => {\n * return await this.validateUser(username, password);\n * }\n * }\n * });\n *\n * // External OIDC provider\n * keycloak = $auth({\n * oidc: {\n * issuer: \"https://auth.example.com\",\n * clientId: \"my-app\",\n * clientSecret: \"secret\",\n * redirectUri: \"/auth/callback\"\n * }\n * });\n * }\n * ```\n */\nexport const $auth = (options: AuthPrimitiveOptions): AuthPrimitive => {\n return createPrimitive(AuthPrimitive, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport type AuthPrimitiveOptions = {\n /**\n * Name of the identity provider.\n * If not provided, it will be derived from the property key.\n */\n name?: string;\n\n /**\n * If true, auth provider will be skipped.\n */\n disabled?: boolean;\n} & (AuthExternal | AuthInternal);\n\n/**\n * When you let an external service handle authentication. (e.g. Keycloak, Auth0, etc.)\n */\nexport type AuthExternal = {\n /**\n * Only OIDC is supported for external authentication.\n */\n oidc: OidcOptions;\n\n /**\n * For anonymous access, this will expect a service account access token.\n *\n * ```ts\n * class App {\n * anonymous = $serviceAccount(...);\n * auth = $auth({\n * // ... config ...\n * fallback: this.anonymous,\n * })\n * }\n * ```\n */\n fallback?: () => Async<AccessToken>;\n};\n\n/**\n * When using your own authentication system, e.g. using a database to store user accounts.\n * This is usually used with a custom login form.\n *\n * This relies on the `issuer`, which is used to create/verify the access token.\n */\nexport type AuthInternal = {\n issuer: IssuerPrimitive;\n} & (\n | {\n /**\n * The common username/password authentication.\n *\n * - It uses the OAuth2 Client Credentials flow to obtain an access token.\n *\n * This is usually used with a custom login form on your website or mobile app.\n */\n credentials: CredentialsOptions;\n }\n | {\n /**\n * OAuth2 authentication. Delegates authentication to an OAuth2 provider. (e.g. Google, GitHub, etc.)\n *\n * - It uses the OAuth2 Authorization Code flow to obtain an access token and user information.\n *\n * This is usually used with a login button that redirects to the OAuth2 provider.\n */\n oauth: OAuth2Options;\n }\n | {\n /**\n * Like OAuth2, but uses OIDC (OpenID Connect) for authentication and user information retrieval.\n * OIDC is an identity layer on top of OAuth2, providing user authentication and profile information.\n *\n * - It uses the OAuth2 Authorization Code flow to obtain an access token and user information.\n * - PCKE (Proof Key for Code Exchange) is recommended for security.\n *\n * This is usually used with a login button that redirects to the OIDC provider.\n */\n oidc: OidcOptions;\n }\n);\n\nexport type CredentialsOptions = {\n account: CredentialsFn;\n};\n\nexport type CredentialsFn = (\n credentials: Credentials,\n) => Async<UserAccount | undefined>;\n\nexport interface Credentials {\n username: string;\n password: string;\n}\n\nexport interface OidcOptions {\n /**\n * URL of the OIDC issuer.\n */\n issuer: string;\n\n /**\n * Client ID for the OIDC client.\n */\n clientId: string;\n\n /**\n * Client secret for the OIDC client.\n * Optional if PKCE (Proof Key for Code Exchange) is used.\n */\n clientSecret?: string;\n\n /**\n * Redirect URI for the OIDC client.\n * This is where the user will be redirected after authentication.\n */\n redirectUri?: string;\n\n /**\n * For external auth providers only.\n * Take the ID token instead of the access token for validation.\n */\n useIdToken?: boolean;\n\n /**\n * URI to redirect the user after logout.\n */\n logoutUri?: string;\n\n /**\n * Optional scope for the OIDC client.\n * @default \"openid profile email\".\n */\n scope?: string;\n\n account?: LinkAccountFn;\n}\n\nexport interface LinkAccountOptions {\n access_token: string;\n user: OAuth2Profile;\n id_token?: string;\n expires_in?: number;\n scope?: string;\n}\n\nexport type LinkAccountFn = (tokens: LinkAccountOptions) => Async<UserAccount>;\n\nexport interface OAuth2Options {\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n clientId: string;\n\n /**\n * Client secret for the OAuth2 client.\n */\n clientSecret: string;\n\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n authorization: string;\n\n /**\n * URL of the OAuth2 token endpoint.\n */\n token: string;\n\n /**\n * Function to retrieve user profile information from the OAuth2 tokens.\n */\n userinfo: (tokens: Tokens) => Async<OAuth2Profile>;\n\n account?: LinkAccountFn;\n\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n redirectUri?: string;\n\n /**\n * URL of the OAuth2 authorization endpoint.\n */\n scope?: string;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class AuthPrimitive extends Primitive<AuthPrimitiveOptions> {\n protected readonly securityProvider = $inject(SecurityProvider);\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n\n public oauth?: Configuration;\n\n public get name() {\n return this.options.name ?? this.config.propertyKey;\n }\n\n public get issuer(): IssuerPrimitive | undefined {\n if (\"issuer\" in this.options) {\n return this.options.issuer;\n }\n return undefined;\n }\n\n public get jwks_uri(): string {\n const jwks = this.oauth?.serverMetadata().jwks_uri;\n if (!jwks) {\n throw new AlephaError(\"No JWKS URI available for the auth provider\");\n }\n return jwks;\n }\n\n public get scope(): string | undefined {\n if (\"oauth\" in this.options) {\n return this.options.oauth.scope;\n }\n if (\"oidc\" in this.options) {\n return this.options.oidc.scope || \"openid profile email\";\n }\n throw new AlephaError(\n \"No OAuth2 or OIDC configuration available for the auth provider\",\n );\n }\n\n public get redirect_uri() {\n if (\"oauth\" in this.options) {\n return this.options.oauth.redirectUri;\n }\n if (\"oidc\" in this.options) {\n return this.options.oidc.redirectUri;\n }\n throw new AlephaError(\n \"No OAuth2 or OIDC configuration available for the auth provider\",\n );\n }\n\n /**\n * Refreshes the access token using the refresh token.\n * Can be used on oauth2, oidc or credentials auth providers.\n */\n public async refresh(\n refreshToken: string,\n accessToken?: string,\n ): Promise<AccessTokenResponse> {\n if (\"issuer\" in this.options) {\n return this.options.issuer\n .refreshToken(refreshToken, accessToken)\n .then((it) => it.tokens)\n .catch((error) => {\n throw new SecurityError(\n \"Failed to refresh access token using the refresh token (issuer)\",\n {\n cause: error,\n },\n );\n });\n } else if (this.oauth) {\n try {\n return {\n ...(await refreshTokenGrant(this.oauth, refreshToken)),\n issued_at: this.dateTimeProvider.now().unix(),\n };\n } catch (error) {\n throw new SecurityError(\n \"Failed to refresh access token using the refresh token (oauth2)\",\n {\n cause: error,\n },\n );\n }\n }\n\n throw new AlephaError(\n \"No issuer or OAuth2 configuration available for refreshing the access token\",\n );\n }\n\n /**\n * Extracts user information from the access token.\n * This is used to create a user account from the access token.\n */\n public async user(tokens: Tokens): Promise<UserAccount> {\n try {\n if (\"oauth\" in this.options) {\n const profile = await this.options.oauth.userinfo(tokens);\n\n if (this.options.oauth.account) {\n return this.options.oauth.account({\n ...tokens,\n user: profile,\n });\n }\n\n return this.securityProvider.createUserFromPayload(profile);\n }\n\n if (\"oidc\" in this.options) {\n const payload = this.getUserFromIdToken(tokens.id_token || \"\");\n\n if (this.options.oidc.account) {\n return this.options.oidc.account({\n ...tokens,\n user: payload,\n });\n }\n\n return this.securityProvider.createUserFromPayload(payload);\n }\n } catch (error) {\n throw new SecurityError(\n \"Failed to extract user from identity provider tokens\",\n {\n cause: error,\n },\n );\n }\n\n throw new AlephaError(\n \"This authentication does not support user extraction from tokens\",\n );\n }\n\n protected getUserFromIdToken(idToken: string): OAuth2Profile {\n try {\n return JSON.parse(\n Buffer.from(idToken.split(\".\")[1], \"base64\").toString(\"utf8\"),\n ) as OAuth2Profile;\n } catch (error) {\n throw new AlephaError(\"Failed to parse ID Token payload\", {\n cause: error,\n });\n }\n }\n\n public async prepare() {\n const addons: Array<(config: Configuration) => void> = [];\n\n addons.push(allowInsecureRequests);\n\n if (\"oidc\" in this.options) {\n const { oidc } = this.options;\n\n this.oauth = await discovery(\n new URL(oidc.issuer),\n oidc.clientId,\n {\n client_secret: oidc.clientSecret,\n },\n undefined,\n {\n execute: addons,\n },\n );\n }\n\n if (\"oauth\" in this.options) {\n const { oauth } = this.options;\n\n this.oauth = new Configuration(\n {\n authorization_endpoint: oauth.authorization,\n token_endpoint: oauth.token,\n issuer: oauth.authorization, // use authorization URL as a pseudo-issuer?\n // we don't need all of these endpoints\n jwks_uri: undefined,\n end_session_endpoint: undefined,\n },\n oauth.clientId,\n {\n client_secret: oauth.clientSecret,\n },\n );\n }\n }\n}\n\n$auth[KIND] = AuthPrimitive;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport type AccessToken = string | { token: () => Async<string> };\n\nexport interface WithLinkFn {\n link?: (name: string) => (opts: LinkAccountOptions) => Async<UserAccount>;\n}\n\nexport interface WithLoginFn {\n login?: (\n provider: string,\n ) => (creds: Credentials) => Async<UserAccount | undefined>;\n}\n","export const alephaServerAuthRoutes = {\n login: \"/oauth/login\",\n callback: \"/oauth/callback\",\n logout: \"/oauth/logout\",\n token: \"/_auth/token\",\n refresh: \"/_auth/refresh\",\n userinfo: \"/_auth/userinfo\",\n};\n","import type { Static } from \"alepha\";\nimport { t } from \"alepha\";\n\nexport const tokensSchema = t.object({\n provider: t.text(),\n access_token: t.text({ size: \"rich\" }),\n issued_at: t.number(),\n expires_in: t.optional(t.number()),\n refresh_token: t.optional(t.text({ size: \"rich\" })),\n refresh_token_expires_in: t.optional(t.number()),\n refresh_expires_in: t.optional(\n t.number({\n description:\n \"Alias of `refresh_token_expires_in` for compatibility with some providers.\",\n }),\n ),\n id_token: t.optional(t.text({ size: \"rich\" })),\n scope: t.optional(t.text()),\n});\n\nexport type Tokens = Static<typeof tokensSchema>;\n","import { type Static, t } from \"alepha\";\nimport { userAccountInfoSchema } from \"alepha/security\";\nimport { apiLinksResponseSchema } from \"alepha/server/links\";\nimport { tokensSchema } from \"./tokensSchema.ts\";\n\nexport const tokenResponseSchema = t.extend(tokensSchema, {\n user: userAccountInfoSchema,\n api: apiLinksResponseSchema,\n});\n\nexport type TokenResponse = Static<typeof tokenResponseSchema>;\n","import { type Static, t } from \"alepha\";\nimport { userAccountInfoSchema } from \"alepha/security\";\nimport { apiLinksResponseSchema } from \"alepha/server/links\";\n\nexport const userinfoResponseSchema = t.object({\n user: t.optional(userAccountInfoSchema),\n api: apiLinksResponseSchema,\n});\n\nexport type UserinfoResponse = Static<typeof userinfoResponseSchema>;\n","import { $hook, $inject, Alepha, t } from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport { $logger } from \"alepha/logger\";\nimport {\n InvalidCredentialsError,\n SecurityError,\n type UserAccount,\n} from \"alepha/security\";\nimport { $route, BadRequestError } from \"alepha/server\";\nimport {\n $cookie,\n type Cookies,\n ServerCookiesProvider,\n} from \"alepha/server/cookies\";\nimport { ServerLinksProvider } from \"alepha/server/links\";\nimport {\n authorizationCodeGrant,\n buildAuthorizationUrl,\n buildEndSessionUrl,\n calculatePKCECodeChallenge,\n randomPKCECodeVerifier,\n randomState,\n} from \"openid-client\";\nimport { alephaServerAuthRoutes } from \"../constants/routes.ts\";\nimport { $auth, type AuthPrimitive } from \"../primitives/$auth.ts\";\nimport type { AuthenticationProvider } from \"../schemas/authenticationProviderSchema.ts\";\nimport { tokenResponseSchema } from \"../schemas/tokenResponseSchema.ts\";\nimport { type Tokens, tokensSchema } from \"../schemas/tokensSchema.ts\";\nimport { userinfoResponseSchema } from \"../schemas/userinfoResponseSchema.ts\";\n\nexport class ServerAuthProvider {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n protected readonly serverCookiesProvider = $inject(ServerCookiesProvider);\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n protected readonly serverLinksProvider = $inject(ServerLinksProvider);\n\n protected readonly authorizationCode = $cookie({\n name: \"authorizationCode\",\n ttl: [15, \"minutes\"],\n httpOnly: true,\n schema: t.object({\n provider: t.text(),\n realm: t.optional(t.text()),\n codeVerifier: t.optional(t.text({ size: \"long\" })),\n redirectUri: t.optional(t.text({ size: \"long\" })),\n state: t.optional(t.text()),\n nonce: t.optional(t.text()),\n }),\n });\n\n public readonly tokens = $cookie({\n name: \"tokens\",\n ttl: [30, \"days\"],\n httpOnly: true,\n compress: true,\n encrypt: true,\n schema: tokensSchema,\n });\n\n public get identities(): Array<AuthPrimitive> {\n return this.alepha\n .primitives($auth)\n .filter((auth) => !auth.options.disabled);\n }\n\n public getAuthenticationProviders(\n filters: { realmName?: string } = {},\n ): AuthenticationProvider[] {\n const providers: AuthenticationProvider[] = [];\n\n for (const identity of this.identities) {\n if (filters.realmName) {\n const issuer = identity.issuer;\n if (!issuer || issuer.name !== filters.realmName) {\n continue;\n }\n }\n\n const type =\n \"oidc\" in identity.options\n ? \"OIDC\"\n : \"oauth\" in identity.options\n ? \"OAUTH2\"\n : \"credentials\" in identity.options\n ? \"CREDENTIALS\"\n : undefined;\n\n if (!type) {\n continue;\n }\n\n providers.push({\n name: identity.name,\n type,\n });\n }\n\n return providers;\n }\n\n protected readonly configure = $hook({\n on: \"configure\",\n handler: async () => {\n for (const identity of this.identities) {\n await identity.prepare();\n }\n },\n });\n\n protected getAccessTokens(tokens: Tokens) {\n const idp = this.provider(tokens.provider);\n\n if (\n \"oidc\" in idp.options &&\n !(\"realm\" in idp.options) &&\n idp.options.oidc?.useIdToken\n ) {\n return tokens.id_token;\n }\n\n return tokens.access_token;\n }\n\n /**\n * Fill request headers with access token from cookies or fallback to provider's fallback function.\n */\n protected readonly onRequest = $hook({\n on: \"server:onRequest\",\n after: this.serverCookiesProvider,\n handler: async ({ request }) => {\n const cookies = request.cookies;\n\n // [feature] forward cookies to request headers\n if (cookies) {\n const tokens = await this.cookiesToTokens(cookies);\n if (tokens) {\n request.headers.authorization = `Bearer ${this.getAccessTokens(tokens)}`;\n this.log.trace(\"Access token set in request headers\", {\n provider: tokens.provider,\n });\n }\n }\n\n // [feature] support for auth providers with fallback\n if (!request.headers.authorization) {\n for (const provider of this.identities) {\n if (\"fallback\" in provider.options && !!provider.options.fallback) {\n const token = await provider.options.fallback();\n if (token) {\n request.headers.authorization = `Bearer ${token}`;\n break;\n }\n }\n }\n }\n },\n });\n\n /**\n * Convert cookies to tokens.\n * If the tokens are expired, try to refresh them using the refresh token.\n */\n protected async cookiesToTokens(\n cookies: Cookies,\n ): Promise<Tokens | undefined> {\n const tokens = this.getTokens(cookies);\n if (!tokens) {\n // no cookie, no tokens\n this.log.trace(\"No tokens found in cookies\");\n return;\n }\n\n this.log.trace(\"Tokens found in cookies\", {\n expires_in: tokens.expires_in,\n issued_at: tokens.issued_at,\n });\n\n // check if tokens are expired\n const refreshedTokens = await this.refreshTokens(tokens);\n if (!refreshedTokens) {\n this.tokens.del({ cookies });\n // 08/25: exception here will go to Server error handler, not the React one\n // better to remove cookie & session and let the page handle 401 Unauthorized\n //throw new SessionExpiredError(\"Session expired. Please login again.\");\n return;\n }\n\n if (refreshedTokens.access_token !== tokens.access_token) {\n this.setTokens(refreshedTokens, cookies);\n }\n\n return refreshedTokens;\n }\n\n protected async refreshTokens(tokens: Tokens): Promise<Tokens | undefined> {\n if (tokens.expires_in && tokens.issued_at) {\n const gracePeriodSec = 10;\n const expiresAt = tokens.issued_at + (tokens.expires_in - gracePeriodSec);\n\n if (expiresAt < this.dateTimeProvider.now().unix()) {\n this.log.trace(\"Tokens are expired\");\n\n // oh no, it is expired\n if (tokens.refresh_token) {\n this.log.trace(\"Trying to refresh tokens using refresh token\");\n // but has refresh token!\n try {\n const provider = this.provider(tokens);\n const result = await provider.refresh(\n tokens.refresh_token,\n tokens.access_token,\n );\n const newTokens = {\n ...result,\n provider: tokens.provider,\n issued_at: this.dateTimeProvider.now().unix(),\n };\n\n this.log.debug(\"Tokens refreshed successfully\");\n\n return newTokens;\n } catch (e) {\n this.log.warn(\"Failed to refresh token\", e);\n }\n }\n\n // session expired and no (valid) refresh token\n return;\n }\n }\n\n if (!tokens.issued_at && tokens.access_token) {\n return;\n }\n\n return tokens;\n }\n\n // -------------------------------------------------------------------------------------------------------------------\n\n /**\n * Get user information.\n */\n public readonly userinfo = $route({\n path: alephaServerAuthRoutes.userinfo,\n schema: {\n response: userinfoResponseSchema,\n },\n handler: async ({ user, headers, cookies }) => {\n const tokens = this.getTokens(cookies);\n if (tokens) {\n const provider = this.provider(tokens);\n if (!(\"realm\" in provider.options)) {\n const user = await provider.user(tokens);\n const api = await this.serverLinksProvider.getUserApiLinks({\n authorization: headers.authorization,\n user,\n });\n return {\n api,\n user,\n };\n }\n }\n\n const api = await this.serverLinksProvider.getUserApiLinks({\n authorization: headers.authorization,\n user,\n });\n\n return {\n api,\n user,\n };\n },\n });\n\n /**\n * Refresh a token for internal providers.\n */\n public readonly refresh = $route({\n path: alephaServerAuthRoutes.refresh,\n method: \"POST\",\n schema: {\n query: t.object({\n provider: t.text(),\n }),\n body: t.object({\n refresh_token: t.text({\n size: \"rich\",\n }),\n access_token: t.optional(\n t.text({\n size: \"rich\",\n description:\n \"Required if provider has stateless refresh token on credentials mode\",\n }),\n ),\n }),\n response: tokensSchema,\n },\n handler: async ({ query, body, cookies }) => {\n const provider = this.provider(query);\n\n const tokens = {\n provider: query.provider,\n ...(await provider.refresh(body.refresh_token, body.access_token)),\n };\n\n // for web applications, we store tokens in cookies\n this.setTokens(tokens, cookies);\n\n return tokens;\n },\n });\n\n /**\n * Login for local password-based authentication.\n */\n public readonly token = $route({\n path: alephaServerAuthRoutes.token,\n method: \"POST\",\n schema: {\n query: t.object({\n provider: t.text(),\n realm: t.optional(\n t.text({ description: \"Realm name for multi-realm setups\" }),\n ),\n }),\n body: t.object({\n username: t.text(),\n password: t.text(),\n }),\n response: tokenResponseSchema,\n },\n handler: async ({ query, body, cookies }) => {\n const provider = this.provider({\n provider: query.provider,\n realm: query.realm,\n });\n\n const issuer = provider.issuer;\n if (!issuer) {\n throw new SecurityError(\n `Auth provider '${query.provider}' does not support password grant`,\n );\n }\n\n const credentials =\n \"credentials\" in provider.options && provider.options.credentials;\n\n if (!credentials) {\n throw new SecurityError(\n `Auth provider '${query.provider}' does not support password grant`,\n );\n }\n\n let user: UserAccount | undefined;\n try {\n user = await credentials.account(body);\n } catch (e) {\n if (e instanceof InvalidCredentialsError) {\n throw e;\n }\n this.log.error(\"Failed to authenticate user\", e);\n throw new InvalidCredentialsError();\n }\n\n if (!user) {\n throw new InvalidCredentialsError();\n }\n\n const tokens = {\n provider: query.provider,\n ...(await issuer.createToken(user)),\n };\n\n // for web applications, we store tokens in cookies\n this.setTokens(tokens, cookies);\n\n const api = await this.serverLinksProvider.getUserApiLinks({\n user,\n });\n\n // mobile apps require this\n return {\n ...tokens,\n user,\n api,\n };\n },\n });\n\n /**\n * Oauth2/OIDC login route.\n */\n public readonly login = $route({\n path: alephaServerAuthRoutes.login,\n schema: {\n query: t.object({\n provider: t.text(),\n realm: t.optional(\n t.text({ description: \"Realm name for multi-realm setups\" }),\n ),\n redirect_uri: t.optional(t.text({ size: \"rich\" })),\n }),\n },\n handler: async ({ query, url, reply }) => {\n const provider = this.provider({\n provider: query.provider,\n realm: query.realm,\n });\n const oauth = provider.oauth;\n if (!oauth) {\n throw new SecurityError(\n `Auth provider '${query.provider}' does not support OAuth2`,\n );\n }\n\n const scope = provider.scope;\n let redirect_uri =\n provider.redirect_uri || alephaServerAuthRoutes.callback;\n if (redirect_uri.startsWith(\"/\")) {\n redirect_uri = `${url.protocol}//${url.host}${redirect_uri}`;\n }\n\n const oidc = \"oidc\" in provider.options && provider.options.oidc;\n\n if (!oauth.serverMetadata().supportsPKCE()) {\n const state = randomState();\n const parameters: Record<string, string> = {\n redirect_uri,\n state,\n };\n\n if (oidc) {\n parameters.nonce = randomState();\n }\n\n if (scope) {\n parameters.scope = scope;\n }\n\n this.authorizationCode.set({\n state,\n nonce: parameters.nonce,\n redirectUri: query.redirect_uri ?? \"/\",\n provider: query.provider,\n realm: query.realm,\n });\n\n reply.redirect(buildAuthorizationUrl(oauth, parameters).toString());\n return;\n }\n\n const codeVerifier = randomPKCECodeVerifier();\n const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);\n\n const parameters: Record<string, string> = {\n redirect_uri,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n };\n\n if (scope) {\n parameters.scope = scope;\n }\n\n this.authorizationCode.set({\n codeVerifier,\n redirectUri: query.redirect_uri ?? \"/\",\n provider: query.provider,\n realm: query.realm,\n });\n\n reply.redirect(buildAuthorizationUrl(oauth, parameters).toString());\n },\n });\n\n /**\n * Callback for OAuth2/OIDC providers.\n * It handles the authorization code flow and retrieves the access token.\n */\n public readonly callback = $route({\n path: alephaServerAuthRoutes.callback,\n handler: async ({ url, reply, cookies }) => {\n const authorizationCode = this.authorizationCode.get({ cookies });\n if (!authorizationCode) {\n throw new BadRequestError(\"Missing code verifier\");\n }\n\n const provider = this.provider(authorizationCode);\n const oauth = provider.oauth;\n if (!oauth) {\n throw new SecurityError(\n `Auth provider '${provider.name}' does not support OAuth2`,\n );\n }\n\n const redirectUri = authorizationCode.redirectUri ?? \"/\";\n\n const externalTokens = await authorizationCodeGrant(oauth, url, {\n pkceCodeVerifier: authorizationCode.codeVerifier,\n expectedState: authorizationCode.state,\n expectedNonce: authorizationCode.nonce,\n })\n .then((tokens) => ({\n issued_at: this.dateTimeProvider.now().unix(),\n provider: provider.name,\n ...tokens,\n }))\n .catch((e) => {\n this.log.error(\"Failed to get access token\", e);\n throw new SecurityError(\"Failed to get access token\", {\n cause: e,\n });\n });\n\n this.authorizationCode.del({ cookies });\n\n const issuer = provider.issuer;\n\n // external, full OIDC System (e.g. Keycloak, Auth0)\n if (!issuer) {\n this.setTokens(externalTokens, cookies);\n reply.redirect(redirectUri);\n return;\n }\n\n // internal, we need to create our own tokens\n\n const user = await provider.user(externalTokens);\n const tokens = await issuer.createToken(user);\n\n this.setTokens(\n {\n ...tokens,\n issued_at: this.dateTimeProvider.now().unix(),\n provider: provider.name,\n },\n cookies,\n );\n\n reply.redirect(redirectUri);\n },\n });\n\n /**\n * Logout route for OAuth2/OIDC providers.\n */\n public readonly logout = $route({\n path: alephaServerAuthRoutes.logout,\n method: \"GET\",\n schema: {\n query: t.object({\n post_logout_redirect_uri: t.optional(t.text()),\n }),\n },\n handler: async ({ query, reply, cookies }) => {\n const redirect = query.post_logout_redirect_uri ?? \"/\";\n const tokens = this.getTokens(cookies);\n if (!tokens) {\n reply.redirect(redirect);\n return;\n }\n\n const provider = this.provider(tokens.provider);\n\n this.tokens.del({ cookies });\n\n // for internal providers, we can delete the session - if available\n if (provider.issuer && tokens.refresh_token) {\n const onDeleteSession =\n provider.issuer.options.settings?.onDeleteSession;\n if (onDeleteSession) {\n try {\n await onDeleteSession(tokens.refresh_token);\n } catch (e) {\n this.log.error(\"Failed to delete session\", e);\n }\n }\n }\n\n const oauth = provider.oauth;\n if (!oauth) {\n reply.redirect(redirect);\n return;\n }\n\n const params = new URLSearchParams();\n const idToken = tokens?.id_token;\n\n params.set(\"post_logout_redirect_uri\", redirect);\n if (idToken) {\n params.set(\"id_token_hint\", idToken);\n }\n\n const customLogoutUri =\n \"oidc\" in provider.options\n ? provider.options.oidc?.logoutUri\n : undefined;\n\n if (customLogoutUri) {\n reply.redirect(`${customLogoutUri}?${params}`);\n return;\n }\n\n if (!oauth.serverMetadata().end_session_endpoint) {\n // await tokenRevocation(\n // \toauth,\n // \ttokens?.refresh_token ?? tokens.access_token,\n // );\n reply.redirect(redirect);\n return;\n }\n\n reply.redirect(buildEndSessionUrl(oauth, params).toString());\n },\n });\n\n /**\n * Find an auth provider by name and optionally by realm.\n * When realm is specified, it filters providers by both name and realm.\n * This enables multi-realm setups where multiple providers share the same name (e.g., \"credentials\").\n */\n protected provider(\n opts: string | { provider: string; realm?: string },\n ): AuthPrimitive {\n const name = typeof opts === \"string\" ? opts : opts.provider;\n const realmName = typeof opts === \"string\" ? undefined : opts.realm;\n\n const identity = this.identities.find((identity) => {\n if (identity.name !== name) {\n return false;\n }\n\n // If realm filter is specified, match against provider's issuer\n if (realmName && identity.issuer?.name !== realmName) {\n return false;\n }\n\n return true;\n });\n\n if (!identity) {\n const realmInfo = realmName ? ` for realm '${realmName}'` : \"\";\n throw new SecurityError(`Auth provider '${name}'${realmInfo} not found`);\n }\n\n return identity;\n }\n\n protected getTokens(cookies?: Cookies): Tokens | undefined {\n return this.tokens.get({ cookies });\n }\n\n protected setTokens(tokens: Tokens, cookies?: Cookies): void {\n const exp =\n tokens.refresh_token_expires_in ||\n tokens.refresh_expires_in ||\n tokens.expires_in;\n\n const ttl = exp\n ? this.dateTimeProvider.duration(exp, \"seconds\")\n : undefined;\n\n this.tokens.set(tokens, {\n cookies,\n ttl,\n });\n }\n}\n\nexport interface OAuth2Profile {\n sub: string; // Subject - unique ID per user (required by OpenID)\n email?: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string; // ISO 8601: YYYY-MM-DD\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: {\n formatted?: string;\n street_address?: string;\n locality?: string;\n region?: string;\n postal_code?: string;\n country?: string;\n };\n updated_at?: number; // seconds since epoch\n // Allow additional fields (provider-specific)\n [key: string]: unknown;\n}\n","import { type Static, t } from \"alepha\";\n\nexport const authenticationProviderSchema = t.object(\n {\n name: t.text({\n description: \"Name of the authentication provider.\",\n }),\n type: t.enum([\"OAUTH2\", \"OIDC\", \"CREDENTIALS\"], {\n description: \"Type of the authentication provider.\",\n }),\n },\n {\n title: \"AuthenticationProvider\",\n },\n);\n\nexport type AuthenticationProvider = Static<\n typeof authenticationProviderSchema\n>;\n","import { AlephaError } from \"alepha\";\nimport type { IssuerPrimitive } from \"alepha/security\";\nimport {\n $auth,\n type CredentialsFn,\n type CredentialsOptions,\n type WithLoginFn,\n} from \"./$auth.ts\";\n\n/**\n * Already configured Credentials authentication primitive.\n *\n * Uses username and password to authenticate users.\n */\nexport const $authCredentials = (\n realm: IssuerPrimitive & WithLoginFn,\n options: Partial<CredentialsOptions> = {},\n) => {\n const name = \"credentials\";\n\n const account: CredentialsFn | undefined = realm.login\n ? realm.login(name)\n : options.account;\n\n if (!account) {\n throw new AlephaError(\n \"Credentials authentication requires a login function in the realm primitive.\",\n );\n }\n\n return $auth({\n issuer: realm,\n name,\n credentials: {\n account,\n },\n });\n};\n","import { $context, AlephaError, t } from \"alepha\";\nimport type { IssuerPrimitive } from \"alepha/security\";\nimport type { OAuth2Profile } from \"../providers/ServerAuthProvider.ts\";\nimport {\n $auth,\n type LinkAccountFn,\n type OidcOptions,\n type WithLinkFn,\n} from \"./$auth.ts\";\n\n/**\n * Already configured GitHub authentication primitive.\n *\n * Uses OAuth2 to authenticate users via their GitHub accounts.\n * Upon successful authentication, it links the GitHub account to a user session.\n *\n * Environment Variables:\n * - `GITHUB_CLIENT_ID`: The client ID obtained from the GitHub Developer Settings.\n * - `GITHUB_CLIENT_SECRET`: The client secret obtained from the GitHub Developer Settings.\n */\nexport const $authGithub = (\n realm: IssuerPrimitive & WithLinkFn,\n options: Partial<OidcOptions> = {},\n) => {\n const { alepha } = $context();\n\n const env = alepha.parseEnv(\n t.object({\n GITHUB_CLIENT_ID: t.optional(t.text()),\n GITHUB_CLIENT_SECRET: t.optional(t.text()),\n }),\n );\n\n const disabled = !env.GITHUB_CLIENT_ID || !env.GITHUB_CLIENT_SECRET;\n\n const name = \"github\";\n\n const account: LinkAccountFn | undefined =\n options.account ?? (realm.link ? realm.link(name) : undefined);\n\n if (!account) {\n throw new AlephaError(\n \"Authentication requires a link function in the realm primitive.\",\n );\n }\n\n return $auth({\n issuer: realm,\n name,\n oauth: {\n clientId: env.GITHUB_CLIENT_ID!,\n clientSecret: env.GITHUB_CLIENT_SECRET!,\n authorization: \"https://github.com/login/oauth/authorize\",\n token: \"https://github.com/login/oauth/access_token\",\n scope: \"read:user user:email\",\n userinfo: async (tokens) => {\n const BASE_URL = \"https://api.github.com\";\n const res = await fetch(`${BASE_URL}/user`, {\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n \"User-Agent\": \"Alepha\",\n },\n }).then((res) => res.json());\n\n const user: OAuth2Profile = {\n sub: res.id.toString(),\n };\n\n if (res.email) {\n user.email = res.email;\n }\n\n if (res.name) {\n user.name = res.name.trim();\n }\n\n if (res.avatar_url) {\n user.picture = res.avatar_url;\n }\n\n if (!user.email) {\n const res = await fetch(`${BASE_URL}/user/emails`, {\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n \"User-Agent\": \"Alepha\",\n },\n });\n if (res.ok) {\n const emails: any[] = await res.json();\n user.email = (emails.find((e) => e.primary) ?? emails[0]).email;\n }\n }\n\n return user;\n },\n ...options,\n account,\n },\n disabled,\n });\n};\n","import { $context, AlephaError, t } from \"alepha\";\nimport type { IssuerPrimitive } from \"alepha/security\";\nimport {\n $auth,\n type LinkAccountFn,\n type OidcOptions,\n type WithLinkFn,\n} from \"./$auth.ts\";\n\n/**\n * Already configured Google authentication primitive.\n *\n * Uses OpenID Connect (OIDC) to authenticate users via their Google accounts.\n * Upon successful authentication, it links the Google account to a user session.\n *\n * Environment Variables:\n * - `GOOGLE_CLIENT_ID`: The client ID obtained from the Google Developer Console.\n * - `GOOGLE_CLIENT_SECRET`: The client secret obtained from the Google Developer Console.\n */\nexport const $authGoogle = (\n realm: IssuerPrimitive & WithLinkFn,\n options: Partial<OidcOptions> = {},\n) => {\n const { alepha } = $context();\n\n const env = alepha.parseEnv(\n t.object({\n GOOGLE_CLIENT_ID: t.optional(t.text()),\n GOOGLE_CLIENT_SECRET: t.optional(t.text()),\n }),\n );\n\n const disabled = !env.GOOGLE_CLIENT_ID || !env.GOOGLE_CLIENT_SECRET;\n\n const name = \"google\";\n\n const account: LinkAccountFn | undefined =\n options.account ?? (realm.link ? realm.link(name) : undefined);\n\n if (!account) {\n throw new AlephaError(\n \"Authentication requires a link function in the realm primitive.\",\n );\n }\n\n return $auth({\n issuer: realm,\n name,\n oidc: {\n issuer: \"https://accounts.google.com\",\n clientId: env.GOOGLE_CLIENT_ID!,\n clientSecret: env.GOOGLE_CLIENT_SECRET,\n ...options,\n account,\n },\n disabled,\n });\n};\n","import { $module } from \"alepha\";\nimport type { UserAccount } from \"alepha/security\";\nimport { AlephaServerCookies } from \"alepha/server/cookies\";\nimport { $auth } from \"./primitives/$auth.ts\";\nimport { ServerAuthProvider } from \"./providers/ServerAuthProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./index.shared.ts\";\nexport * from \"./primitives/$auth.ts\";\nexport * from \"./primitives/$authCredentials.ts\";\nexport * from \"./primitives/$authGithub.ts\";\nexport * from \"./primitives/$authGoogle.ts\";\nexport * from \"./providers/ServerAuthProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha\" {\n export interface State {\n /**\n * The authenticated user account attached to the server request state.\n *\n * @internal\n */\n \"alepha.server.request.user\"?: UserAccount;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Allow authentication services for server applications.\n * It provides login and logout functionalities.\n *\n * There are multiple authentication providers available (e.g., Google, GitHub).\n * You can also delegate authentication to your own OIDC/OAuth2, for example using Keycloak or Auth0.\n *\n * It's cookie-based and SSR friendly.\n *\n * @see {@link $auth}\n * @see {@link ServerAuthProvider}\n * @module alepha.server.auth\n */\nexport const AlephaServerAuth = $module({\n name: \"alepha.server.auth\",\n primitives: [$auth],\n services: [AlephaServerCookies, ServerAuthProvider],\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,MAAa,SAAS,YAAiD;AACrE,QAAO,gBAAgB,eAAe,QAAQ;;AAiMhD,IAAa,gBAAb,cAAmC,UAAgC;CACjE,AAAmB,mBAAmB,QAAQ,iBAAiB;CAC/D,AAAmB,mBAAmB,QAAQ,iBAAiB;CAE/D,AAAO;CAEP,IAAW,OAAO;AAChB,SAAO,KAAK,QAAQ,QAAQ,KAAK,OAAO;;CAG1C,IAAW,SAAsC;AAC/C,MAAI,YAAY,KAAK,QACnB,QAAO,KAAK,QAAQ;;CAKxB,IAAW,WAAmB;EAC5B,MAAM,OAAO,KAAK,OAAO,gBAAgB,CAAC;AAC1C,M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,IAAI,MACN,MAAK,QAAQ,IAAI;AAGnB,QAAI,IAAI,KACN,MAAK,OAAO,IAAI,KAAK,MAAM;AAG7B,QAAI,IAAI,WACN,MAAK,UAAU,IAAI;AAGrB,QAAI,CAAC,KAAK,OAAO;KACf,MAAMA,QAAM,MAAM,MAAM,GAAG,SAAS,eAAe,EACjD,SAAS;MACP,eAAe,UAAU,OAAO;MAChC,cAAc;MACf,EACF,CAAC;AACF,SAAIA,MAAI,IAAI;MACV,MAAM,SAAgB,MAAMA,MAAI,MAAM;AACtC,WAAK,SAAS,OAAO,MAAM,MAAM,EAAE,QAAQ,IAAI,OAAO,IAAI;;;AAI9D,WAAO;;GAET,GAAG;GACH;GACD;EACD;EACD,CAAC;;;;;;;;;;;;;;;AChFJ,MAAa,eACX,OACA,UAAgC,EAAE,KAC/B;CACH,MAAM,EAAE,WAAW,UAAU;CAE7B,MAAM,MAAM,OAAO,SACjB,EAAE,OAAO;EACP,kBAAkB,EAAE,SAAS,EAAE,MAAM,CAAC;EACtC,sBAAsB,EAAE,SAAS,EAAE,MAAM,CAAC;EAC3C,CAAC,CACH;CAED,MAAM,WAAW,CAAC,IAAI,oBAAoB,CAAC,IAAI;CAE/C,MAAM,OAAO;CAEb,MAAM,UACJ,QAAQ,YAAY,MAAM,OAAO,MAAM,KAAK,KAAK,GAAG;AAEtD,KAAI,CAAC,QACH,OAAM,IAAI,YACR,kEACD;AAGH,QAAO,MAAM;EACX,QAAQ;EACR;EACA,MAAM;GACJ,QAAQ;GACR,UAAU,IAAI;GACd,cAAc,IAAI;GAClB,GAAG;GACH;GACD;EACD;EACD,CAAC;;;;;;;;;;;;;;;;;;ACbJ,MAAa,mBAAmB,QAAQ;CACtC,MAAM;CACN,YAAY,CAAC,MAAM;CACnB,UAAU,CAAC,qBAAqB,mBAAmB;CACpD,CAAC"}
|
|
@@ -11,12 +11,12 @@ import { RequestConfigSchema, ServerRequest, ServerRoute } from "alepha/server";
|
|
|
11
11
|
declare module "alepha/server" {
|
|
12
12
|
interface ServerRoute {
|
|
13
13
|
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
* Enable caching for this route.
|
|
15
|
+
* - If true: enables both store and etag
|
|
16
|
+
* - If object: fine-grained control over store, etag, and cache-control headers
|
|
17
|
+
*
|
|
18
|
+
* @default false
|
|
19
|
+
*/
|
|
20
20
|
cache?: ServerRouteCache;
|
|
21
21
|
}
|
|
22
22
|
interface ActionPrimitive<TConfig extends RequestConfigSchema> {
|
|
@@ -41,16 +41,16 @@ declare class ServerCacheProvider {
|
|
|
41
41
|
protected shouldUseEtag(cache?: ServerRouteCache): boolean;
|
|
42
42
|
protected createCacheKey(route: ServerRoute, config?: ServerRequest): string;
|
|
43
43
|
/**
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
44
|
+
* Collect a ReadableStream into a string and store it in the cache.
|
|
45
|
+
* This runs in the background while the original stream is sent to the client.
|
|
46
|
+
*
|
|
47
|
+
* @param stream - The stream to collect
|
|
48
|
+
* @param key - Cache key
|
|
49
|
+
* @param status - HTTP status code
|
|
50
|
+
* @param contentType - Content-Type header
|
|
51
|
+
* @param generateEtag - Whether to generate and return an ETag
|
|
52
|
+
* @returns The generated ETag hash, or undefined
|
|
53
|
+
*/
|
|
54
54
|
protected collectStreamForCache(stream: ReadableStream<Uint8Array>, key: string, status: number | undefined, contentType: string | undefined, generateEtag: boolean): Promise<string | undefined>;
|
|
55
55
|
}
|
|
56
56
|
type ServerRouteCache =
|
|
@@ -64,72 +64,75 @@ boolean
|
|
|
64
64
|
* Object configuration for fine-grained cache control.
|
|
65
65
|
*
|
|
66
66
|
* If empty, no caching will be applied.
|
|
67
|
-
*/
|
|
67
|
+
*/
|
|
68
|
+
| {
|
|
68
69
|
/**
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
70
|
+
* If true, enables storing cached responses. (in-memory, Redis, @see alepha/cache for other providers)
|
|
71
|
+
* If a DurationLike is provided, it will be used as the TTL for the cache.
|
|
72
|
+
* If CachePrimitiveOptions is provided, it will be used to configure the cache storage.
|
|
73
|
+
*
|
|
74
|
+
* @default false
|
|
75
|
+
*/
|
|
75
76
|
store?: true | DurationLike | CachePrimitiveOptions;
|
|
76
77
|
/**
|
|
77
|
-
|
|
78
|
-
|
|
78
|
+
* If true, enables ETag support for the cached responses.
|
|
79
|
+
*/
|
|
79
80
|
etag?: true;
|
|
80
81
|
/**
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
* - If true, sets Cache-Control to "public, max-age=300" (5 minutes).
|
|
83
|
+
* - If string, sets Cache-Control to the provided value directly.
|
|
84
|
+
* - If object, configures Cache-Control directives.
|
|
85
|
+
*/
|
|
85
86
|
control?: true
|
|
86
87
|
/**
|
|
87
|
-
|
|
88
|
-
|
|
88
|
+
* If string, sets Cache-Control to the provided value directly.
|
|
89
|
+
*/
|
|
90
|
+
| string
|
|
89
91
|
/**
|
|
90
|
-
|
|
91
|
-
|
|
92
|
+
* If object, configures Cache-Control directives.
|
|
93
|
+
*/
|
|
94
|
+
| {
|
|
92
95
|
/**
|
|
93
|
-
|
|
94
|
-
|
|
96
|
+
* Indicates that the response may be cached by any cache.
|
|
97
|
+
*/
|
|
95
98
|
public?: boolean;
|
|
96
99
|
/**
|
|
97
|
-
|
|
98
|
-
|
|
100
|
+
* Indicates that the response is intended for a single user and must not be stored by a shared cache.
|
|
101
|
+
*/
|
|
99
102
|
private?: boolean;
|
|
100
103
|
/**
|
|
101
|
-
|
|
102
|
-
|
|
104
|
+
* Forces caches to submit the request to the origin server for validation before releasing a cached copy.
|
|
105
|
+
*/
|
|
103
106
|
noCache?: boolean;
|
|
104
107
|
/**
|
|
105
|
-
|
|
106
|
-
|
|
108
|
+
* Instructs caches not to store the response.
|
|
109
|
+
*/
|
|
107
110
|
noStore?: boolean;
|
|
108
111
|
/**
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
112
|
+
* Maximum amount of time a resource is considered fresh.
|
|
113
|
+
* Can be specified as a number (seconds) or as a DurationLike object.
|
|
114
|
+
*
|
|
115
|
+
* @example 300 // 5 minutes in seconds
|
|
116
|
+
* @example { minutes: 5 } // 5 minutes
|
|
117
|
+
* @example { hours: 1 } // 1 hour
|
|
118
|
+
*/
|
|
116
119
|
maxAge?: number | DurationLike;
|
|
117
120
|
/**
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
+
* Overrides max-age for shared caches (e.g., CDNs).
|
|
122
|
+
* Can be specified as a number (seconds) or as a DurationLike object.
|
|
123
|
+
*/
|
|
121
124
|
sMaxAge?: number | DurationLike;
|
|
122
125
|
/**
|
|
123
|
-
|
|
124
|
-
|
|
126
|
+
* Indicates that once a resource becomes stale, caches must not use it without successful validation.
|
|
127
|
+
*/
|
|
125
128
|
mustRevalidate?: boolean;
|
|
126
129
|
/**
|
|
127
|
-
|
|
128
|
-
|
|
130
|
+
* Similar to must-revalidate, but only for shared caches.
|
|
131
|
+
*/
|
|
129
132
|
proxyRevalidate?: boolean;
|
|
130
133
|
/**
|
|
131
|
-
|
|
132
|
-
|
|
134
|
+
* Indicates that the response can be stored but must be revalidated before each use.
|
|
135
|
+
*/
|
|
133
136
|
immutable?: boolean;
|
|
134
137
|
};
|
|
135
138
|
};
|