@guren/server 2.15.0 → 2.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DocsViewerServiceProvider-qFCaeiUv.js → DocsViewerServiceProvider-D2cuVgtN.js} +7 -12
- package/dist/{Hash-C8aejmi8.js → Hash-D2DFd8xX.js} +7 -57
- package/dist/{HttpException-BkS3euNG.js → HttpException-BlQ2yEmT.js} +2 -79
- package/dist/{Job-BVT813DO.js → Job-DxQK8h3P.js} +24 -179
- package/dist/{McpServiceProvider-BawsYjgN.js → McpServiceProvider-Zihx3Bjq.js} +35 -20
- package/dist/{Random-DbIJ22KQ.js → Random-S0OvCuR8.js} +9 -106
- package/dist/agent/AgentApprovalRequested.d.ts +11 -39
- package/dist/agent/approval-status.d.ts +56 -0
- package/dist/agent/approval.d.ts +76 -187
- package/dist/agent/audit-emitter.d.ts +16 -44
- package/dist/agent/audit.d.ts +20 -56
- package/dist/agent/derive.d.ts +32 -66
- package/dist/agent/dispatch.d.ts +38 -90
- package/dist/agent/events.d.ts +17 -23
- package/dist/agent/gate.d.ts +118 -0
- package/dist/agent/meta-tools.d.ts +18 -46
- package/dist/agent/pipeline.d.ts +234 -0
- package/dist/agent/public.d.ts +6 -25
- package/dist/agent/public.js +1 -1
- package/dist/agent/redact.d.ts +16 -38
- package/dist/agent/scopes.d.ts +55 -69
- package/dist/auth/AgentPrincipalGuard.d.ts +49 -0
- package/dist/auth/AuthManager.d.ts +22 -43
- package/dist/auth/AuthenticatableModel.d.ts +2 -2
- package/dist/auth/SessionGuard.d.ts +0 -1
- package/dist/auth/TokenGuard.d.ts +6 -26
- package/dist/auth/api-token.d.ts +16 -148
- package/dist/auth/context.d.ts +5 -10
- package/dist/auth/email-verification.d.ts +29 -127
- package/dist/auth/index.js +1 -1
- package/dist/auth/oauth/index.d.ts +35 -57
- package/dist/auth/password/DefaultHasher.d.ts +5 -14
- package/dist/auth/password/PasswordHasher.d.ts +5 -13
- package/dist/auth/password/hash-format.d.ts +5 -13
- package/dist/auth/password-reset.d.ts +16 -42
- package/dist/auth/providers/ModelUserProvider.d.ts +3 -4
- package/dist/auth/providers/UserProvider.d.ts +4 -4
- package/dist/auth/signed-token.d.ts +18 -0
- package/dist/auth/types.d.ts +9 -32
- package/dist/auth/utils.d.ts +6 -27
- package/dist/{auth-DkYoAPVn.js → auth-Gg54ppQi.js} +279 -519
- package/dist/authorization/Gate.d.ts +9 -145
- package/dist/authorization/Policy.d.ts +6 -53
- package/dist/authorization/index.js +1 -1
- package/dist/authorization/middleware.d.ts +16 -62
- package/dist/authorization/types.d.ts +8 -64
- package/dist/{authorization-CdfbCj8J.js → authorization-CdEWZZw3.js} +44 -309
- package/dist/broadcasting/BroadcastManager.d.ts +29 -149
- package/dist/broadcasting/channels/Channel.d.ts +1 -19
- package/dist/broadcasting/channels/PresenceChannel.d.ts +1 -55
- package/dist/broadcasting/channels/PrivateChannel.d.ts +1 -23
- package/dist/broadcasting/drivers/MemoryDriver.d.ts +18 -70
- package/dist/broadcasting/drivers/RedisDriver.d.ts +3 -80
- package/dist/broadcasting/drivers/index.d.ts +1 -1
- package/dist/broadcasting/index.d.ts +1 -1
- package/dist/broadcasting/index.js +1 -1
- package/dist/broadcasting/types.d.ts +7 -88
- package/dist/{broadcasting-BwodCA4q.js → broadcasting-B5RzB0A2.js} +87 -414
- package/dist/cache/CacheManager.d.ts +8 -62
- package/dist/cache/TaggedCache.d.ts +2 -35
- package/dist/cache/index.js +1 -1
- package/dist/cache/stores/FileStore.d.ts +2 -36
- package/dist/cache/stores/MemoryStore.d.ts +2 -26
- package/dist/cache/stores/RedisStore.d.ts +1 -29
- package/dist/cache/types.d.ts +21 -128
- package/dist/{cache-BYnZf2FR.js → cache-BOOIr324.js} +19 -198
- package/dist/client-C4TEr_Dd.js +9 -0
- package/dist/console/Command.d.ts +17 -126
- package/dist/console/ConsoleKernel.d.ts +2 -74
- package/dist/console/Input.d.ts +5 -113
- package/dist/console/Output.d.ts +3 -99
- package/dist/console/types.d.ts +3 -33
- package/dist/container/Container.d.ts +12 -103
- package/dist/container/ServiceProvider.d.ts +17 -61
- package/dist/container/bindings.d.ts +5 -26
- package/dist/container/defineModule.d.ts +16 -54
- package/dist/container/definePlugin.d.ts +12 -45
- package/dist/container/types.d.ts +2 -34
- package/dist/context-CXk_umpT.js +21 -0
- package/dist/database/Factory.d.ts +4 -57
- package/dist/database/Seeder.d.ts +8 -46
- package/dist/database/SeederRunner.d.ts +3 -33
- package/dist/database/types.d.ts +3 -24
- package/dist/discovery/AutoDiscovery.d.ts +10 -82
- package/dist/{dispatch-erOS9epZ.js → dispatch-BAwzftws.js} +32 -79
- package/dist/docs-viewer/DocsViewerServiceProvider.d.ts +2 -5
- package/dist/docs-viewer/endpoint.d.ts +5 -11
- package/dist/encryption/Encrypter.d.ts +5 -71
- package/dist/encryption/Hash.d.ts +7 -57
- package/dist/encryption/Random.d.ts +6 -99
- package/dist/encryption/index.js +3 -3
- package/dist/encryption/types.d.ts +10 -72
- package/dist/{encryption-D99Vmls3.js → encryption-uwP3Di4D.js} +9 -78
- package/dist/{endpoint-D6GIqOpe.js → endpoint-BXipU2Jj.js} +6 -12
- package/dist/endpoint-Dsw3Acvq.js +26 -0
- package/dist/errors/ExceptionHandler.d.ts +3 -90
- package/dist/errors/HttpException.d.ts +2 -79
- package/dist/errors/debug-page.d.ts +3 -17
- package/dist/errors/error-page.d.ts +1 -0
- package/dist/errors/exceptions/AuthenticationException.d.ts +2 -24
- package/dist/errors/exceptions/AuthorizationException.d.ts +1 -24
- package/dist/errors/exceptions/MethodNotAllowedException.d.ts +1 -23
- package/dist/errors/exceptions/NotFoundHttpException.d.ts +1 -27
- package/dist/errors/exceptions/ValidationException.d.ts +2 -43
- package/dist/errors/types.d.ts +1 -25
- package/dist/{errors-BgeOl_DC.js → errors-JpkcCjjn.js} +3 -41
- package/dist/events/Event.d.ts +1 -28
- package/dist/events/EventManager.d.ts +5 -107
- package/dist/events/Listener.d.ts +7 -55
- package/dist/events/builtin.d.ts +0 -24
- package/dist/events/index.js +1 -1
- package/dist/events/types.d.ts +4 -22
- package/dist/{events-aIH_bWRx.js → events-DOmAHDeP.js} +11 -191
- package/dist/facades/index.d.ts +2 -14
- package/dist/health/HealthCheck.d.ts +0 -24
- package/dist/health/HealthManager.d.ts +0 -36
- package/dist/health/checks/CacheCheck.d.ts +2 -17
- package/dist/health/checks/CustomCheck.d.ts +0 -9
- package/dist/health/checks/DatabaseCheck.d.ts +2 -17
- package/dist/health/checks/MemoryCheck.d.ts +3 -12
- package/dist/health/checks/RedisCheck.d.ts +1 -13
- package/dist/health/checks/StorageCheck.d.ts +2 -17
- package/dist/health/index.js +1 -1
- package/dist/health/types.d.ts +4 -24
- package/dist/{health-VWdWXRwh.js → health-DQSvUplL.js} +1 -76
- package/dist/hot-disposables-B5BXqaIH.js +167 -0
- package/dist/hot-reload/hot-disposables.d.ts +22 -74
- package/dist/hot-reload/testing.d.ts +4 -9
- package/dist/http/Application.d.ts +77 -205
- package/dist/http/FormRequest.d.ts +4 -55
- package/dist/http/dev-assets.d.ts +13 -31
- package/dist/http/dev-banner.d.ts +2 -5
- package/dist/http/inertia-assets.d.ts +3 -6
- package/dist/http/middleware/capabilities.d.ts +27 -50
- package/dist/http/middleware/cors.d.ts +4 -29
- package/dist/http/middleware/csp.d.ts +2 -25
- package/dist/http/middleware/csrf.d.ts +28 -95
- package/dist/http/middleware/detect-locale.d.ts +7 -27
- package/dist/http/middleware/force-https.d.ts +6 -24
- package/dist/http/middleware/host-authorization.d.ts +2 -12
- package/dist/http/middleware/index.d.ts +1 -1
- package/dist/http/middleware/loopback-guard.d.ts +15 -33
- package/dist/http/middleware/rate-limit.d.ts +29 -126
- package/dist/http/middleware/redirect-safety.d.ts +2 -20
- package/dist/http/middleware/request-id.d.ts +1 -14
- package/dist/http/middleware/request-logging.d.ts +2 -13
- package/dist/http/middleware/response-headers.d.ts +5 -13
- package/dist/http/middleware/security-headers.d.ts +2 -16
- package/dist/http/middleware/session.d.ts +15 -34
- package/dist/http/middleware/validation-errors-cookie.d.ts +7 -18
- package/dist/http/middleware/validation.d.ts +8 -63
- package/dist/http/public-assets.d.ts +11 -7
- package/dist/http/request.d.ts +32 -118
- package/dist/http/resources/CursorPaginator.d.ts +5 -64
- package/dist/http/resources/Paginator.d.ts +7 -84
- package/dist/http/resources/Resource.d.ts +9 -65
- package/dist/http/resources/ResourceCollection.d.ts +5 -39
- package/dist/http/resources/types.d.ts +10 -30
- package/dist/http/static-documents.d.ts +10 -20
- package/dist/http/validation/Validator.d.ts +25 -85
- package/dist/http/validation/rules.d.ts +48 -147
- package/dist/http/validation/types.d.ts +16 -61
- package/dist/http/vite-assets.d.ts +5 -28
- package/dist/http/vite-dev-server.d.ts +6 -9
- package/dist/http/vite-manifest.d.ts +19 -33
- package/dist/i18n/I18nManager.d.ts +12 -78
- package/dist/i18n/Translator.d.ts +3 -54
- package/dist/i18n/index.js +1 -1
- package/dist/i18n/loaders/JsonLoader.d.ts +4 -31
- package/dist/i18n/loaders/MemoryLoader.d.ts +1 -21
- package/dist/i18n/pluralization.d.ts +4 -13
- package/dist/i18n/types.d.ts +17 -69
- package/dist/{i18n-mcWi7LCd.js → i18n-Cg1aajRP.js} +31 -225
- package/dist/index.d.ts +11 -4
- package/dist/index.js +1186 -3040
- package/dist/internal/agent-preflight.d.ts +9 -21
- package/dist/internal/agent-principal.d.ts +32 -0
- package/dist/internal/request.d.ts +6 -19
- package/dist/internal/request.js +1 -1
- package/dist/internal/route-path.d.ts +9 -21
- package/dist/internal/route-path.js +9 -21
- package/dist/internal/zod-compat.d.ts +55 -122
- package/dist/internal/zod-compat.js +39 -70
- package/dist/internal/zod-json-schema.d.ts +18 -54
- package/dist/internal/zod-json-schema.js +46 -123
- package/dist/jsx-runtime.d.ts +3 -8
- package/dist/lambda/index.d.ts +17 -79
- package/dist/lambda/index.js +11 -59
- package/dist/logging/LogManager.d.ts +1 -51
- package/dist/logging/Logger.d.ts +8 -47
- package/dist/logging/channels/ConsoleChannel.d.ts +1 -3
- package/dist/logging/channels/DailyFileChannel.d.ts +1 -3
- package/dist/logging/channels/FileChannel.d.ts +1 -3
- package/dist/logging/daily-file-path.d.ts +7 -16
- package/dist/logging/index.js +1 -1
- package/dist/logging/types.d.ts +13 -45
- package/dist/{logging-B-kngi3q.js → logging-zOY1XCtq.js} +52 -141
- package/dist/{loopback-guard-D0Kc7-xc.js → loopback-guard-DT9gHF0F.js} +41 -92
- package/dist/mail/Mail.d.ts +10 -106
- package/dist/mail/MailManager.d.ts +2 -60
- package/dist/mail/index.js +1 -1
- package/dist/mail/transports/LogTransport.d.ts +1 -4
- package/dist/mail/transports/MemoryTransport.d.ts +1 -63
- package/dist/mail/transports/ResendTransport.d.ts +1 -23
- package/dist/mail/transports/SmtpTransport.d.ts +1 -31
- package/dist/mail/types.d.ts +28 -150
- package/dist/{mail-DfEfSQEr.js → mail-76DWy9lj.js} +31 -289
- package/dist/mcp/McpServiceProvider.d.ts +4 -10
- package/dist/mcp/create-mcp-server.d.ts +42 -57
- package/dist/mcp/endpoint.d.ts +12 -36
- package/dist/mcp/index.js +1 -1
- package/dist/mvc/Controller.d.ts +46 -227
- package/dist/mvc/Router.d.ts +50 -129
- package/dist/mvc/inertia/InertiaEngine.d.ts +18 -48
- package/dist/mvc/inertia/shared.d.ts +6 -19
- package/dist/mvc/mount-route.d.ts +2 -6
- package/dist/mvc/view.d.ts +1 -2
- package/dist/notifications/Notification.d.ts +8 -75
- package/dist/notifications/NotificationManager.d.ts +15 -88
- package/dist/notifications/channels/DatabaseChannel.d.ts +1 -41
- package/dist/notifications/channels/MailChannel.d.ts +2 -31
- package/dist/notifications/channels/MemoryChannel.d.ts +2 -62
- package/dist/notifications/channels/SlackChannel.d.ts +3 -48
- package/dist/notifications/index.js +1 -1
- package/dist/notifications/notifiable-type.d.ts +3 -6
- package/dist/notifications/registry.d.ts +8 -27
- package/dist/notifications/types.d.ts +16 -53
- package/dist/{notifications-BGqmUNZ8.js → notifications-okWFs9ly.js} +37 -335
- package/dist/providers/AuthServiceProvider.d.ts +1 -3
- package/dist/providers/AuthorizationServiceProvider.d.ts +2 -3
- package/dist/providers/BroadcastServiceProvider.d.ts +1 -3
- package/dist/providers/CacheServiceProvider.d.ts +1 -3
- package/dist/providers/EncryptionServiceProvider.d.ts +1 -3
- package/dist/providers/ErrorServiceProvider.d.ts +1 -4
- package/dist/providers/EventServiceProvider.d.ts +1 -3
- package/dist/providers/HealthServiceProvider.d.ts +1 -3
- package/dist/providers/I18nServiceProvider.d.ts +6 -10
- package/dist/providers/InertiaServiceProvider.d.ts +1 -4
- package/dist/providers/LogServiceProvider.d.ts +1 -3
- package/dist/providers/MailServiceProvider.d.ts +1 -3
- package/dist/providers/NotificationServiceProvider.d.ts +1 -3
- package/dist/providers/OAuthServiceProvider.d.ts +1 -3
- package/dist/providers/QueueServiceProvider.d.ts +1 -3
- package/dist/providers/SchedulingServiceProvider.d.ts +1 -3
- package/dist/providers/StorageServiceProvider.d.ts +1 -3
- package/dist/queue/FailedJobReporter.d.ts +1 -24
- package/dist/queue/Job.d.ts +12 -99
- package/dist/queue/QueueManager.d.ts +6 -57
- package/dist/queue/Worker.d.ts +4 -65
- package/dist/queue/drivers/MemoryDriver.d.ts +3 -44
- package/dist/queue/drivers/RedisDriver.d.ts +7 -65
- package/dist/queue/drivers/SqsDriver.d.ts +6 -57
- package/dist/queue/drivers/SyncDriver.d.ts +10 -13
- package/dist/queue/index.js +2 -2
- package/dist/queue/types.d.ts +10 -92
- package/dist/{queue-CXrRK85G.js → queue-CcXCjuJI.js} +32 -260
- package/dist/redis/RedisApiTokenStore.d.ts +4 -56
- package/dist/redis/RedisEmailVerificationStore.d.ts +4 -37
- package/dist/redis/RedisOAuthStateStore.d.ts +2 -10
- package/dist/redis/RedisPasswordResetStore.d.ts +4 -37
- package/dist/redis/RedisRateLimitStore.d.ts +16 -49
- package/dist/redis/RedisSessionStore.d.ts +3 -44
- package/dist/redis/client.d.ts +2 -32
- package/dist/redis/index.js +47 -232
- package/dist/redis/redis-values.d.ts +6 -12
- package/dist/redis/scan-keys.d.ts +1 -4
- package/dist/request-CLOYytGP.js +68 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.js +50 -92
- package/dist/scheduling/CronParser.d.ts +0 -29
- package/dist/scheduling/Schedule.d.ts +1 -153
- package/dist/scheduling/ScheduledTask.d.ts +0 -31
- package/dist/scheduling/Scheduler.d.ts +0 -70
- package/dist/scheduling/index.js +1 -1
- package/dist/scheduling/types.d.ts +4 -65
- package/dist/{scheduling-CPiEdtQd.js → scheduling-C6tcOtUl.js} +2 -287
- package/dist/storage/StorageManager.d.ts +0 -48
- package/dist/storage/drivers/LocalDriver.d.ts +1 -25
- package/dist/storage/drivers/MemoryDriver.d.ts +5 -35
- package/dist/storage/drivers/S3Driver.d.ts +6 -36
- package/dist/storage/drivers/s3-acl.d.ts +5 -10
- package/dist/storage/index.js +1 -1
- package/dist/storage/types.d.ts +27 -265
- package/dist/{storage-TLD9t0Q2.js → storage-BB59f07j.js} +17 -157
- package/dist/support/contained-path.d.ts +10 -20
- package/dist/support/error-polyfill.d.ts +4 -6
- package/dist/support/expiry.d.ts +17 -33
- package/dist/support/expiry.js +17 -33
- package/dist/support/import-map.d.ts +3 -7
- package/dist/support/inertia-defaults.d.ts +5 -10
- package/dist/support/redirect-target.d.ts +4 -6
- package/dist/support/stack-frames.d.ts +11 -50
- package/dist/support/trim-slashes.d.ts +4 -7
- package/dist/support/warn-once.d.ts +2 -6
- package/dist/{trim-slashes-ZJ_VsY5s.js → trim-slashes-BLY9hKAa.js} +4 -7
- package/dist/{vite-manifest-w_RSOvQW.js → vite-manifest-B_Iy5183.js} +34 -58
- package/package.json +2 -2
- package/dist/client-Dd7vLcqp.js +0 -27
- package/dist/context-DoD0c7J_.js +0 -26
- package/dist/endpoint-D-20PiHY.js +0 -46
- package/dist/hot-disposables-WsTX2ySN.js +0 -281
- package/dist/request-CVQwpu2J.js +0 -129
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as HttpException } from "./HttpException-
|
|
1
|
+
import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
|
|
2
2
|
import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
|
|
3
|
-
import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-
|
|
3
|
+
import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
|
|
4
4
|
import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
|
|
5
|
-
import { n as getAuthContext } from "./context-
|
|
5
|
+
import { n as getAuthContext } from "./context-CXk_umpT.js";
|
|
6
6
|
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
7
7
|
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
8
8
|
import { Model } from "@guren/orm";
|
|
@@ -121,10 +121,9 @@ var SessionImpl = class {
|
|
|
121
121
|
this.dirty = true;
|
|
122
122
|
}
|
|
123
123
|
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
* every request carrying a session would persist unconditionally.
|
|
124
|
+
* Called at the start of each request by the session middleware. Only dirties
|
|
125
|
+
* the session when there was flash data to age, or every request carrying a
|
|
126
|
+
* session would persist unconditionally.
|
|
128
127
|
*/
|
|
129
128
|
ageFlashData() {
|
|
130
129
|
const hadFlash = this.hasFlash();
|
|
@@ -245,9 +244,7 @@ function createSessionMiddleware(options = {}) {
|
|
|
245
244
|
sameSite: cookieSameSite,
|
|
246
245
|
httpOnly: cookieHttpOnly
|
|
247
246
|
});
|
|
248
|
-
|
|
249
|
-
}
|
|
250
|
-
if (!session.shouldPersist()) {
|
|
247
|
+
} else if (!session.shouldPersist()) {
|
|
251
248
|
if (existingId) {
|
|
252
249
|
if (store.touch) await store.touch(existingId, ttlSeconds);
|
|
253
250
|
else await store.write(existingId, session.snapshot(), ttlSeconds);
|
|
@@ -260,19 +257,19 @@ function createSessionMiddleware(options = {}) {
|
|
|
260
257
|
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
261
258
|
});
|
|
262
259
|
}
|
|
263
|
-
|
|
260
|
+
} else {
|
|
261
|
+
const nextId = session.id;
|
|
262
|
+
await store.write(nextId, session.snapshot(), ttlSeconds);
|
|
263
|
+
if (session.wasRegenerated() && session.originalSessionId() !== nextId) await store.destroy(session.originalSessionId());
|
|
264
|
+
setCookie(ctx, cookieName, signer.sign(nextId), {
|
|
265
|
+
path: cookiePath,
|
|
266
|
+
domain: cookieDomain,
|
|
267
|
+
secure: cookieSecure,
|
|
268
|
+
sameSite: cookieSameSite,
|
|
269
|
+
httpOnly: cookieHttpOnly,
|
|
270
|
+
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
271
|
+
});
|
|
264
272
|
}
|
|
265
|
-
const nextId = session.id;
|
|
266
|
-
await store.write(nextId, session.snapshot(), ttlSeconds);
|
|
267
|
-
if (session.wasRegenerated() && session.originalSessionId() !== nextId) await store.destroy(session.originalSessionId());
|
|
268
|
-
setCookie(ctx, cookieName, signer.sign(nextId), {
|
|
269
|
-
path: cookiePath,
|
|
270
|
-
domain: cookieDomain,
|
|
271
|
-
secure: cookieSecure,
|
|
272
|
-
sameSite: cookieSameSite,
|
|
273
|
-
httpOnly: cookieHttpOnly,
|
|
274
|
-
maxAge: cookieMaxAgeSeconds ?? ttlSeconds
|
|
275
|
-
});
|
|
276
273
|
}
|
|
277
274
|
};
|
|
278
275
|
}
|
|
@@ -280,27 +277,108 @@ function getSessionFromContext(ctx) {
|
|
|
280
277
|
return ctx.get(SESSION_CONTEXT_KEY);
|
|
281
278
|
}
|
|
282
279
|
//#endregion
|
|
283
|
-
//#region src/
|
|
280
|
+
//#region src/internal/agent-principal.ts
|
|
281
|
+
const installed = /* @__PURE__ */ new WeakMap();
|
|
284
282
|
/**
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
* ```typescript
|
|
291
|
-
* throw new AuthenticationException()
|
|
292
|
-
* throw new AuthenticationException('Invalid token')
|
|
293
|
-
* throw new AuthenticationException('Session expired', 'login')
|
|
294
|
-
* ```
|
|
283
|
+
* Mark `request` as carrying `principal`, returning that same object — a copy
|
|
284
|
+
* would key the map on something the auth context never sees. Returning it is
|
|
285
|
+
* what makes the identity requirement hard to get wrong at a call site:
|
|
286
|
+
* `app.fetch(installAgentPrincipal(request, installed), env, ctx)`. Callers
|
|
287
|
+
* reach this through the pipeline's `handoff: 'seam'`, and the reader not at all.
|
|
295
288
|
*/
|
|
296
|
-
|
|
289
|
+
function installAgentPrincipal(request, value) {
|
|
290
|
+
installed.set(request, value);
|
|
291
|
+
return request;
|
|
292
|
+
}
|
|
293
|
+
/** The principal installed on this exact request object, or `undefined`. */
|
|
294
|
+
function readAgentPrincipal(request) {
|
|
295
|
+
return installed.get(request);
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/auth/providers/UserProvider.ts
|
|
299
|
+
/**
|
|
300
|
+
* Run a user record through the provider's optional `sanitize` before it leaves
|
|
301
|
+
* the auth layer. Every guard must call this on anything it returns from
|
|
302
|
+
* `user()` — a guard that forgets the ternary leaks password hashes, so the
|
|
303
|
+
* ternary lives here, once.
|
|
304
|
+
*/
|
|
305
|
+
function sanitizeUser(provider, user) {
|
|
306
|
+
return provider.sanitize ? provider.sanitize(user) : user;
|
|
307
|
+
}
|
|
308
|
+
var BaseUserProvider = class {
|
|
309
|
+
async setRememberToken(user, token) {
|
|
310
|
+
if (typeof user.setRememberToken === "function") await user.setRememberToken(token);
|
|
311
|
+
}
|
|
312
|
+
async getRememberToken(user) {
|
|
313
|
+
if (typeof user.getRememberToken === "function") return await user.getRememberToken() ?? null;
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/auth/AgentPrincipalGuard.ts
|
|
319
|
+
/**
|
|
320
|
+
* The guard answering for a principal the pipeline installed (RFC 0017 §2), for
|
|
321
|
+
* an **unqualified** lookup on a seam-marked request; explicit `guard('web')` /
|
|
322
|
+
* `guard('token')` is untouched, and `guardNames()` never lists this one. It
|
|
323
|
+
* satisfies `requireAuthenticated()`, `Controller.auth` and `Gate`, but not
|
|
324
|
+
* `createBearerTokenMiddleware` / `tokenCan*`, which judge an `ApiToken`.
|
|
325
|
+
*/
|
|
326
|
+
var AgentPrincipalGuard = class {
|
|
327
|
+
installed;
|
|
328
|
+
provider;
|
|
329
|
+
resolvedUser;
|
|
330
|
+
constructor(options) {
|
|
331
|
+
this.installed = options.installed;
|
|
332
|
+
this.provider = options.provider;
|
|
333
|
+
}
|
|
297
334
|
/**
|
|
298
|
-
*
|
|
335
|
+
* `user() !== null`, the predicate `TokenGuard` answers `check()` with: true
|
|
336
|
+
* in every case but one, a `kind: 'user'` principal a configured provider
|
|
337
|
+
* cannot resolve. Answering true there would admit a request whose
|
|
338
|
+
* `Controller.auth.userOrFail()` then throws.
|
|
299
339
|
*/
|
|
300
|
-
|
|
340
|
+
async check() {
|
|
341
|
+
return await this.user() !== null;
|
|
342
|
+
}
|
|
343
|
+
async guest() {
|
|
344
|
+
return !await this.check();
|
|
345
|
+
}
|
|
301
346
|
/**
|
|
302
|
-
*
|
|
347
|
+
* `kind: 'service'` is always the minimal `{ id }`: a service principal names
|
|
348
|
+
* no user, so a lookup would resolve an id in a table it does not belong to.
|
|
349
|
+
* `kind: 'user'` goes through the provider when one is configured.
|
|
303
350
|
*/
|
|
351
|
+
user() {
|
|
352
|
+
if (!this.resolvedUser) this.resolvedUser = (async () => {
|
|
353
|
+
const { principal } = this.installed;
|
|
354
|
+
if (principal.kind !== "user" || !this.provider) return { id: principal.id };
|
|
355
|
+
const record = await this.provider.retrieveById(principal.id);
|
|
356
|
+
return record ? sanitizeUser(this.provider, record) : null;
|
|
357
|
+
})();
|
|
358
|
+
return this.resolvedUser;
|
|
359
|
+
}
|
|
360
|
+
async id() {
|
|
361
|
+
return this.installed.principal.id;
|
|
362
|
+
}
|
|
363
|
+
async login() {
|
|
364
|
+
throw new Error("The agent principal guard does not support login(); the principal is installed by the invocation pipeline for one request.");
|
|
365
|
+
}
|
|
366
|
+
async attempt(_credentials, _remember) {
|
|
367
|
+
throw new Error("The agent principal guard does not support attempt(); an installed principal is not credential-based.");
|
|
368
|
+
}
|
|
369
|
+
async validate(_credentials) {
|
|
370
|
+
throw new Error("The agent principal guard does not support validate(); an installed principal is not credential-based.");
|
|
371
|
+
}
|
|
372
|
+
/** Nothing to end: no session, and no stored credential to revoke. */
|
|
373
|
+
async logout() {}
|
|
374
|
+
session() {}
|
|
375
|
+
};
|
|
376
|
+
//#endregion
|
|
377
|
+
//#region src/errors/exceptions/AuthenticationException.ts
|
|
378
|
+
/** 401: the user is not authenticated, or the credentials were invalid. */
|
|
379
|
+
var AuthenticationException = class AuthenticationException extends HttpException {
|
|
380
|
+
/** The guard that threw. */
|
|
381
|
+
guard;
|
|
304
382
|
redirectTo;
|
|
305
383
|
constructor(message = "Unauthenticated.", guard, redirectTo) {
|
|
306
384
|
super(401, message);
|
|
@@ -308,15 +386,9 @@ var AuthenticationException = class AuthenticationException extends HttpExceptio
|
|
|
308
386
|
this.guard = guard;
|
|
309
387
|
this.redirectTo = redirectTo;
|
|
310
388
|
}
|
|
311
|
-
/**
|
|
312
|
-
* Create exception with redirect URL.
|
|
313
|
-
*/
|
|
314
389
|
static withRedirect(redirectTo, message) {
|
|
315
390
|
return new AuthenticationException(message, void 0, redirectTo);
|
|
316
391
|
}
|
|
317
|
-
/**
|
|
318
|
-
* Create exception for a specific guard.
|
|
319
|
-
*/
|
|
320
392
|
static forGuard(guard, message) {
|
|
321
393
|
return new AuthenticationException(message, guard);
|
|
322
394
|
}
|
|
@@ -372,16 +444,10 @@ var RequestAuthContext = class {
|
|
|
372
444
|
};
|
|
373
445
|
/**
|
|
374
446
|
* Prefixes of every hash format the built-in hashers produce: Bun's argon2
|
|
375
|
-
* family
|
|
376
|
-
*
|
|
377
|
-
*
|
|
378
|
-
*
|
|
379
|
-
* be a password hash at all", which is all the argument-order check below
|
|
380
|
-
* needs; whether the hash is well-formed stays the implementation's job.
|
|
381
|
-
*
|
|
382
|
-
* Full prefixes rather than the `$argon2` / `$2` stems they share: a password
|
|
383
|
-
* of `$2fast4u` is not bcrypt, and treating it as one turns a correct call
|
|
384
|
-
* against a non-hash credential column into a false accusation.
|
|
447
|
+
* family, bcrypt, and the Node fallback's scrypt. A *shape* test, not a
|
|
448
|
+
* validity test. Full prefixes rather than the shared `$argon2` / `$2` stems:
|
|
449
|
+
* a password of `$2fast4u` is not bcrypt, and treating it as one turns a
|
|
450
|
+
* correct call into a false accusation.
|
|
385
451
|
*/
|
|
386
452
|
const HASH_PREFIXES = [
|
|
387
453
|
"$argon2id$",
|
|
@@ -396,19 +462,11 @@ function looksLikePasswordHash(value) {
|
|
|
396
462
|
return HASH_PREFIXES.some((prefix) => value.startsWith(prefix));
|
|
397
463
|
}
|
|
398
464
|
/**
|
|
399
|
-
* Throws when `verify()` was called as `verify(plain, hashed)`.
|
|
400
|
-
*
|
|
401
|
-
*
|
|
402
|
-
*
|
|
403
|
-
*
|
|
404
|
-
* credential column - `passwordHash: 'oauth:...'`, the sentinel this repo
|
|
405
|
-
* documents for OAuth-only accounts - as a caller mistake. Those keep falling
|
|
406
|
-
* through to the implementation, which rejects them as before.
|
|
407
|
-
*
|
|
408
|
-
* Neither argument is included in the message: one of them is a plaintext
|
|
409
|
-
* password, and this throw is reached on a live login attempt.
|
|
410
|
-
*
|
|
411
|
-
* See `PasswordHasher.verify` for why the order is easy to get wrong.
|
|
465
|
+
* Throws when `verify()` was called as `verify(plain, hashed)`. Two-sided on
|
|
466
|
+
* purpose: fires only when the second argument looks like a hash *and* the
|
|
467
|
+
* first does not, so a legitimate non-hash credential column
|
|
468
|
+
* (`passwordHash: 'oauth:...'`) is not misdiagnosed as a caller mistake.
|
|
469
|
+
* Neither argument is in the message: one is a plaintext password on a live login.
|
|
412
470
|
*/
|
|
413
471
|
function assertVerifyArgumentOrder(hashed, plain) {
|
|
414
472
|
if (!looksLikePasswordHash(hashed) && looksLikePasswordHash(plain)) throw new TypeError("PasswordHasher.verify(hashed, plain) received its arguments in the wrong order: the second argument looks like a password hash and the first does not. Note this order is the inverse of Bun.password.verify(plain, hashed) and of verifyPassword(plain, hashed).");
|
|
@@ -496,20 +554,11 @@ var NodeHasher = class {
|
|
|
496
554
|
//#endregion
|
|
497
555
|
//#region src/auth/password/DefaultHasher.ts
|
|
498
556
|
/**
|
|
499
|
-
* Runtime-detecting password hasher
|
|
500
|
-
*
|
|
501
|
-
* `crypto.scrypt` otherwise
|
|
502
|
-
* the
|
|
503
|
-
*
|
|
504
|
-
*
|
|
505
|
-
* **Verification routes on the stored hash, not on the runtime.** The two
|
|
506
|
-
* delegates write different formats, and neither can read the other's, so
|
|
507
|
-
* picking a delegate by runtime alone would 500 on every login for an app
|
|
508
|
-
* whose password column was written elsewhere - a seeder run on Bun against a
|
|
509
|
-
* database a Node deploy then serves. Bun implements `node:crypto`, so a
|
|
510
|
-
* `$scrypt$` hash verifies on either runtime; an Argon2id or bcrypt hash needs
|
|
511
|
-
* `Bun.password` and cannot be read off Bun at all, which this reports as
|
|
512
|
-
* itself rather than as an opaque parse failure.
|
|
557
|
+
* Runtime-detecting password hasher behind `Hash`, the default for
|
|
558
|
+
* `AuthenticatableModel` and `ModelUserProvider`: `Bun.password` on Bun (Argon2id,
|
|
559
|
+
* despite `ScryptHasher`'s name), `crypto.scrypt` otherwise. **Verification routes
|
|
560
|
+
* on the stored hash, not the runtime**, or a column written elsewhere would 500 on
|
|
561
|
+
* every login; `$scrypt$` verifies anywhere, Argon2id/bcrypt needs `Bun.password`.
|
|
513
562
|
*/
|
|
514
563
|
var DefaultHasher = class {
|
|
515
564
|
bun;
|
|
@@ -538,26 +587,6 @@ var DefaultHasher = class {
|
|
|
538
587
|
}
|
|
539
588
|
};
|
|
540
589
|
//#endregion
|
|
541
|
-
//#region src/auth/providers/UserProvider.ts
|
|
542
|
-
/**
|
|
543
|
-
* Run a user record through the provider's optional `sanitize` before it
|
|
544
|
-
* leaves the auth layer. Every guard must call this on anything it returns
|
|
545
|
-
* from `user()` — a guard that forgets the optional-chaining ternary leaks
|
|
546
|
-
* password hashes, so the ternary lives here, once.
|
|
547
|
-
*/
|
|
548
|
-
function sanitizeUser(provider, user) {
|
|
549
|
-
return provider.sanitize ? provider.sanitize(user) : user;
|
|
550
|
-
}
|
|
551
|
-
var BaseUserProvider = class {
|
|
552
|
-
async setRememberToken(user, token) {
|
|
553
|
-
if (typeof user.setRememberToken === "function") await user.setRememberToken(token);
|
|
554
|
-
}
|
|
555
|
-
async getRememberToken(user) {
|
|
556
|
-
if (typeof user.getRememberToken === "function") return await user.getRememberToken() ?? null;
|
|
557
|
-
return null;
|
|
558
|
-
}
|
|
559
|
-
};
|
|
560
|
-
//#endregion
|
|
561
590
|
//#region src/auth/providers/ModelUserProvider.ts
|
|
562
591
|
/**
|
|
563
592
|
* Capability check, not `instanceof AuthenticatableModel`: a nominal check
|
|
@@ -622,10 +651,9 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
622
651
|
return user[this.idColumn];
|
|
623
652
|
}
|
|
624
653
|
/**
|
|
625
|
-
* Strip the password hash, remember token, and the model's `hidden`
|
|
626
|
-
*
|
|
627
|
-
*
|
|
628
|
-
* never affects login — only what `auth.user()` exposes.
|
|
654
|
+
* Strip the password hash, remember token, and the model's `hidden` fields
|
|
655
|
+
* before the record leaves the auth layer. Credential validation runs on the
|
|
656
|
+
* raw record first, so this never affects login — only `auth.user()`.
|
|
629
657
|
*/
|
|
630
658
|
sanitize(user) {
|
|
631
659
|
const authModel = credentialColumnSource(this.model);
|
|
@@ -653,33 +681,21 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
653
681
|
};
|
|
654
682
|
//#endregion
|
|
655
683
|
//#region src/auth/utils.ts
|
|
656
|
-
/**
|
|
657
|
-
* Hash a token using SHA-256 or SHA-512.
|
|
658
|
-
*/
|
|
659
684
|
function hashToken(token, algorithm = "sha256") {
|
|
660
685
|
return createHash(algorithm).update(token).digest("hex");
|
|
661
686
|
}
|
|
662
|
-
/**
|
|
663
|
-
* Generate a secure random token.
|
|
664
|
-
*/
|
|
665
687
|
function generateToken(length = 32) {
|
|
666
688
|
return randomBytes(length).toString("hex");
|
|
667
689
|
}
|
|
668
|
-
/**
|
|
669
|
-
* Generate a random ID (16 bytes = 32 hex chars).
|
|
670
|
-
*/
|
|
690
|
+
/** Generate a random ID (16 bytes = 32 hex chars). */
|
|
671
691
|
function generateId() {
|
|
672
692
|
return randomBytes(16).toString("hex");
|
|
673
693
|
}
|
|
674
694
|
/**
|
|
675
|
-
*
|
|
676
|
-
*
|
|
677
|
-
*
|
|
678
|
-
*
|
|
679
|
-
* 'yyyy' both decode to nothing — and 'abcz' and 'abdz' both decode to the
|
|
680
|
-
* one byte they share — and would compare equal. A short decode is how the
|
|
681
|
-
* decoder reports that, which beats restating its grammar in a regex here.
|
|
682
|
-
* Use `secureStringCompare` for values that are not hex.
|
|
695
|
+
* Timing-safe comparison of two hex strings. Non-hex or odd-length input is
|
|
696
|
+
* rejected rather than compared: `Buffer.from(x, 'hex')` stops at the first
|
|
697
|
+
* invalid pair, so 'zzzz' and 'yyyy' would both decode to nothing and compare
|
|
698
|
+
* equal. Use `secureStringCompare` for values that are not hex.
|
|
683
699
|
*/
|
|
684
700
|
function secureCompare(a, b) {
|
|
685
701
|
if (a.length !== b.length) return false;
|
|
@@ -688,28 +704,19 @@ function secureCompare(a, b) {
|
|
|
688
704
|
if (bufA.length !== a.length / 2 || bufB.length !== b.length / 2) return false;
|
|
689
705
|
return timingSafeEqual(bufA, bufB);
|
|
690
706
|
}
|
|
691
|
-
/**
|
|
692
|
-
* Securely compare two arbitrary strings using timing-safe comparison.
|
|
693
|
-
* Unlike secureCompare, this works with any string encoding (UUIDs, tokens, etc.).
|
|
694
|
-
*/
|
|
707
|
+
/** Timing-safe comparison for arbitrary strings — unlike secureCompare, not hex-only. */
|
|
695
708
|
function secureStringCompare(a, b) {
|
|
696
709
|
const bufA = Buffer.from(a, "utf8");
|
|
697
710
|
const bufB = Buffer.from(b, "utf8");
|
|
698
711
|
if (bufA.length !== bufB.length) return false;
|
|
699
712
|
return timingSafeEqual(bufA, bufB);
|
|
700
713
|
}
|
|
701
|
-
/**
|
|
702
|
-
* Build a URL with token and optional email parameters.
|
|
703
|
-
*/
|
|
704
714
|
function buildTokenUrl(baseUrl, token, email) {
|
|
705
715
|
const url = new URL(baseUrl);
|
|
706
716
|
url.searchParams.set("token", token);
|
|
707
717
|
if (email) url.searchParams.set("email", email);
|
|
708
718
|
return url.toString();
|
|
709
719
|
}
|
|
710
|
-
/**
|
|
711
|
-
* Parse a URL to extract token and email parameters.
|
|
712
|
-
*/
|
|
713
720
|
function parseTokenUrl(url) {
|
|
714
721
|
try {
|
|
715
722
|
const parsed = new URL(url);
|
|
@@ -765,7 +772,6 @@ var SessionGuard = class {
|
|
|
765
772
|
this.cachedUser = sanitized;
|
|
766
773
|
return sanitized;
|
|
767
774
|
}
|
|
768
|
-
/** Strip auth-internal fields before a record is cached or exposed. */
|
|
769
775
|
sanitizeUser(user) {
|
|
770
776
|
return sanitizeUser(this.provider, user);
|
|
771
777
|
}
|
|
@@ -889,35 +895,16 @@ var MemoryApiTokenStore = class {
|
|
|
889
895
|
const token = this.tokens.get(id);
|
|
890
896
|
if (token) token.lastUsedAt = timestamp;
|
|
891
897
|
}
|
|
892
|
-
/**
|
|
893
|
-
* Clear all tokens (useful for testing).
|
|
894
|
-
*/
|
|
895
898
|
clear() {
|
|
896
899
|
this.tokens.clear();
|
|
897
900
|
this.byHash.clear();
|
|
898
901
|
}
|
|
899
|
-
/**
|
|
900
|
-
* Get the number of stored tokens.
|
|
901
|
-
*/
|
|
902
902
|
get size() {
|
|
903
903
|
return this.tokens.size;
|
|
904
904
|
}
|
|
905
905
|
};
|
|
906
906
|
/**
|
|
907
907
|
* Create a new API token.
|
|
908
|
-
*
|
|
909
|
-
* @example
|
|
910
|
-
* ```ts
|
|
911
|
-
* const { plainTextToken, token } = await createApiToken(store, {
|
|
912
|
-
* name: 'My App Token',
|
|
913
|
-
* userId: user.id,
|
|
914
|
-
* abilities: ['read', 'write'],
|
|
915
|
-
* expiresIn: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
916
|
-
* })
|
|
917
|
-
*
|
|
918
|
-
* // Return plainTextToken to user - this is the only time it's available
|
|
919
|
-
* return ctx.json({ token: plainTextToken })
|
|
920
|
-
* ```
|
|
921
908
|
*/
|
|
922
909
|
async function createApiToken(store, options) {
|
|
923
910
|
const { name, userId, abilities = ["*"], expiresIn = null, tokenLength = 32 } = options;
|
|
@@ -955,39 +942,27 @@ function parseApiToken(plainTextToken) {
|
|
|
955
942
|
};
|
|
956
943
|
}
|
|
957
944
|
/**
|
|
958
|
-
* Extract the bearer token from an Authorization header
|
|
959
|
-
*
|
|
960
|
-
* `
|
|
961
|
-
*
|
|
945
|
+
* Extract the bearer token from an Authorization header. The one parsing rule
|
|
946
|
+
* shared by `createBearerTokenMiddleware`, `TokenGuard` and `hasBearerHeader`.
|
|
947
|
+
* `\S` keeps the match linear — `\s+(.+)` backtracks quadratically when a
|
|
948
|
+
* trailing newline makes `$` unreachable, on a pre-authentication header — and
|
|
949
|
+
* makes an all-whitespace token "not a bearer request", so CSRF is not skipped.
|
|
962
950
|
*/
|
|
963
951
|
function readBearerToken(header) {
|
|
964
952
|
if (!header) return null;
|
|
965
|
-
const match = header.match(/^Bearer\s+(
|
|
953
|
+
const match = header.match(/^Bearer\s+(\S.*)$/i);
|
|
966
954
|
return match ? match[1] : null;
|
|
967
955
|
}
|
|
968
956
|
/**
|
|
969
|
-
* The one answer to "is this request bearer-authenticated?"
|
|
970
|
-
*
|
|
971
|
-
*
|
|
972
|
-
* requests: both must classify a request identically, and a second copy of
|
|
973
|
-
* the header name is how they would drift apart.
|
|
957
|
+
* The one answer to "is this request bearer-authenticated?", shared by
|
|
958
|
+
* `AuthManager.resolveGuardName` and the CSRF skip for cookie-less bearer
|
|
959
|
+
* requests, which must classify a request identically.
|
|
974
960
|
*/
|
|
975
961
|
function hasBearerHeader(ctx) {
|
|
976
962
|
return readBearerToken(ctx.req.header("Authorization")) !== null;
|
|
977
963
|
}
|
|
978
964
|
/**
|
|
979
965
|
* Verify an API token and return the associated user ID.
|
|
980
|
-
*
|
|
981
|
-
* @example
|
|
982
|
-
* ```ts
|
|
983
|
-
* const result = await verifyApiToken(plainTextToken, store)
|
|
984
|
-
*
|
|
985
|
-
* if (!result) {
|
|
986
|
-
* return ctx.json({ error: 'Invalid token' }, 401)
|
|
987
|
-
* }
|
|
988
|
-
*
|
|
989
|
-
* console.log(`User ${result.userId} authenticated with abilities:`, result.abilities)
|
|
990
|
-
* ```
|
|
991
966
|
*/
|
|
992
967
|
async function verifyApiToken(plainTextToken, store, options = {}) {
|
|
993
968
|
const { updateLastUsed = true } = options;
|
|
@@ -1029,35 +1004,18 @@ function tokenCanAny(token, abilities) {
|
|
|
1029
1004
|
}
|
|
1030
1005
|
/**
|
|
1031
1006
|
* Revoke (delete) an API token.
|
|
1032
|
-
*
|
|
1033
|
-
* @example
|
|
1034
|
-
* ```ts
|
|
1035
|
-
* await revokeApiToken(tokenId, store)
|
|
1036
|
-
* ```
|
|
1037
1007
|
*/
|
|
1038
1008
|
async function revokeApiToken(id, store) {
|
|
1039
1009
|
await store.delete(id);
|
|
1040
1010
|
}
|
|
1041
1011
|
/**
|
|
1042
1012
|
* Revoke all API tokens for a user.
|
|
1043
|
-
*
|
|
1044
|
-
* @example
|
|
1045
|
-
* ```ts
|
|
1046
|
-
* // Revoke all tokens when user changes password
|
|
1047
|
-
* await revokeAllApiTokens(user.id, store)
|
|
1048
|
-
* ```
|
|
1049
1013
|
*/
|
|
1050
1014
|
async function revokeAllApiTokens(userId, store) {
|
|
1051
1015
|
await store.deleteForUser(userId);
|
|
1052
1016
|
}
|
|
1053
1017
|
/**
|
|
1054
1018
|
* Get all API tokens for a user.
|
|
1055
|
-
*
|
|
1056
|
-
* @example
|
|
1057
|
-
* ```ts
|
|
1058
|
-
* const tokens = await getUserApiTokens(user.id, store)
|
|
1059
|
-
* // Returns tokens without the plain text (only metadata)
|
|
1060
|
-
* ```
|
|
1061
1019
|
*/
|
|
1062
1020
|
async function getUserApiTokens(userId, store) {
|
|
1063
1021
|
return store.findByUserId(userId);
|
|
@@ -1068,25 +1026,9 @@ async function getUserApiTokens(userId, store) {
|
|
|
1068
1026
|
const API_TOKEN_KEY = "guren:api-token";
|
|
1069
1027
|
/**
|
|
1070
1028
|
* Create middleware that authenticates requests using Bearer tokens.
|
|
1071
|
-
*
|
|
1072
1029
|
* @example
|
|
1073
1030
|
* ```ts
|
|
1074
|
-
*
|
|
1075
|
-
* app.use('/api/*', createBearerTokenMiddleware({ store }))
|
|
1076
|
-
*
|
|
1077
|
-
* // With ability requirement
|
|
1078
|
-
* router.delete('/api/posts/:id', [PostController, 'destroy'],
|
|
1079
|
-
* createBearerTokenMiddleware({
|
|
1080
|
-
* store,
|
|
1081
|
-
* abilities: ['posts:delete'],
|
|
1082
|
-
* })
|
|
1083
|
-
* )
|
|
1084
|
-
*
|
|
1085
|
-
* // With user loading
|
|
1086
|
-
* app.use('/api/*', createBearerTokenMiddleware({
|
|
1087
|
-
* store,
|
|
1088
|
-
* loadUser: async (userId) => User.find(userId),
|
|
1089
|
-
* }))
|
|
1031
|
+
* app.use('/api/*', createBearerTokenMiddleware({ store, abilities: ['posts:delete'] }))
|
|
1090
1032
|
* ```
|
|
1091
1033
|
*/
|
|
1092
1034
|
function createBearerTokenMiddleware(options) {
|
|
@@ -1126,14 +1068,6 @@ function createBearerTokenMiddleware(options) {
|
|
|
1126
1068
|
}
|
|
1127
1069
|
/**
|
|
1128
1070
|
* Get the authenticated API token from the request context.
|
|
1129
|
-
*
|
|
1130
|
-
* @example
|
|
1131
|
-
* ```ts
|
|
1132
|
-
* router.get('/api/me', async (ctx) => {
|
|
1133
|
-
* const { token, userId, abilities } = getApiToken(ctx)!
|
|
1134
|
-
* return ctx.json({ userId, tokenName: token.name, abilities })
|
|
1135
|
-
* })
|
|
1136
|
-
* ```
|
|
1137
1071
|
*/
|
|
1138
1072
|
function getApiToken(ctx) {
|
|
1139
1073
|
return ctx.get(API_TOKEN_KEY);
|
|
@@ -1142,14 +1076,6 @@ function getApiToken(ctx) {
|
|
|
1142
1076
|
* Get the authenticated API token from the request context, or throw.
|
|
1143
1077
|
*
|
|
1144
1078
|
* @throws {AuthenticationException} When no token is present in the context.
|
|
1145
|
-
*
|
|
1146
|
-
* @example
|
|
1147
|
-
* ```ts
|
|
1148
|
-
* router.get('/api/me', async (ctx) => {
|
|
1149
|
-
* const { token, userId, abilities } = getApiTokenOrFail(ctx)
|
|
1150
|
-
* return ctx.json({ userId, tokenName: token.name, abilities })
|
|
1151
|
-
* })
|
|
1152
|
-
* ```
|
|
1153
1079
|
*/
|
|
1154
1080
|
function getApiTokenOrFail(ctx) {
|
|
1155
1081
|
const result = getApiToken(ctx);
|
|
@@ -1159,28 +1085,10 @@ function getApiTokenOrFail(ctx) {
|
|
|
1159
1085
|
//#endregion
|
|
1160
1086
|
//#region src/auth/TokenGuard.ts
|
|
1161
1087
|
/**
|
|
1162
|
-
* Bearer-token
|
|
1163
|
-
*
|
|
1164
|
-
*
|
|
1165
|
-
*
|
|
1166
|
-
* SessionGuard implements — so `requireAuthenticated()`, `Controller.auth`,
|
|
1167
|
-
* and Gate resolution treat session- and token-authenticated requests
|
|
1168
|
-
* identically. On successful verification the result is also written to
|
|
1169
|
-
* `ctx[API_TOKEN_KEY]`, keeping `getApiToken(ctx)` and `tokenCan*` working
|
|
1170
|
-
* exactly as they do behind `createBearerTokenMiddleware` — and when that
|
|
1171
|
-
* middleware already verified this request's token, the guard reuses its
|
|
1172
|
-
* result instead of paying a second store read and lastUsedAt write.
|
|
1173
|
-
*
|
|
1174
|
-
* Credential flows do not apply to bearer tokens: `attempt()`, `login()` and
|
|
1175
|
-
* `validate()` throw. `logout()` is not a no-op — it revokes the presented
|
|
1176
|
-
* token, the closest meaningful analogue to ending a session. On a request
|
|
1177
|
-
* that carries a session cookie *and* a Bearer header, only the token is
|
|
1178
|
-
* revoked; end the session explicitly via `auth.guard('web').logout()`.
|
|
1179
|
-
*
|
|
1180
|
-
* This guard answers authentication only. Token *abilities* are not
|
|
1181
|
-
* consulted here or by Gate/policies — enforce them where the operation is
|
|
1182
|
-
* dispatched (`tokenCan*`, `createBearerTokenMiddleware({ abilities })`, or
|
|
1183
|
-
* the RFC 0016 scope gate), per the RFC's scope-before-policy layering.
|
|
1088
|
+
* Bearer-token Guard (RFC 0016 Phase 0). Credential flows (`attempt`,
|
|
1089
|
+
* `login`, `validate`) throw; `logout()` revokes the presented token and
|
|
1090
|
+
* leaves a co-present session alone. Answers authentication only — token
|
|
1091
|
+
* abilities are enforced elsewhere (`tokenCan*`, the RFC 0016 scope gate).
|
|
1184
1092
|
*/
|
|
1185
1093
|
var TokenGuard = class {
|
|
1186
1094
|
ctx;
|
|
@@ -1248,6 +1156,14 @@ var TokenGuard = class {
|
|
|
1248
1156
|
//#endregion
|
|
1249
1157
|
//#region src/auth/AuthManager.ts
|
|
1250
1158
|
const DEFAULT_GUARD = "web";
|
|
1159
|
+
/**
|
|
1160
|
+
* The guard name an unqualified lookup resolves to on a request the pipeline
|
|
1161
|
+
* installed a principal on (RFC 0017 §2). Deliberately **not** registered:
|
|
1162
|
+
* registering it would publish a name an application could select, default to,
|
|
1163
|
+
* or shadow. Namespaced so it cannot collide, and `createGuard` refuses it for
|
|
1164
|
+
* a request carrying no principal, so naming it explicitly buys nothing.
|
|
1165
|
+
*/
|
|
1166
|
+
const AGENT_PRINCIPAL_GUARD = "guren.agent-principal";
|
|
1251
1167
|
var AuthManager = class {
|
|
1252
1168
|
guards = /* @__PURE__ */ new Map();
|
|
1253
1169
|
providers = /* @__PURE__ */ new Map();
|
|
@@ -1274,6 +1190,13 @@ var AuthManager = class {
|
|
|
1274
1190
|
return entry.instance;
|
|
1275
1191
|
}
|
|
1276
1192
|
createGuard(name, context) {
|
|
1193
|
+
if (name === AGENT_PRINCIPAL_GUARD) {
|
|
1194
|
+
const installed = readAgentPrincipal(context.ctx.req.raw);
|
|
1195
|
+
if (installed) return new AgentPrincipalGuard({
|
|
1196
|
+
installed,
|
|
1197
|
+
...this.apiTokenOptions.provider ? { provider: this.getProvider(this.apiTokenOptions.provider) } : {}
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1277
1200
|
const entry = this.guards.get(name);
|
|
1278
1201
|
if (!entry) throw new Error(`AuthManager: guard "${name}" has not been registered.`);
|
|
1279
1202
|
return entry.factory(context);
|
|
@@ -1289,15 +1212,15 @@ var AuthManager = class {
|
|
|
1289
1212
|
return this.defaultGuard;
|
|
1290
1213
|
}
|
|
1291
1214
|
/**
|
|
1292
|
-
* The guard
|
|
1293
|
-
*
|
|
1294
|
-
*
|
|
1295
|
-
*
|
|
1296
|
-
*
|
|
1297
|
-
* requests flow through the same auth surface without configuration.
|
|
1215
|
+
* The guard an unqualified `auth.guard()` / `auth.user()` resolves to.
|
|
1216
|
+
* Explicit names win; otherwise a principal the pipeline installed on this
|
|
1217
|
+
* exact request answers first, then a token guard for a Bearer header, then
|
|
1218
|
+
* the default — RFC 0016's composite rule with RFC 0017 §2's seam in front,
|
|
1219
|
+
* so a header cannot win over an identity the framework itself established.
|
|
1298
1220
|
*/
|
|
1299
1221
|
resolveGuardName(ctx, name) {
|
|
1300
1222
|
if (name) return name;
|
|
1223
|
+
if (readAgentPrincipal(ctx.req.raw)) return AGENT_PRINCIPAL_GUARD;
|
|
1301
1224
|
if (this.tokenGuard && hasBearerHeader(ctx)) return this.tokenGuard;
|
|
1302
1225
|
return this.defaultGuard;
|
|
1303
1226
|
}
|
|
@@ -1317,13 +1240,11 @@ var AuthManager = class {
|
|
|
1317
1240
|
return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
|
|
1318
1241
|
}
|
|
1319
1242
|
/**
|
|
1320
|
-
*
|
|
1321
|
-
*
|
|
1243
|
+
* Register a model-based authentication provider and session guard — the
|
|
1244
|
+
* common case of authenticating users via a database model.
|
|
1322
1245
|
*
|
|
1323
|
-
* @param
|
|
1324
|
-
* @param
|
|
1325
|
-
* @param providerName - Name for the provider (defaults to 'users')
|
|
1326
|
-
* @param guardName - Name for the guard (defaults to 'web')
|
|
1246
|
+
* @param providerName - Defaults to 'users'
|
|
1247
|
+
* @param guardName - Defaults to 'web'
|
|
1327
1248
|
*/
|
|
1328
1249
|
useModel(model, options = {}, providerName = "users", guardName = "web") {
|
|
1329
1250
|
const defaultOptions = {
|
|
@@ -1344,15 +1265,9 @@ var AuthManager = class {
|
|
|
1344
1265
|
/**
|
|
1345
1266
|
* Register a bearer-token guard backed by an ApiTokenStore and enable
|
|
1346
1267
|
* header-based guard selection: requests carrying `Authorization: Bearer`
|
|
1347
|
-
* resolve to this guard, everything else keeps the default (session)
|
|
1348
|
-
*
|
|
1349
|
-
*
|
|
1350
|
-
*
|
|
1351
|
-
* @param store - Where issued tokens live (see createApiToken)
|
|
1352
|
-
* @param options.provider - Registered provider name used to load the full
|
|
1353
|
-
* user record from the token's userId. Without it, `auth.user()` resolves
|
|
1354
|
-
* to a minimal `{ id }` record (enough for Gate/policy evaluation).
|
|
1355
|
-
* @param options.guardName - Guard registry name (defaults to 'token')
|
|
1268
|
+
* resolve to this guard, everything else keeps the default (session) guard.
|
|
1269
|
+
* Without `options.provider`, `auth.user()` resolves to a minimal `{ id }`
|
|
1270
|
+
* record (enough for Gate/policy evaluation).
|
|
1356
1271
|
*/
|
|
1357
1272
|
useTokens(store, options = {}) {
|
|
1358
1273
|
const guardName = options.guardName ?? "token";
|
|
@@ -1370,33 +1285,21 @@ var AuthManager = class {
|
|
|
1370
1285
|
this.apiTokenOptions = { ...options };
|
|
1371
1286
|
}
|
|
1372
1287
|
/**
|
|
1373
|
-
* The options the last `useTokens()` call configured its guard with.
|
|
1374
|
-
*
|
|
1375
|
-
*
|
|
1376
|
-
* anything else about how tokens authenticate — `guren tool:dev` installs an
|
|
1377
|
-
* ephemeral store over the app's, and doing that with a bare `useTokens(store)`
|
|
1288
|
+
* The options the last `useTokens()` call configured its guard with. Read by
|
|
1289
|
+
* machinery that has to *replace* the store without changing anything else —
|
|
1290
|
+
* `guren tool:dev` installs an ephemeral store, and a bare `useTokens(store)`
|
|
1378
1291
|
* silently dropped the app's `provider`, so a token resolved to a bare
|
|
1379
|
-
* `{ id }`
|
|
1380
|
-
* field behaved differently for no stated reason.
|
|
1292
|
+
* `{ id }` and every policy reading a user field behaved differently.
|
|
1381
1293
|
*/
|
|
1382
1294
|
getApiTokenOptions() {
|
|
1383
1295
|
return { ...this.apiTokenOptions };
|
|
1384
1296
|
}
|
|
1385
1297
|
/**
|
|
1386
|
-
* The token store {@link useTokens} was configured with, or `undefined
|
|
1387
|
-
*
|
|
1388
|
-
*
|
|
1389
|
-
*
|
|
1390
|
-
*
|
|
1391
|
-
* store the guard verifies against. `useTokens` otherwise closes over
|
|
1392
|
-
* `store` inside the guard factory, where nothing outside a live request
|
|
1393
|
-
* can see it, so an issuance command could only write tokens into a store
|
|
1394
|
-
* of its own making, which no running app would ever read.
|
|
1395
|
-
*
|
|
1396
|
-
* Deliberately on this class rather than on `AuthManagerContract`: the
|
|
1397
|
-
* contract describes what a *request* needs from auth, and handing out the
|
|
1398
|
-
* raw store is not part of that. Callers reach it through the concrete
|
|
1399
|
-
* manager (`Application.auth`).
|
|
1298
|
+
* The token store {@link useTokens} was configured with, or `undefined`. The
|
|
1299
|
+
* one path by which out-of-request machinery (`guren token:issue`, the App MCP
|
|
1300
|
+
* adapter's principal lookup) reaches the store the guard verifies against —
|
|
1301
|
+
* otherwise `store` is closed over inside the guard factory. On this class
|
|
1302
|
+
* rather than `AuthManagerContract`, which describes what a *request* needs.
|
|
1400
1303
|
*/
|
|
1401
1304
|
getApiTokenStore() {
|
|
1402
1305
|
return this.apiTokenStore ?? void 0;
|
|
@@ -1405,19 +1308,17 @@ var AuthManager = class {
|
|
|
1405
1308
|
//#endregion
|
|
1406
1309
|
//#region src/support/redirect-target.ts
|
|
1407
1310
|
/**
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1311
|
+
* Open-redirect classification shared by the redirect-safety middleware and the
|
|
1312
|
+
* OAuth `redirectTo` sanitizer. Every hardening fix belongs here so the two
|
|
1313
|
+
* layers cannot drift.
|
|
1411
1314
|
*/
|
|
1412
|
-
/**
|
|
1315
|
+
/** Defuses backslash tricks such as `/\evil.com`. */
|
|
1413
1316
|
function normalizeRedirectTarget(value) {
|
|
1414
1317
|
return value.replace(/\\/g, "/");
|
|
1415
1318
|
}
|
|
1416
|
-
/** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
|
|
1417
1319
|
function isAppRelativePath(value) {
|
|
1418
1320
|
return value.startsWith("/") && !value.startsWith("//");
|
|
1419
1321
|
}
|
|
1420
|
-
/** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
|
|
1421
1322
|
function hostMatchesAllowlist(target, allowedHosts) {
|
|
1422
1323
|
const hostname = target.hostname.toLowerCase();
|
|
1423
1324
|
const host = target.host.toLowerCase();
|
|
@@ -1432,20 +1333,16 @@ function hostMatchesAllowlist(target, allowedHosts) {
|
|
|
1432
1333
|
/** Session key holding the per-browser bindings between authorize and callback. */
|
|
1433
1334
|
const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
|
|
1434
1335
|
/**
|
|
1435
|
-
* How many unfinished flows one browser may have bindings for.
|
|
1436
|
-
*
|
|
1437
|
-
*
|
|
1438
|
-
* until it expires, so the list is capped. Beyond the cap the oldest entry is
|
|
1439
|
-
* dropped — that flow's callback then fails, which is the same outcome it had
|
|
1440
|
-
* before any of this existed.
|
|
1336
|
+
* How many unfinished flows one browser may have bindings for. An abandoned
|
|
1337
|
+
* flow leaves an entry behind until it expires, so the list is capped; beyond
|
|
1338
|
+
* it the oldest is dropped and that flow's callback fails.
|
|
1441
1339
|
*/
|
|
1442
1340
|
const MAX_PENDING_SESSION_BINDINGS = 5;
|
|
1443
1341
|
let warnedAboutUnboundState = false;
|
|
1444
1342
|
/**
|
|
1445
1343
|
* An unbound `state` is transferable between browsers, which is exactly the
|
|
1446
|
-
* attack `state` exists to stop. Verification stays permissive so apps
|
|
1447
|
-
*
|
|
1448
|
-
* them they are exposed.
|
|
1344
|
+
* attack `state` exists to stop. Verification stays permissive so older apps
|
|
1345
|
+
* keep working, so this warning is the only thing telling them they are exposed.
|
|
1449
1346
|
*/
|
|
1450
1347
|
function warnOnceAboutUnboundState() {
|
|
1451
1348
|
if (warnedAboutUnboundState) return;
|
|
@@ -1474,11 +1371,9 @@ function issueSessionBinding(session) {
|
|
|
1474
1371
|
return generateToken(DEFAULT_STATE_LENGTH);
|
|
1475
1372
|
}
|
|
1476
1373
|
/**
|
|
1477
|
-
* Park a minted binding against the state it belongs to.
|
|
1478
|
-
*
|
|
1479
|
-
*
|
|
1480
|
-
* flows in flight — two tabs, or a visitor who picks a different provider —
|
|
1481
|
-
* without each `authorize()` invalidating the one before it.
|
|
1374
|
+
* Park a minted binding against the state it belongs to. Keyed by state rather
|
|
1375
|
+
* than kept in one slot, so a browser can have several flows in flight without
|
|
1376
|
+
* each `authorize()` invalidating the one before it.
|
|
1482
1377
|
*/
|
|
1483
1378
|
function rememberSessionBinding(session, stateHash, binding, expiresAt) {
|
|
1484
1379
|
const pending = readPendingBindings(session);
|
|
@@ -1490,11 +1385,9 @@ function rememberSessionBinding(session, stateHash, binding, expiresAt) {
|
|
|
1490
1385
|
session.set(OAUTH_SESSION_BINDING_KEY, pending.slice(Math.max(0, pending.length - MAX_PENDING_SESSION_BINDINGS)));
|
|
1491
1386
|
}
|
|
1492
1387
|
/**
|
|
1493
|
-
* Take the binding belonging to this callback's state, leaving the rest.
|
|
1494
|
-
*
|
|
1495
|
-
*
|
|
1496
|
-
* state must not be able to strip a real flow's binding and lock the visitor
|
|
1497
|
-
* out of the login they actually started.
|
|
1388
|
+
* Take the binding belonging to this callback's state, leaving the rest. Only
|
|
1389
|
+
* the matching entry is removed: a forged callback carrying an unknown state
|
|
1390
|
+
* must not be able to strip a real flow's binding and lock the visitor out.
|
|
1498
1391
|
*/
|
|
1499
1392
|
function consumeSessionBinding(session, stateHash) {
|
|
1500
1393
|
if (!session) return void 0;
|
|
@@ -1594,10 +1487,9 @@ var OAuthManager = class {
|
|
|
1594
1487
|
return profile;
|
|
1595
1488
|
}
|
|
1596
1489
|
/**
|
|
1597
|
-
* Verify the callback and return the user profile together with the
|
|
1598
|
-
*
|
|
1599
|
-
* pass to a redirect response
|
|
1600
|
-
* only.
|
|
1490
|
+
* Verify the callback and return the user profile together with the sanitized
|
|
1491
|
+
* `redirectTo` stored at authorize time — app-relative paths and allowlisted
|
|
1492
|
+
* hosts only, so it is safe to pass to a redirect response.
|
|
1601
1493
|
*/
|
|
1602
1494
|
async handleCallback(providerName, payload) {
|
|
1603
1495
|
const provider = this.getProvider(providerName);
|
|
@@ -1642,11 +1534,9 @@ async function verifyOAuthState(state, provider, store, config = {}, bindTo) {
|
|
|
1642
1534
|
}
|
|
1643
1535
|
/**
|
|
1644
1536
|
* Whether the presented value matches the binding recorded at authorize time.
|
|
1645
|
-
*
|
|
1646
1537
|
* A state created without a binding still verifies, so an app that has not
|
|
1647
|
-
* adopted `bindTo` keeps working
|
|
1648
|
-
* browser that cannot present it,
|
|
1649
|
-
* wrong value fails.
|
|
1538
|
+
* adopted `bindTo` keeps working; a state created *with* one is useless to a
|
|
1539
|
+
* browser that cannot present it, so a missing or wrong value fails.
|
|
1650
1540
|
*/
|
|
1651
1541
|
function bindingMatches(stored, presented, hashAlgorithm) {
|
|
1652
1542
|
if (!stored) {
|
|
@@ -1663,11 +1553,10 @@ async function findAndDeleteState(store, stateHash) {
|
|
|
1663
1553
|
return payload;
|
|
1664
1554
|
}
|
|
1665
1555
|
/**
|
|
1666
|
-
* Reduce a `redirectTo` value to a safe target: app-relative paths always
|
|
1667
|
-
*
|
|
1668
|
-
*
|
|
1669
|
-
*
|
|
1670
|
-
* `undefined`.
|
|
1556
|
+
* Reduce a `redirectTo` value to a safe target: app-relative paths always pass;
|
|
1557
|
+
* absolute http(s) URLs pass only when their host is in the allowlist (with
|
|
1558
|
+
* `*.example.com` wildcards). Everything else — protocol-relative URLs,
|
|
1559
|
+
* backslash tricks, `javascript:` and other schemes — returns `undefined`.
|
|
1671
1560
|
*/
|
|
1672
1561
|
function sanitizeOAuthRedirect(redirectTo, allowedHosts = []) {
|
|
1673
1562
|
const value = redirectTo?.trim();
|
|
@@ -1845,8 +1734,8 @@ var AuthenticatableModel = class extends Model {
|
|
|
1845
1734
|
* Credential columns can never be mass-assigned: the resolved password-hash
|
|
1846
1735
|
* column (unless the model hashes in place into the password field itself)
|
|
1847
1736
|
* and the remember-token column. Resolved at call time so a renamed column
|
|
1848
|
-
* stays covered. Use `forceCreate()`/`forceUpdate()` for trusted
|
|
1849
|
-
*
|
|
1737
|
+
* stays covered. Use `forceCreate()`/`forceUpdate()` for trusted server-side
|
|
1738
|
+
* values such as `passwordHash: 'oauth:...'`.
|
|
1850
1739
|
*/
|
|
1851
1740
|
static deniedFields() {
|
|
1852
1741
|
const denied = [...super.deniedFields()];
|
|
@@ -1874,10 +1763,30 @@ var AuthenticatableModel = class extends Model {
|
|
|
1874
1763
|
}
|
|
1875
1764
|
};
|
|
1876
1765
|
//#endregion
|
|
1877
|
-
//#region src/auth/
|
|
1766
|
+
//#region src/auth/signed-token.ts
|
|
1878
1767
|
/**
|
|
1879
|
-
*
|
|
1768
|
+
* Read the claims of a signed one-time token, deciding expiry from the `exp`
|
|
1769
|
+
* claim signed into it rather than from the store's copy.
|
|
1770
|
+
*
|
|
1771
|
+
* The signature is checked before anything is deleted, so the housekeeping
|
|
1772
|
+
* `store.delete` only ever runs for an id this app issued.
|
|
1880
1773
|
*/
|
|
1774
|
+
async function readSignedTokenClaims(signer, token, purpose, store) {
|
|
1775
|
+
const claims = signer.verify(token, { purpose });
|
|
1776
|
+
if (claims?.id && claims.email) return {
|
|
1777
|
+
id: claims.id,
|
|
1778
|
+
email: claims.email
|
|
1779
|
+
};
|
|
1780
|
+
const expired = signer.verify(token, {
|
|
1781
|
+
purpose,
|
|
1782
|
+
allowExpired: true
|
|
1783
|
+
});
|
|
1784
|
+
if (expired?.id) await store.delete(expired.id);
|
|
1785
|
+
return null;
|
|
1786
|
+
}
|
|
1787
|
+
//#endregion
|
|
1788
|
+
//#region src/auth/password-reset.ts
|
|
1789
|
+
/** In-memory token store for testing and development. */
|
|
1881
1790
|
var MemoryPasswordResetStore = class {
|
|
1882
1791
|
tokens = /* @__PURE__ */ new Map();
|
|
1883
1792
|
async store(tokenId, email, expiresAt) {
|
|
@@ -1912,14 +1821,7 @@ const PASSWORD_RESET_PURPOSE = "password-reset";
|
|
|
1912
1821
|
function createPasswordResetSigner() {
|
|
1913
1822
|
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "password-reset-signing"));
|
|
1914
1823
|
}
|
|
1915
|
-
/**
|
|
1916
|
-
* Create a password reset token for a user.
|
|
1917
|
-
*
|
|
1918
|
-
* @param email - The user's email address
|
|
1919
|
-
* @param store - The token storage implementation
|
|
1920
|
-
* @param config - Optional configuration
|
|
1921
|
-
* @returns The token result containing plain token and hash
|
|
1922
|
-
*/
|
|
1824
|
+
/** Create a password reset token for a user. */
|
|
1923
1825
|
async function createPasswordResetToken(email, store, config = {}) {
|
|
1924
1826
|
const expiresIn = config.expiresIn ?? DEFAULT_EXPIRES_IN;
|
|
1925
1827
|
const tokenLength = config.tokenLength ?? DEFAULT_TOKEN_LENGTH;
|
|
@@ -1941,75 +1843,40 @@ async function createPasswordResetToken(email, store, config = {}) {
|
|
|
1941
1843
|
expiresAt
|
|
1942
1844
|
};
|
|
1943
1845
|
}
|
|
1944
|
-
/**
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
* @param config - Optional configuration (must match createPasswordResetToken config)
|
|
1950
|
-
* @returns The email if token is valid, null otherwise
|
|
1951
|
-
*/
|
|
1952
|
-
async function verifyPasswordResetToken(token, store, _config = {}) {
|
|
1953
|
-
const payload = createPasswordResetSigner().verify(token, {
|
|
1954
|
-
purpose: PASSWORD_RESET_PURPOSE,
|
|
1955
|
-
allowExpired: true
|
|
1956
|
-
});
|
|
1957
|
-
if (!payload?.id || !payload.email) return null;
|
|
1958
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1959
|
-
await store.delete(payload.id);
|
|
1960
|
-
return null;
|
|
1961
|
-
}
|
|
1962
|
-
const record = await store.find(payload.id);
|
|
1846
|
+
/** Verify a password reset token, returning the email it was issued for. */
|
|
1847
|
+
async function verifyPasswordResetToken(token, store) {
|
|
1848
|
+
const claims = await readSignedTokenClaims(createPasswordResetSigner(), token, PASSWORD_RESET_PURPOSE, store);
|
|
1849
|
+
if (!claims) return null;
|
|
1850
|
+
const record = await store.find(claims.id);
|
|
1963
1851
|
if (!record) return null;
|
|
1964
|
-
return record.email.toLowerCase() ===
|
|
1852
|
+
return record.email.toLowerCase() === claims.email.toLowerCase() ? record.email : null;
|
|
1965
1853
|
}
|
|
1966
1854
|
/**
|
|
1967
|
-
* Complete a password reset
|
|
1968
|
-
*
|
|
1969
|
-
* @param token - The plain-text token from the reset URL
|
|
1970
|
-
* @param newPassword - The new password (should be validated by caller)
|
|
1971
|
-
* @param store - The token storage implementation
|
|
1972
|
-
* @param provider - The user provider to look up and update the user
|
|
1973
|
-
* @param updatePassword - Function to update the user's password
|
|
1974
|
-
* @param config - Optional configuration
|
|
1975
|
-
* @returns The user if reset was successful, null if token is invalid
|
|
1855
|
+
* Complete a password reset: update the user's password and invalidate the
|
|
1856
|
+
* token. Returns the user, or `null` when the token is invalid.
|
|
1976
1857
|
*/
|
|
1977
|
-
async function completePasswordReset(token, newPassword, store, provider, updatePassword
|
|
1978
|
-
const
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
});
|
|
1982
|
-
if (!payload?.id || !payload.email) return null;
|
|
1983
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1984
|
-
await store.delete(payload.id);
|
|
1985
|
-
return null;
|
|
1986
|
-
}
|
|
1987
|
-
const record = await store.find(payload.id);
|
|
1858
|
+
async function completePasswordReset(token, newPassword, store, provider, updatePassword) {
|
|
1859
|
+
const claims = await readSignedTokenClaims(createPasswordResetSigner(), token, PASSWORD_RESET_PURPOSE, store);
|
|
1860
|
+
if (!claims) return null;
|
|
1861
|
+
const record = await store.find(claims.id);
|
|
1988
1862
|
if (!record) return null;
|
|
1989
|
-
if (record.email.toLowerCase() !==
|
|
1863
|
+
if (record.email.toLowerCase() !== claims.email.toLowerCase()) return null;
|
|
1990
1864
|
const user = await provider.retrieveByCredentials({ email: record.email });
|
|
1991
1865
|
if (!user) {
|
|
1992
|
-
await store.delete(
|
|
1866
|
+
await store.delete(claims.id);
|
|
1993
1867
|
return null;
|
|
1994
1868
|
}
|
|
1995
1869
|
await updatePassword(user, newPassword);
|
|
1996
|
-
await store.delete(
|
|
1870
|
+
await store.delete(claims.id);
|
|
1997
1871
|
return user;
|
|
1998
1872
|
}
|
|
1999
|
-
/**
|
|
2000
|
-
* Build a password reset URL from a base URL and token.
|
|
2001
|
-
*/
|
|
1873
|
+
/** Build a password reset URL from a base URL and token. */
|
|
2002
1874
|
const buildPasswordResetUrl = buildTokenUrl;
|
|
2003
|
-
/**
|
|
2004
|
-
* Parse a password reset URL to extract the token and optional email.
|
|
2005
|
-
*/
|
|
1875
|
+
/** Parse a password reset URL to extract the token and optional email. */
|
|
2006
1876
|
const parsePasswordResetUrl = parseTokenUrl;
|
|
2007
1877
|
//#endregion
|
|
2008
1878
|
//#region src/auth/email-verification.ts
|
|
2009
|
-
/**
|
|
2010
|
-
* In-memory store for testing purposes.
|
|
2011
|
-
* Do NOT use in production - tokens will be lost on restart.
|
|
2012
|
-
*/
|
|
1879
|
+
/** In-memory store for testing. Tokens are lost on restart. */
|
|
2013
1880
|
var MemoryEmailVerificationStore = class {
|
|
2014
1881
|
tokens = /* @__PURE__ */ new Map();
|
|
2015
1882
|
async store(token) {
|
|
@@ -2025,15 +1892,11 @@ var MemoryEmailVerificationStore = class {
|
|
|
2025
1892
|
const normalizedEmail = email.toLowerCase();
|
|
2026
1893
|
for (const [key, token] of this.tokens.entries()) if (token.email.toLowerCase() === normalizedEmail) this.tokens.delete(key);
|
|
2027
1894
|
}
|
|
2028
|
-
/**
|
|
2029
|
-
* Clear all tokens (useful for testing).
|
|
2030
|
-
*/
|
|
1895
|
+
/** Clear all tokens (useful for testing). */
|
|
2031
1896
|
clear() {
|
|
2032
1897
|
this.tokens.clear();
|
|
2033
1898
|
}
|
|
2034
|
-
/**
|
|
2035
|
-
* Get the count of stored tokens (useful for testing).
|
|
2036
|
-
*/
|
|
1899
|
+
/** Count of stored tokens (useful for testing). */
|
|
2037
1900
|
get size() {
|
|
2038
1901
|
return this.tokens.size;
|
|
2039
1902
|
}
|
|
@@ -2047,27 +1910,8 @@ function createEmailVerificationSigner() {
|
|
|
2047
1910
|
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "email-verification-signing"));
|
|
2048
1911
|
}
|
|
2049
1912
|
/**
|
|
2050
|
-
* Create a new email verification token
|
|
2051
|
-
*
|
|
2052
|
-
* @param email - The email address to verify
|
|
2053
|
-
* @param store - Token store implementation
|
|
2054
|
-
* @param config - Optional configuration
|
|
2055
|
-
* @returns The raw token to send via email
|
|
2056
|
-
*
|
|
2057
|
-
* @example
|
|
2058
|
-
* ```ts
|
|
2059
|
-
* const { token, expiresAt } = await createEmailVerificationToken(
|
|
2060
|
-
* user.email,
|
|
2061
|
-
* verificationStore
|
|
2062
|
-
* )
|
|
2063
|
-
*
|
|
2064
|
-
* // Send email with verification link
|
|
2065
|
-
* await sendEmail({
|
|
2066
|
-
* to: user.email,
|
|
2067
|
-
* subject: 'Verify your email',
|
|
2068
|
-
* html: `<a href="${buildVerificationUrl(baseUrl, token)}">Verify Email</a>`,
|
|
2069
|
-
* })
|
|
2070
|
-
* ```
|
|
1913
|
+
* Create a new email verification token; the raw token is returned to send by
|
|
1914
|
+
* email and is never stored.
|
|
2071
1915
|
*/
|
|
2072
1916
|
async function createEmailVerificationToken(email, store, config = {}) {
|
|
2073
1917
|
const { expiresIn, tokenLength } = {
|
|
@@ -2098,127 +1942,43 @@ async function createEmailVerificationToken(email, store, config = {}) {
|
|
|
2098
1942
|
};
|
|
2099
1943
|
}
|
|
2100
1944
|
/**
|
|
2101
|
-
* Verify an email verification token
|
|
2102
|
-
*
|
|
2103
|
-
* @param token - The raw token from the verification link
|
|
2104
|
-
* @param store - Token store implementation
|
|
2105
|
-
* @param config - Optional configuration (not currently used, reserved for future)
|
|
2106
|
-
* @returns The email address if valid, null if invalid or expired
|
|
2107
|
-
*
|
|
2108
|
-
* @example
|
|
2109
|
-
* ```ts
|
|
2110
|
-
* const email = await verifyEmailToken(token, verificationStore)
|
|
2111
|
-
*
|
|
2112
|
-
* if (!email) {
|
|
2113
|
-
* return ctx.json({ error: 'Invalid or expired token' }, 400)
|
|
2114
|
-
* }
|
|
2115
|
-
*
|
|
2116
|
-
* // Mark user as verified
|
|
2117
|
-
* await User.update({ email }, { emailVerifiedAt: new Date() })
|
|
2118
|
-
* ```
|
|
1945
|
+
* Verify an email verification token, returning the email address it was
|
|
1946
|
+
* issued for or `null` when it is invalid or expired.
|
|
2119
1947
|
*/
|
|
2120
|
-
async function verifyEmailToken(token, store
|
|
2121
|
-
const
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
});
|
|
2125
|
-
if (!payload?.id || !payload.email) return null;
|
|
2126
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
2127
|
-
await store.delete(payload.id);
|
|
2128
|
-
return null;
|
|
2129
|
-
}
|
|
2130
|
-
const storedToken = await store.findByTokenId(payload.id);
|
|
1948
|
+
async function verifyEmailToken(token, store) {
|
|
1949
|
+
const claims = await readSignedTokenClaims(createEmailVerificationSigner(), token, EMAIL_VERIFICATION_PURPOSE, store);
|
|
1950
|
+
if (!claims) return null;
|
|
1951
|
+
const storedToken = await store.findByTokenId(claims.id);
|
|
2131
1952
|
if (!storedToken) return null;
|
|
2132
|
-
|
|
2133
|
-
await store.delete(payload.id);
|
|
2134
|
-
return null;
|
|
2135
|
-
}
|
|
2136
|
-
return storedToken.email.toLowerCase() === payload.email.toLowerCase() ? storedToken.email : null;
|
|
1953
|
+
return storedToken.email.toLowerCase() === claims.email.toLowerCase() ? storedToken.email : null;
|
|
2137
1954
|
}
|
|
2138
1955
|
/**
|
|
2139
|
-
* Complete email verification by consuming the token.
|
|
2140
|
-
*
|
|
2141
|
-
* @param token - The raw token from the verification link
|
|
2142
|
-
* @param store - Token store implementation
|
|
2143
|
-
* @param markVerified - Function to mark the user as verified
|
|
2144
|
-
* @returns The result of markVerified if successful, null if token invalid
|
|
2145
|
-
*
|
|
2146
|
-
* @example
|
|
2147
|
-
* ```ts
|
|
2148
|
-
* const result = await completeEmailVerification(
|
|
2149
|
-
* token,
|
|
2150
|
-
* verificationStore,
|
|
2151
|
-
* async (email) => {
|
|
2152
|
-
* await User.update({ email }, { emailVerifiedAt: new Date() })
|
|
2153
|
-
* return User.findByEmail(email)
|
|
2154
|
-
* }
|
|
2155
|
-
* )
|
|
2156
|
-
*
|
|
2157
|
-
* if (!result) {
|
|
2158
|
-
* return ctx.json({ error: 'Invalid or expired token' }, 400)
|
|
2159
|
-
* }
|
|
2160
|
-
*
|
|
2161
|
-
* return ctx.redirect('/dashboard')
|
|
2162
|
-
* ```
|
|
1956
|
+
* Complete email verification by consuming the token. Returns the result of
|
|
1957
|
+
* `markVerified`, or `null` when the token is invalid.
|
|
2163
1958
|
*/
|
|
2164
1959
|
async function completeEmailVerification(token, store, markVerified) {
|
|
2165
|
-
const
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
});
|
|
2169
|
-
if (!payload?.id || !payload.email) return null;
|
|
2170
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
2171
|
-
await store.delete(payload.id);
|
|
2172
|
-
return null;
|
|
2173
|
-
}
|
|
2174
|
-
const storedToken = await store.findByTokenId(payload.id);
|
|
1960
|
+
const claims = await readSignedTokenClaims(createEmailVerificationSigner(), token, EMAIL_VERIFICATION_PURPOSE, store);
|
|
1961
|
+
if (!claims) return null;
|
|
1962
|
+
const storedToken = await store.findByTokenId(claims.id);
|
|
2175
1963
|
if (!storedToken) return null;
|
|
2176
|
-
if (
|
|
2177
|
-
await store.delete(payload.id);
|
|
2178
|
-
return null;
|
|
2179
|
-
}
|
|
2180
|
-
if (storedToken.email.toLowerCase() !== payload.email.toLowerCase()) return null;
|
|
1964
|
+
if (storedToken.email.toLowerCase() !== claims.email.toLowerCase()) return null;
|
|
2181
1965
|
const result = await markVerified(storedToken.email);
|
|
2182
|
-
await store.delete(
|
|
1966
|
+
await store.delete(claims.id);
|
|
2183
1967
|
return result;
|
|
2184
1968
|
}
|
|
2185
|
-
/**
|
|
2186
|
-
* Build a verification URL.
|
|
2187
|
-
*/
|
|
1969
|
+
/** Build a verification URL. */
|
|
2188
1970
|
const buildVerificationUrl = buildTokenUrl;
|
|
2189
|
-
/**
|
|
2190
|
-
* Parse a verification URL to extract token and email.
|
|
2191
|
-
*/
|
|
1971
|
+
/** Parse a verification URL to extract token and email. */
|
|
2192
1972
|
const parseVerificationUrl = parseTokenUrl;
|
|
2193
|
-
/**
|
|
2194
|
-
* Check if a user's email is verified.
|
|
2195
|
-
* Helper function for use with User models.
|
|
2196
|
-
*
|
|
2197
|
-
* @param user - User object with emailVerifiedAt field
|
|
2198
|
-
* @returns true if verified, false otherwise
|
|
2199
|
-
*
|
|
2200
|
-
* @example
|
|
2201
|
-
* ```ts
|
|
2202
|
-
* if (!isEmailVerified(user)) {
|
|
2203
|
-
* return ctx.redirect('/verify-email')
|
|
2204
|
-
* }
|
|
2205
|
-
* ```
|
|
2206
|
-
*/
|
|
1973
|
+
/** Whether a user's `emailVerifiedAt` is set. */
|
|
2207
1974
|
function isEmailVerified(user) {
|
|
2208
1975
|
return user?.emailVerifiedAt != null;
|
|
2209
1976
|
}
|
|
2210
1977
|
/**
|
|
2211
1978
|
* Middleware factory to require verified email.
|
|
2212
|
-
*
|
|
2213
|
-
* @param options - Configuration options
|
|
2214
|
-
* @returns Middleware function
|
|
2215
|
-
*
|
|
2216
1979
|
* @example
|
|
2217
1980
|
* ```ts
|
|
2218
|
-
*
|
|
2219
|
-
* requireAuthenticated(),
|
|
2220
|
-
* requireVerifiedEmail({ redirectTo: '/verify-email' })
|
|
2221
|
-
* )
|
|
1981
|
+
* requireVerifiedEmail({ redirectTo: '/verify-email' })
|
|
2222
1982
|
* ```
|
|
2223
1983
|
*/
|
|
2224
1984
|
function requireVerifiedEmail(options = {}) {
|
|
@@ -2231,4 +1991,4 @@ function requireVerifiedEmail(options = {}) {
|
|
|
2231
1991
|
};
|
|
2232
1992
|
}
|
|
2233
1993
|
//#endregion
|
|
2234
|
-
export { buildTokenUrl as $, verifyOAuthState as A, getApiToken as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, TokenGuard as F, readBearerToken as G, getUserApiTokens as H, API_TOKEN_KEY as I, tokenCan as J, revokeAllApiTokens as K, MemoryApiTokenStore as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, SessionGuard as Q, createApiToken as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, hasBearerHeader as U, getApiTokenOrFail as V, parseApiToken as W, tokenCanAny as X, tokenCanAll as Y, verifyApiToken as Z, OAUTH_SESSION_BINDING_KEY as _, isEmailVerified as a, secureStringCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c,
|
|
1994
|
+
export { buildTokenUrl as $, verifyOAuthState as A, getApiToken as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, TokenGuard as F, readBearerToken as G, getUserApiTokens as H, API_TOKEN_KEY as I, tokenCan as J, revokeAllApiTokens as K, MemoryApiTokenStore as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, SessionGuard as Q, createApiToken as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, hasBearerHeader as U, getApiTokenOrFail as V, parseApiToken as W, tokenCanAny as X, tokenCanAll as Y, verifyApiToken as Z, OAUTH_SESSION_BINDING_KEY as _, isEmailVerified as a, secureStringCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c, NodeHasher as ct, completePasswordReset as d, BaseUserProvider as dt, generateId as et, createPasswordResetToken as f, installAgentPrincipal as ft, MemoryOAuthStateStore as g, getSessionFromContext as gt, AuthenticatableModel as h, createSessionMiddleware as ht, createEmailVerificationToken as i, secureCompare as it, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, ScryptHasher as lt, verifyPasswordResetToken as m, MemorySessionStore as mt, buildVerificationUrl as n, hashToken as nt, parseVerificationUrl as o, ModelUserProvider as ot, parsePasswordResetUrl as p, readAgentPrincipal as pt, revokeApiToken as q, completeEmailVerification as r, parseTokenUrl as rt, requireVerifiedEmail as s, DefaultHasher as st, MemoryEmailVerificationStore as t, generateToken as tt, buildPasswordResetUrl as u, AuthenticationException as ut, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, createBearerTokenMiddleware as z };
|