@guren/server 2.14.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-CzrwKeDp.js → Hash-D2DFd8xX.js} +12 -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 +31 -0
- package/dist/agent/approval.d.ts +184 -0
- package/dist/agent/audit-emitter.d.ts +36 -0
- package/dist/agent/audit.d.ts +67 -0
- package/dist/agent/derive.d.ts +32 -66
- package/dist/agent/dispatch.d.ts +53 -63
- package/dist/agent/events.d.ts +11 -19
- package/dist/agent/meta-tools.d.ts +34 -0
- package/dist/agent/public.d.ts +14 -0
- package/dist/agent/public.js +2 -0
- 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 +9 -5
- package/dist/auth/password/PasswordHasher.d.ts +7 -0
- package/dist/auth/password/hash-format.d.ts +11 -0
- 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-BSUc14CD.js → auth-CbdPH4Cd.js} +252 -496
- 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-BxU-LIfF.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 +10 -12
- 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-BAwzftws.js +238 -0
- 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-DJtkkhiw.js → encryption-uwP3Di4D.js} +13 -79
- 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 +16 -18
- 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 +14 -0
- package/dist/http/request.d.ts +49 -48
- 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 +21 -0
- 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 +13 -4
- package/dist/index.js +1036 -3080
- package/dist/internal/agent-preflight.d.ts +9 -21
- package/dist/internal/request.d.ts +10 -17
- package/dist/internal/request.js +2 -2
- 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 -5
- package/dist/logging/channels/FileChannel.d.ts +1 -3
- package/dist/logging/daily-file-path.d.ts +15 -0
- package/dist/logging/index.d.ts +1 -0
- package/dist/logging/index.js +2 -2
- package/dist/logging/types.d.ts +13 -45
- package/dist/{logging-CPaRMuPP.js → logging-zOY1XCtq.js} +83 -129
- 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 -253
- 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 +108 -74
- 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-BGfWbPYp.js → vite-manifest-CTQp-SOo.js} +34 -58
- package/package.json +6 -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-CRVuIiQr.js +0 -78
|
@@ -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-D2DFd8xX.js";
|
|
3
4
|
import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
|
|
4
|
-
import { n as getAuthContext } from "./context-
|
|
5
|
-
import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-CzrwKeDp.js";
|
|
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
|
}
|
|
@@ -370,6 +345,35 @@ var RequestAuthContext = class {
|
|
|
370
345
|
await this.guard().logout();
|
|
371
346
|
}
|
|
372
347
|
};
|
|
348
|
+
/**
|
|
349
|
+
* Prefixes of every hash format the built-in hashers produce: Bun's argon2
|
|
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.
|
|
354
|
+
*/
|
|
355
|
+
const HASH_PREFIXES = [
|
|
356
|
+
"$argon2id$",
|
|
357
|
+
"$argon2i$",
|
|
358
|
+
"$argon2d$",
|
|
359
|
+
"$2a$",
|
|
360
|
+
"$2b$",
|
|
361
|
+
"$2y$",
|
|
362
|
+
"$scrypt$"
|
|
363
|
+
];
|
|
364
|
+
function looksLikePasswordHash(value) {
|
|
365
|
+
return HASH_PREFIXES.some((prefix) => value.startsWith(prefix));
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
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.
|
|
373
|
+
*/
|
|
374
|
+
function assertVerifyArgumentOrder(hashed, plain) {
|
|
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).");
|
|
376
|
+
}
|
|
373
377
|
//#endregion
|
|
374
378
|
//#region src/auth/password/ScryptHasher.ts
|
|
375
379
|
var ScryptHasher = class {
|
|
@@ -395,6 +399,7 @@ var ScryptHasher = class {
|
|
|
395
399
|
});
|
|
396
400
|
}
|
|
397
401
|
async verify(hashed, plain) {
|
|
402
|
+
assertVerifyArgumentOrder(hashed, plain);
|
|
398
403
|
return Bun.password.verify(plain, hashed);
|
|
399
404
|
}
|
|
400
405
|
needsRehash(hashed) {
|
|
@@ -423,12 +428,74 @@ var ScryptHasher = class {
|
|
|
423
428
|
}
|
|
424
429
|
};
|
|
425
430
|
//#endregion
|
|
431
|
+
//#region src/auth/password/NodeHasher.ts
|
|
432
|
+
/**
|
|
433
|
+
* Node.js-compatible password hasher using crypto.scrypt.
|
|
434
|
+
* Use this instead of ScryptHasher when deploying to non-Bun runtimes (e.g. AWS Lambda).
|
|
435
|
+
*/
|
|
436
|
+
var NodeHasher = class {
|
|
437
|
+
options;
|
|
438
|
+
constructor(options = {}) {
|
|
439
|
+
this.options = {
|
|
440
|
+
cost: options.cost,
|
|
441
|
+
memory: options.memory,
|
|
442
|
+
saltLength: options.saltLength,
|
|
443
|
+
keyLength: options.keyLength
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
async hash(plain) {
|
|
447
|
+
return hashPassword(plain, this.options);
|
|
448
|
+
}
|
|
449
|
+
async verify(hashed, plain) {
|
|
450
|
+
assertVerifyArgumentOrder(hashed, plain);
|
|
451
|
+
return verifyPassword(plain, hashed);
|
|
452
|
+
}
|
|
453
|
+
needsRehash(hashed) {
|
|
454
|
+
return needsRehash(hashed, this.options);
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
//#endregion
|
|
458
|
+
//#region src/auth/password/DefaultHasher.ts
|
|
459
|
+
/**
|
|
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`.
|
|
465
|
+
*/
|
|
466
|
+
var DefaultHasher = class {
|
|
467
|
+
bun;
|
|
468
|
+
node;
|
|
469
|
+
constructor() {
|
|
470
|
+
this.bun = typeof Bun !== "undefined" ? new ScryptHasher() : null;
|
|
471
|
+
this.node = new NodeHasher();
|
|
472
|
+
}
|
|
473
|
+
hash(plain) {
|
|
474
|
+
return (this.bun ?? this.node).hash(plain);
|
|
475
|
+
}
|
|
476
|
+
verify(hashed, plain) {
|
|
477
|
+
return this.delegateFor(hashed).verify(hashed, plain);
|
|
478
|
+
}
|
|
479
|
+
needsRehash(hashed) {
|
|
480
|
+
if (hashed.startsWith("$scrypt$") !== (this.bun === null)) return true;
|
|
481
|
+
return this.delegateFor(hashed).needsRehash(hashed);
|
|
482
|
+
}
|
|
483
|
+
delegateFor(hashed) {
|
|
484
|
+
if (hashed.startsWith("$scrypt$")) return this.node;
|
|
485
|
+
if (!this.bun) {
|
|
486
|
+
if (!looksLikePasswordHash(hashed)) throw new Error("This value is not a password hash in any format the built-in hashers produce, so it cannot be verified. A credential column holding a sentinel for a passwordless account should not reach verify().");
|
|
487
|
+
throw new Error("This password hash was written by Bun.password (Argon2id or bcrypt) and cannot be verified on a runtime without Bun. Hash formats follow the runtime that wrote them, so a column seeded under Bun has to be rehashed before a Node or Workers deploy can read it.");
|
|
488
|
+
}
|
|
489
|
+
return this.bun;
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
//#endregion
|
|
426
493
|
//#region src/auth/providers/UserProvider.ts
|
|
427
494
|
/**
|
|
428
|
-
* Run a user record through the provider's optional `sanitize` before it
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
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.
|
|
432
499
|
*/
|
|
433
500
|
function sanitizeUser(provider, user) {
|
|
434
501
|
return provider.sanitize ? provider.sanitize(user) : user;
|
|
@@ -471,7 +538,7 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
471
538
|
this.usernameColumn = options.usernameColumn ?? "email";
|
|
472
539
|
this.passwordColumn = options.passwordColumn ?? authModel?.resolvePasswordHashField() ?? "passwordHash";
|
|
473
540
|
this.rememberTokenColumn = options.rememberTokenColumn ?? authModel?.resolveRememberTokenField() ?? "rememberToken";
|
|
474
|
-
this.hasher = options.hasher ?? new
|
|
541
|
+
this.hasher = options.hasher ?? new DefaultHasher();
|
|
475
542
|
this.credentialsPasswordField = options.credentialsPasswordField ?? "password";
|
|
476
543
|
}
|
|
477
544
|
cast(record) {
|
|
@@ -497,7 +564,7 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
497
564
|
const plain = credentials[this.credentialsPasswordField];
|
|
498
565
|
if (typeof plain !== "string") return false;
|
|
499
566
|
const hashed = user[this.passwordColumn];
|
|
500
|
-
if (typeof hashed !== "string") {
|
|
567
|
+
if (typeof hashed !== "string" || !looksLikePasswordHash(hashed)) {
|
|
501
568
|
await this.hasher.hash("dummy-timing-equalization");
|
|
502
569
|
return false;
|
|
503
570
|
}
|
|
@@ -507,10 +574,9 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
507
574
|
return user[this.idColumn];
|
|
508
575
|
}
|
|
509
576
|
/**
|
|
510
|
-
* Strip the password hash, remember token, and the model's `hidden`
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
* 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()`.
|
|
514
580
|
*/
|
|
515
581
|
sanitize(user) {
|
|
516
582
|
const authModel = credentialColumnSource(this.model);
|
|
@@ -538,33 +604,21 @@ var ModelUserProvider = class extends BaseUserProvider {
|
|
|
538
604
|
};
|
|
539
605
|
//#endregion
|
|
540
606
|
//#region src/auth/utils.ts
|
|
541
|
-
/**
|
|
542
|
-
* Hash a token using SHA-256 or SHA-512.
|
|
543
|
-
*/
|
|
544
607
|
function hashToken(token, algorithm = "sha256") {
|
|
545
608
|
return createHash(algorithm).update(token).digest("hex");
|
|
546
609
|
}
|
|
547
|
-
/**
|
|
548
|
-
* Generate a secure random token.
|
|
549
|
-
*/
|
|
550
610
|
function generateToken(length = 32) {
|
|
551
611
|
return randomBytes(length).toString("hex");
|
|
552
612
|
}
|
|
553
|
-
/**
|
|
554
|
-
* Generate a random ID (16 bytes = 32 hex chars).
|
|
555
|
-
*/
|
|
613
|
+
/** Generate a random ID (16 bytes = 32 hex chars). */
|
|
556
614
|
function generateId() {
|
|
557
615
|
return randomBytes(16).toString("hex");
|
|
558
616
|
}
|
|
559
617
|
/**
|
|
560
|
-
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
563
|
-
*
|
|
564
|
-
* 'yyyy' both decode to nothing — and 'abcz' and 'abdz' both decode to the
|
|
565
|
-
* one byte they share — and would compare equal. A short decode is how the
|
|
566
|
-
* decoder reports that, which beats restating its grammar in a regex here.
|
|
567
|
-
* 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.
|
|
568
622
|
*/
|
|
569
623
|
function secureCompare(a, b) {
|
|
570
624
|
if (a.length !== b.length) return false;
|
|
@@ -573,28 +627,19 @@ function secureCompare(a, b) {
|
|
|
573
627
|
if (bufA.length !== a.length / 2 || bufB.length !== b.length / 2) return false;
|
|
574
628
|
return timingSafeEqual(bufA, bufB);
|
|
575
629
|
}
|
|
576
|
-
/**
|
|
577
|
-
* Securely compare two arbitrary strings using timing-safe comparison.
|
|
578
|
-
* Unlike secureCompare, this works with any string encoding (UUIDs, tokens, etc.).
|
|
579
|
-
*/
|
|
630
|
+
/** Timing-safe comparison for arbitrary strings — unlike secureCompare, not hex-only. */
|
|
580
631
|
function secureStringCompare(a, b) {
|
|
581
632
|
const bufA = Buffer.from(a, "utf8");
|
|
582
633
|
const bufB = Buffer.from(b, "utf8");
|
|
583
634
|
if (bufA.length !== bufB.length) return false;
|
|
584
635
|
return timingSafeEqual(bufA, bufB);
|
|
585
636
|
}
|
|
586
|
-
/**
|
|
587
|
-
* Build a URL with token and optional email parameters.
|
|
588
|
-
*/
|
|
589
637
|
function buildTokenUrl(baseUrl, token, email) {
|
|
590
638
|
const url = new URL(baseUrl);
|
|
591
639
|
url.searchParams.set("token", token);
|
|
592
640
|
if (email) url.searchParams.set("email", email);
|
|
593
641
|
return url.toString();
|
|
594
642
|
}
|
|
595
|
-
/**
|
|
596
|
-
* Parse a URL to extract token and email parameters.
|
|
597
|
-
*/
|
|
598
643
|
function parseTokenUrl(url) {
|
|
599
644
|
try {
|
|
600
645
|
const parsed = new URL(url);
|
|
@@ -650,7 +695,6 @@ var SessionGuard = class {
|
|
|
650
695
|
this.cachedUser = sanitized;
|
|
651
696
|
return sanitized;
|
|
652
697
|
}
|
|
653
|
-
/** Strip auth-internal fields before a record is cached or exposed. */
|
|
654
698
|
sanitizeUser(user) {
|
|
655
699
|
return sanitizeUser(this.provider, user);
|
|
656
700
|
}
|
|
@@ -774,35 +818,16 @@ var MemoryApiTokenStore = class {
|
|
|
774
818
|
const token = this.tokens.get(id);
|
|
775
819
|
if (token) token.lastUsedAt = timestamp;
|
|
776
820
|
}
|
|
777
|
-
/**
|
|
778
|
-
* Clear all tokens (useful for testing).
|
|
779
|
-
*/
|
|
780
821
|
clear() {
|
|
781
822
|
this.tokens.clear();
|
|
782
823
|
this.byHash.clear();
|
|
783
824
|
}
|
|
784
|
-
/**
|
|
785
|
-
* Get the number of stored tokens.
|
|
786
|
-
*/
|
|
787
825
|
get size() {
|
|
788
826
|
return this.tokens.size;
|
|
789
827
|
}
|
|
790
828
|
};
|
|
791
829
|
/**
|
|
792
830
|
* Create a new API token.
|
|
793
|
-
*
|
|
794
|
-
* @example
|
|
795
|
-
* ```ts
|
|
796
|
-
* const { plainTextToken, token } = await createApiToken(store, {
|
|
797
|
-
* name: 'My App Token',
|
|
798
|
-
* userId: user.id,
|
|
799
|
-
* abilities: ['read', 'write'],
|
|
800
|
-
* expiresIn: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
801
|
-
* })
|
|
802
|
-
*
|
|
803
|
-
* // Return plainTextToken to user - this is the only time it's available
|
|
804
|
-
* return ctx.json({ token: plainTextToken })
|
|
805
|
-
* ```
|
|
806
831
|
*/
|
|
807
832
|
async function createApiToken(store, options) {
|
|
808
833
|
const { name, userId, abilities = ["*"], expiresIn = null, tokenLength = 32 } = options;
|
|
@@ -840,39 +865,27 @@ function parseApiToken(plainTextToken) {
|
|
|
840
865
|
};
|
|
841
866
|
}
|
|
842
867
|
/**
|
|
843
|
-
* Extract the bearer token from an Authorization header
|
|
844
|
-
*
|
|
845
|
-
* `
|
|
846
|
-
*
|
|
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.
|
|
847
873
|
*/
|
|
848
874
|
function readBearerToken(header) {
|
|
849
875
|
if (!header) return null;
|
|
850
|
-
const match = header.match(/^Bearer\s+(
|
|
876
|
+
const match = header.match(/^Bearer\s+(\S.*)$/i);
|
|
851
877
|
return match ? match[1] : null;
|
|
852
878
|
}
|
|
853
879
|
/**
|
|
854
|
-
* The one answer to "is this request bearer-authenticated?"
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
-
* requests: both must classify a request identically, and a second copy of
|
|
858
|
-
* 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.
|
|
859
883
|
*/
|
|
860
884
|
function hasBearerHeader(ctx) {
|
|
861
885
|
return readBearerToken(ctx.req.header("Authorization")) !== null;
|
|
862
886
|
}
|
|
863
887
|
/**
|
|
864
888
|
* Verify an API token and return the associated user ID.
|
|
865
|
-
*
|
|
866
|
-
* @example
|
|
867
|
-
* ```ts
|
|
868
|
-
* const result = await verifyApiToken(plainTextToken, store)
|
|
869
|
-
*
|
|
870
|
-
* if (!result) {
|
|
871
|
-
* return ctx.json({ error: 'Invalid token' }, 401)
|
|
872
|
-
* }
|
|
873
|
-
*
|
|
874
|
-
* console.log(`User ${result.userId} authenticated with abilities:`, result.abilities)
|
|
875
|
-
* ```
|
|
876
889
|
*/
|
|
877
890
|
async function verifyApiToken(plainTextToken, store, options = {}) {
|
|
878
891
|
const { updateLastUsed = true } = options;
|
|
@@ -914,35 +927,18 @@ function tokenCanAny(token, abilities) {
|
|
|
914
927
|
}
|
|
915
928
|
/**
|
|
916
929
|
* Revoke (delete) an API token.
|
|
917
|
-
*
|
|
918
|
-
* @example
|
|
919
|
-
* ```ts
|
|
920
|
-
* await revokeApiToken(tokenId, store)
|
|
921
|
-
* ```
|
|
922
930
|
*/
|
|
923
931
|
async function revokeApiToken(id, store) {
|
|
924
932
|
await store.delete(id);
|
|
925
933
|
}
|
|
926
934
|
/**
|
|
927
935
|
* Revoke all API tokens for a user.
|
|
928
|
-
*
|
|
929
|
-
* @example
|
|
930
|
-
* ```ts
|
|
931
|
-
* // Revoke all tokens when user changes password
|
|
932
|
-
* await revokeAllApiTokens(user.id, store)
|
|
933
|
-
* ```
|
|
934
936
|
*/
|
|
935
937
|
async function revokeAllApiTokens(userId, store) {
|
|
936
938
|
await store.deleteForUser(userId);
|
|
937
939
|
}
|
|
938
940
|
/**
|
|
939
941
|
* Get all API tokens for a user.
|
|
940
|
-
*
|
|
941
|
-
* @example
|
|
942
|
-
* ```ts
|
|
943
|
-
* const tokens = await getUserApiTokens(user.id, store)
|
|
944
|
-
* // Returns tokens without the plain text (only metadata)
|
|
945
|
-
* ```
|
|
946
942
|
*/
|
|
947
943
|
async function getUserApiTokens(userId, store) {
|
|
948
944
|
return store.findByUserId(userId);
|
|
@@ -953,25 +949,9 @@ async function getUserApiTokens(userId, store) {
|
|
|
953
949
|
const API_TOKEN_KEY = "guren:api-token";
|
|
954
950
|
/**
|
|
955
951
|
* Create middleware that authenticates requests using Bearer tokens.
|
|
956
|
-
*
|
|
957
952
|
* @example
|
|
958
953
|
* ```ts
|
|
959
|
-
*
|
|
960
|
-
* app.use('/api/*', createBearerTokenMiddleware({ store }))
|
|
961
|
-
*
|
|
962
|
-
* // With ability requirement
|
|
963
|
-
* router.delete('/api/posts/:id', [PostController, 'destroy'],
|
|
964
|
-
* createBearerTokenMiddleware({
|
|
965
|
-
* store,
|
|
966
|
-
* abilities: ['posts:delete'],
|
|
967
|
-
* })
|
|
968
|
-
* )
|
|
969
|
-
*
|
|
970
|
-
* // With user loading
|
|
971
|
-
* app.use('/api/*', createBearerTokenMiddleware({
|
|
972
|
-
* store,
|
|
973
|
-
* loadUser: async (userId) => User.find(userId),
|
|
974
|
-
* }))
|
|
954
|
+
* app.use('/api/*', createBearerTokenMiddleware({ store, abilities: ['posts:delete'] }))
|
|
975
955
|
* ```
|
|
976
956
|
*/
|
|
977
957
|
function createBearerTokenMiddleware(options) {
|
|
@@ -1011,14 +991,6 @@ function createBearerTokenMiddleware(options) {
|
|
|
1011
991
|
}
|
|
1012
992
|
/**
|
|
1013
993
|
* Get the authenticated API token from the request context.
|
|
1014
|
-
*
|
|
1015
|
-
* @example
|
|
1016
|
-
* ```ts
|
|
1017
|
-
* router.get('/api/me', async (ctx) => {
|
|
1018
|
-
* const { token, userId, abilities } = getApiToken(ctx)!
|
|
1019
|
-
* return ctx.json({ userId, tokenName: token.name, abilities })
|
|
1020
|
-
* })
|
|
1021
|
-
* ```
|
|
1022
994
|
*/
|
|
1023
995
|
function getApiToken(ctx) {
|
|
1024
996
|
return ctx.get(API_TOKEN_KEY);
|
|
@@ -1027,14 +999,6 @@ function getApiToken(ctx) {
|
|
|
1027
999
|
* Get the authenticated API token from the request context, or throw.
|
|
1028
1000
|
*
|
|
1029
1001
|
* @throws {AuthenticationException} When no token is present in the context.
|
|
1030
|
-
*
|
|
1031
|
-
* @example
|
|
1032
|
-
* ```ts
|
|
1033
|
-
* router.get('/api/me', async (ctx) => {
|
|
1034
|
-
* const { token, userId, abilities } = getApiTokenOrFail(ctx)
|
|
1035
|
-
* return ctx.json({ userId, tokenName: token.name, abilities })
|
|
1036
|
-
* })
|
|
1037
|
-
* ```
|
|
1038
1002
|
*/
|
|
1039
1003
|
function getApiTokenOrFail(ctx) {
|
|
1040
1004
|
const result = getApiToken(ctx);
|
|
@@ -1044,28 +1008,10 @@ function getApiTokenOrFail(ctx) {
|
|
|
1044
1008
|
//#endregion
|
|
1045
1009
|
//#region src/auth/TokenGuard.ts
|
|
1046
1010
|
/**
|
|
1047
|
-
* Bearer-token
|
|
1048
|
-
*
|
|
1049
|
-
*
|
|
1050
|
-
*
|
|
1051
|
-
* SessionGuard implements — so `requireAuthenticated()`, `Controller.auth`,
|
|
1052
|
-
* and Gate resolution treat session- and token-authenticated requests
|
|
1053
|
-
* identically. On successful verification the result is also written to
|
|
1054
|
-
* `ctx[API_TOKEN_KEY]`, keeping `getApiToken(ctx)` and `tokenCan*` working
|
|
1055
|
-
* exactly as they do behind `createBearerTokenMiddleware` — and when that
|
|
1056
|
-
* middleware already verified this request's token, the guard reuses its
|
|
1057
|
-
* result instead of paying a second store read and lastUsedAt write.
|
|
1058
|
-
*
|
|
1059
|
-
* Credential flows do not apply to bearer tokens: `attempt()`, `login()` and
|
|
1060
|
-
* `validate()` throw. `logout()` is not a no-op — it revokes the presented
|
|
1061
|
-
* token, the closest meaningful analogue to ending a session. On a request
|
|
1062
|
-
* that carries a session cookie *and* a Bearer header, only the token is
|
|
1063
|
-
* revoked; end the session explicitly via `auth.guard('web').logout()`.
|
|
1064
|
-
*
|
|
1065
|
-
* This guard answers authentication only. Token *abilities* are not
|
|
1066
|
-
* consulted here or by Gate/policies — enforce them where the operation is
|
|
1067
|
-
* dispatched (`tokenCan*`, `createBearerTokenMiddleware({ abilities })`, or
|
|
1068
|
-
* 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).
|
|
1069
1015
|
*/
|
|
1070
1016
|
var TokenGuard = class {
|
|
1071
1017
|
ctx;
|
|
@@ -1177,9 +1123,8 @@ var AuthManager = class {
|
|
|
1177
1123
|
* The guard name an unqualified `auth.guard()` / `auth.user()` call resolves
|
|
1178
1124
|
* to for this request. Explicit names always win; otherwise a registered
|
|
1179
1125
|
* token guard is selected when the request carries a Bearer Authorization
|
|
1180
|
-
* header, falling back to the default (session) guard
|
|
1181
|
-
*
|
|
1182
|
-
* 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.
|
|
1183
1128
|
*/
|
|
1184
1129
|
resolveGuardName(ctx, name) {
|
|
1185
1130
|
if (name) return name;
|
|
@@ -1202,19 +1147,17 @@ var AuthManager = class {
|
|
|
1202
1147
|
return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
|
|
1203
1148
|
}
|
|
1204
1149
|
/**
|
|
1205
|
-
*
|
|
1206
|
-
*
|
|
1150
|
+
* Register a model-based authentication provider and session guard — the
|
|
1151
|
+
* common case of authenticating users via a database model.
|
|
1207
1152
|
*
|
|
1208
|
-
* @param
|
|
1209
|
-
* @param
|
|
1210
|
-
* @param providerName - Name for the provider (defaults to 'users')
|
|
1211
|
-
* @param guardName - Name for the guard (defaults to 'web')
|
|
1153
|
+
* @param providerName - Defaults to 'users'
|
|
1154
|
+
* @param guardName - Defaults to 'web'
|
|
1212
1155
|
*/
|
|
1213
1156
|
useModel(model, options = {}, providerName = "users", guardName = "web") {
|
|
1214
1157
|
const defaultOptions = {
|
|
1215
1158
|
usernameColumn: "email",
|
|
1216
1159
|
credentialsPasswordField: "password",
|
|
1217
|
-
hasher: new
|
|
1160
|
+
hasher: new DefaultHasher(),
|
|
1218
1161
|
...options
|
|
1219
1162
|
};
|
|
1220
1163
|
this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
|
|
@@ -1229,15 +1172,9 @@ var AuthManager = class {
|
|
|
1229
1172
|
/**
|
|
1230
1173
|
* Register a bearer-token guard backed by an ApiTokenStore and enable
|
|
1231
1174
|
* header-based guard selection: requests carrying `Authorization: Bearer`
|
|
1232
|
-
* resolve to this guard, everything else keeps the default (session)
|
|
1233
|
-
*
|
|
1234
|
-
*
|
|
1235
|
-
*
|
|
1236
|
-
* @param store - Where issued tokens live (see createApiToken)
|
|
1237
|
-
* @param options.provider - Registered provider name used to load the full
|
|
1238
|
-
* user record from the token's userId. Without it, `auth.user()` resolves
|
|
1239
|
-
* to a minimal `{ id }` record (enough for Gate/policy evaluation).
|
|
1240
|
-
* @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).
|
|
1241
1178
|
*/
|
|
1242
1179
|
useTokens(store, options = {}) {
|
|
1243
1180
|
const guardName = options.guardName ?? "token";
|
|
@@ -1255,33 +1192,21 @@ var AuthManager = class {
|
|
|
1255
1192
|
this.apiTokenOptions = { ...options };
|
|
1256
1193
|
}
|
|
1257
1194
|
/**
|
|
1258
|
-
* The options the last `useTokens()` call configured its guard with.
|
|
1259
|
-
*
|
|
1260
|
-
*
|
|
1261
|
-
* anything else about how tokens authenticate — `guren tool:dev` installs an
|
|
1262
|
-
* 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)`
|
|
1263
1198
|
* silently dropped the app's `provider`, so a token resolved to a bare
|
|
1264
|
-
* `{ id }`
|
|
1265
|
-
* field behaved differently for no stated reason.
|
|
1199
|
+
* `{ id }` and every policy reading a user field behaved differently.
|
|
1266
1200
|
*/
|
|
1267
1201
|
getApiTokenOptions() {
|
|
1268
1202
|
return { ...this.apiTokenOptions };
|
|
1269
1203
|
}
|
|
1270
1204
|
/**
|
|
1271
|
-
* The token store {@link useTokens} was configured with, or `undefined
|
|
1272
|
-
*
|
|
1273
|
-
*
|
|
1274
|
-
*
|
|
1275
|
-
*
|
|
1276
|
-
* store the guard verifies against. `useTokens` otherwise closes over
|
|
1277
|
-
* `store` inside the guard factory, where nothing outside a live request
|
|
1278
|
-
* can see it, so an issuance command could only write tokens into a store
|
|
1279
|
-
* of its own making, which no running app would ever read.
|
|
1280
|
-
*
|
|
1281
|
-
* Deliberately on this class rather than on `AuthManagerContract`: the
|
|
1282
|
-
* contract describes what a *request* needs from auth, and handing out the
|
|
1283
|
-
* raw store is not part of that. Callers reach it through the concrete
|
|
1284
|
-
* 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.
|
|
1285
1210
|
*/
|
|
1286
1211
|
getApiTokenStore() {
|
|
1287
1212
|
return this.apiTokenStore ?? void 0;
|
|
@@ -1290,19 +1215,17 @@ var AuthManager = class {
|
|
|
1290
1215
|
//#endregion
|
|
1291
1216
|
//#region src/support/redirect-target.ts
|
|
1292
1217
|
/**
|
|
1293
|
-
*
|
|
1294
|
-
*
|
|
1295
|
-
*
|
|
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.
|
|
1296
1221
|
*/
|
|
1297
|
-
/**
|
|
1222
|
+
/** Defuses backslash tricks such as `/\evil.com`. */
|
|
1298
1223
|
function normalizeRedirectTarget(value) {
|
|
1299
1224
|
return value.replace(/\\/g, "/");
|
|
1300
1225
|
}
|
|
1301
|
-
/** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
|
|
1302
1226
|
function isAppRelativePath(value) {
|
|
1303
1227
|
return value.startsWith("/") && !value.startsWith("//");
|
|
1304
1228
|
}
|
|
1305
|
-
/** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
|
|
1306
1229
|
function hostMatchesAllowlist(target, allowedHosts) {
|
|
1307
1230
|
const hostname = target.hostname.toLowerCase();
|
|
1308
1231
|
const host = target.host.toLowerCase();
|
|
@@ -1317,20 +1240,16 @@ function hostMatchesAllowlist(target, allowedHosts) {
|
|
|
1317
1240
|
/** Session key holding the per-browser bindings between authorize and callback. */
|
|
1318
1241
|
const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
|
|
1319
1242
|
/**
|
|
1320
|
-
* How many unfinished flows one browser may have bindings for.
|
|
1321
|
-
*
|
|
1322
|
-
*
|
|
1323
|
-
* until it expires, so the list is capped. Beyond the cap the oldest entry is
|
|
1324
|
-
* dropped — that flow's callback then fails, which is the same outcome it had
|
|
1325
|
-
* 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.
|
|
1326
1246
|
*/
|
|
1327
1247
|
const MAX_PENDING_SESSION_BINDINGS = 5;
|
|
1328
1248
|
let warnedAboutUnboundState = false;
|
|
1329
1249
|
/**
|
|
1330
1250
|
* An unbound `state` is transferable between browsers, which is exactly the
|
|
1331
|
-
* attack `state` exists to stop. Verification stays permissive so apps
|
|
1332
|
-
*
|
|
1333
|
-
* 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.
|
|
1334
1253
|
*/
|
|
1335
1254
|
function warnOnceAboutUnboundState() {
|
|
1336
1255
|
if (warnedAboutUnboundState) return;
|
|
@@ -1359,11 +1278,9 @@ function issueSessionBinding(session) {
|
|
|
1359
1278
|
return generateToken(DEFAULT_STATE_LENGTH);
|
|
1360
1279
|
}
|
|
1361
1280
|
/**
|
|
1362
|
-
* Park a minted binding against the state it belongs to.
|
|
1363
|
-
*
|
|
1364
|
-
*
|
|
1365
|
-
* flows in flight — two tabs, or a visitor who picks a different provider —
|
|
1366
|
-
* 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.
|
|
1367
1284
|
*/
|
|
1368
1285
|
function rememberSessionBinding(session, stateHash, binding, expiresAt) {
|
|
1369
1286
|
const pending = readPendingBindings(session);
|
|
@@ -1375,11 +1292,9 @@ function rememberSessionBinding(session, stateHash, binding, expiresAt) {
|
|
|
1375
1292
|
session.set(OAUTH_SESSION_BINDING_KEY, pending.slice(Math.max(0, pending.length - MAX_PENDING_SESSION_BINDINGS)));
|
|
1376
1293
|
}
|
|
1377
1294
|
/**
|
|
1378
|
-
* Take the binding belonging to this callback's state, leaving the rest.
|
|
1379
|
-
*
|
|
1380
|
-
*
|
|
1381
|
-
* state must not be able to strip a real flow's binding and lock the visitor
|
|
1382
|
-
* 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.
|
|
1383
1298
|
*/
|
|
1384
1299
|
function consumeSessionBinding(session, stateHash) {
|
|
1385
1300
|
if (!session) return void 0;
|
|
@@ -1479,10 +1394,9 @@ var OAuthManager = class {
|
|
|
1479
1394
|
return profile;
|
|
1480
1395
|
}
|
|
1481
1396
|
/**
|
|
1482
|
-
* Verify the callback and return the user profile together with the
|
|
1483
|
-
*
|
|
1484
|
-
* pass to a redirect response
|
|
1485
|
-
* 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.
|
|
1486
1400
|
*/
|
|
1487
1401
|
async handleCallback(providerName, payload) {
|
|
1488
1402
|
const provider = this.getProvider(providerName);
|
|
@@ -1527,11 +1441,9 @@ async function verifyOAuthState(state, provider, store, config = {}, bindTo) {
|
|
|
1527
1441
|
}
|
|
1528
1442
|
/**
|
|
1529
1443
|
* Whether the presented value matches the binding recorded at authorize time.
|
|
1530
|
-
*
|
|
1531
1444
|
* A state created without a binding still verifies, so an app that has not
|
|
1532
|
-
* adopted `bindTo` keeps working
|
|
1533
|
-
* browser that cannot present it,
|
|
1534
|
-
* 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.
|
|
1535
1447
|
*/
|
|
1536
1448
|
function bindingMatches(stored, presented, hashAlgorithm) {
|
|
1537
1449
|
if (!stored) {
|
|
@@ -1548,11 +1460,10 @@ async function findAndDeleteState(store, stateHash) {
|
|
|
1548
1460
|
return payload;
|
|
1549
1461
|
}
|
|
1550
1462
|
/**
|
|
1551
|
-
* Reduce a `redirectTo` value to a safe target: app-relative paths always
|
|
1552
|
-
*
|
|
1553
|
-
*
|
|
1554
|
-
*
|
|
1555
|
-
* `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`.
|
|
1556
1467
|
*/
|
|
1557
1468
|
function sanitizeOAuthRedirect(redirectTo, allowedHosts = []) {
|
|
1558
1469
|
const value = redirectTo?.trim();
|
|
@@ -1710,32 +1621,6 @@ function parseOAuthRedirectUrl(url) {
|
|
|
1710
1621
|
return parseTokenUrl(url);
|
|
1711
1622
|
}
|
|
1712
1623
|
//#endregion
|
|
1713
|
-
//#region src/auth/password/NodeHasher.ts
|
|
1714
|
-
/**
|
|
1715
|
-
* Node.js-compatible password hasher using crypto.scrypt.
|
|
1716
|
-
* Use this instead of ScryptHasher when deploying to non-Bun runtimes (e.g. AWS Lambda).
|
|
1717
|
-
*/
|
|
1718
|
-
var NodeHasher = class {
|
|
1719
|
-
options;
|
|
1720
|
-
constructor(options = {}) {
|
|
1721
|
-
this.options = {
|
|
1722
|
-
cost: options.cost,
|
|
1723
|
-
memory: options.memory,
|
|
1724
|
-
saltLength: options.saltLength,
|
|
1725
|
-
keyLength: options.keyLength
|
|
1726
|
-
};
|
|
1727
|
-
}
|
|
1728
|
-
async hash(plain) {
|
|
1729
|
-
return hashPassword(plain, this.options);
|
|
1730
|
-
}
|
|
1731
|
-
async verify(hashed, plain) {
|
|
1732
|
-
return verifyPassword(plain, hashed);
|
|
1733
|
-
}
|
|
1734
|
-
needsRehash(hashed) {
|
|
1735
|
-
return needsRehash(hashed, this.options);
|
|
1736
|
-
}
|
|
1737
|
-
};
|
|
1738
|
-
//#endregion
|
|
1739
1624
|
//#region src/auth/AuthenticatableModel.ts
|
|
1740
1625
|
var AuthenticatableModel = class extends Model {
|
|
1741
1626
|
static createType = void 0;
|
|
@@ -1756,8 +1641,8 @@ var AuthenticatableModel = class extends Model {
|
|
|
1756
1641
|
* Credential columns can never be mass-assigned: the resolved password-hash
|
|
1757
1642
|
* column (unless the model hashes in place into the password field itself)
|
|
1758
1643
|
* and the remember-token column. Resolved at call time so a renamed column
|
|
1759
|
-
* stays covered. Use `forceCreate()`/`forceUpdate()` for trusted
|
|
1760
|
-
*
|
|
1644
|
+
* stays covered. Use `forceCreate()`/`forceUpdate()` for trusted server-side
|
|
1645
|
+
* values such as `passwordHash: 'oauth:...'`.
|
|
1761
1646
|
*/
|
|
1762
1647
|
static deniedFields() {
|
|
1763
1648
|
const denied = [...super.deniedFields()];
|
|
@@ -1768,7 +1653,7 @@ var AuthenticatableModel = class extends Model {
|
|
|
1768
1653
|
}
|
|
1769
1654
|
static resolvePasswordHasher() {
|
|
1770
1655
|
if (this.passwordHasher) return this.passwordHasher;
|
|
1771
|
-
const hasher = new
|
|
1656
|
+
const hasher = new DefaultHasher();
|
|
1772
1657
|
this.passwordHasher = hasher;
|
|
1773
1658
|
return hasher;
|
|
1774
1659
|
}
|
|
@@ -1785,10 +1670,30 @@ var AuthenticatableModel = class extends Model {
|
|
|
1785
1670
|
}
|
|
1786
1671
|
};
|
|
1787
1672
|
//#endregion
|
|
1788
|
-
//#region src/auth/
|
|
1673
|
+
//#region src/auth/signed-token.ts
|
|
1789
1674
|
/**
|
|
1790
|
-
*
|
|
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.
|
|
1791
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. */
|
|
1792
1697
|
var MemoryPasswordResetStore = class {
|
|
1793
1698
|
tokens = /* @__PURE__ */ new Map();
|
|
1794
1699
|
async store(tokenId, email, expiresAt) {
|
|
@@ -1823,14 +1728,7 @@ const PASSWORD_RESET_PURPOSE = "password-reset";
|
|
|
1823
1728
|
function createPasswordResetSigner() {
|
|
1824
1729
|
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "password-reset-signing"));
|
|
1825
1730
|
}
|
|
1826
|
-
/**
|
|
1827
|
-
* Create a password reset token for a user.
|
|
1828
|
-
*
|
|
1829
|
-
* @param email - The user's email address
|
|
1830
|
-
* @param store - The token storage implementation
|
|
1831
|
-
* @param config - Optional configuration
|
|
1832
|
-
* @returns The token result containing plain token and hash
|
|
1833
|
-
*/
|
|
1731
|
+
/** Create a password reset token for a user. */
|
|
1834
1732
|
async function createPasswordResetToken(email, store, config = {}) {
|
|
1835
1733
|
const expiresIn = config.expiresIn ?? DEFAULT_EXPIRES_IN;
|
|
1836
1734
|
const tokenLength = config.tokenLength ?? DEFAULT_TOKEN_LENGTH;
|
|
@@ -1852,75 +1750,40 @@ async function createPasswordResetToken(email, store, config = {}) {
|
|
|
1852
1750
|
expiresAt
|
|
1853
1751
|
};
|
|
1854
1752
|
}
|
|
1855
|
-
/**
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
* @param config - Optional configuration (must match createPasswordResetToken config)
|
|
1861
|
-
* @returns The email if token is valid, null otherwise
|
|
1862
|
-
*/
|
|
1863
|
-
async function verifyPasswordResetToken(token, store, _config = {}) {
|
|
1864
|
-
const payload = createPasswordResetSigner().verify(token, {
|
|
1865
|
-
purpose: PASSWORD_RESET_PURPOSE,
|
|
1866
|
-
allowExpired: true
|
|
1867
|
-
});
|
|
1868
|
-
if (!payload?.id || !payload.email) return null;
|
|
1869
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1870
|
-
await store.delete(payload.id);
|
|
1871
|
-
return null;
|
|
1872
|
-
}
|
|
1873
|
-
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);
|
|
1874
1758
|
if (!record) return null;
|
|
1875
|
-
return record.email.toLowerCase() ===
|
|
1759
|
+
return record.email.toLowerCase() === claims.email.toLowerCase() ? record.email : null;
|
|
1876
1760
|
}
|
|
1877
1761
|
/**
|
|
1878
|
-
* Complete a password reset
|
|
1879
|
-
*
|
|
1880
|
-
* @param token - The plain-text token from the reset URL
|
|
1881
|
-
* @param newPassword - The new password (should be validated by caller)
|
|
1882
|
-
* @param store - The token storage implementation
|
|
1883
|
-
* @param provider - The user provider to look up and update the user
|
|
1884
|
-
* @param updatePassword - Function to update the user's password
|
|
1885
|
-
* @param config - Optional configuration
|
|
1886
|
-
* @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.
|
|
1887
1764
|
*/
|
|
1888
|
-
async function completePasswordReset(token, newPassword, store, provider, updatePassword
|
|
1889
|
-
const
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
});
|
|
1893
|
-
if (!payload?.id || !payload.email) return null;
|
|
1894
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
1895
|
-
await store.delete(payload.id);
|
|
1896
|
-
return null;
|
|
1897
|
-
}
|
|
1898
|
-
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);
|
|
1899
1769
|
if (!record) return null;
|
|
1900
|
-
if (record.email.toLowerCase() !==
|
|
1770
|
+
if (record.email.toLowerCase() !== claims.email.toLowerCase()) return null;
|
|
1901
1771
|
const user = await provider.retrieveByCredentials({ email: record.email });
|
|
1902
1772
|
if (!user) {
|
|
1903
|
-
await store.delete(
|
|
1773
|
+
await store.delete(claims.id);
|
|
1904
1774
|
return null;
|
|
1905
1775
|
}
|
|
1906
1776
|
await updatePassword(user, newPassword);
|
|
1907
|
-
await store.delete(
|
|
1777
|
+
await store.delete(claims.id);
|
|
1908
1778
|
return user;
|
|
1909
1779
|
}
|
|
1910
|
-
/**
|
|
1911
|
-
* Build a password reset URL from a base URL and token.
|
|
1912
|
-
*/
|
|
1780
|
+
/** Build a password reset URL from a base URL and token. */
|
|
1913
1781
|
const buildPasswordResetUrl = buildTokenUrl;
|
|
1914
|
-
/**
|
|
1915
|
-
* Parse a password reset URL to extract the token and optional email.
|
|
1916
|
-
*/
|
|
1782
|
+
/** Parse a password reset URL to extract the token and optional email. */
|
|
1917
1783
|
const parsePasswordResetUrl = parseTokenUrl;
|
|
1918
1784
|
//#endregion
|
|
1919
1785
|
//#region src/auth/email-verification.ts
|
|
1920
|
-
/**
|
|
1921
|
-
* In-memory store for testing purposes.
|
|
1922
|
-
* Do NOT use in production - tokens will be lost on restart.
|
|
1923
|
-
*/
|
|
1786
|
+
/** In-memory store for testing. Tokens are lost on restart. */
|
|
1924
1787
|
var MemoryEmailVerificationStore = class {
|
|
1925
1788
|
tokens = /* @__PURE__ */ new Map();
|
|
1926
1789
|
async store(token) {
|
|
@@ -1936,15 +1799,11 @@ var MemoryEmailVerificationStore = class {
|
|
|
1936
1799
|
const normalizedEmail = email.toLowerCase();
|
|
1937
1800
|
for (const [key, token] of this.tokens.entries()) if (token.email.toLowerCase() === normalizedEmail) this.tokens.delete(key);
|
|
1938
1801
|
}
|
|
1939
|
-
/**
|
|
1940
|
-
* Clear all tokens (useful for testing).
|
|
1941
|
-
*/
|
|
1802
|
+
/** Clear all tokens (useful for testing). */
|
|
1942
1803
|
clear() {
|
|
1943
1804
|
this.tokens.clear();
|
|
1944
1805
|
}
|
|
1945
|
-
/**
|
|
1946
|
-
* Get the count of stored tokens (useful for testing).
|
|
1947
|
-
*/
|
|
1806
|
+
/** Count of stored tokens (useful for testing). */
|
|
1948
1807
|
get size() {
|
|
1949
1808
|
return this.tokens.size;
|
|
1950
1809
|
}
|
|
@@ -1958,27 +1817,8 @@ function createEmailVerificationSigner() {
|
|
|
1958
1817
|
return new MessageSigner(deriveAppKeyring(getAppKeyringFromEnv(), "email-verification-signing"));
|
|
1959
1818
|
}
|
|
1960
1819
|
/**
|
|
1961
|
-
* Create a new email verification token
|
|
1962
|
-
*
|
|
1963
|
-
* @param email - The email address to verify
|
|
1964
|
-
* @param store - Token store implementation
|
|
1965
|
-
* @param config - Optional configuration
|
|
1966
|
-
* @returns The raw token to send via email
|
|
1967
|
-
*
|
|
1968
|
-
* @example
|
|
1969
|
-
* ```ts
|
|
1970
|
-
* const { token, expiresAt } = await createEmailVerificationToken(
|
|
1971
|
-
* user.email,
|
|
1972
|
-
* verificationStore
|
|
1973
|
-
* )
|
|
1974
|
-
*
|
|
1975
|
-
* // Send email with verification link
|
|
1976
|
-
* await sendEmail({
|
|
1977
|
-
* to: user.email,
|
|
1978
|
-
* subject: 'Verify your email',
|
|
1979
|
-
* html: `<a href="${buildVerificationUrl(baseUrl, token)}">Verify Email</a>`,
|
|
1980
|
-
* })
|
|
1981
|
-
* ```
|
|
1820
|
+
* Create a new email verification token; the raw token is returned to send by
|
|
1821
|
+
* email and is never stored.
|
|
1982
1822
|
*/
|
|
1983
1823
|
async function createEmailVerificationToken(email, store, config = {}) {
|
|
1984
1824
|
const { expiresIn, tokenLength } = {
|
|
@@ -2009,127 +1849,43 @@ async function createEmailVerificationToken(email, store, config = {}) {
|
|
|
2009
1849
|
};
|
|
2010
1850
|
}
|
|
2011
1851
|
/**
|
|
2012
|
-
* Verify an email verification token
|
|
2013
|
-
*
|
|
2014
|
-
* @param token - The raw token from the verification link
|
|
2015
|
-
* @param store - Token store implementation
|
|
2016
|
-
* @param config - Optional configuration (not currently used, reserved for future)
|
|
2017
|
-
* @returns The email address if valid, null if invalid or expired
|
|
2018
|
-
*
|
|
2019
|
-
* @example
|
|
2020
|
-
* ```ts
|
|
2021
|
-
* const email = await verifyEmailToken(token, verificationStore)
|
|
2022
|
-
*
|
|
2023
|
-
* if (!email) {
|
|
2024
|
-
* return ctx.json({ error: 'Invalid or expired token' }, 400)
|
|
2025
|
-
* }
|
|
2026
|
-
*
|
|
2027
|
-
* // Mark user as verified
|
|
2028
|
-
* await User.update({ email }, { emailVerifiedAt: new Date() })
|
|
2029
|
-
* ```
|
|
1852
|
+
* Verify an email verification token, returning the email address it was
|
|
1853
|
+
* issued for or `null` when it is invalid or expired.
|
|
2030
1854
|
*/
|
|
2031
|
-
async function verifyEmailToken(token, store
|
|
2032
|
-
const
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
});
|
|
2036
|
-
if (!payload?.id || !payload.email) return null;
|
|
2037
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
2038
|
-
await store.delete(payload.id);
|
|
2039
|
-
return null;
|
|
2040
|
-
}
|
|
2041
|
-
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);
|
|
2042
1859
|
if (!storedToken) return null;
|
|
2043
|
-
|
|
2044
|
-
await store.delete(payload.id);
|
|
2045
|
-
return null;
|
|
2046
|
-
}
|
|
2047
|
-
return storedToken.email.toLowerCase() === payload.email.toLowerCase() ? storedToken.email : null;
|
|
1860
|
+
return storedToken.email.toLowerCase() === claims.email.toLowerCase() ? storedToken.email : null;
|
|
2048
1861
|
}
|
|
2049
1862
|
/**
|
|
2050
|
-
* Complete email verification by consuming the token.
|
|
2051
|
-
*
|
|
2052
|
-
* @param token - The raw token from the verification link
|
|
2053
|
-
* @param store - Token store implementation
|
|
2054
|
-
* @param markVerified - Function to mark the user as verified
|
|
2055
|
-
* @returns The result of markVerified if successful, null if token invalid
|
|
2056
|
-
*
|
|
2057
|
-
* @example
|
|
2058
|
-
* ```ts
|
|
2059
|
-
* const result = await completeEmailVerification(
|
|
2060
|
-
* token,
|
|
2061
|
-
* verificationStore,
|
|
2062
|
-
* async (email) => {
|
|
2063
|
-
* await User.update({ email }, { emailVerifiedAt: new Date() })
|
|
2064
|
-
* return User.findByEmail(email)
|
|
2065
|
-
* }
|
|
2066
|
-
* )
|
|
2067
|
-
*
|
|
2068
|
-
* if (!result) {
|
|
2069
|
-
* return ctx.json({ error: 'Invalid or expired token' }, 400)
|
|
2070
|
-
* }
|
|
2071
|
-
*
|
|
2072
|
-
* return ctx.redirect('/dashboard')
|
|
2073
|
-
* ```
|
|
1863
|
+
* Complete email verification by consuming the token. Returns the result of
|
|
1864
|
+
* `markVerified`, or `null` when the token is invalid.
|
|
2074
1865
|
*/
|
|
2075
1866
|
async function completeEmailVerification(token, store, markVerified) {
|
|
2076
|
-
const
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
});
|
|
2080
|
-
if (!payload?.id || !payload.email) return null;
|
|
2081
|
-
if (typeof payload.exp === "number" && payload.exp < Math.floor(Date.now() / 1e3)) {
|
|
2082
|
-
await store.delete(payload.id);
|
|
2083
|
-
return null;
|
|
2084
|
-
}
|
|
2085
|
-
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);
|
|
2086
1870
|
if (!storedToken) return null;
|
|
2087
|
-
if (
|
|
2088
|
-
await store.delete(payload.id);
|
|
2089
|
-
return null;
|
|
2090
|
-
}
|
|
2091
|
-
if (storedToken.email.toLowerCase() !== payload.email.toLowerCase()) return null;
|
|
1871
|
+
if (storedToken.email.toLowerCase() !== claims.email.toLowerCase()) return null;
|
|
2092
1872
|
const result = await markVerified(storedToken.email);
|
|
2093
|
-
await store.delete(
|
|
1873
|
+
await store.delete(claims.id);
|
|
2094
1874
|
return result;
|
|
2095
1875
|
}
|
|
2096
|
-
/**
|
|
2097
|
-
* Build a verification URL.
|
|
2098
|
-
*/
|
|
1876
|
+
/** Build a verification URL. */
|
|
2099
1877
|
const buildVerificationUrl = buildTokenUrl;
|
|
2100
|
-
/**
|
|
2101
|
-
* Parse a verification URL to extract token and email.
|
|
2102
|
-
*/
|
|
1878
|
+
/** Parse a verification URL to extract token and email. */
|
|
2103
1879
|
const parseVerificationUrl = parseTokenUrl;
|
|
2104
|
-
/**
|
|
2105
|
-
* Check if a user's email is verified.
|
|
2106
|
-
* Helper function for use with User models.
|
|
2107
|
-
*
|
|
2108
|
-
* @param user - User object with emailVerifiedAt field
|
|
2109
|
-
* @returns true if verified, false otherwise
|
|
2110
|
-
*
|
|
2111
|
-
* @example
|
|
2112
|
-
* ```ts
|
|
2113
|
-
* if (!isEmailVerified(user)) {
|
|
2114
|
-
* return ctx.redirect('/verify-email')
|
|
2115
|
-
* }
|
|
2116
|
-
* ```
|
|
2117
|
-
*/
|
|
1880
|
+
/** Whether a user's `emailVerifiedAt` is set. */
|
|
2118
1881
|
function isEmailVerified(user) {
|
|
2119
1882
|
return user?.emailVerifiedAt != null;
|
|
2120
1883
|
}
|
|
2121
1884
|
/**
|
|
2122
1885
|
* Middleware factory to require verified email.
|
|
2123
|
-
*
|
|
2124
|
-
* @param options - Configuration options
|
|
2125
|
-
* @returns Middleware function
|
|
2126
|
-
*
|
|
2127
1886
|
* @example
|
|
2128
1887
|
* ```ts
|
|
2129
|
-
*
|
|
2130
|
-
* requireAuthenticated(),
|
|
2131
|
-
* requireVerifiedEmail({ redirectTo: '/verify-email' })
|
|
2132
|
-
* )
|
|
1888
|
+
* requireVerifiedEmail({ redirectTo: '/verify-email' })
|
|
2133
1889
|
* ```
|
|
2134
1890
|
*/
|
|
2135
1891
|
function requireVerifiedEmail(options = {}) {
|
|
@@ -2142,4 +1898,4 @@ function requireVerifiedEmail(options = {}) {
|
|
|
2142
1898
|
};
|
|
2143
1899
|
}
|
|
2144
1900
|
//#endregion
|
|
2145
|
-
export {
|
|
1901
|
+
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, DefaultHasher as ct, completePasswordReset as d, AuthenticationException as dt, generateId as et, createPasswordResetToken as f, MemorySessionStore as ft, MemoryOAuthStateStore as g, AuthenticatableModel as h, createEmailVerificationToken as i, secureCompare as it, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, NodeHasher as lt, verifyPasswordResetToken as m, getSessionFromContext as mt, buildVerificationUrl as n, hashToken as nt, parseVerificationUrl as o, ModelUserProvider as ot, parsePasswordResetUrl as p, createSessionMiddleware as pt, revokeApiToken as q, completeEmailVerification as r, parseTokenUrl as rt, requireVerifiedEmail as s, BaseUserProvider as st, MemoryEmailVerificationStore as t, generateToken as tt, buildPasswordResetUrl as u, ScryptHasher as ut, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, createBearerTokenMiddleware as z };
|