alepha 0.14.4 → 0.15.1
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 +44 -102
- package/dist/api/audits/index.d.ts +331 -443
- package/dist/api/audits/index.d.ts.map +1 -1
- package/dist/api/audits/index.js +2 -2
- package/dist/api/audits/index.js.map +1 -1
- package/dist/api/files/index.d.ts +0 -113
- package/dist/api/files/index.d.ts.map +1 -1
- package/dist/api/files/index.js +2 -3
- package/dist/api/files/index.js.map +1 -1
- package/dist/api/jobs/index.d.ts +151 -262
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/notifications/index.browser.js +4 -4
- package/dist/api/notifications/index.browser.js.map +1 -1
- package/dist/api/notifications/index.d.ts +164 -276
- package/dist/api/notifications/index.d.ts.map +1 -1
- package/dist/api/notifications/index.js +4 -4
- package/dist/api/notifications/index.js.map +1 -1
- package/dist/api/parameters/index.d.ts +265 -377
- 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 +195 -301
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/users/index.js +203 -184
- package/dist/api/users/index.js.map +1 -1
- package/dist/api/verifications/index.d.ts.map +1 -1
- 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.map +1 -1
- package/dist/cache/core/index.d.ts.map +1 -1
- package/dist/cache/redis/index.d.ts.map +1 -1
- package/dist/cache/redis/index.js +2 -2
- package/dist/cache/redis/index.js.map +1 -1
- package/dist/cli/index.d.ts +5900 -165
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +1481 -639
- package/dist/cli/index.js.map +1 -1
- package/dist/command/index.d.ts +8 -4
- package/dist/command/index.d.ts.map +1 -1
- package/dist/command/index.js +29 -25
- package/dist/command/index.js.map +1 -1
- package/dist/core/index.browser.js +563 -54
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.d.ts +175 -8
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +564 -54
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js +563 -54
- package/dist/core/index.native.js.map +1 -1
- 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 +89 -42
- 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 +7969 -2
- package/dist/fake/index.d.ts.map +1 -1
- package/dist/fake/index.js +22 -22
- package/dist/fake/index.js.map +1 -1
- package/dist/file/index.d.ts +134 -1
- 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.map +1 -1
- package/dist/lock/redis/index.d.ts.map +1 -1
- package/dist/logger/index.d.ts +1 -2
- package/dist/logger/index.d.ts.map +1 -1
- package/dist/logger/index.js +1 -5
- package/dist/logger/index.js.map +1 -1
- package/dist/mcp/index.d.ts +19 -1
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +28 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/orm/chunk-DH6iiROE.js +38 -0
- package/dist/orm/index.browser.js +9 -9
- package/dist/orm/index.browser.js.map +1 -1
- package/dist/orm/index.bun.js +2821 -0
- package/dist/orm/index.bun.js.map +1 -0
- package/dist/orm/index.d.ts +318 -169
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +2086 -1776
- package/dist/orm/index.js.map +1 -1
- package/dist/queue/core/index.d.ts +4 -4
- 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 +13 -31
- 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.map +1 -1
- package/dist/router/index.d.ts.map +1 -1
- package/dist/scheduler/index.d.ts +83 -1
- package/dist/scheduler/index.d.ts.map +1 -1
- package/dist/scheduler/index.js +393 -1
- package/dist/scheduler/index.js.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 +598 -112
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/index.js +1808 -97
- package/dist/security/index.js.map +1 -1
- package/dist/server/auth/index.d.ts +1200 -175
- package/dist/server/auth/index.d.ts.map +1 -1
- package/dist/server/auth/index.js +1268 -37
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/cache/index.d.ts +6 -3
- 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.map +1 -1
- 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 +115 -13
- package/dist/server/core/index.d.ts.map +1 -1
- package/dist/server/core/index.js +321 -139
- package/dist/server/core/index.js.map +1 -1
- package/dist/server/cors/index.d.ts +0 -1
- 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.map +1 -1
- package/dist/server/links/index.browser.js +9 -1
- package/dist/server/links/index.browser.js.map +1 -1
- package/dist/server/links/index.d.ts +1 -2
- package/dist/server/links/index.d.ts.map +1 -1
- package/dist/server/links/index.js +14 -7
- package/dist/server/links/index.js.map +1 -1
- package/dist/server/metrics/index.d.ts +514 -1
- package/dist/server/metrics/index.d.ts.map +1 -1
- package/dist/server/metrics/index.js +4462 -4
- package/dist/server/metrics/index.js.map +1 -1
- package/dist/server/multipart/index.d.ts.map +1 -1
- package/dist/server/proxy/index.d.ts +0 -1
- package/dist/server/proxy/index.d.ts.map +1 -1
- package/dist/server/rate-limit/index.d.ts.map +1 -1
- package/dist/server/static/index.d.ts.map +1 -1
- package/dist/server/swagger/index.d.ts +1 -2
- 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 +3 -1
- package/dist/sms/index.d.ts.map +1 -1
- package/dist/sms/index.js +10 -10
- package/dist/sms/index.js.map +1 -1
- package/dist/thread/index.d.ts +0 -1
- package/dist/thread/index.d.ts.map +1 -1
- package/dist/thread/index.js +2 -2
- package/dist/thread/index.js.map +1 -1
- package/dist/topic/core/index.d.ts.map +1 -1
- package/dist/topic/redis/index.d.ts.map +1 -1
- package/dist/vite/index.d.ts +6315 -149
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +140 -469
- package/dist/vite/index.js.map +1 -1
- package/dist/websocket/index.browser.js +9 -9
- package/dist/websocket/index.browser.js.map +1 -1
- package/dist/websocket/index.d.ts +28 -28
- package/dist/websocket/index.d.ts.map +1 -1
- package/dist/websocket/index.js +9 -9
- package/dist/websocket/index.js.map +1 -1
- package/package.json +13 -18
- 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 +27 -18
- package/src/api/users/services/UserService.ts +7 -7
- package/src/batch/providers/BatchProvider.ts +1 -2
- package/src/cli/apps/AlephaCli.ts +2 -2
- package/src/cli/apps/AlephaPackageBuilderCli.ts +47 -20
- package/src/cli/assets/apiHelloControllerTs.ts +19 -0
- package/src/cli/assets/apiIndexTs.ts +16 -0
- package/src/cli/assets/biomeJson.ts +2 -1
- package/src/cli/assets/claudeMd.ts +308 -0
- package/src/cli/assets/dummySpecTs.ts +2 -1
- package/src/cli/assets/editorconfig.ts +2 -1
- package/src/cli/assets/mainBrowserTs.ts +4 -3
- package/src/cli/assets/mainCss.ts +24 -0
- package/src/cli/assets/mainServerTs.ts +24 -0
- package/src/cli/assets/tsconfigJson.ts +2 -1
- package/src/cli/assets/webAppRouterTs.ts +16 -0
- package/src/cli/assets/webHelloComponentTsx.ts +20 -0
- package/src/cli/assets/webIndexTs.ts +16 -0
- package/src/cli/atoms/appEntryOptions.ts +13 -0
- package/src/cli/atoms/buildOptions.ts +1 -1
- package/src/cli/atoms/changelogOptions.ts +1 -1
- package/src/cli/commands/build.ts +97 -61
- package/src/cli/commands/db.ts +21 -18
- package/src/cli/commands/deploy.ts +17 -5
- package/src/cli/commands/dev.ts +26 -47
- package/src/cli/commands/gen/env.ts +1 -1
- package/src/cli/commands/init.ts +79 -25
- package/src/cli/commands/lint.ts +9 -3
- 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/defineConfig.ts +9 -0
- package/src/cli/index.ts +2 -1
- package/src/cli/providers/AppEntryProvider.ts +131 -0
- package/src/cli/providers/ViteBuildProvider.ts +82 -0
- package/src/cli/providers/ViteDevServerProvider.ts +350 -0
- package/src/cli/providers/ViteTemplateProvider.ts +27 -0
- package/src/cli/services/AlephaCliUtils.ts +72 -602
- package/src/cli/services/PackageManagerUtils.ts +308 -0
- package/src/cli/services/ProjectScaffolder.ts +329 -0
- package/src/command/helpers/Runner.ts +15 -3
- package/src/core/Alepha.ts +2 -8
- 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/primitives/$module.ts +12 -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 +878 -0
- package/src/core/providers/KeylessJsonSchemaCodec.ts +789 -0
- package/src/core/providers/SchemaValidator.spec.ts +236 -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/logger/providers/PrettyFormatterProvider.ts +0 -9
- package/src/mcp/errors/McpError.ts +30 -0
- package/src/mcp/index.ts +3 -0
- package/src/mcp/transports/SseMcpTransport.ts +16 -6
- 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/DrizzleKitProvider.ts +3 -5
- 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 +19 -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/index.ts +1 -1
- package/src/server/core/providers/BunHttpServerProvider.ts +1 -1
- package/src/server/core/providers/NodeHttpServerProvider.spec.ts +125 -0
- package/src/server/core/providers/NodeHttpServerProvider.ts +92 -24
- 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 -24
- package/src/server/core/providers/ServerRouterProvider.ts +259 -115
- package/src/server/core/providers/ServerTimingProvider.ts +2 -2
- package/src/server/links/atoms/apiLinksAtom.ts +7 -0
- package/src/server/links/index.browser.ts +2 -0
- package/src/server/links/index.ts +3 -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/index.ts +3 -2
- package/src/vite/tasks/buildClient.ts +0 -1
- package/src/vite/tasks/buildServer.ts +80 -22
- package/src/vite/tasks/copyAssets.ts +5 -4
- package/src/vite/tasks/generateCloudflare.ts +7 -0
- package/src/vite/tasks/generateSitemap.ts +64 -23
- package/src/vite/tasks/index.ts +0 -2
- package/src/vite/tasks/prerenderPages.ts +49 -24
- 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/indexHtml.ts +0 -15
- package/src/cli/assets/mainTs.ts +0 -13
- package/src/cli/commands/format.ts +0 -17
- package/src/server/security/index.browser.ts +0 -10
- package/src/server/security/index.ts +0 -94
- package/src/vite/helpers/boot.ts +0 -106
- package/src/vite/plugins/viteAlephaDev.ts +0 -177
- package/src/vite/tasks/devServer.ts +0 -69
- package/src/vite/tasks/runAlepha.ts +0 -270
- /package/src/{server/security → security}/primitives/$basicAuth.ts +0 -0
- /package/src/{server/security → security}/providers/ServerBasicAuthProvider.ts +0 -0
package/dist/security/index.js
CHANGED
|
@@ -1,32 +1,147 @@
|
|
|
1
1
|
import { $context, $env, $hook, $inject, $module, Alepha, AlephaError, AppNotStartedError, ContainerLockedError, KIND, Primitive, createPrimitive, t } from "alepha";
|
|
2
|
-
import { $
|
|
2
|
+
import { $action, AlephaServer, ForbiddenError, HttpError, ServerRouterProvider, UnauthorizedError } from "alepha/server";
|
|
3
3
|
import { createSecretKey, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
|
|
4
|
+
import { $logger } from "alepha/logger";
|
|
4
5
|
import { DateTimeProvider } from "alepha/datetime";
|
|
5
|
-
import { SignJWT, createLocalJWKSet, createRemoteJWKSet, jwtVerify } from "jose";
|
|
6
|
-
import { JWTClaimValidationFailed, JWTExpired } from "jose/errors";
|
|
7
6
|
import { promisify } from "node:util";
|
|
8
|
-
import { UnauthorizedError } from "alepha/server";
|
|
9
7
|
|
|
10
|
-
//#region ../../src/security/
|
|
11
|
-
var
|
|
12
|
-
|
|
13
|
-
|
|
8
|
+
//#region ../../src/security/providers/ServerBasicAuthProvider.ts
|
|
9
|
+
var ServerBasicAuthProvider = class {
|
|
10
|
+
alepha = $inject(Alepha);
|
|
11
|
+
log = $logger();
|
|
12
|
+
routerProvider = $inject(ServerRouterProvider);
|
|
13
|
+
realm = "Secure Area";
|
|
14
|
+
/**
|
|
15
|
+
* Registered basic auth primitives with their configurations
|
|
16
|
+
*/
|
|
17
|
+
registeredAuths = [];
|
|
18
|
+
/**
|
|
19
|
+
* Register a basic auth configuration (called by primitives)
|
|
20
|
+
*/
|
|
21
|
+
registerAuth(config) {
|
|
22
|
+
this.registeredAuths.push(config);
|
|
23
|
+
}
|
|
24
|
+
onStart = $hook({
|
|
25
|
+
on: "start",
|
|
26
|
+
handler: async () => {
|
|
27
|
+
for (const auth of this.registeredAuths) if (auth.paths) for (const pattern of auth.paths) {
|
|
28
|
+
const matchedRoutes = this.routerProvider.getRoutes(pattern);
|
|
29
|
+
for (const route of matchedRoutes) route.secure = { basic: {
|
|
30
|
+
username: auth.username,
|
|
31
|
+
password: auth.password
|
|
32
|
+
} };
|
|
33
|
+
}
|
|
34
|
+
if (this.registeredAuths.length > 0) this.log.info(`Initialized with ${this.registeredAuths.length} registered basic-auth configurations.`);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
/**
|
|
38
|
+
* Hook into server:onRequest to check basic auth
|
|
39
|
+
*/
|
|
40
|
+
onRequest = $hook({
|
|
41
|
+
on: "server:onRequest",
|
|
42
|
+
handler: async ({ route, request }) => {
|
|
43
|
+
const routeAuth = route.secure;
|
|
44
|
+
if (typeof routeAuth === "object" && "basic" in routeAuth && routeAuth.basic) this.checkAuth(request, routeAuth.basic);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* Hook into action:onRequest to check basic auth for actions
|
|
49
|
+
*/
|
|
50
|
+
onActionRequest = $hook({
|
|
51
|
+
on: "action:onRequest",
|
|
52
|
+
handler: async ({ action, request }) => {
|
|
53
|
+
const routeAuth = action.route.secure;
|
|
54
|
+
if (isBasicAuth(routeAuth)) this.checkAuth(request, routeAuth.basic);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Check basic authentication
|
|
59
|
+
*/
|
|
60
|
+
checkAuth(request, options) {
|
|
61
|
+
const authHeader = request.headers?.authorization;
|
|
62
|
+
if (!authHeader || !authHeader.startsWith("Basic ")) {
|
|
63
|
+
this.sendAuthRequired(request);
|
|
64
|
+
throw new HttpError({
|
|
65
|
+
status: 401,
|
|
66
|
+
message: "Authentication required"
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const base64Credentials = authHeader.slice(6);
|
|
70
|
+
const credentials = Buffer.from(base64Credentials, "base64").toString("utf-8");
|
|
71
|
+
const colonIndex = credentials.indexOf(":");
|
|
72
|
+
const username = colonIndex !== -1 ? credentials.slice(0, colonIndex) : credentials;
|
|
73
|
+
const password = colonIndex !== -1 ? credentials.slice(colonIndex + 1) : "";
|
|
74
|
+
if (!this.timingSafeCredentialCheck(username, password, options.username, options.password)) {
|
|
75
|
+
this.sendAuthRequired(request);
|
|
76
|
+
this.log.warn(`Failed basic auth attempt for user`, { username });
|
|
77
|
+
throw new HttpError({
|
|
78
|
+
status: 401,
|
|
79
|
+
message: "Invalid credentials"
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Performs a timing-safe comparison of credentials to prevent timing attacks.
|
|
85
|
+
* Always compares both username and password to avoid leaking which one is wrong.
|
|
86
|
+
*/
|
|
87
|
+
timingSafeCredentialCheck(inputUsername, inputPassword, expectedUsername, expectedPassword) {
|
|
88
|
+
const inputUserBuf = Buffer.from(inputUsername, "utf-8");
|
|
89
|
+
const expectedUserBuf = Buffer.from(expectedUsername, "utf-8");
|
|
90
|
+
const inputPassBuf = Buffer.from(inputPassword, "utf-8");
|
|
91
|
+
const expectedPassBuf = Buffer.from(expectedPassword, "utf-8");
|
|
92
|
+
return (this.safeCompare(inputUserBuf, expectedUserBuf) & this.safeCompare(inputPassBuf, expectedPassBuf)) === 1;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Compares two buffers in constant time, handling different lengths safely.
|
|
96
|
+
* Returns 1 if equal, 0 if not equal.
|
|
97
|
+
*/
|
|
98
|
+
safeCompare(input, expected) {
|
|
99
|
+
if (input.length !== expected.length) {
|
|
100
|
+
timingSafeEqual(input, input);
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
return timingSafeEqual(input, expected) ? 1 : 0;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Send WWW-Authenticate header
|
|
107
|
+
*/
|
|
108
|
+
sendAuthRequired(request) {
|
|
109
|
+
request.reply.setHeader("WWW-Authenticate", `Basic realm="${this.realm}"`);
|
|
14
110
|
}
|
|
15
111
|
};
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
//#region ../../src/security/errors/InvalidTokenError.ts
|
|
19
|
-
var InvalidTokenError = class extends Error {
|
|
20
|
-
status = 401;
|
|
112
|
+
const isBasicAuth = (value) => {
|
|
113
|
+
return typeof value === "object" && !!value && "basic" in value && !!value.basic;
|
|
21
114
|
};
|
|
22
115
|
|
|
23
116
|
//#endregion
|
|
24
|
-
//#region ../../src/security/
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
117
|
+
//#region ../../src/security/primitives/$basicAuth.ts
|
|
118
|
+
/**
|
|
119
|
+
* Declares HTTP Basic Authentication for server routes.
|
|
120
|
+
* This primitive provides methods to protect routes with username/password authentication.
|
|
121
|
+
*/
|
|
122
|
+
const $basicAuth = (options) => {
|
|
123
|
+
return createPrimitive(BasicAuthPrimitive, options);
|
|
124
|
+
};
|
|
125
|
+
var BasicAuthPrimitive = class extends Primitive {
|
|
126
|
+
serverBasicAuthProvider = $inject(ServerBasicAuthProvider);
|
|
127
|
+
get name() {
|
|
128
|
+
return this.options.name ?? `${this.config.propertyKey}`;
|
|
129
|
+
}
|
|
130
|
+
onInit() {
|
|
131
|
+
this.serverBasicAuthProvider.registerAuth(this.options);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Checks basic auth for the given request using this primitive's configuration.
|
|
135
|
+
*/
|
|
136
|
+
check(request, options) {
|
|
137
|
+
const mergedOptions = {
|
|
138
|
+
...this.options,
|
|
139
|
+
...options
|
|
140
|
+
};
|
|
141
|
+
this.serverBasicAuthProvider.checkAuth(request, mergedOptions);
|
|
28
142
|
}
|
|
29
143
|
};
|
|
144
|
+
$basicAuth[KIND] = BasicAuthPrimitive;
|
|
30
145
|
|
|
31
146
|
//#endregion
|
|
32
147
|
//#region ../../src/security/errors/SecurityError.ts
|
|
@@ -35,6 +150,1419 @@ var SecurityError = class extends Error {
|
|
|
35
150
|
status = 403;
|
|
36
151
|
};
|
|
37
152
|
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/buffer_utils.js
|
|
155
|
+
const encoder = new TextEncoder();
|
|
156
|
+
const decoder = new TextDecoder();
|
|
157
|
+
const MAX_INT32 = 2 ** 32;
|
|
158
|
+
function concat(...buffers) {
|
|
159
|
+
const size = buffers.reduce((acc, { length }) => acc + length, 0);
|
|
160
|
+
const buf = new Uint8Array(size);
|
|
161
|
+
let i = 0;
|
|
162
|
+
for (const buffer of buffers) {
|
|
163
|
+
buf.set(buffer, i);
|
|
164
|
+
i += buffer.length;
|
|
165
|
+
}
|
|
166
|
+
return buf;
|
|
167
|
+
}
|
|
168
|
+
function encode$1(string) {
|
|
169
|
+
const bytes = new Uint8Array(string.length);
|
|
170
|
+
for (let i = 0; i < string.length; i++) {
|
|
171
|
+
const code = string.charCodeAt(i);
|
|
172
|
+
if (code > 127) throw new TypeError("non-ASCII string encountered in encode()");
|
|
173
|
+
bytes[i] = code;
|
|
174
|
+
}
|
|
175
|
+
return bytes;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/base64.js
|
|
180
|
+
function encodeBase64(input) {
|
|
181
|
+
if (Uint8Array.prototype.toBase64) return input.toBase64();
|
|
182
|
+
const CHUNK_SIZE = 32768;
|
|
183
|
+
const arr = [];
|
|
184
|
+
for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
185
|
+
return btoa(arr.join(""));
|
|
186
|
+
}
|
|
187
|
+
function decodeBase64(encoded) {
|
|
188
|
+
if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
|
|
189
|
+
const binary = atob(encoded);
|
|
190
|
+
const bytes = new Uint8Array(binary.length);
|
|
191
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
192
|
+
return bytes;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
//#endregion
|
|
196
|
+
//#region ../../../../node_modules/jose/dist/webapi/util/base64url.js
|
|
197
|
+
function decode(input) {
|
|
198
|
+
if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
|
|
199
|
+
let encoded = input;
|
|
200
|
+
if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
|
|
201
|
+
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
202
|
+
try {
|
|
203
|
+
return decodeBase64(encoded);
|
|
204
|
+
} catch {
|
|
205
|
+
throw new TypeError("The input to be decoded is not correctly encoded.");
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function encode(input) {
|
|
209
|
+
let unencoded = input;
|
|
210
|
+
if (typeof unencoded === "string") unencoded = encoder.encode(unencoded);
|
|
211
|
+
if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
|
|
212
|
+
alphabet: "base64url",
|
|
213
|
+
omitPadding: true
|
|
214
|
+
});
|
|
215
|
+
return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region ../../../../node_modules/jose/dist/webapi/util/errors.js
|
|
220
|
+
var JOSEError = class extends Error {
|
|
221
|
+
static code = "ERR_JOSE_GENERIC";
|
|
222
|
+
code = "ERR_JOSE_GENERIC";
|
|
223
|
+
constructor(message, options) {
|
|
224
|
+
super(message, options);
|
|
225
|
+
this.name = this.constructor.name;
|
|
226
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
var JWTClaimValidationFailed = class extends JOSEError {
|
|
230
|
+
static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
231
|
+
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
232
|
+
claim;
|
|
233
|
+
reason;
|
|
234
|
+
payload;
|
|
235
|
+
constructor(message, payload, claim = "unspecified", reason = "unspecified") {
|
|
236
|
+
super(message, { cause: {
|
|
237
|
+
claim,
|
|
238
|
+
reason,
|
|
239
|
+
payload
|
|
240
|
+
} });
|
|
241
|
+
this.claim = claim;
|
|
242
|
+
this.reason = reason;
|
|
243
|
+
this.payload = payload;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
var JWTExpired = class extends JOSEError {
|
|
247
|
+
static code = "ERR_JWT_EXPIRED";
|
|
248
|
+
code = "ERR_JWT_EXPIRED";
|
|
249
|
+
claim;
|
|
250
|
+
reason;
|
|
251
|
+
payload;
|
|
252
|
+
constructor(message, payload, claim = "unspecified", reason = "unspecified") {
|
|
253
|
+
super(message, { cause: {
|
|
254
|
+
claim,
|
|
255
|
+
reason,
|
|
256
|
+
payload
|
|
257
|
+
} });
|
|
258
|
+
this.claim = claim;
|
|
259
|
+
this.reason = reason;
|
|
260
|
+
this.payload = payload;
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
var JOSEAlgNotAllowed = class extends JOSEError {
|
|
264
|
+
static code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
265
|
+
code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
266
|
+
};
|
|
267
|
+
var JOSENotSupported = class extends JOSEError {
|
|
268
|
+
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
269
|
+
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
270
|
+
};
|
|
271
|
+
var JWSInvalid = class extends JOSEError {
|
|
272
|
+
static code = "ERR_JWS_INVALID";
|
|
273
|
+
code = "ERR_JWS_INVALID";
|
|
274
|
+
};
|
|
275
|
+
var JWTInvalid = class extends JOSEError {
|
|
276
|
+
static code = "ERR_JWT_INVALID";
|
|
277
|
+
code = "ERR_JWT_INVALID";
|
|
278
|
+
};
|
|
279
|
+
var JWKSInvalid = class extends JOSEError {
|
|
280
|
+
static code = "ERR_JWKS_INVALID";
|
|
281
|
+
code = "ERR_JWKS_INVALID";
|
|
282
|
+
};
|
|
283
|
+
var JWKSNoMatchingKey = class extends JOSEError {
|
|
284
|
+
static code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
285
|
+
code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
286
|
+
constructor(message = "no applicable key found in the JSON Web Key Set", options) {
|
|
287
|
+
super(message, options);
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
var JWKSMultipleMatchingKeys = class extends JOSEError {
|
|
291
|
+
[Symbol.asyncIterator];
|
|
292
|
+
static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
293
|
+
code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
294
|
+
constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
|
|
295
|
+
super(message, options);
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
var JWKSTimeout = class extends JOSEError {
|
|
299
|
+
static code = "ERR_JWKS_TIMEOUT";
|
|
300
|
+
code = "ERR_JWKS_TIMEOUT";
|
|
301
|
+
constructor(message = "request timed out", options) {
|
|
302
|
+
super(message, options);
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
var JWSSignatureVerificationFailed = class extends JOSEError {
|
|
306
|
+
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
307
|
+
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
308
|
+
constructor(message = "signature verification failed", options) {
|
|
309
|
+
super(message, options);
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
//#endregion
|
|
314
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/crypto_key.js
|
|
315
|
+
const unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
316
|
+
const isAlgorithm = (algorithm, name) => algorithm.name === name;
|
|
317
|
+
function getHashLength(hash) {
|
|
318
|
+
return parseInt(hash.name.slice(4), 10);
|
|
319
|
+
}
|
|
320
|
+
function getNamedCurve(alg) {
|
|
321
|
+
switch (alg) {
|
|
322
|
+
case "ES256": return "P-256";
|
|
323
|
+
case "ES384": return "P-384";
|
|
324
|
+
case "ES512": return "P-521";
|
|
325
|
+
default: throw new Error("unreachable");
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function checkUsage(key, usage) {
|
|
329
|
+
if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
330
|
+
}
|
|
331
|
+
function checkSigCryptoKey(key, alg, usage) {
|
|
332
|
+
switch (alg) {
|
|
333
|
+
case "HS256":
|
|
334
|
+
case "HS384":
|
|
335
|
+
case "HS512": {
|
|
336
|
+
if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
|
|
337
|
+
const expected = parseInt(alg.slice(2), 10);
|
|
338
|
+
if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
339
|
+
break;
|
|
340
|
+
}
|
|
341
|
+
case "RS256":
|
|
342
|
+
case "RS384":
|
|
343
|
+
case "RS512": {
|
|
344
|
+
if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
|
|
345
|
+
const expected = parseInt(alg.slice(2), 10);
|
|
346
|
+
if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
347
|
+
break;
|
|
348
|
+
}
|
|
349
|
+
case "PS256":
|
|
350
|
+
case "PS384":
|
|
351
|
+
case "PS512": {
|
|
352
|
+
if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
|
|
353
|
+
const expected = parseInt(alg.slice(2), 10);
|
|
354
|
+
if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
case "Ed25519":
|
|
358
|
+
case "EdDSA":
|
|
359
|
+
if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
|
|
360
|
+
break;
|
|
361
|
+
case "ML-DSA-44":
|
|
362
|
+
case "ML-DSA-65":
|
|
363
|
+
case "ML-DSA-87":
|
|
364
|
+
if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
|
|
365
|
+
break;
|
|
366
|
+
case "ES256":
|
|
367
|
+
case "ES384":
|
|
368
|
+
case "ES512": {
|
|
369
|
+
if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
|
|
370
|
+
const expected = getNamedCurve(alg);
|
|
371
|
+
if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
default: throw new TypeError("CryptoKey does not support this operation");
|
|
375
|
+
}
|
|
376
|
+
checkUsage(key, usage);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
//#endregion
|
|
380
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/invalid_key_input.js
|
|
381
|
+
function message(msg, actual, ...types) {
|
|
382
|
+
types = types.filter(Boolean);
|
|
383
|
+
if (types.length > 2) {
|
|
384
|
+
const last = types.pop();
|
|
385
|
+
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
386
|
+
} else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
|
|
387
|
+
else msg += `of type ${types[0]}.`;
|
|
388
|
+
if (actual == null) msg += ` Received ${actual}`;
|
|
389
|
+
else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
|
|
390
|
+
else if (typeof actual === "object" && actual != null) {
|
|
391
|
+
if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
|
|
392
|
+
}
|
|
393
|
+
return msg;
|
|
394
|
+
}
|
|
395
|
+
const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
|
|
396
|
+
const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
|
|
397
|
+
|
|
398
|
+
//#endregion
|
|
399
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/is_key_like.js
|
|
400
|
+
const isCryptoKey = (key) => {
|
|
401
|
+
if (key?.[Symbol.toStringTag] === "CryptoKey") return true;
|
|
402
|
+
try {
|
|
403
|
+
return key instanceof CryptoKey;
|
|
404
|
+
} catch {
|
|
405
|
+
return false;
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
409
|
+
const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
410
|
+
|
|
411
|
+
//#endregion
|
|
412
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/is_disjoint.js
|
|
413
|
+
function isDisjoint(...headers) {
|
|
414
|
+
const sources = headers.filter(Boolean);
|
|
415
|
+
if (sources.length === 0 || sources.length === 1) return true;
|
|
416
|
+
let acc;
|
|
417
|
+
for (const header of sources) {
|
|
418
|
+
const parameters = Object.keys(header);
|
|
419
|
+
if (!acc || acc.size === 0) {
|
|
420
|
+
acc = new Set(parameters);
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
for (const parameter of parameters) {
|
|
424
|
+
if (acc.has(parameter)) return false;
|
|
425
|
+
acc.add(parameter);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return true;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
//#endregion
|
|
432
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/is_object.js
|
|
433
|
+
const isObjectLike = (value) => typeof value === "object" && value !== null;
|
|
434
|
+
function isObject(input) {
|
|
435
|
+
if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
|
|
436
|
+
if (Object.getPrototypeOf(input) === null) return true;
|
|
437
|
+
let proto = input;
|
|
438
|
+
while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
|
|
439
|
+
return Object.getPrototypeOf(input) === proto;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
//#endregion
|
|
443
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/check_key_length.js
|
|
444
|
+
function checkKeyLength(alg, key) {
|
|
445
|
+
if (alg.startsWith("RS") || alg.startsWith("PS")) {
|
|
446
|
+
const { modulusLength } = key.algorithm;
|
|
447
|
+
if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
//#endregion
|
|
452
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
|
|
453
|
+
function subtleMapping(jwk) {
|
|
454
|
+
let algorithm;
|
|
455
|
+
let keyUsages;
|
|
456
|
+
switch (jwk.kty) {
|
|
457
|
+
case "AKP":
|
|
458
|
+
switch (jwk.alg) {
|
|
459
|
+
case "ML-DSA-44":
|
|
460
|
+
case "ML-DSA-65":
|
|
461
|
+
case "ML-DSA-87":
|
|
462
|
+
algorithm = { name: jwk.alg };
|
|
463
|
+
keyUsages = jwk.priv ? ["sign"] : ["verify"];
|
|
464
|
+
break;
|
|
465
|
+
default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
|
|
466
|
+
}
|
|
467
|
+
break;
|
|
468
|
+
case "RSA":
|
|
469
|
+
switch (jwk.alg) {
|
|
470
|
+
case "PS256":
|
|
471
|
+
case "PS384":
|
|
472
|
+
case "PS512":
|
|
473
|
+
algorithm = {
|
|
474
|
+
name: "RSA-PSS",
|
|
475
|
+
hash: `SHA-${jwk.alg.slice(-3)}`
|
|
476
|
+
};
|
|
477
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
478
|
+
break;
|
|
479
|
+
case "RS256":
|
|
480
|
+
case "RS384":
|
|
481
|
+
case "RS512":
|
|
482
|
+
algorithm = {
|
|
483
|
+
name: "RSASSA-PKCS1-v1_5",
|
|
484
|
+
hash: `SHA-${jwk.alg.slice(-3)}`
|
|
485
|
+
};
|
|
486
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
487
|
+
break;
|
|
488
|
+
case "RSA-OAEP":
|
|
489
|
+
case "RSA-OAEP-256":
|
|
490
|
+
case "RSA-OAEP-384":
|
|
491
|
+
case "RSA-OAEP-512":
|
|
492
|
+
algorithm = {
|
|
493
|
+
name: "RSA-OAEP",
|
|
494
|
+
hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
|
|
495
|
+
};
|
|
496
|
+
keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
|
|
497
|
+
break;
|
|
498
|
+
default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
|
|
499
|
+
}
|
|
500
|
+
break;
|
|
501
|
+
case "EC":
|
|
502
|
+
switch (jwk.alg) {
|
|
503
|
+
case "ES256":
|
|
504
|
+
algorithm = {
|
|
505
|
+
name: "ECDSA",
|
|
506
|
+
namedCurve: "P-256"
|
|
507
|
+
};
|
|
508
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
509
|
+
break;
|
|
510
|
+
case "ES384":
|
|
511
|
+
algorithm = {
|
|
512
|
+
name: "ECDSA",
|
|
513
|
+
namedCurve: "P-384"
|
|
514
|
+
};
|
|
515
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
516
|
+
break;
|
|
517
|
+
case "ES512":
|
|
518
|
+
algorithm = {
|
|
519
|
+
name: "ECDSA",
|
|
520
|
+
namedCurve: "P-521"
|
|
521
|
+
};
|
|
522
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
523
|
+
break;
|
|
524
|
+
case "ECDH-ES":
|
|
525
|
+
case "ECDH-ES+A128KW":
|
|
526
|
+
case "ECDH-ES+A192KW":
|
|
527
|
+
case "ECDH-ES+A256KW":
|
|
528
|
+
algorithm = {
|
|
529
|
+
name: "ECDH",
|
|
530
|
+
namedCurve: jwk.crv
|
|
531
|
+
};
|
|
532
|
+
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
533
|
+
break;
|
|
534
|
+
default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
|
|
535
|
+
}
|
|
536
|
+
break;
|
|
537
|
+
case "OKP":
|
|
538
|
+
switch (jwk.alg) {
|
|
539
|
+
case "Ed25519":
|
|
540
|
+
case "EdDSA":
|
|
541
|
+
algorithm = { name: "Ed25519" };
|
|
542
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
543
|
+
break;
|
|
544
|
+
case "ECDH-ES":
|
|
545
|
+
case "ECDH-ES+A128KW":
|
|
546
|
+
case "ECDH-ES+A192KW":
|
|
547
|
+
case "ECDH-ES+A256KW":
|
|
548
|
+
algorithm = { name: jwk.crv };
|
|
549
|
+
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
550
|
+
break;
|
|
551
|
+
default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
|
|
552
|
+
}
|
|
553
|
+
break;
|
|
554
|
+
default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
|
|
555
|
+
}
|
|
556
|
+
return {
|
|
557
|
+
algorithm,
|
|
558
|
+
keyUsages
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
async function jwkToKey(jwk) {
|
|
562
|
+
if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
|
|
563
|
+
const { algorithm, keyUsages } = subtleMapping(jwk);
|
|
564
|
+
const keyData = { ...jwk };
|
|
565
|
+
if (keyData.kty !== "AKP") delete keyData.alg;
|
|
566
|
+
delete keyData.use;
|
|
567
|
+
return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
//#endregion
|
|
571
|
+
//#region ../../../../node_modules/jose/dist/webapi/key/import.js
|
|
572
|
+
async function importJWK(jwk, alg, options) {
|
|
573
|
+
if (!isObject(jwk)) throw new TypeError("JWK must be an object");
|
|
574
|
+
let ext;
|
|
575
|
+
alg ??= jwk.alg;
|
|
576
|
+
ext ??= options?.extractable ?? jwk.ext;
|
|
577
|
+
switch (jwk.kty) {
|
|
578
|
+
case "oct":
|
|
579
|
+
if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
|
|
580
|
+
return decode(jwk.k);
|
|
581
|
+
case "RSA":
|
|
582
|
+
if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
|
|
583
|
+
return jwkToKey({
|
|
584
|
+
...jwk,
|
|
585
|
+
alg,
|
|
586
|
+
ext
|
|
587
|
+
});
|
|
588
|
+
case "AKP":
|
|
589
|
+
if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
|
|
590
|
+
if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
|
|
591
|
+
return jwkToKey({
|
|
592
|
+
...jwk,
|
|
593
|
+
ext
|
|
594
|
+
});
|
|
595
|
+
case "EC":
|
|
596
|
+
case "OKP": return jwkToKey({
|
|
597
|
+
...jwk,
|
|
598
|
+
alg,
|
|
599
|
+
ext
|
|
600
|
+
});
|
|
601
|
+
default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/validate_crit.js
|
|
607
|
+
function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
|
|
608
|
+
if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
|
|
609
|
+
if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set();
|
|
610
|
+
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
|
|
611
|
+
let recognized;
|
|
612
|
+
if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
|
|
613
|
+
else recognized = recognizedDefault;
|
|
614
|
+
for (const parameter of protectedHeader.crit) {
|
|
615
|
+
if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
616
|
+
if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
617
|
+
if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
618
|
+
}
|
|
619
|
+
return new Set(protectedHeader.crit);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
//#endregion
|
|
623
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
|
|
624
|
+
function validateAlgorithms(option, algorithms) {
|
|
625
|
+
if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
|
|
626
|
+
if (!algorithms) return;
|
|
627
|
+
return new Set(algorithms);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/is_jwk.js
|
|
632
|
+
const isJWK = (key) => isObject(key) && typeof key.kty === "string";
|
|
633
|
+
const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
|
|
634
|
+
const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
|
|
635
|
+
const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
|
|
636
|
+
|
|
637
|
+
//#endregion
|
|
638
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/normalize_key.js
|
|
639
|
+
let cache;
|
|
640
|
+
const handleJWK = async (key, jwk, alg, freeze = false) => {
|
|
641
|
+
cache ||= /* @__PURE__ */ new WeakMap();
|
|
642
|
+
let cached = cache.get(key);
|
|
643
|
+
if (cached?.[alg]) return cached[alg];
|
|
644
|
+
const cryptoKey = await jwkToKey({
|
|
645
|
+
...jwk,
|
|
646
|
+
alg
|
|
647
|
+
});
|
|
648
|
+
if (freeze) Object.freeze(key);
|
|
649
|
+
if (!cached) cache.set(key, { [alg]: cryptoKey });
|
|
650
|
+
else cached[alg] = cryptoKey;
|
|
651
|
+
return cryptoKey;
|
|
652
|
+
};
|
|
653
|
+
const handleKeyObject = (keyObject, alg) => {
|
|
654
|
+
cache ||= /* @__PURE__ */ new WeakMap();
|
|
655
|
+
let cached = cache.get(keyObject);
|
|
656
|
+
if (cached?.[alg]) return cached[alg];
|
|
657
|
+
const isPublic = keyObject.type === "public";
|
|
658
|
+
const extractable = isPublic ? true : false;
|
|
659
|
+
let cryptoKey;
|
|
660
|
+
if (keyObject.asymmetricKeyType === "x25519") {
|
|
661
|
+
switch (alg) {
|
|
662
|
+
case "ECDH-ES":
|
|
663
|
+
case "ECDH-ES+A128KW":
|
|
664
|
+
case "ECDH-ES+A192KW":
|
|
665
|
+
case "ECDH-ES+A256KW": break;
|
|
666
|
+
default: throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
667
|
+
}
|
|
668
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
|
|
669
|
+
}
|
|
670
|
+
if (keyObject.asymmetricKeyType === "ed25519") {
|
|
671
|
+
if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
672
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
|
|
673
|
+
}
|
|
674
|
+
switch (keyObject.asymmetricKeyType) {
|
|
675
|
+
case "ml-dsa-44":
|
|
676
|
+
case "ml-dsa-65":
|
|
677
|
+
case "ml-dsa-87":
|
|
678
|
+
if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
679
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
|
|
680
|
+
}
|
|
681
|
+
if (keyObject.asymmetricKeyType === "rsa") {
|
|
682
|
+
let hash;
|
|
683
|
+
switch (alg) {
|
|
684
|
+
case "RSA-OAEP":
|
|
685
|
+
hash = "SHA-1";
|
|
686
|
+
break;
|
|
687
|
+
case "RS256":
|
|
688
|
+
case "PS256":
|
|
689
|
+
case "RSA-OAEP-256":
|
|
690
|
+
hash = "SHA-256";
|
|
691
|
+
break;
|
|
692
|
+
case "RS384":
|
|
693
|
+
case "PS384":
|
|
694
|
+
case "RSA-OAEP-384":
|
|
695
|
+
hash = "SHA-384";
|
|
696
|
+
break;
|
|
697
|
+
case "RS512":
|
|
698
|
+
case "PS512":
|
|
699
|
+
case "RSA-OAEP-512":
|
|
700
|
+
hash = "SHA-512";
|
|
701
|
+
break;
|
|
702
|
+
default: throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
703
|
+
}
|
|
704
|
+
if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
|
|
705
|
+
name: "RSA-OAEP",
|
|
706
|
+
hash
|
|
707
|
+
}, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
|
|
708
|
+
cryptoKey = keyObject.toCryptoKey({
|
|
709
|
+
name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
|
|
710
|
+
hash
|
|
711
|
+
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
712
|
+
}
|
|
713
|
+
if (keyObject.asymmetricKeyType === "ec") {
|
|
714
|
+
const namedCurve = new Map([
|
|
715
|
+
["prime256v1", "P-256"],
|
|
716
|
+
["secp384r1", "P-384"],
|
|
717
|
+
["secp521r1", "P-521"]
|
|
718
|
+
]).get(keyObject.asymmetricKeyDetails?.namedCurve);
|
|
719
|
+
if (!namedCurve) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
720
|
+
if (alg === "ES256" && namedCurve === "P-256") cryptoKey = keyObject.toCryptoKey({
|
|
721
|
+
name: "ECDSA",
|
|
722
|
+
namedCurve
|
|
723
|
+
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
724
|
+
if (alg === "ES384" && namedCurve === "P-384") cryptoKey = keyObject.toCryptoKey({
|
|
725
|
+
name: "ECDSA",
|
|
726
|
+
namedCurve
|
|
727
|
+
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
728
|
+
if (alg === "ES512" && namedCurve === "P-521") cryptoKey = keyObject.toCryptoKey({
|
|
729
|
+
name: "ECDSA",
|
|
730
|
+
namedCurve
|
|
731
|
+
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
732
|
+
if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
|
|
733
|
+
name: "ECDH",
|
|
734
|
+
namedCurve
|
|
735
|
+
}, extractable, isPublic ? [] : ["deriveBits"]);
|
|
736
|
+
}
|
|
737
|
+
if (!cryptoKey) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
738
|
+
if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
|
|
739
|
+
else cached[alg] = cryptoKey;
|
|
740
|
+
return cryptoKey;
|
|
741
|
+
};
|
|
742
|
+
async function normalizeKey(key, alg) {
|
|
743
|
+
if (key instanceof Uint8Array) return key;
|
|
744
|
+
if (isCryptoKey(key)) return key;
|
|
745
|
+
if (isKeyObject(key)) {
|
|
746
|
+
if (key.type === "secret") return key.export();
|
|
747
|
+
if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
|
|
748
|
+
return handleKeyObject(key, alg);
|
|
749
|
+
} catch (err) {
|
|
750
|
+
if (err instanceof TypeError) throw err;
|
|
751
|
+
}
|
|
752
|
+
return handleJWK(key, key.export({ format: "jwk" }), alg);
|
|
753
|
+
}
|
|
754
|
+
if (isJWK(key)) {
|
|
755
|
+
if (key.k) return decode(key.k);
|
|
756
|
+
return handleJWK(key, key, alg, true);
|
|
757
|
+
}
|
|
758
|
+
throw new Error("unreachable");
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
//#endregion
|
|
762
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/check_key_type.js
|
|
763
|
+
const tag = (key) => key?.[Symbol.toStringTag];
|
|
764
|
+
const jwkMatchesOp = (alg, key, usage) => {
|
|
765
|
+
if (key.use !== void 0) {
|
|
766
|
+
let expected;
|
|
767
|
+
switch (usage) {
|
|
768
|
+
case "sign":
|
|
769
|
+
case "verify":
|
|
770
|
+
expected = "sig";
|
|
771
|
+
break;
|
|
772
|
+
case "encrypt":
|
|
773
|
+
case "decrypt":
|
|
774
|
+
expected = "enc";
|
|
775
|
+
break;
|
|
776
|
+
}
|
|
777
|
+
if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
778
|
+
}
|
|
779
|
+
if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
780
|
+
if (Array.isArray(key.key_ops)) {
|
|
781
|
+
let expectedKeyOp;
|
|
782
|
+
switch (true) {
|
|
783
|
+
case usage === "sign" || usage === "verify":
|
|
784
|
+
case alg === "dir":
|
|
785
|
+
case alg.includes("CBC-HS"):
|
|
786
|
+
expectedKeyOp = usage;
|
|
787
|
+
break;
|
|
788
|
+
case alg.startsWith("PBES2"):
|
|
789
|
+
expectedKeyOp = "deriveBits";
|
|
790
|
+
break;
|
|
791
|
+
case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
|
|
792
|
+
if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
|
|
793
|
+
else expectedKeyOp = usage;
|
|
794
|
+
break;
|
|
795
|
+
case usage === "encrypt" && alg.startsWith("RSA"):
|
|
796
|
+
expectedKeyOp = "wrapKey";
|
|
797
|
+
break;
|
|
798
|
+
case usage === "decrypt":
|
|
799
|
+
expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
|
|
800
|
+
break;
|
|
801
|
+
}
|
|
802
|
+
if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
803
|
+
}
|
|
804
|
+
return true;
|
|
805
|
+
};
|
|
806
|
+
const symmetricTypeCheck = (alg, key, usage) => {
|
|
807
|
+
if (key instanceof Uint8Array) return;
|
|
808
|
+
if (isJWK(key)) {
|
|
809
|
+
if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
|
|
810
|
+
throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
|
|
811
|
+
}
|
|
812
|
+
if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
|
|
813
|
+
if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
|
|
814
|
+
};
|
|
815
|
+
const asymmetricTypeCheck = (alg, key, usage) => {
|
|
816
|
+
if (isJWK(key)) switch (usage) {
|
|
817
|
+
case "decrypt":
|
|
818
|
+
case "sign":
|
|
819
|
+
if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
|
|
820
|
+
throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
|
|
821
|
+
case "encrypt":
|
|
822
|
+
case "verify":
|
|
823
|
+
if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
|
|
824
|
+
throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
|
|
825
|
+
}
|
|
826
|
+
if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
827
|
+
if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
|
|
828
|
+
if (key.type === "public") switch (usage) {
|
|
829
|
+
case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
|
|
830
|
+
case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
|
|
831
|
+
}
|
|
832
|
+
if (key.type === "private") switch (usage) {
|
|
833
|
+
case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
|
|
834
|
+
case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
function checkKeyType(alg, key, usage) {
|
|
838
|
+
switch (alg.substring(0, 2)) {
|
|
839
|
+
case "A1":
|
|
840
|
+
case "A2":
|
|
841
|
+
case "di":
|
|
842
|
+
case "HS":
|
|
843
|
+
case "PB":
|
|
844
|
+
symmetricTypeCheck(alg, key, usage);
|
|
845
|
+
break;
|
|
846
|
+
default: asymmetricTypeCheck(alg, key, usage);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
//#endregion
|
|
851
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/subtle_dsa.js
|
|
852
|
+
function subtleAlgorithm(alg, algorithm) {
|
|
853
|
+
const hash = `SHA-${alg.slice(-3)}`;
|
|
854
|
+
switch (alg) {
|
|
855
|
+
case "HS256":
|
|
856
|
+
case "HS384":
|
|
857
|
+
case "HS512": return {
|
|
858
|
+
hash,
|
|
859
|
+
name: "HMAC"
|
|
860
|
+
};
|
|
861
|
+
case "PS256":
|
|
862
|
+
case "PS384":
|
|
863
|
+
case "PS512": return {
|
|
864
|
+
hash,
|
|
865
|
+
name: "RSA-PSS",
|
|
866
|
+
saltLength: parseInt(alg.slice(-3), 10) >> 3
|
|
867
|
+
};
|
|
868
|
+
case "RS256":
|
|
869
|
+
case "RS384":
|
|
870
|
+
case "RS512": return {
|
|
871
|
+
hash,
|
|
872
|
+
name: "RSASSA-PKCS1-v1_5"
|
|
873
|
+
};
|
|
874
|
+
case "ES256":
|
|
875
|
+
case "ES384":
|
|
876
|
+
case "ES512": return {
|
|
877
|
+
hash,
|
|
878
|
+
name: "ECDSA",
|
|
879
|
+
namedCurve: algorithm.namedCurve
|
|
880
|
+
};
|
|
881
|
+
case "Ed25519":
|
|
882
|
+
case "EdDSA": return { name: "Ed25519" };
|
|
883
|
+
case "ML-DSA-44":
|
|
884
|
+
case "ML-DSA-65":
|
|
885
|
+
case "ML-DSA-87": return { name: alg };
|
|
886
|
+
default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
//#endregion
|
|
891
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
|
|
892
|
+
async function getSigKey(alg, key, usage) {
|
|
893
|
+
if (key instanceof Uint8Array) {
|
|
894
|
+
if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
895
|
+
return crypto.subtle.importKey("raw", key, {
|
|
896
|
+
hash: `SHA-${alg.slice(-3)}`,
|
|
897
|
+
name: "HMAC"
|
|
898
|
+
}, false, [usage]);
|
|
899
|
+
}
|
|
900
|
+
checkSigCryptoKey(key, alg, usage);
|
|
901
|
+
return key;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
//#endregion
|
|
905
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/verify.js
|
|
906
|
+
async function verify(alg, key, signature, data) {
|
|
907
|
+
const cryptoKey = await getSigKey(alg, key, "verify");
|
|
908
|
+
checkKeyLength(alg, cryptoKey);
|
|
909
|
+
const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
|
|
910
|
+
try {
|
|
911
|
+
return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
|
|
912
|
+
} catch {
|
|
913
|
+
return false;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
//#endregion
|
|
918
|
+
//#region ../../../../node_modules/jose/dist/webapi/jws/flattened/verify.js
|
|
919
|
+
async function flattenedVerify(jws, key, options) {
|
|
920
|
+
if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
|
|
921
|
+
if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
|
|
922
|
+
if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
|
|
923
|
+
if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
|
|
924
|
+
if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
|
|
925
|
+
if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
|
|
926
|
+
let parsedProt = {};
|
|
927
|
+
if (jws.protected) try {
|
|
928
|
+
const protectedHeader = decode(jws.protected);
|
|
929
|
+
parsedProt = JSON.parse(decoder.decode(protectedHeader));
|
|
930
|
+
} catch {
|
|
931
|
+
throw new JWSInvalid("JWS Protected Header is invalid");
|
|
932
|
+
}
|
|
933
|
+
if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
934
|
+
const joseHeader = {
|
|
935
|
+
...parsedProt,
|
|
936
|
+
...jws.header
|
|
937
|
+
};
|
|
938
|
+
const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
|
|
939
|
+
let b64 = true;
|
|
940
|
+
if (extensions.has("b64")) {
|
|
941
|
+
b64 = parsedProt.b64;
|
|
942
|
+
if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
|
|
943
|
+
}
|
|
944
|
+
const { alg } = joseHeader;
|
|
945
|
+
if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
|
|
946
|
+
const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
|
|
947
|
+
if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
|
|
948
|
+
if (b64) {
|
|
949
|
+
if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
|
|
950
|
+
} else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
|
|
951
|
+
let resolvedKey = false;
|
|
952
|
+
if (typeof key === "function") {
|
|
953
|
+
key = await key(parsedProt, jws);
|
|
954
|
+
resolvedKey = true;
|
|
955
|
+
}
|
|
956
|
+
checkKeyType(alg, key, "verify");
|
|
957
|
+
const data = concat(jws.protected !== void 0 ? encode$1(jws.protected) : new Uint8Array(), encode$1("."), typeof jws.payload === "string" ? b64 ? encode$1(jws.payload) : encoder.encode(jws.payload) : jws.payload);
|
|
958
|
+
let signature;
|
|
959
|
+
try {
|
|
960
|
+
signature = decode(jws.signature);
|
|
961
|
+
} catch {
|
|
962
|
+
throw new JWSInvalid("Failed to base64url decode the signature");
|
|
963
|
+
}
|
|
964
|
+
const k = await normalizeKey(key, alg);
|
|
965
|
+
if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
|
|
966
|
+
let payload;
|
|
967
|
+
if (b64) try {
|
|
968
|
+
payload = decode(jws.payload);
|
|
969
|
+
} catch {
|
|
970
|
+
throw new JWSInvalid("Failed to base64url decode the payload");
|
|
971
|
+
}
|
|
972
|
+
else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload);
|
|
973
|
+
else payload = jws.payload;
|
|
974
|
+
const result = { payload };
|
|
975
|
+
if (jws.protected !== void 0) result.protectedHeader = parsedProt;
|
|
976
|
+
if (jws.header !== void 0) result.unprotectedHeader = jws.header;
|
|
977
|
+
if (resolvedKey) return {
|
|
978
|
+
...result,
|
|
979
|
+
key: k
|
|
980
|
+
};
|
|
981
|
+
return result;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
//#endregion
|
|
985
|
+
//#region ../../../../node_modules/jose/dist/webapi/jws/compact/verify.js
|
|
986
|
+
async function compactVerify(jws, key, options) {
|
|
987
|
+
if (jws instanceof Uint8Array) jws = decoder.decode(jws);
|
|
988
|
+
if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
|
|
989
|
+
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
|
|
990
|
+
if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
|
|
991
|
+
const verified = await flattenedVerify({
|
|
992
|
+
payload,
|
|
993
|
+
protected: protectedHeader,
|
|
994
|
+
signature
|
|
995
|
+
}, key, options);
|
|
996
|
+
const result = {
|
|
997
|
+
payload: verified.payload,
|
|
998
|
+
protectedHeader: verified.protectedHeader
|
|
999
|
+
};
|
|
1000
|
+
if (typeof key === "function") return {
|
|
1001
|
+
...result,
|
|
1002
|
+
key: verified.key
|
|
1003
|
+
};
|
|
1004
|
+
return result;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
//#endregion
|
|
1008
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js
|
|
1009
|
+
const epoch = (date) => Math.floor(date.getTime() / 1e3);
|
|
1010
|
+
const minute = 60;
|
|
1011
|
+
const hour = minute * 60;
|
|
1012
|
+
const day = hour * 24;
|
|
1013
|
+
const week = day * 7;
|
|
1014
|
+
const year = day * 365.25;
|
|
1015
|
+
const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
|
1016
|
+
function secs(str) {
|
|
1017
|
+
const matched = REGEX.exec(str);
|
|
1018
|
+
if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
|
|
1019
|
+
const value = parseFloat(matched[2]);
|
|
1020
|
+
const unit = matched[3].toLowerCase();
|
|
1021
|
+
let numericDate;
|
|
1022
|
+
switch (unit) {
|
|
1023
|
+
case "sec":
|
|
1024
|
+
case "secs":
|
|
1025
|
+
case "second":
|
|
1026
|
+
case "seconds":
|
|
1027
|
+
case "s":
|
|
1028
|
+
numericDate = Math.round(value);
|
|
1029
|
+
break;
|
|
1030
|
+
case "minute":
|
|
1031
|
+
case "minutes":
|
|
1032
|
+
case "min":
|
|
1033
|
+
case "mins":
|
|
1034
|
+
case "m":
|
|
1035
|
+
numericDate = Math.round(value * minute);
|
|
1036
|
+
break;
|
|
1037
|
+
case "hour":
|
|
1038
|
+
case "hours":
|
|
1039
|
+
case "hr":
|
|
1040
|
+
case "hrs":
|
|
1041
|
+
case "h":
|
|
1042
|
+
numericDate = Math.round(value * hour);
|
|
1043
|
+
break;
|
|
1044
|
+
case "day":
|
|
1045
|
+
case "days":
|
|
1046
|
+
case "d":
|
|
1047
|
+
numericDate = Math.round(value * day);
|
|
1048
|
+
break;
|
|
1049
|
+
case "week":
|
|
1050
|
+
case "weeks":
|
|
1051
|
+
case "w":
|
|
1052
|
+
numericDate = Math.round(value * week);
|
|
1053
|
+
break;
|
|
1054
|
+
default:
|
|
1055
|
+
numericDate = Math.round(value * year);
|
|
1056
|
+
break;
|
|
1057
|
+
}
|
|
1058
|
+
if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
|
|
1059
|
+
return numericDate;
|
|
1060
|
+
}
|
|
1061
|
+
function validateInput(label, input) {
|
|
1062
|
+
if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
|
|
1063
|
+
return input;
|
|
1064
|
+
}
|
|
1065
|
+
const normalizeTyp = (value) => {
|
|
1066
|
+
if (value.includes("/")) return value.toLowerCase();
|
|
1067
|
+
return `application/${value.toLowerCase()}`;
|
|
1068
|
+
};
|
|
1069
|
+
const checkAudiencePresence = (audPayload, audOption) => {
|
|
1070
|
+
if (typeof audPayload === "string") return audOption.includes(audPayload);
|
|
1071
|
+
if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
|
|
1072
|
+
return false;
|
|
1073
|
+
};
|
|
1074
|
+
function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
|
|
1075
|
+
let payload;
|
|
1076
|
+
try {
|
|
1077
|
+
payload = JSON.parse(decoder.decode(encodedPayload));
|
|
1078
|
+
} catch {}
|
|
1079
|
+
if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
|
|
1080
|
+
const { typ } = options;
|
|
1081
|
+
if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
|
|
1082
|
+
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
|
|
1083
|
+
const presenceCheck = [...requiredClaims];
|
|
1084
|
+
if (maxTokenAge !== void 0) presenceCheck.push("iat");
|
|
1085
|
+
if (audience !== void 0) presenceCheck.push("aud");
|
|
1086
|
+
if (subject !== void 0) presenceCheck.push("sub");
|
|
1087
|
+
if (issuer !== void 0) presenceCheck.push("iss");
|
|
1088
|
+
for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
|
|
1089
|
+
if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
|
|
1090
|
+
if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
|
|
1091
|
+
if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
|
|
1092
|
+
let tolerance;
|
|
1093
|
+
switch (typeof options.clockTolerance) {
|
|
1094
|
+
case "string":
|
|
1095
|
+
tolerance = secs(options.clockTolerance);
|
|
1096
|
+
break;
|
|
1097
|
+
case "number":
|
|
1098
|
+
tolerance = options.clockTolerance;
|
|
1099
|
+
break;
|
|
1100
|
+
case "undefined":
|
|
1101
|
+
tolerance = 0;
|
|
1102
|
+
break;
|
|
1103
|
+
default: throw new TypeError("Invalid clockTolerance option type");
|
|
1104
|
+
}
|
|
1105
|
+
const { currentDate } = options;
|
|
1106
|
+
const now = epoch(currentDate || /* @__PURE__ */ new Date());
|
|
1107
|
+
if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
|
|
1108
|
+
if (payload.nbf !== void 0) {
|
|
1109
|
+
if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
|
|
1110
|
+
if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
|
|
1111
|
+
}
|
|
1112
|
+
if (payload.exp !== void 0) {
|
|
1113
|
+
if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
|
|
1114
|
+
if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
|
|
1115
|
+
}
|
|
1116
|
+
if (maxTokenAge) {
|
|
1117
|
+
const age = now - payload.iat;
|
|
1118
|
+
const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
|
|
1119
|
+
if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
|
|
1120
|
+
if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
|
|
1121
|
+
}
|
|
1122
|
+
return payload;
|
|
1123
|
+
}
|
|
1124
|
+
var JWTClaimsBuilder = class {
|
|
1125
|
+
#payload;
|
|
1126
|
+
constructor(payload) {
|
|
1127
|
+
if (!isObject(payload)) throw new TypeError("JWT Claims Set MUST be an object");
|
|
1128
|
+
this.#payload = structuredClone(payload);
|
|
1129
|
+
}
|
|
1130
|
+
data() {
|
|
1131
|
+
return encoder.encode(JSON.stringify(this.#payload));
|
|
1132
|
+
}
|
|
1133
|
+
get iss() {
|
|
1134
|
+
return this.#payload.iss;
|
|
1135
|
+
}
|
|
1136
|
+
set iss(value) {
|
|
1137
|
+
this.#payload.iss = value;
|
|
1138
|
+
}
|
|
1139
|
+
get sub() {
|
|
1140
|
+
return this.#payload.sub;
|
|
1141
|
+
}
|
|
1142
|
+
set sub(value) {
|
|
1143
|
+
this.#payload.sub = value;
|
|
1144
|
+
}
|
|
1145
|
+
get aud() {
|
|
1146
|
+
return this.#payload.aud;
|
|
1147
|
+
}
|
|
1148
|
+
set aud(value) {
|
|
1149
|
+
this.#payload.aud = value;
|
|
1150
|
+
}
|
|
1151
|
+
set jti(value) {
|
|
1152
|
+
this.#payload.jti = value;
|
|
1153
|
+
}
|
|
1154
|
+
set nbf(value) {
|
|
1155
|
+
if (typeof value === "number") this.#payload.nbf = validateInput("setNotBefore", value);
|
|
1156
|
+
else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value));
|
|
1157
|
+
else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
|
|
1158
|
+
}
|
|
1159
|
+
set exp(value) {
|
|
1160
|
+
if (typeof value === "number") this.#payload.exp = validateInput("setExpirationTime", value);
|
|
1161
|
+
else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value));
|
|
1162
|
+
else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
|
|
1163
|
+
}
|
|
1164
|
+
set iat(value) {
|
|
1165
|
+
if (value === void 0) this.#payload.iat = epoch(/* @__PURE__ */ new Date());
|
|
1166
|
+
else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value));
|
|
1167
|
+
else if (typeof value === "string") this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
|
|
1168
|
+
else this.#payload.iat = validateInput("setIssuedAt", value);
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
|
|
1172
|
+
//#endregion
|
|
1173
|
+
//#region ../../../../node_modules/jose/dist/webapi/jwt/verify.js
|
|
1174
|
+
async function jwtVerify(jwt, key, options) {
|
|
1175
|
+
const verified = await compactVerify(jwt, key, options);
|
|
1176
|
+
if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1177
|
+
const result = {
|
|
1178
|
+
payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
|
|
1179
|
+
protectedHeader: verified.protectedHeader
|
|
1180
|
+
};
|
|
1181
|
+
if (typeof key === "function") return {
|
|
1182
|
+
...result,
|
|
1183
|
+
key: verified.key
|
|
1184
|
+
};
|
|
1185
|
+
return result;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
//#endregion
|
|
1189
|
+
//#region ../../../../node_modules/jose/dist/webapi/lib/sign.js
|
|
1190
|
+
async function sign(alg, key, data) {
|
|
1191
|
+
const cryptoKey = await getSigKey(alg, key, "sign");
|
|
1192
|
+
checkKeyLength(alg, cryptoKey);
|
|
1193
|
+
const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
|
|
1194
|
+
return new Uint8Array(signature);
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
//#endregion
|
|
1198
|
+
//#region ../../../../node_modules/jose/dist/webapi/jws/flattened/sign.js
|
|
1199
|
+
var FlattenedSign = class {
|
|
1200
|
+
#payload;
|
|
1201
|
+
#protectedHeader;
|
|
1202
|
+
#unprotectedHeader;
|
|
1203
|
+
constructor(payload) {
|
|
1204
|
+
if (!(payload instanceof Uint8Array)) throw new TypeError("payload must be an instance of Uint8Array");
|
|
1205
|
+
this.#payload = payload;
|
|
1206
|
+
}
|
|
1207
|
+
setProtectedHeader(protectedHeader) {
|
|
1208
|
+
if (this.#protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
|
|
1209
|
+
this.#protectedHeader = protectedHeader;
|
|
1210
|
+
return this;
|
|
1211
|
+
}
|
|
1212
|
+
setUnprotectedHeader(unprotectedHeader) {
|
|
1213
|
+
if (this.#unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
|
|
1214
|
+
this.#unprotectedHeader = unprotectedHeader;
|
|
1215
|
+
return this;
|
|
1216
|
+
}
|
|
1217
|
+
async sign(key, options) {
|
|
1218
|
+
if (!this.#protectedHeader && !this.#unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
|
|
1219
|
+
if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
1220
|
+
const joseHeader = {
|
|
1221
|
+
...this.#protectedHeader,
|
|
1222
|
+
...this.#unprotectedHeader
|
|
1223
|
+
};
|
|
1224
|
+
const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
|
|
1225
|
+
let b64 = true;
|
|
1226
|
+
if (extensions.has("b64")) {
|
|
1227
|
+
b64 = this.#protectedHeader.b64;
|
|
1228
|
+
if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
|
|
1229
|
+
}
|
|
1230
|
+
const { alg } = joseHeader;
|
|
1231
|
+
if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
|
|
1232
|
+
checkKeyType(alg, key, "sign");
|
|
1233
|
+
let payloadS;
|
|
1234
|
+
let payloadB;
|
|
1235
|
+
if (b64) {
|
|
1236
|
+
payloadS = encode(this.#payload);
|
|
1237
|
+
payloadB = encode$1(payloadS);
|
|
1238
|
+
} else {
|
|
1239
|
+
payloadB = this.#payload;
|
|
1240
|
+
payloadS = "";
|
|
1241
|
+
}
|
|
1242
|
+
let protectedHeaderString;
|
|
1243
|
+
let protectedHeaderBytes;
|
|
1244
|
+
if (this.#protectedHeader) {
|
|
1245
|
+
protectedHeaderString = encode(JSON.stringify(this.#protectedHeader));
|
|
1246
|
+
protectedHeaderBytes = encode$1(protectedHeaderString);
|
|
1247
|
+
} else {
|
|
1248
|
+
protectedHeaderString = "";
|
|
1249
|
+
protectedHeaderBytes = new Uint8Array();
|
|
1250
|
+
}
|
|
1251
|
+
const data = concat(protectedHeaderBytes, encode$1("."), payloadB);
|
|
1252
|
+
const jws = {
|
|
1253
|
+
signature: encode(await sign(alg, await normalizeKey(key, alg), data)),
|
|
1254
|
+
payload: payloadS
|
|
1255
|
+
};
|
|
1256
|
+
if (this.#unprotectedHeader) jws.header = this.#unprotectedHeader;
|
|
1257
|
+
if (this.#protectedHeader) jws.protected = protectedHeaderString;
|
|
1258
|
+
return jws;
|
|
1259
|
+
}
|
|
1260
|
+
};
|
|
1261
|
+
|
|
1262
|
+
//#endregion
|
|
1263
|
+
//#region ../../../../node_modules/jose/dist/webapi/jws/compact/sign.js
|
|
1264
|
+
var CompactSign = class {
|
|
1265
|
+
#flattened;
|
|
1266
|
+
constructor(payload) {
|
|
1267
|
+
this.#flattened = new FlattenedSign(payload);
|
|
1268
|
+
}
|
|
1269
|
+
setProtectedHeader(protectedHeader) {
|
|
1270
|
+
this.#flattened.setProtectedHeader(protectedHeader);
|
|
1271
|
+
return this;
|
|
1272
|
+
}
|
|
1273
|
+
async sign(key, options) {
|
|
1274
|
+
const jws = await this.#flattened.sign(key, options);
|
|
1275
|
+
if (jws.payload === void 0) throw new TypeError("use the flattened module for creating JWS with b64: false");
|
|
1276
|
+
return `${jws.protected}.${jws.payload}.${jws.signature}`;
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
|
|
1280
|
+
//#endregion
|
|
1281
|
+
//#region ../../../../node_modules/jose/dist/webapi/jwt/sign.js
|
|
1282
|
+
var SignJWT = class {
|
|
1283
|
+
#protectedHeader;
|
|
1284
|
+
#jwt;
|
|
1285
|
+
constructor(payload = {}) {
|
|
1286
|
+
this.#jwt = new JWTClaimsBuilder(payload);
|
|
1287
|
+
}
|
|
1288
|
+
setIssuer(issuer) {
|
|
1289
|
+
this.#jwt.iss = issuer;
|
|
1290
|
+
return this;
|
|
1291
|
+
}
|
|
1292
|
+
setSubject(subject) {
|
|
1293
|
+
this.#jwt.sub = subject;
|
|
1294
|
+
return this;
|
|
1295
|
+
}
|
|
1296
|
+
setAudience(audience) {
|
|
1297
|
+
this.#jwt.aud = audience;
|
|
1298
|
+
return this;
|
|
1299
|
+
}
|
|
1300
|
+
setJti(jwtId) {
|
|
1301
|
+
this.#jwt.jti = jwtId;
|
|
1302
|
+
return this;
|
|
1303
|
+
}
|
|
1304
|
+
setNotBefore(input) {
|
|
1305
|
+
this.#jwt.nbf = input;
|
|
1306
|
+
return this;
|
|
1307
|
+
}
|
|
1308
|
+
setExpirationTime(input) {
|
|
1309
|
+
this.#jwt.exp = input;
|
|
1310
|
+
return this;
|
|
1311
|
+
}
|
|
1312
|
+
setIssuedAt(input) {
|
|
1313
|
+
this.#jwt.iat = input;
|
|
1314
|
+
return this;
|
|
1315
|
+
}
|
|
1316
|
+
setProtectedHeader(protectedHeader) {
|
|
1317
|
+
this.#protectedHeader = protectedHeader;
|
|
1318
|
+
return this;
|
|
1319
|
+
}
|
|
1320
|
+
async sign(key, options) {
|
|
1321
|
+
const sig = new CompactSign(this.#jwt.data());
|
|
1322
|
+
sig.setProtectedHeader(this.#protectedHeader);
|
|
1323
|
+
if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1324
|
+
return sig.sign(key, options);
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
|
|
1328
|
+
//#endregion
|
|
1329
|
+
//#region ../../../../node_modules/jose/dist/webapi/jwks/local.js
|
|
1330
|
+
function getKtyFromAlg(alg) {
|
|
1331
|
+
switch (typeof alg === "string" && alg.slice(0, 2)) {
|
|
1332
|
+
case "RS":
|
|
1333
|
+
case "PS": return "RSA";
|
|
1334
|
+
case "ES": return "EC";
|
|
1335
|
+
case "Ed": return "OKP";
|
|
1336
|
+
case "ML": return "AKP";
|
|
1337
|
+
default: throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
function isJWKSLike(jwks) {
|
|
1341
|
+
return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
|
|
1342
|
+
}
|
|
1343
|
+
function isJWKLike(key) {
|
|
1344
|
+
return isObject(key);
|
|
1345
|
+
}
|
|
1346
|
+
var LocalJWKSet = class {
|
|
1347
|
+
#jwks;
|
|
1348
|
+
#cached = /* @__PURE__ */ new WeakMap();
|
|
1349
|
+
constructor(jwks) {
|
|
1350
|
+
if (!isJWKSLike(jwks)) throw new JWKSInvalid("JSON Web Key Set malformed");
|
|
1351
|
+
this.#jwks = structuredClone(jwks);
|
|
1352
|
+
}
|
|
1353
|
+
jwks() {
|
|
1354
|
+
return this.#jwks;
|
|
1355
|
+
}
|
|
1356
|
+
async getKey(protectedHeader, token) {
|
|
1357
|
+
const { alg, kid } = {
|
|
1358
|
+
...protectedHeader,
|
|
1359
|
+
...token?.header
|
|
1360
|
+
};
|
|
1361
|
+
const kty = getKtyFromAlg(alg);
|
|
1362
|
+
const candidates = this.#jwks.keys.filter((jwk) => {
|
|
1363
|
+
let candidate = kty === jwk.kty;
|
|
1364
|
+
if (candidate && typeof kid === "string") candidate = kid === jwk.kid;
|
|
1365
|
+
if (candidate && (typeof jwk.alg === "string" || kty === "AKP")) candidate = alg === jwk.alg;
|
|
1366
|
+
if (candidate && typeof jwk.use === "string") candidate = jwk.use === "sig";
|
|
1367
|
+
if (candidate && Array.isArray(jwk.key_ops)) candidate = jwk.key_ops.includes("verify");
|
|
1368
|
+
if (candidate) switch (alg) {
|
|
1369
|
+
case "ES256":
|
|
1370
|
+
candidate = jwk.crv === "P-256";
|
|
1371
|
+
break;
|
|
1372
|
+
case "ES384":
|
|
1373
|
+
candidate = jwk.crv === "P-384";
|
|
1374
|
+
break;
|
|
1375
|
+
case "ES512":
|
|
1376
|
+
candidate = jwk.crv === "P-521";
|
|
1377
|
+
break;
|
|
1378
|
+
case "Ed25519":
|
|
1379
|
+
case "EdDSA":
|
|
1380
|
+
candidate = jwk.crv === "Ed25519";
|
|
1381
|
+
break;
|
|
1382
|
+
}
|
|
1383
|
+
return candidate;
|
|
1384
|
+
});
|
|
1385
|
+
const { 0: jwk, length } = candidates;
|
|
1386
|
+
if (length === 0) throw new JWKSNoMatchingKey();
|
|
1387
|
+
if (length !== 1) {
|
|
1388
|
+
const error = new JWKSMultipleMatchingKeys();
|
|
1389
|
+
const _cached = this.#cached;
|
|
1390
|
+
error[Symbol.asyncIterator] = async function* () {
|
|
1391
|
+
for (const jwk of candidates) try {
|
|
1392
|
+
yield await importWithAlgCache(_cached, jwk, alg);
|
|
1393
|
+
} catch {}
|
|
1394
|
+
};
|
|
1395
|
+
throw error;
|
|
1396
|
+
}
|
|
1397
|
+
return importWithAlgCache(this.#cached, jwk, alg);
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
async function importWithAlgCache(cache, jwk, alg) {
|
|
1401
|
+
const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
|
|
1402
|
+
if (cached[alg] === void 0) {
|
|
1403
|
+
const key = await importJWK({
|
|
1404
|
+
...jwk,
|
|
1405
|
+
ext: true
|
|
1406
|
+
}, alg);
|
|
1407
|
+
if (key instanceof Uint8Array || key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
|
|
1408
|
+
cached[alg] = key;
|
|
1409
|
+
}
|
|
1410
|
+
return cached[alg];
|
|
1411
|
+
}
|
|
1412
|
+
function createLocalJWKSet(jwks) {
|
|
1413
|
+
const set = new LocalJWKSet(jwks);
|
|
1414
|
+
const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
|
1415
|
+
Object.defineProperties(localJWKSet, { jwks: {
|
|
1416
|
+
value: () => structuredClone(set.jwks()),
|
|
1417
|
+
enumerable: false,
|
|
1418
|
+
configurable: false,
|
|
1419
|
+
writable: false
|
|
1420
|
+
} });
|
|
1421
|
+
return localJWKSet;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
//#endregion
|
|
1425
|
+
//#region ../../../../node_modules/jose/dist/webapi/jwks/remote.js
|
|
1426
|
+
function isCloudflareWorkers() {
|
|
1427
|
+
return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
|
|
1428
|
+
}
|
|
1429
|
+
let USER_AGENT;
|
|
1430
|
+
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.1.3`;
|
|
1431
|
+
const customFetch = Symbol();
|
|
1432
|
+
async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
|
|
1433
|
+
const response = await fetchImpl(url, {
|
|
1434
|
+
method: "GET",
|
|
1435
|
+
signal,
|
|
1436
|
+
redirect: "manual",
|
|
1437
|
+
headers
|
|
1438
|
+
}).catch((err) => {
|
|
1439
|
+
if (err.name === "TimeoutError") throw new JWKSTimeout();
|
|
1440
|
+
throw err;
|
|
1441
|
+
});
|
|
1442
|
+
if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
|
|
1443
|
+
try {
|
|
1444
|
+
return await response.json();
|
|
1445
|
+
} catch {
|
|
1446
|
+
throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
const jwksCache = Symbol();
|
|
1450
|
+
function isFreshJwksCache(input, cacheMaxAge) {
|
|
1451
|
+
if (typeof input !== "object" || input === null) return false;
|
|
1452
|
+
if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) return false;
|
|
1453
|
+
if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) return false;
|
|
1454
|
+
return true;
|
|
1455
|
+
}
|
|
1456
|
+
var RemoteJWKSet = class {
|
|
1457
|
+
#url;
|
|
1458
|
+
#timeoutDuration;
|
|
1459
|
+
#cooldownDuration;
|
|
1460
|
+
#cacheMaxAge;
|
|
1461
|
+
#jwksTimestamp;
|
|
1462
|
+
#pendingFetch;
|
|
1463
|
+
#headers;
|
|
1464
|
+
#customFetch;
|
|
1465
|
+
#local;
|
|
1466
|
+
#cache;
|
|
1467
|
+
constructor(url, options) {
|
|
1468
|
+
if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
|
|
1469
|
+
this.#url = new URL(url.href);
|
|
1470
|
+
this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
|
|
1471
|
+
this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
|
|
1472
|
+
this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
|
|
1473
|
+
this.#headers = new Headers(options?.headers);
|
|
1474
|
+
if (USER_AGENT && !this.#headers.has("User-Agent")) this.#headers.set("User-Agent", USER_AGENT);
|
|
1475
|
+
if (!this.#headers.has("accept")) {
|
|
1476
|
+
this.#headers.set("accept", "application/json");
|
|
1477
|
+
this.#headers.append("accept", "application/jwk-set+json");
|
|
1478
|
+
}
|
|
1479
|
+
this.#customFetch = options?.[customFetch];
|
|
1480
|
+
if (options?.[jwksCache] !== void 0) {
|
|
1481
|
+
this.#cache = options?.[jwksCache];
|
|
1482
|
+
if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
|
|
1483
|
+
this.#jwksTimestamp = this.#cache.uat;
|
|
1484
|
+
this.#local = createLocalJWKSet(this.#cache.jwks);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
pendingFetch() {
|
|
1489
|
+
return !!this.#pendingFetch;
|
|
1490
|
+
}
|
|
1491
|
+
coolingDown() {
|
|
1492
|
+
return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
|
|
1493
|
+
}
|
|
1494
|
+
fresh() {
|
|
1495
|
+
return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
|
|
1496
|
+
}
|
|
1497
|
+
jwks() {
|
|
1498
|
+
return this.#local?.jwks();
|
|
1499
|
+
}
|
|
1500
|
+
async getKey(protectedHeader, token) {
|
|
1501
|
+
if (!this.#local || !this.fresh()) await this.reload();
|
|
1502
|
+
try {
|
|
1503
|
+
return await this.#local(protectedHeader, token);
|
|
1504
|
+
} catch (err) {
|
|
1505
|
+
if (err instanceof JWKSNoMatchingKey) {
|
|
1506
|
+
if (this.coolingDown() === false) {
|
|
1507
|
+
await this.reload();
|
|
1508
|
+
return this.#local(protectedHeader, token);
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
throw err;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
async reload() {
|
|
1515
|
+
if (this.#pendingFetch && isCloudflareWorkers()) this.#pendingFetch = void 0;
|
|
1516
|
+
this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => {
|
|
1517
|
+
this.#local = createLocalJWKSet(json);
|
|
1518
|
+
if (this.#cache) {
|
|
1519
|
+
this.#cache.uat = Date.now();
|
|
1520
|
+
this.#cache.jwks = json;
|
|
1521
|
+
}
|
|
1522
|
+
this.#jwksTimestamp = Date.now();
|
|
1523
|
+
this.#pendingFetch = void 0;
|
|
1524
|
+
}).catch((err) => {
|
|
1525
|
+
this.#pendingFetch = void 0;
|
|
1526
|
+
throw err;
|
|
1527
|
+
});
|
|
1528
|
+
await this.#pendingFetch;
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1531
|
+
function createRemoteJWKSet(url, options) {
|
|
1532
|
+
const set = new RemoteJWKSet(url, options);
|
|
1533
|
+
const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
|
1534
|
+
Object.defineProperties(remoteJWKSet, {
|
|
1535
|
+
coolingDown: {
|
|
1536
|
+
get: () => set.coolingDown(),
|
|
1537
|
+
enumerable: true,
|
|
1538
|
+
configurable: false
|
|
1539
|
+
},
|
|
1540
|
+
fresh: {
|
|
1541
|
+
get: () => set.fresh(),
|
|
1542
|
+
enumerable: true,
|
|
1543
|
+
configurable: false
|
|
1544
|
+
},
|
|
1545
|
+
reload: {
|
|
1546
|
+
value: () => set.reload(),
|
|
1547
|
+
enumerable: true,
|
|
1548
|
+
configurable: false,
|
|
1549
|
+
writable: false
|
|
1550
|
+
},
|
|
1551
|
+
reloading: {
|
|
1552
|
+
get: () => set.pendingFetch(),
|
|
1553
|
+
enumerable: true,
|
|
1554
|
+
configurable: false
|
|
1555
|
+
},
|
|
1556
|
+
jwks: {
|
|
1557
|
+
value: () => set.jwks(),
|
|
1558
|
+
enumerable: true,
|
|
1559
|
+
configurable: false,
|
|
1560
|
+
writable: false
|
|
1561
|
+
}
|
|
1562
|
+
});
|
|
1563
|
+
return remoteJWKSet;
|
|
1564
|
+
}
|
|
1565
|
+
|
|
38
1566
|
//#endregion
|
|
39
1567
|
//#region ../../src/security/providers/JwtProvider.ts
|
|
40
1568
|
/**
|
|
@@ -137,6 +1665,28 @@ var JwtProvider = class {
|
|
|
137
1665
|
}
|
|
138
1666
|
};
|
|
139
1667
|
|
|
1668
|
+
//#endregion
|
|
1669
|
+
//#region ../../src/security/errors/InvalidPermissionError.ts
|
|
1670
|
+
var InvalidPermissionError = class extends Error {
|
|
1671
|
+
constructor(name) {
|
|
1672
|
+
super(`Permission '${name}' is invalid`);
|
|
1673
|
+
}
|
|
1674
|
+
};
|
|
1675
|
+
|
|
1676
|
+
//#endregion
|
|
1677
|
+
//#region ../../src/security/errors/InvalidTokenError.ts
|
|
1678
|
+
var InvalidTokenError = class extends Error {
|
|
1679
|
+
status = 401;
|
|
1680
|
+
};
|
|
1681
|
+
|
|
1682
|
+
//#endregion
|
|
1683
|
+
//#region ../../src/security/errors/RealmNotFoundError.ts
|
|
1684
|
+
var RealmNotFoundError = class extends Error {
|
|
1685
|
+
constructor(realm) {
|
|
1686
|
+
super(`Realm '${realm}' not found`);
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
|
|
140
1690
|
//#endregion
|
|
141
1691
|
//#region ../../src/security/providers/SecurityProvider.ts
|
|
142
1692
|
const DEFAULT_APP_SECRET = "05759934015388327323179852515731";
|
|
@@ -305,12 +1855,12 @@ var SecurityProvider = class {
|
|
|
305
1855
|
*/
|
|
306
1856
|
checkPermission(permissionLike, ...roleEntries) {
|
|
307
1857
|
const roles = roleEntries.map((it) => {
|
|
308
|
-
const role = this.getRoles().find((role
|
|
1858
|
+
const role = this.getRoles().find((role) => role.name === it);
|
|
309
1859
|
if (!role) throw new SecurityError(`Role '${it}' not found`);
|
|
310
1860
|
return role;
|
|
311
1861
|
});
|
|
312
1862
|
const permission = this.permissionToString(permissionLike);
|
|
313
|
-
if (roles.find((it) => it.permissions.find((it
|
|
1863
|
+
if (roles.find((it) => it.permissions.find((it) => it.name === "*" && !it.exclude && !it.ownership))) return {
|
|
314
1864
|
isAuthorized: true,
|
|
315
1865
|
ownership: false
|
|
316
1866
|
};
|
|
@@ -530,50 +2080,17 @@ var SecurityProvider = class {
|
|
|
530
2080
|
};
|
|
531
2081
|
|
|
532
2082
|
//#endregion
|
|
533
|
-
//#region ../../src/security/primitives/$
|
|
2083
|
+
//#region ../../src/security/primitives/$issuer.ts
|
|
534
2084
|
/**
|
|
535
|
-
* Create a new
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
};
|
|
540
|
-
var PermissionPrimitive = class extends Primitive {
|
|
541
|
-
securityProvider = $inject(SecurityProvider);
|
|
542
|
-
get name() {
|
|
543
|
-
return this.options.name || this.config.propertyKey;
|
|
544
|
-
}
|
|
545
|
-
get group() {
|
|
546
|
-
return this.options.group || this.config.service.name;
|
|
547
|
-
}
|
|
548
|
-
toString() {
|
|
549
|
-
return `${this.group}:${this.name}`;
|
|
550
|
-
}
|
|
551
|
-
onInit() {
|
|
552
|
-
this.securityProvider.createPermission({
|
|
553
|
-
name: this.name,
|
|
554
|
-
group: this.group,
|
|
555
|
-
description: this.options.description
|
|
556
|
-
});
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* Check if the user has the permission.
|
|
560
|
-
*/
|
|
561
|
-
can(user) {
|
|
562
|
-
if (!user?.roles) return false;
|
|
563
|
-
return this.securityProvider.checkPermission(this, ...user.roles).isAuthorized;
|
|
564
|
-
}
|
|
565
|
-
};
|
|
566
|
-
$permission[KIND] = PermissionPrimitive;
|
|
567
|
-
|
|
568
|
-
//#endregion
|
|
569
|
-
//#region ../../src/security/primitives/$realm.ts
|
|
570
|
-
/**
|
|
571
|
-
* Create a new realm.
|
|
2085
|
+
* Create a new issuer.
|
|
2086
|
+
*
|
|
2087
|
+
* An issuer is responsible for creating and verifying JWT tokens.
|
|
2088
|
+
* It can be internal (with a secret) or external (with a JWKS).
|
|
572
2089
|
*/
|
|
573
|
-
const $
|
|
574
|
-
return createPrimitive(
|
|
2090
|
+
const $issuer = (options) => {
|
|
2091
|
+
return createPrimitive(IssuerPrimitive, options);
|
|
575
2092
|
};
|
|
576
|
-
var
|
|
2093
|
+
var IssuerPrimitive = class extends Primitive {
|
|
577
2094
|
securityProvider = $inject(SecurityProvider);
|
|
578
2095
|
dateTimeProvider = $inject(DateTimeProvider);
|
|
579
2096
|
jwt = $inject(JwtProvider);
|
|
@@ -590,7 +2107,7 @@ var RealmPrimitive = class extends Primitive {
|
|
|
590
2107
|
onInit() {
|
|
591
2108
|
const roles = this.options.roles?.map((it) => {
|
|
592
2109
|
if (typeof it === "string") {
|
|
593
|
-
const role = this.getRoles().find((role
|
|
2110
|
+
const role = this.getRoles().find((role) => role.name === it);
|
|
594
2111
|
if (!role) throw new SecurityError(`Role '${it}' not found`);
|
|
595
2112
|
return role;
|
|
596
2113
|
}
|
|
@@ -604,13 +2121,13 @@ var RealmPrimitive = class extends Primitive {
|
|
|
604
2121
|
});
|
|
605
2122
|
}
|
|
606
2123
|
/**
|
|
607
|
-
* Get all roles in the
|
|
2124
|
+
* Get all roles in the issuer.
|
|
608
2125
|
*/
|
|
609
2126
|
getRoles() {
|
|
610
2127
|
return this.securityProvider.getRoles(this.name);
|
|
611
2128
|
}
|
|
612
2129
|
/**
|
|
613
|
-
* Set all roles in the
|
|
2130
|
+
* Set all roles in the issuer.
|
|
614
2131
|
*/
|
|
615
2132
|
async setRoles(roles) {
|
|
616
2133
|
await this.securityProvider.updateRealm(this.name, roles);
|
|
@@ -640,8 +2157,8 @@ var RealmPrimitive = class extends Primitive {
|
|
|
640
2157
|
const create = this.options.settings?.onCreateSession;
|
|
641
2158
|
if (create) {
|
|
642
2159
|
const expiresIn = this.refreshTokenExpiration.asSeconds();
|
|
643
|
-
const { refreshToken
|
|
644
|
-
refresh_token = refreshToken
|
|
2160
|
+
const { refreshToken, sessionId } = await create(user, { expiresIn });
|
|
2161
|
+
refresh_token = refreshToken;
|
|
645
2162
|
refresh_token_expires_in = expiresIn;
|
|
646
2163
|
sid = sessionId;
|
|
647
2164
|
} else {
|
|
@@ -686,13 +2203,13 @@ var RealmPrimitive = class extends Primitive {
|
|
|
686
2203
|
}
|
|
687
2204
|
async refreshToken(refreshToken, accessToken) {
|
|
688
2205
|
if (this.options.settings?.onRefreshSession) {
|
|
689
|
-
const { user
|
|
2206
|
+
const { user, expiresIn, sessionId } = await this.options.settings.onRefreshSession(refreshToken);
|
|
690
2207
|
return {
|
|
691
|
-
user
|
|
692
|
-
tokens: await this.createToken(user
|
|
2208
|
+
user,
|
|
2209
|
+
tokens: await this.createToken(user, {
|
|
693
2210
|
sid: sessionId,
|
|
694
2211
|
refresh_token: refreshToken,
|
|
695
|
-
refresh_token_expires_in: expiresIn
|
|
2212
|
+
refresh_token_expires_in: expiresIn
|
|
696
2213
|
})
|
|
697
2214
|
};
|
|
698
2215
|
}
|
|
@@ -718,7 +2235,43 @@ var RealmPrimitive = class extends Primitive {
|
|
|
718
2235
|
};
|
|
719
2236
|
}
|
|
720
2237
|
};
|
|
721
|
-
$
|
|
2238
|
+
$issuer[KIND] = IssuerPrimitive;
|
|
2239
|
+
|
|
2240
|
+
//#endregion
|
|
2241
|
+
//#region ../../src/security/primitives/$permission.ts
|
|
2242
|
+
/**
|
|
2243
|
+
* Create a new permission.
|
|
2244
|
+
*/
|
|
2245
|
+
const $permission = (options = {}) => {
|
|
2246
|
+
return createPrimitive(PermissionPrimitive, options);
|
|
2247
|
+
};
|
|
2248
|
+
var PermissionPrimitive = class extends Primitive {
|
|
2249
|
+
securityProvider = $inject(SecurityProvider);
|
|
2250
|
+
get name() {
|
|
2251
|
+
return this.options.name || this.config.propertyKey;
|
|
2252
|
+
}
|
|
2253
|
+
get group() {
|
|
2254
|
+
return this.options.group || this.config.service.name;
|
|
2255
|
+
}
|
|
2256
|
+
toString() {
|
|
2257
|
+
return `${this.group}:${this.name}`;
|
|
2258
|
+
}
|
|
2259
|
+
onInit() {
|
|
2260
|
+
this.securityProvider.createPermission({
|
|
2261
|
+
name: this.name,
|
|
2262
|
+
group: this.group,
|
|
2263
|
+
description: this.options.description
|
|
2264
|
+
});
|
|
2265
|
+
}
|
|
2266
|
+
/**
|
|
2267
|
+
* Check if the user has the permission.
|
|
2268
|
+
*/
|
|
2269
|
+
can(user) {
|
|
2270
|
+
if (!user?.roles) return false;
|
|
2271
|
+
return this.securityProvider.checkPermission(this, ...user.roles).isAuthorized;
|
|
2272
|
+
}
|
|
2273
|
+
};
|
|
2274
|
+
$permission[KIND] = PermissionPrimitive;
|
|
722
2275
|
|
|
723
2276
|
//#endregion
|
|
724
2277
|
//#region ../../src/security/primitives/$role.ts
|
|
@@ -744,10 +2297,10 @@ var RolePrimitive = class extends Primitive {
|
|
|
744
2297
|
});
|
|
745
2298
|
}
|
|
746
2299
|
/**
|
|
747
|
-
* Get the
|
|
2300
|
+
* Get the issuer of the role.
|
|
748
2301
|
*/
|
|
749
|
-
get
|
|
750
|
-
return this.options.
|
|
2302
|
+
get issuer() {
|
|
2303
|
+
return this.options.issuer;
|
|
751
2304
|
}
|
|
752
2305
|
can(permission) {
|
|
753
2306
|
return this.securityProvider.can(this.name, permission);
|
|
@@ -787,6 +2340,160 @@ var CryptoProvider = class {
|
|
|
787
2340
|
}
|
|
788
2341
|
};
|
|
789
2342
|
|
|
2343
|
+
//#endregion
|
|
2344
|
+
//#region ../../src/security/schemas/userAccountInfoSchema.ts
|
|
2345
|
+
const userAccountInfoSchema = t.object({
|
|
2346
|
+
id: t.text({ description: "Unique identifier for the user." }),
|
|
2347
|
+
name: t.optional(t.text({ description: "Full name of the user." })),
|
|
2348
|
+
email: t.optional(t.text({
|
|
2349
|
+
description: "Email address of the user.",
|
|
2350
|
+
format: "email"
|
|
2351
|
+
})),
|
|
2352
|
+
username: t.optional(t.text({ description: "Preferred username of the user." })),
|
|
2353
|
+
picture: t.optional(t.text({ description: "URL to the user's profile picture." })),
|
|
2354
|
+
sessionId: t.optional(t.text({ description: "Session identifier for the user, if applicable." })),
|
|
2355
|
+
organizations: t.optional(t.array(t.text(), { description: "List of organizations the user belongs to." })),
|
|
2356
|
+
roles: t.optional(t.array(t.text(), { description: "List of roles assigned to the user." }))
|
|
2357
|
+
});
|
|
2358
|
+
|
|
2359
|
+
//#endregion
|
|
2360
|
+
//#region ../../src/security/providers/ServerSecurityProvider.ts
|
|
2361
|
+
var ServerSecurityProvider = class {
|
|
2362
|
+
log = $logger();
|
|
2363
|
+
securityProvider = $inject(SecurityProvider);
|
|
2364
|
+
jwtProvider = $inject(JwtProvider);
|
|
2365
|
+
alepha = $inject(Alepha);
|
|
2366
|
+
onConfigure = $hook({
|
|
2367
|
+
on: "configure",
|
|
2368
|
+
handler: async () => {
|
|
2369
|
+
for (const action of this.alepha.primitives($action)) {
|
|
2370
|
+
if (action.options.disabled || action.options.secure === false || this.securityProvider.getRealms().length === 0) continue;
|
|
2371
|
+
if (typeof action.options.secure !== "object") this.securityProvider.createPermission({
|
|
2372
|
+
name: action.name,
|
|
2373
|
+
group: action.group,
|
|
2374
|
+
method: action.route.method,
|
|
2375
|
+
path: action.route.path
|
|
2376
|
+
});
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
});
|
|
2380
|
+
onActionRequest = $hook({
|
|
2381
|
+
on: "action:onRequest",
|
|
2382
|
+
handler: async ({ action, request, options }) => {
|
|
2383
|
+
if (action.options.secure === false && !options.user) {
|
|
2384
|
+
this.log.trace("Skipping security check for route");
|
|
2385
|
+
return;
|
|
2386
|
+
}
|
|
2387
|
+
if (isBasicAuth(action.route.secure)) return;
|
|
2388
|
+
const permission = this.securityProvider.getPermissions().find((it) => it.path === action.route.path && it.method === action.route.method);
|
|
2389
|
+
try {
|
|
2390
|
+
request.user = this.createUserFromLocalFunctionContext(options, permission);
|
|
2391
|
+
const route = action.route;
|
|
2392
|
+
if (typeof route.secure === "object") this.check(request.user, route.secure);
|
|
2393
|
+
this.alepha.store.set("alepha.server.request.user", this.alepha.codec.decode(userAccountInfoSchema, request.user));
|
|
2394
|
+
} catch (error) {
|
|
2395
|
+
if (action.options.secure || permission) throw error;
|
|
2396
|
+
this.log.trace("Skipping security check for action");
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
});
|
|
2400
|
+
onRequest = $hook({
|
|
2401
|
+
on: "server:onRequest",
|
|
2402
|
+
priority: "last",
|
|
2403
|
+
handler: async ({ request, route }) => {
|
|
2404
|
+
if (route.secure === false) {
|
|
2405
|
+
this.log.trace("Skipping security check for route - explicitly disabled");
|
|
2406
|
+
return;
|
|
2407
|
+
}
|
|
2408
|
+
if (isBasicAuth(route.secure)) return;
|
|
2409
|
+
const permission = this.securityProvider.getPermissions().find((it) => it.path === route.path && it.method === route.method);
|
|
2410
|
+
if (!request.headers.authorization && !route.secure && !permission) {
|
|
2411
|
+
this.log.trace("Skipping security check for route - no authorization header and not secure");
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
try {
|
|
2415
|
+
request.user = await this.securityProvider.createUserFromToken(request.headers.authorization, { permission });
|
|
2416
|
+
if (typeof route.secure === "object") this.check(request.user, route.secure);
|
|
2417
|
+
this.alepha.store.set("alepha.server.request.user", this.alepha.codec.decode(userAccountInfoSchema, request.user));
|
|
2418
|
+
this.log.trace("User set from request token", {
|
|
2419
|
+
user: request.user,
|
|
2420
|
+
permission
|
|
2421
|
+
});
|
|
2422
|
+
} catch (error) {
|
|
2423
|
+
if (route.secure || permission) throw error;
|
|
2424
|
+
this.log.trace("Skipping security check for route - error occurred", error);
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
});
|
|
2428
|
+
check(user, secure) {
|
|
2429
|
+
if (secure.realm) {
|
|
2430
|
+
if (user.realm !== secure.realm) throw new ForbiddenError(`User must belong to realm '${secure.realm}' to access this route`);
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
/**
|
|
2434
|
+
* Get the user account token for a local action call.
|
|
2435
|
+
* There are three possible sources for the user:
|
|
2436
|
+
* - `options.user`: the user passed in the options
|
|
2437
|
+
* - `"system"`: the system user from the state (you MUST set state `server.security.system.user`)
|
|
2438
|
+
* - `"context"`: the user from the request context (you MUST be in an HTTP request context)
|
|
2439
|
+
*
|
|
2440
|
+
* Priority order: `options.user` > `"system"` > `"context"`.
|
|
2441
|
+
*
|
|
2442
|
+
* In testing environment, if no user is provided, a test user is created based on the SecurityProvider's roles.
|
|
2443
|
+
*/
|
|
2444
|
+
createUserFromLocalFunctionContext(options, permission) {
|
|
2445
|
+
const fromOptions = typeof options.user === "object" ? options.user : void 0;
|
|
2446
|
+
const type = typeof options.user === "string" ? options.user : void 0;
|
|
2447
|
+
let user;
|
|
2448
|
+
const fromContext = this.alepha.context.get("request")?.user;
|
|
2449
|
+
const fromSystem = this.alepha.store.get("alepha.server.security.system.user");
|
|
2450
|
+
if (type === "system") user = fromSystem;
|
|
2451
|
+
else if (type === "context") user = fromContext;
|
|
2452
|
+
else user = fromOptions ?? fromContext ?? fromSystem;
|
|
2453
|
+
if (!user) {
|
|
2454
|
+
if (this.alepha.isTest() && !("user" in options)) return this.createTestUser();
|
|
2455
|
+
throw new UnauthorizedError("User is required for calling this action");
|
|
2456
|
+
}
|
|
2457
|
+
const roles = user.roles ?? (this.alepha.isTest() ? this.securityProvider.getRoles().map((role) => role.name) : []);
|
|
2458
|
+
let ownership;
|
|
2459
|
+
if (permission) {
|
|
2460
|
+
const result = this.securityProvider.checkPermission(permission, ...roles);
|
|
2461
|
+
if (!result.isAuthorized) throw new ForbiddenError(`Permission '${this.securityProvider.permissionToString(permission)}' is required for this route`);
|
|
2462
|
+
ownership = result.ownership;
|
|
2463
|
+
}
|
|
2464
|
+
return {
|
|
2465
|
+
...user,
|
|
2466
|
+
ownership
|
|
2467
|
+
};
|
|
2468
|
+
}
|
|
2469
|
+
createTestUser() {
|
|
2470
|
+
return {
|
|
2471
|
+
id: randomUUID(),
|
|
2472
|
+
name: "Test",
|
|
2473
|
+
roles: this.securityProvider.getRoles().map((role) => role.name)
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
onClientRequest = $hook({
|
|
2477
|
+
on: "client:onRequest",
|
|
2478
|
+
handler: async ({ request, options }) => {
|
|
2479
|
+
if (!this.alepha.isTest()) return;
|
|
2480
|
+
if ("user" in options && options.user === void 0) return;
|
|
2481
|
+
request.headers = new Headers(request.headers);
|
|
2482
|
+
if (!request.headers.has("authorization")) {
|
|
2483
|
+
const test = this.createTestUser();
|
|
2484
|
+
const user = typeof options?.user === "object" ? options.user : void 0;
|
|
2485
|
+
const sub = user?.id ?? test.id;
|
|
2486
|
+
const roles = user?.roles ?? test.roles;
|
|
2487
|
+
const token = await this.jwtProvider.create({
|
|
2488
|
+
sub,
|
|
2489
|
+
roles
|
|
2490
|
+
}, user?.realm ?? this.securityProvider.getRealms()[0]?.name);
|
|
2491
|
+
request.headers.set("authorization", `Bearer ${token}`);
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
});
|
|
2495
|
+
};
|
|
2496
|
+
|
|
790
2497
|
//#endregion
|
|
791
2498
|
//#region ../../src/security/errors/InvalidCredentialsError.ts
|
|
792
2499
|
/**
|
|
@@ -893,7 +2600,7 @@ const $serviceAccount = (options) => {
|
|
|
893
2600
|
return { token: async () => {
|
|
894
2601
|
const tokenFromCache = getTokenFromCache();
|
|
895
2602
|
if (tokenFromCache) return tokenFromCache;
|
|
896
|
-
const token = await options.
|
|
2603
|
+
const token = await options.issuer.createToken(options.user);
|
|
897
2604
|
cacheToken({
|
|
898
2605
|
...token,
|
|
899
2606
|
issued_at: dateTimeProvider.now().unix()
|
|
@@ -925,50 +2632,54 @@ const roleSchema = t.object({
|
|
|
925
2632
|
}))
|
|
926
2633
|
});
|
|
927
2634
|
|
|
928
|
-
//#endregion
|
|
929
|
-
//#region ../../src/security/schemas/userAccountInfoSchema.ts
|
|
930
|
-
const userAccountInfoSchema = t.object({
|
|
931
|
-
id: t.text({ description: "Unique identifier for the user." }),
|
|
932
|
-
name: t.optional(t.text({ description: "Full name of the user." })),
|
|
933
|
-
email: t.optional(t.text({
|
|
934
|
-
description: "Email address of the user.",
|
|
935
|
-
format: "email"
|
|
936
|
-
})),
|
|
937
|
-
username: t.optional(t.text({ description: "Preferred username of the user." })),
|
|
938
|
-
picture: t.optional(t.text({ description: "URL to the user's profile picture." })),
|
|
939
|
-
sessionId: t.optional(t.text({ description: "Session identifier for the user, if applicable." })),
|
|
940
|
-
organizations: t.optional(t.array(t.text(), { description: "List of organizations the user belongs to." })),
|
|
941
|
-
roles: t.optional(t.array(t.text(), { description: "List of roles assigned to the user." }))
|
|
942
|
-
});
|
|
943
|
-
|
|
944
2635
|
//#endregion
|
|
945
2636
|
//#region ../../src/security/index.ts
|
|
946
2637
|
/**
|
|
947
2638
|
* Provides comprehensive authentication and authorization capabilities with JWT tokens, role-based access control, and user management.
|
|
948
2639
|
*
|
|
949
|
-
* The security module enables building secure applications using primitives like `$
|
|
2640
|
+
* The security module enables building secure applications using primitives like `$issuer`, `$role`, and `$permission`
|
|
950
2641
|
* on class properties. It offers JWT-based authentication, fine-grained permissions, service accounts, and seamless
|
|
951
2642
|
* integration with various authentication providers and user management systems.
|
|
952
2643
|
*
|
|
953
|
-
*
|
|
2644
|
+
* When used with `AlephaServer`, this module automatically registers `ServerSecurityProvider` and `ServerBasicAuthProvider`
|
|
2645
|
+
* to protect HTTP routes and actions with JWT and Basic Auth.
|
|
2646
|
+
*
|
|
2647
|
+
* @see {@link $issuer}
|
|
954
2648
|
* @see {@link $role}
|
|
955
2649
|
* @see {@link $permission}
|
|
2650
|
+
* @see {@link $basicAuth}
|
|
956
2651
|
* @module alepha.security
|
|
957
2652
|
*/
|
|
958
2653
|
const AlephaSecurity = $module({
|
|
959
2654
|
name: "alepha.security",
|
|
960
2655
|
primitives: [
|
|
961
|
-
$
|
|
2656
|
+
$issuer,
|
|
962
2657
|
$role,
|
|
963
|
-
$permission
|
|
2658
|
+
$permission,
|
|
2659
|
+
$basicAuth
|
|
964
2660
|
],
|
|
965
2661
|
services: [
|
|
966
2662
|
SecurityProvider,
|
|
967
2663
|
JwtProvider,
|
|
968
|
-
CryptoProvider
|
|
969
|
-
|
|
2664
|
+
CryptoProvider,
|
|
2665
|
+
ServerSecurityProvider,
|
|
2666
|
+
ServerBasicAuthProvider
|
|
2667
|
+
],
|
|
2668
|
+
register: (alepha) => {
|
|
2669
|
+
alepha.with(SecurityProvider);
|
|
2670
|
+
alepha.with(JwtProvider);
|
|
2671
|
+
alepha.with(CryptoProvider);
|
|
2672
|
+
if (alepha.has(AlephaServer)) {
|
|
2673
|
+
alepha.with(ServerSecurityProvider);
|
|
2674
|
+
alepha.with(ServerBasicAuthProvider);
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
970
2677
|
});
|
|
2678
|
+
/**
|
|
2679
|
+
* @deprecated Use `AlephaSecurity` instead. Server security providers are automatically registered when `AlephaServer` is available.
|
|
2680
|
+
*/
|
|
2681
|
+
const AlephaServerSecurity = AlephaSecurity;
|
|
971
2682
|
|
|
972
2683
|
//#endregion
|
|
973
|
-
export { $
|
|
2684
|
+
export { $basicAuth, $issuer, $permission, $role, $serviceAccount, AlephaSecurity, AlephaServerSecurity, BasicAuthPrimitive, CryptoProvider, DEFAULT_APP_SECRET, InvalidCredentialsError, InvalidPermissionError, IssuerPrimitive, JwtProvider, PermissionPrimitive, RolePrimitive, SecurityError, SecurityProvider, ServerBasicAuthProvider, ServerSecurityProvider, isBasicAuth, permissionSchema, roleSchema, userAccountInfoSchema };
|
|
974
2685
|
//# sourceMappingURL=index.js.map
|