@guren/server 2.15.0 → 2.16.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-nNcbCIQX.js} +11 -20
- package/dist/{Random-DbIJ22KQ.js → Random-S0OvCuR8.js} +9 -106
- package/dist/agent/AgentApprovalRequested.d.ts +11 -39
- 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 +11 -19
- package/dist/agent/meta-tools.d.ts +18 -46
- 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 +23 -69
- package/dist/auth/AuthManager.d.ts +19 -40
- 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-CbdPH4Cd.js} +169 -502
- 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 +62 -208
- 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 +20 -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/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 +2 -1
- package/dist/index.js +714 -3011
- package/dist/internal/agent-preflight.d.ts +9 -21
- 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 +25 -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-CTQp-SOo.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
|
}
|
|
@@ -281,26 +278,10 @@ function getSessionFromContext(ctx) {
|
|
|
281
278
|
}
|
|
282
279
|
//#endregion
|
|
283
280
|
//#region src/errors/exceptions/AuthenticationException.ts
|
|
284
|
-
/**
|
|
285
|
-
* Authentication exception.
|
|
286
|
-
*
|
|
287
|
-
* Thrown when a user is not authenticated or credentials are invalid.
|
|
288
|
-
*
|
|
289
|
-
* @example
|
|
290
|
-
* ```typescript
|
|
291
|
-
* throw new AuthenticationException()
|
|
292
|
-
* throw new AuthenticationException('Invalid token')
|
|
293
|
-
* throw new AuthenticationException('Session expired', 'login')
|
|
294
|
-
* ```
|
|
295
|
-
*/
|
|
281
|
+
/** 401: the user is not authenticated, or the credentials were invalid. */
|
|
296
282
|
var AuthenticationException = class AuthenticationException extends HttpException {
|
|
297
|
-
/**
|
|
298
|
-
* The guard that threw the exception.
|
|
299
|
-
*/
|
|
283
|
+
/** The guard that threw. */
|
|
300
284
|
guard;
|
|
301
|
-
/**
|
|
302
|
-
* URL to redirect to for authentication.
|
|
303
|
-
*/
|
|
304
285
|
redirectTo;
|
|
305
286
|
constructor(message = "Unauthenticated.", guard, redirectTo) {
|
|
306
287
|
super(401, message);
|
|
@@ -308,15 +289,9 @@ var AuthenticationException = class AuthenticationException extends HttpExceptio
|
|
|
308
289
|
this.guard = guard;
|
|
309
290
|
this.redirectTo = redirectTo;
|
|
310
291
|
}
|
|
311
|
-
/**
|
|
312
|
-
* Create exception with redirect URL.
|
|
313
|
-
*/
|
|
314
292
|
static withRedirect(redirectTo, message) {
|
|
315
293
|
return new AuthenticationException(message, void 0, redirectTo);
|
|
316
294
|
}
|
|
317
|
-
/**
|
|
318
|
-
* Create exception for a specific guard.
|
|
319
|
-
*/
|
|
320
295
|
static forGuard(guard, message) {
|
|
321
296
|
return new AuthenticationException(message, guard);
|
|
322
297
|
}
|
|
@@ -372,16 +347,10 @@ var RequestAuthContext = class {
|
|
|
372
347
|
};
|
|
373
348
|
/**
|
|
374
349
|
* 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.
|
|
350
|
+
* family, bcrypt, and the Node fallback's scrypt. A *shape* test, not a
|
|
351
|
+
* validity test. Full prefixes rather than the shared `$argon2` / `$2` stems:
|
|
352
|
+
* a password of `$2fast4u` is not bcrypt, and treating it as one turns a
|
|
353
|
+
* correct call into a false accusation.
|
|
385
354
|
*/
|
|
386
355
|
const HASH_PREFIXES = [
|
|
387
356
|
"$argon2id$",
|
|
@@ -396,19 +365,11 @@ function looksLikePasswordHash(value) {
|
|
|
396
365
|
return HASH_PREFIXES.some((prefix) => value.startsWith(prefix));
|
|
397
366
|
}
|
|
398
367
|
/**
|
|
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.
|
|
368
|
+
* Throws when `verify()` was called as `verify(plain, hashed)`. Two-sided on
|
|
369
|
+
* purpose: fires only when the second argument looks like a hash *and* the
|
|
370
|
+
* first does not, so a legitimate non-hash credential column
|
|
371
|
+
* (`passwordHash: 'oauth:...'`) is not misdiagnosed as a caller mistake.
|
|
372
|
+
* Neither argument is in the message: one is a plaintext password on a live login.
|
|
412
373
|
*/
|
|
413
374
|
function assertVerifyArgumentOrder(hashed, plain) {
|
|
414
375
|
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 +457,11 @@ var NodeHasher = class {
|
|
|
496
457
|
//#endregion
|
|
497
458
|
//#region src/auth/password/DefaultHasher.ts
|
|
498
459
|
/**
|
|
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.
|
|
460
|
+
* Runtime-detecting password hasher behind `Hash`, the default for
|
|
461
|
+
* `AuthenticatableModel` and `ModelUserProvider`: `Bun.password` on Bun (Argon2id,
|
|
462
|
+
* despite `ScryptHasher`'s name), `crypto.scrypt` otherwise. **Verification routes
|
|
463
|
+
* on the stored hash, not the runtime**, or a column written elsewhere would 500 on
|
|
464
|
+
* every login; `$scrypt$` verifies anywhere, Argon2id/bcrypt needs `Bun.password`.
|
|
513
465
|
*/
|
|
514
466
|
var DefaultHasher = class {
|
|
515
467
|
bun;
|
|
@@ -540,10 +492,10 @@ var DefaultHasher = class {
|
|
|
540
492
|
//#endregion
|
|
541
493
|
//#region src/auth/providers/UserProvider.ts
|
|
542
494
|
/**
|
|
543
|
-
* Run a user record through the provider's optional `sanitize` before it
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
*
|
|
495
|
+
* Run a user record through the provider's optional `sanitize` before it leaves
|
|
496
|
+
* the auth layer. Every guard must call this on anything it returns from
|
|
497
|
+
* `user()` — a guard that forgets the ternary leaks password hashes, so the
|
|
498
|
+
* ternary lives here, once.
|
|
547
499
|
*/
|
|
548
500
|
function sanitizeUser(provider, user) {
|
|
549
501
|
return provider.sanitize ? provider.sanitize(user) : user;
|
|
@@ -622,10 +574,9 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
622
574
|
return user[this.idColumn];
|
|
623
575
|
}
|
|
624
576
|
/**
|
|
625
|
-
* Strip the password hash, remember token, and the model's `hidden`
|
|
626
|
-
*
|
|
627
|
-
*
|
|
628
|
-
* never affects login — only what `auth.user()` exposes.
|
|
577
|
+
* Strip the password hash, remember token, and the model's `hidden` fields
|
|
578
|
+
* before the record leaves the auth layer. Credential validation runs on the
|
|
579
|
+
* raw record first, so this never affects login — only `auth.user()`.
|
|
629
580
|
*/
|
|
630
581
|
sanitize(user) {
|
|
631
582
|
const authModel = credentialColumnSource(this.model);
|
|
@@ -653,33 +604,21 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
653
604
|
};
|
|
654
605
|
//#endregion
|
|
655
606
|
//#region src/auth/utils.ts
|
|
656
|
-
/**
|
|
657
|
-
* Hash a token using SHA-256 or SHA-512.
|
|
658
|
-
*/
|
|
659
607
|
function hashToken(token, algorithm = "sha256") {
|
|
660
608
|
return createHash(algorithm).update(token).digest("hex");
|
|
661
609
|
}
|
|
662
|
-
/**
|
|
663
|
-
* Generate a secure random token.
|
|
664
|
-
*/
|
|
665
610
|
function generateToken(length = 32) {
|
|
666
611
|
return randomBytes(length).toString("hex");
|
|
667
612
|
}
|
|
668
|
-
/**
|
|
669
|
-
* Generate a random ID (16 bytes = 32 hex chars).
|
|
670
|
-
*/
|
|
613
|
+
/** Generate a random ID (16 bytes = 32 hex chars). */
|
|
671
614
|
function generateId() {
|
|
672
615
|
return randomBytes(16).toString("hex");
|
|
673
616
|
}
|
|
674
617
|
/**
|
|
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.
|
|
618
|
+
* Timing-safe comparison of two hex strings. Non-hex or odd-length input is
|
|
619
|
+
* rejected rather than compared: `Buffer.from(x, 'hex')` stops at the first
|
|
620
|
+
* invalid pair, so 'zzzz' and 'yyyy' would both decode to nothing and compare
|
|
621
|
+
* equal. Use `secureStringCompare` for values that are not hex.
|
|
683
622
|
*/
|
|
684
623
|
function secureCompare(a, b) {
|
|
685
624
|
if (a.length !== b.length) return false;
|
|
@@ -688,28 +627,19 @@ function secureCompare(a, b) {
|
|
|
688
627
|
if (bufA.length !== a.length / 2 || bufB.length !== b.length / 2) return false;
|
|
689
628
|
return timingSafeEqual(bufA, bufB);
|
|
690
629
|
}
|
|
691
|
-
/**
|
|
692
|
-
* Securely compare two arbitrary strings using timing-safe comparison.
|
|
693
|
-
* Unlike secureCompare, this works with any string encoding (UUIDs, tokens, etc.).
|
|
694
|
-
*/
|
|
630
|
+
/** Timing-safe comparison for arbitrary strings — unlike secureCompare, not hex-only. */
|
|
695
631
|
function secureStringCompare(a, b) {
|
|
696
632
|
const bufA = Buffer.from(a, "utf8");
|
|
697
633
|
const bufB = Buffer.from(b, "utf8");
|
|
698
634
|
if (bufA.length !== bufB.length) return false;
|
|
699
635
|
return timingSafeEqual(bufA, bufB);
|
|
700
636
|
}
|
|
701
|
-
/**
|
|
702
|
-
* Build a URL with token and optional email parameters.
|
|
703
|
-
*/
|
|
704
637
|
function buildTokenUrl(baseUrl, token, email) {
|
|
705
638
|
const url = new URL(baseUrl);
|
|
706
639
|
url.searchParams.set("token", token);
|
|
707
640
|
if (email) url.searchParams.set("email", email);
|
|
708
641
|
return url.toString();
|
|
709
642
|
}
|
|
710
|
-
/**
|
|
711
|
-
* Parse a URL to extract token and email parameters.
|
|
712
|
-
*/
|
|
713
643
|
function parseTokenUrl(url) {
|
|
714
644
|
try {
|
|
715
645
|
const parsed = new URL(url);
|
|
@@ -765,7 +695,6 @@ var SessionGuard = class {
|
|
|
765
695
|
this.cachedUser = sanitized;
|
|
766
696
|
return sanitized;
|
|
767
697
|
}
|
|
768
|
-
/** Strip auth-internal fields before a record is cached or exposed. */
|
|
769
698
|
sanitizeUser(user) {
|
|
770
699
|
return sanitizeUser(this.provider, user);
|
|
771
700
|
}
|
|
@@ -889,35 +818,16 @@ var MemoryApiTokenStore = class {
|
|
|
889
818
|
const token = this.tokens.get(id);
|
|
890
819
|
if (token) token.lastUsedAt = timestamp;
|
|
891
820
|
}
|
|
892
|
-
/**
|
|
893
|
-
* Clear all tokens (useful for testing).
|
|
894
|
-
*/
|
|
895
821
|
clear() {
|
|
896
822
|
this.tokens.clear();
|
|
897
823
|
this.byHash.clear();
|
|
898
824
|
}
|
|
899
|
-
/**
|
|
900
|
-
* Get the number of stored tokens.
|
|
901
|
-
*/
|
|
902
825
|
get size() {
|
|
903
826
|
return this.tokens.size;
|
|
904
827
|
}
|
|
905
828
|
};
|
|
906
829
|
/**
|
|
907
830
|
* 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
831
|
*/
|
|
922
832
|
async function createApiToken(store, options) {
|
|
923
833
|
const { name, userId, abilities = ["*"], expiresIn = null, tokenLength = 32 } = options;
|
|
@@ -955,39 +865,27 @@ function parseApiToken(plainTextToken) {
|
|
|
955
865
|
};
|
|
956
866
|
}
|
|
957
867
|
/**
|
|
958
|
-
* Extract the bearer token from an Authorization header
|
|
959
|
-
*
|
|
960
|
-
* `
|
|
961
|
-
*
|
|
868
|
+
* Extract the bearer token from an Authorization header. The one parsing rule
|
|
869
|
+
* shared by `createBearerTokenMiddleware`, `TokenGuard` and `hasBearerHeader`.
|
|
870
|
+
* `\S` keeps the match linear — `\s+(.+)` backtracks quadratically when a
|
|
871
|
+
* trailing newline makes `$` unreachable, on a pre-authentication header — and
|
|
872
|
+
* makes an all-whitespace token "not a bearer request", so CSRF is not skipped.
|
|
962
873
|
*/
|
|
963
874
|
function readBearerToken(header) {
|
|
964
875
|
if (!header) return null;
|
|
965
|
-
const match = header.match(/^Bearer\s+(
|
|
876
|
+
const match = header.match(/^Bearer\s+(\S.*)$/i);
|
|
966
877
|
return match ? match[1] : null;
|
|
967
878
|
}
|
|
968
879
|
/**
|
|
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.
|
|
880
|
+
* The one answer to "is this request bearer-authenticated?", shared by
|
|
881
|
+
* `AuthManager.resolveGuardName` and the CSRF skip for cookie-less bearer
|
|
882
|
+
* requests, which must classify a request identically.
|
|
974
883
|
*/
|
|
975
884
|
function hasBearerHeader(ctx) {
|
|
976
885
|
return readBearerToken(ctx.req.header("Authorization")) !== null;
|
|
977
886
|
}
|
|
978
887
|
/**
|
|
979
888
|
* 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
889
|
*/
|
|
992
890
|
async function verifyApiToken(plainTextToken, store, options = {}) {
|
|
993
891
|
const { updateLastUsed = true } = options;
|
|
@@ -1029,35 +927,18 @@ function tokenCanAny(token, abilities) {
|
|
|
1029
927
|
}
|
|
1030
928
|
/**
|
|
1031
929
|
* Revoke (delete) an API token.
|
|
1032
|
-
*
|
|
1033
|
-
* @example
|
|
1034
|
-
* ```ts
|
|
1035
|
-
* await revokeApiToken(tokenId, store)
|
|
1036
|
-
* ```
|
|
1037
930
|
*/
|
|
1038
931
|
async function revokeApiToken(id, store) {
|
|
1039
932
|
await store.delete(id);
|
|
1040
933
|
}
|
|
1041
934
|
/**
|
|
1042
935
|
* 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
936
|
*/
|
|
1050
937
|
async function revokeAllApiTokens(userId, store) {
|
|
1051
938
|
await store.deleteForUser(userId);
|
|
1052
939
|
}
|
|
1053
940
|
/**
|
|
1054
941
|
* 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
942
|
*/
|
|
1062
943
|
async function getUserApiTokens(userId, store) {
|
|
1063
944
|
return store.findByUserId(userId);
|
|
@@ -1068,25 +949,9 @@ async function getUserApiTokens(userId, store) {
|
|
|
1068
949
|
const API_TOKEN_KEY = "guren:api-token";
|
|
1069
950
|
/**
|
|
1070
951
|
* Create middleware that authenticates requests using Bearer tokens.
|
|
1071
|
-
*
|
|
1072
952
|
* @example
|
|
1073
953
|
* ```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
|
-
* }))
|
|
954
|
+
* app.use('/api/*', createBearerTokenMiddleware({ store, abilities: ['posts:delete'] }))
|
|
1090
955
|
* ```
|
|
1091
956
|
*/
|
|
1092
957
|
function createBearerTokenMiddleware(options) {
|
|
@@ -1126,14 +991,6 @@ function createBearerTokenMiddleware(options) {
|
|
|
1126
991
|
}
|
|
1127
992
|
/**
|
|
1128
993
|
* 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
994
|
*/
|
|
1138
995
|
function getApiToken(ctx) {
|
|
1139
996
|
return ctx.get(API_TOKEN_KEY);
|
|
@@ -1142,14 +999,6 @@ function getApiToken(ctx) {
|
|
|
1142
999
|
* Get the authenticated API token from the request context, or throw.
|
|
1143
1000
|
*
|
|
1144
1001
|
* @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
1002
|
*/
|
|
1154
1003
|
function getApiTokenOrFail(ctx) {
|
|
1155
1004
|
const result = getApiToken(ctx);
|
|
@@ -1159,28 +1008,10 @@ function getApiTokenOrFail(ctx) {
|
|
|
1159
1008
|
//#endregion
|
|
1160
1009
|
//#region src/auth/TokenGuard.ts
|
|
1161
1010
|
/**
|
|
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.
|
|
1011
|
+
* Bearer-token Guard (RFC 0016 Phase 0). Credential flows (`attempt`,
|
|
1012
|
+
* `login`, `validate`) throw; `logout()` revokes the presented token and
|
|
1013
|
+
* leaves a co-present session alone. Answers authentication only — token
|
|
1014
|
+
* abilities are enforced elsewhere (`tokenCan*`, the RFC 0016 scope gate).
|
|
1184
1015
|
*/
|
|
1185
1016
|
var TokenGuard = class {
|
|
1186
1017
|
ctx;
|
|
@@ -1292,9 +1123,8 @@ var AuthManager = class {
|
|
|
1292
1123
|
* The guard name an unqualified `auth.guard()` / `auth.user()` call resolves
|
|
1293
1124
|
* to for this request. Explicit names always win; otherwise a registered
|
|
1294
1125
|
* token guard is selected when the request carries a Bearer Authorization
|
|
1295
|
-
* header, falling back to the default (session) guard
|
|
1296
|
-
*
|
|
1297
|
-
* requests flow through the same auth surface without configuration.
|
|
1126
|
+
* header, falling back to the default (session) guard — the composite-guard
|
|
1127
|
+
* rule from RFC 0016.
|
|
1298
1128
|
*/
|
|
1299
1129
|
resolveGuardName(ctx, name) {
|
|
1300
1130
|
if (name) return name;
|
|
@@ -1317,13 +1147,11 @@ var AuthManager = class {
|
|
|
1317
1147
|
return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
|
|
1318
1148
|
}
|
|
1319
1149
|
/**
|
|
1320
|
-
*
|
|
1321
|
-
*
|
|
1150
|
+
* Register a model-based authentication provider and session guard — the
|
|
1151
|
+
* common case of authenticating users via a database model.
|
|
1322
1152
|
*
|
|
1323
|
-
* @param
|
|
1324
|
-
* @param
|
|
1325
|
-
* @param providerName - Name for the provider (defaults to 'users')
|
|
1326
|
-
* @param guardName - Name for the guard (defaults to 'web')
|
|
1153
|
+
* @param providerName - Defaults to 'users'
|
|
1154
|
+
* @param guardName - Defaults to 'web'
|
|
1327
1155
|
*/
|
|
1328
1156
|
useModel(model, options = {}, providerName = "users", guardName = "web") {
|
|
1329
1157
|
const defaultOptions = {
|
|
@@ -1344,15 +1172,9 @@ var AuthManager = class {
|
|
|
1344
1172
|
/**
|
|
1345
1173
|
* Register a bearer-token guard backed by an ApiTokenStore and enable
|
|
1346
1174
|
* 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')
|
|
1175
|
+
* resolve to this guard, everything else keeps the default (session) guard.
|
|
1176
|
+
* Without `options.provider`, `auth.user()` resolves to a minimal `{ id }`
|
|
1177
|
+
* record (enough for Gate/policy evaluation).
|
|
1356
1178
|
*/
|
|
1357
1179
|
useTokens(store, options = {}) {
|
|
1358
1180
|
const guardName = options.guardName ?? "token";
|
|
@@ -1370,33 +1192,21 @@ var AuthManager = class {
|
|
|
1370
1192
|
this.apiTokenOptions = { ...options };
|
|
1371
1193
|
}
|
|
1372
1194
|
/**
|
|
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)`
|
|
1195
|
+
* The options the last `useTokens()` call configured its guard with. Read by
|
|
1196
|
+
* machinery that has to *replace* the store without changing anything else —
|
|
1197
|
+
* `guren tool:dev` installs an ephemeral store, and a bare `useTokens(store)`
|
|
1378
1198
|
* silently dropped the app's `provider`, so a token resolved to a bare
|
|
1379
|
-
* `{ id }`
|
|
1380
|
-
* field behaved differently for no stated reason.
|
|
1199
|
+
* `{ id }` and every policy reading a user field behaved differently.
|
|
1381
1200
|
*/
|
|
1382
1201
|
getApiTokenOptions() {
|
|
1383
1202
|
return { ...this.apiTokenOptions };
|
|
1384
1203
|
}
|
|
1385
1204
|
/**
|
|
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`).
|
|
1205
|
+
* The token store {@link useTokens} was configured with, or `undefined`. The
|
|
1206
|
+
* one path by which out-of-request machinery (`guren token:issue`, the App MCP
|
|
1207
|
+
* adapter's principal lookup) reaches the store the guard verifies against —
|
|
1208
|
+
* otherwise `store` is closed over inside the guard factory. On this class
|
|
1209
|
+
* rather than `AuthManagerContract`, which describes what a *request* needs.
|
|
1400
1210
|
*/
|
|
1401
1211
|
getApiTokenStore() {
|
|
1402
1212
|
return this.apiTokenStore ?? void 0;
|
|
@@ -1405,19 +1215,17 @@ var AuthManager = class {
|
|
|
1405
1215
|
//#endregion
|
|
1406
1216
|
//#region src/support/redirect-target.ts
|
|
1407
1217
|
/**
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1218
|
+
* Open-redirect classification shared by the redirect-safety middleware and the
|
|
1219
|
+
* OAuth `redirectTo` sanitizer. Every hardening fix belongs here so the two
|
|
1220
|
+
* layers cannot drift.
|
|
1411
1221
|
*/
|
|
1412
|
-
/**
|
|
1222
|
+
/** Defuses backslash tricks such as `/\evil.com`. */
|
|
1413
1223
|
function normalizeRedirectTarget(value) {
|
|
1414
1224
|
return value.replace(/\\/g, "/");
|
|
1415
1225
|
}
|
|
1416
|
-
/** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
|
|
1417
1226
|
function isAppRelativePath(value) {
|
|
1418
1227
|
return value.startsWith("/") && !value.startsWith("//");
|
|
1419
1228
|
}
|
|
1420
|
-
/** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
|
|
1421
1229
|
function hostMatchesAllowlist(target, allowedHosts) {
|
|
1422
1230
|
const hostname = target.hostname.toLowerCase();
|
|
1423
1231
|
const host = target.host.toLowerCase();
|
|
@@ -1432,20 +1240,16 @@ function hostMatchesAllowlist(target, allowedHosts) {
|
|
|
1432
1240
|
/** Session key holding the per-browser bindings between authorize and callback. */
|
|
1433
1241
|
const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
|
|
1434
1242
|
/**
|
|
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.
|
|
1243
|
+
* How many unfinished flows one browser may have bindings for. An abandoned
|
|
1244
|
+
* flow leaves an entry behind until it expires, so the list is capped; beyond
|
|
1245
|
+
* it the oldest is dropped and that flow's callback fails.
|
|
1441
1246
|
*/
|
|
1442
1247
|
const MAX_PENDING_SESSION_BINDINGS = 5;
|
|
1443
1248
|
let warnedAboutUnboundState = false;
|
|
1444
1249
|
/**
|
|
1445
1250
|
* 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.
|
|
1251
|
+
* attack `state` exists to stop. Verification stays permissive so older apps
|
|
1252
|
+
* keep working, so this warning is the only thing telling them they are exposed.
|
|
1449
1253
|
*/
|
|
1450
1254
|
function warnOnceAboutUnboundState() {
|
|
1451
1255
|
if (warnedAboutUnboundState) return;
|
|
@@ -1474,11 +1278,9 @@ function issueSessionBinding(session) {
|
|
|
1474
1278
|
return generateToken(DEFAULT_STATE_LENGTH);
|
|
1475
1279
|
}
|
|
1476
1280
|
/**
|
|
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.
|
|
1281
|
+
* Park a minted binding against the state it belongs to. Keyed by state rather
|
|
1282
|
+
* than kept in one slot, so a browser can have several flows in flight without
|
|
1283
|
+
* each `authorize()` invalidating the one before it.
|
|
1482
1284
|
*/
|
|
1483
1285
|
function rememberSessionBinding(session, stateHash, binding, expiresAt) {
|
|
1484
1286
|
const pending = readPendingBindings(session);
|
|
@@ -1490,11 +1292,9 @@ function rememberSessionBinding(session, stateHash, binding, expiresAt) {
|
|
|
1490
1292
|
session.set(OAUTH_SESSION_BINDING_KEY, pending.slice(Math.max(0, pending.length - MAX_PENDING_SESSION_BINDINGS)));
|
|
1491
1293
|
}
|
|
1492
1294
|
/**
|
|
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.
|
|
1295
|
+
* Take the binding belonging to this callback's state, leaving the rest. Only
|
|
1296
|
+
* the matching entry is removed: a forged callback carrying an unknown state
|
|
1297
|
+
* must not be able to strip a real flow's binding and lock the visitor out.
|
|
1498
1298
|
*/
|
|
1499
1299
|
function consumeSessionBinding(session, stateHash) {
|
|
1500
1300
|
if (!session) return void 0;
|
|
@@ -1594,10 +1394,9 @@ var OAuthManager = class {
|
|
|
1594
1394
|
return profile;
|
|
1595
1395
|
}
|
|
1596
1396
|
/**
|
|
1597
|
-
* Verify the callback and return the user profile together with the
|
|
1598
|
-
*
|
|
1599
|
-
* pass to a redirect response
|
|
1600
|
-
* only.
|
|
1397
|
+
* Verify the callback and return the user profile together with the sanitized
|
|
1398
|
+
* `redirectTo` stored at authorize time — app-relative paths and allowlisted
|
|
1399
|
+
* hosts only, so it is safe to pass to a redirect response.
|
|
1601
1400
|
*/
|
|
1602
1401
|
async handleCallback(providerName, payload) {
|
|
1603
1402
|
const provider = this.getProvider(providerName);
|
|
@@ -1642,11 +1441,9 @@ async function verifyOAuthState(state, provider, store, config = {}, bindTo) {
|
|
|
1642
1441
|
}
|
|
1643
1442
|
/**
|
|
1644
1443
|
* Whether the presented value matches the binding recorded at authorize time.
|
|
1645
|
-
*
|
|
1646
1444
|
* 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.
|
|
1445
|
+
* adopted `bindTo` keeps working; a state created *with* one is useless to a
|
|
1446
|
+
* browser that cannot present it, so a missing or wrong value fails.
|
|
1650
1447
|
*/
|
|
1651
1448
|
function bindingMatches(stored, presented, hashAlgorithm) {
|
|
1652
1449
|
if (!stored) {
|
|
@@ -1663,11 +1460,10 @@ async function findAndDeleteState(store, stateHash) {
|
|
|
1663
1460
|
return payload;
|
|
1664
1461
|
}
|
|
1665
1462
|
/**
|
|
1666
|
-
* Reduce a `redirectTo` value to a safe target: app-relative paths always
|
|
1667
|
-
*
|
|
1668
|
-
*
|
|
1669
|
-
*
|
|
1670
|
-
* `undefined`.
|
|
1463
|
+
* Reduce a `redirectTo` value to a safe target: app-relative paths always pass;
|
|
1464
|
+
* absolute http(s) URLs pass only when their host is in the allowlist (with
|
|
1465
|
+
* `*.example.com` wildcards). Everything else — protocol-relative URLs,
|
|
1466
|
+
* backslash tricks, `javascript:` and other schemes — returns `undefined`.
|
|
1671
1467
|
*/
|
|
1672
1468
|
function sanitizeOAuthRedirect(redirectTo, allowedHosts = []) {
|
|
1673
1469
|
const value = redirectTo?.trim();
|
|
@@ -1845,8 +1641,8 @@ var AuthenticatableModel = class extends Model {
|
|
|
1845
1641
|
* Credential columns can never be mass-assigned: the resolved password-hash
|
|
1846
1642
|
* column (unless the model hashes in place into the password field itself)
|
|
1847
1643
|
* and the remember-token column. Resolved at call time so a renamed column
|
|
1848
|
-
* stays covered. Use `forceCreate()`/`forceUpdate()` for trusted
|
|
1849
|
-
*
|
|
1644
|
+
* stays covered. Use `forceCreate()`/`forceUpdate()` for trusted server-side
|
|
1645
|
+
* values such as `passwordHash: 'oauth:...'`.
|
|
1850
1646
|
*/
|
|
1851
1647
|
static deniedFields() {
|
|
1852
1648
|
const denied = [...super.deniedFields()];
|
|
@@ -1874,10 +1670,30 @@ var AuthenticatableModel = class extends Model {
|
|
|
1874
1670
|
}
|
|
1875
1671
|
};
|
|
1876
1672
|
//#endregion
|
|
1877
|
-
//#region src/auth/
|
|
1673
|
+
//#region src/auth/signed-token.ts
|
|
1878
1674
|
/**
|
|
1879
|
-
*
|
|
1675
|
+
* Read the claims of a signed one-time token, deciding expiry from the `exp`
|
|
1676
|
+
* claim signed into it rather than from the store's copy.
|
|
1677
|
+
*
|
|
1678
|
+
* The signature is checked before anything is deleted, so the housekeeping
|
|
1679
|
+
* `store.delete` only ever runs for an id this app issued.
|
|
1880
1680
|
*/
|
|
1681
|
+
async function readSignedTokenClaims(signer, token, purpose, store) {
|
|
1682
|
+
const claims = signer.verify(token, { purpose });
|
|
1683
|
+
if (claims?.id && claims.email) return {
|
|
1684
|
+
id: claims.id,
|
|
1685
|
+
email: claims.email
|
|
1686
|
+
};
|
|
1687
|
+
const expired = signer.verify(token, {
|
|
1688
|
+
purpose,
|
|
1689
|
+
allowExpired: true
|
|
1690
|
+
});
|
|
1691
|
+
if (expired?.id) await store.delete(expired.id);
|
|
1692
|
+
return null;
|
|
1693
|
+
}
|
|
1694
|
+
//#endregion
|
|
1695
|
+
//#region src/auth/password-reset.ts
|
|
1696
|
+
/** In-memory token store for testing and development. */
|
|
1881
1697
|
var MemoryPasswordResetStore = class {
|
|
1882
1698
|
tokens = /* @__PURE__ */ new Map();
|
|
1883
1699
|
async store(tokenId, email, expiresAt) {
|
|
@@ -1912,14 +1728,7 @@ const PASSWORD_RESET_PURPOSE = "password-reset";
|
|
|
1912
1728
|
function createPasswordResetSigner() {
|
|
1913
1729
|
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "password-reset-signing"));
|
|
1914
1730
|
}
|
|
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
|
-
*/
|
|
1731
|
+
/** Create a password reset token for a user. */
|
|
1923
1732
|
async function createPasswordResetToken(email, store, config = {}) {
|
|
1924
1733
|
const expiresIn = config.expiresIn ?? DEFAULT_EXPIRES_IN;
|
|
1925
1734
|
const tokenLength = config.tokenLength ?? DEFAULT_TOKEN_LENGTH;
|
|
@@ -1941,75 +1750,40 @@ async function createPasswordResetToken(email, store, config = {}) {
|
|
|
1941
1750
|
expiresAt
|
|
1942
1751
|
};
|
|
1943
1752
|
}
|
|
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);
|
|
1753
|
+
/** Verify a password reset token, returning the email it was issued for. */
|
|
1754
|
+
async function verifyPasswordResetToken(token, store) {
|
|
1755
|
+
const claims = await readSignedTokenClaims(createPasswordResetSigner(), token, PASSWORD_RESET_PURPOSE, store);
|
|
1756
|
+
if (!claims) return null;
|
|
1757
|
+
const record = await store.find(claims.id);
|
|
1963
1758
|
if (!record) return null;
|
|
1964
|
-
return record.email.toLowerCase() ===
|
|
1759
|
+
return record.email.toLowerCase() === claims.email.toLowerCase() ? record.email : null;
|
|
1965
1760
|
}
|
|
1966
1761
|
/**
|
|
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
|
|
1762
|
+
* Complete a password reset: update the user's password and invalidate the
|
|
1763
|
+
* token. Returns the user, or `null` when the token is invalid.
|
|
1976
1764
|
*/
|
|
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);
|
|
1765
|
+
async function completePasswordReset(token, newPassword, store, provider, updatePassword) {
|
|
1766
|
+
const claims = await readSignedTokenClaims(createPasswordResetSigner(), token, PASSWORD_RESET_PURPOSE, store);
|
|
1767
|
+
if (!claims) return null;
|
|
1768
|
+
const record = await store.find(claims.id);
|
|
1988
1769
|
if (!record) return null;
|
|
1989
|
-
if (record.email.toLowerCase() !==
|
|
1770
|
+
if (record.email.toLowerCase() !== claims.email.toLowerCase()) return null;
|
|
1990
1771
|
const user = await provider.retrieveByCredentials({ email: record.email });
|
|
1991
1772
|
if (!user) {
|
|
1992
|
-
await store.delete(
|
|
1773
|
+
await store.delete(claims.id);
|
|
1993
1774
|
return null;
|
|
1994
1775
|
}
|
|
1995
1776
|
await updatePassword(user, newPassword);
|
|
1996
|
-
await store.delete(
|
|
1777
|
+
await store.delete(claims.id);
|
|
1997
1778
|
return user;
|
|
1998
1779
|
}
|
|
1999
|
-
/**
|
|
2000
|
-
* Build a password reset URL from a base URL and token.
|
|
2001
|
-
*/
|
|
1780
|
+
/** Build a password reset URL from a base URL and token. */
|
|
2002
1781
|
const buildPasswordResetUrl = buildTokenUrl;
|
|
2003
|
-
/**
|
|
2004
|
-
* Parse a password reset URL to extract the token and optional email.
|
|
2005
|
-
*/
|
|
1782
|
+
/** Parse a password reset URL to extract the token and optional email. */
|
|
2006
1783
|
const parsePasswordResetUrl = parseTokenUrl;
|
|
2007
1784
|
//#endregion
|
|
2008
1785
|
//#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
|
-
*/
|
|
1786
|
+
/** In-memory store for testing. Tokens are lost on restart. */
|
|
2013
1787
|
var MemoryEmailVerificationStore = class {
|
|
2014
1788
|
tokens = /* @__PURE__ */ new Map();
|
|
2015
1789
|
async store(token) {
|
|
@@ -2025,15 +1799,11 @@ var MemoryEmailVerificationStore = class {
|
|
|
2025
1799
|
const normalizedEmail = email.toLowerCase();
|
|
2026
1800
|
for (const [key, token] of this.tokens.entries()) if (token.email.toLowerCase() === normalizedEmail) this.tokens.delete(key);
|
|
2027
1801
|
}
|
|
2028
|
-
/**
|
|
2029
|
-
* Clear all tokens (useful for testing).
|
|
2030
|
-
*/
|
|
1802
|
+
/** Clear all tokens (useful for testing). */
|
|
2031
1803
|
clear() {
|
|
2032
1804
|
this.tokens.clear();
|
|
2033
1805
|
}
|
|
2034
|
-
/**
|
|
2035
|
-
* Get the count of stored tokens (useful for testing).
|
|
2036
|
-
*/
|
|
1806
|
+
/** Count of stored tokens (useful for testing). */
|
|
2037
1807
|
get size() {
|
|
2038
1808
|
return this.tokens.size;
|
|
2039
1809
|
}
|
|
@@ -2047,27 +1817,8 @@ function createEmailVerificationSigner() {
|
|
|
2047
1817
|
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "email-verification-signing"));
|
|
2048
1818
|
}
|
|
2049
1819
|
/**
|
|
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
|
-
* ```
|
|
1820
|
+
* Create a new email verification token; the raw token is returned to send by
|
|
1821
|
+
* email and is never stored.
|
|
2071
1822
|
*/
|
|
2072
1823
|
async function createEmailVerificationToken(email, store, config = {}) {
|
|
2073
1824
|
const { expiresIn, tokenLength } = {
|
|
@@ -2098,127 +1849,43 @@ async function createEmailVerificationToken(email, store, config = {}) {
|
|
|
2098
1849
|
};
|
|
2099
1850
|
}
|
|
2100
1851
|
/**
|
|
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
|
-
* ```
|
|
1852
|
+
* Verify an email verification token, returning the email address it was
|
|
1853
|
+
* issued for or `null` when it is invalid or expired.
|
|
2119
1854
|
*/
|
|
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);
|
|
1855
|
+
async function verifyEmailToken(token, store) {
|
|
1856
|
+
const claims = await readSignedTokenClaims(createEmailVerificationSigner(), token, EMAIL_VERIFICATION_PURPOSE, store);
|
|
1857
|
+
if (!claims) return null;
|
|
1858
|
+
const storedToken = await store.findByTokenId(claims.id);
|
|
2131
1859
|
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;
|
|
1860
|
+
return storedToken.email.toLowerCase() === claims.email.toLowerCase() ? storedToken.email : null;
|
|
2137
1861
|
}
|
|
2138
1862
|
/**
|
|
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
|
-
* ```
|
|
1863
|
+
* Complete email verification by consuming the token. Returns the result of
|
|
1864
|
+
* `markVerified`, or `null` when the token is invalid.
|
|
2163
1865
|
*/
|
|
2164
1866
|
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);
|
|
1867
|
+
const claims = await readSignedTokenClaims(createEmailVerificationSigner(), token, EMAIL_VERIFICATION_PURPOSE, store);
|
|
1868
|
+
if (!claims) return null;
|
|
1869
|
+
const storedToken = await store.findByTokenId(claims.id);
|
|
2175
1870
|
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;
|
|
1871
|
+
if (storedToken.email.toLowerCase() !== claims.email.toLowerCase()) return null;
|
|
2181
1872
|
const result = await markVerified(storedToken.email);
|
|
2182
|
-
await store.delete(
|
|
1873
|
+
await store.delete(claims.id);
|
|
2183
1874
|
return result;
|
|
2184
1875
|
}
|
|
2185
|
-
/**
|
|
2186
|
-
* Build a verification URL.
|
|
2187
|
-
*/
|
|
1876
|
+
/** Build a verification URL. */
|
|
2188
1877
|
const buildVerificationUrl = buildTokenUrl;
|
|
2189
|
-
/**
|
|
2190
|
-
* Parse a verification URL to extract token and email.
|
|
2191
|
-
*/
|
|
1878
|
+
/** Parse a verification URL to extract token and email. */
|
|
2192
1879
|
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
|
-
*/
|
|
1880
|
+
/** Whether a user's `emailVerifiedAt` is set. */
|
|
2207
1881
|
function isEmailVerified(user) {
|
|
2208
1882
|
return user?.emailVerifiedAt != null;
|
|
2209
1883
|
}
|
|
2210
1884
|
/**
|
|
2211
1885
|
* Middleware factory to require verified email.
|
|
2212
|
-
*
|
|
2213
|
-
* @param options - Configuration options
|
|
2214
|
-
* @returns Middleware function
|
|
2215
|
-
*
|
|
2216
1886
|
* @example
|
|
2217
1887
|
* ```ts
|
|
2218
|
-
*
|
|
2219
|
-
* requireAuthenticated(),
|
|
2220
|
-
* requireVerifiedEmail({ redirectTo: '/verify-email' })
|
|
2221
|
-
* )
|
|
1888
|
+
* requireVerifiedEmail({ redirectTo: '/verify-email' })
|
|
2222
1889
|
* ```
|
|
2223
1890
|
*/
|
|
2224
1891
|
function requireVerifiedEmail(options = {}) {
|