@guren/server 2.15.0 → 2.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DocsViewerServiceProvider-qFCaeiUv.js → DocsViewerServiceProvider-D2cuVgtN.js} +7 -12
- package/dist/{Hash-C8aejmi8.js → Hash-D2DFd8xX.js} +7 -57
- package/dist/{HttpException-BkS3euNG.js → HttpException-BlQ2yEmT.js} +2 -79
- package/dist/{Job-BVT813DO.js → Job-DxQK8h3P.js} +24 -179
- package/dist/{McpServiceProvider-BawsYjgN.js → McpServiceProvider-Zihx3Bjq.js} +35 -20
- package/dist/{Random-DbIJ22KQ.js → Random-S0OvCuR8.js} +9 -106
- package/dist/agent/AgentApprovalRequested.d.ts +11 -39
- package/dist/agent/approval-status.d.ts +56 -0
- package/dist/agent/approval.d.ts +76 -187
- package/dist/agent/audit-emitter.d.ts +16 -44
- package/dist/agent/audit.d.ts +20 -56
- package/dist/agent/derive.d.ts +32 -66
- package/dist/agent/dispatch.d.ts +38 -90
- package/dist/agent/events.d.ts +17 -23
- package/dist/agent/gate.d.ts +118 -0
- package/dist/agent/meta-tools.d.ts +18 -46
- package/dist/agent/pipeline.d.ts +234 -0
- package/dist/agent/public.d.ts +6 -25
- package/dist/agent/public.js +1 -1
- package/dist/agent/redact.d.ts +16 -38
- package/dist/agent/scopes.d.ts +55 -69
- package/dist/auth/AgentPrincipalGuard.d.ts +49 -0
- package/dist/auth/AuthManager.d.ts +22 -43
- package/dist/auth/AuthenticatableModel.d.ts +2 -2
- package/dist/auth/SessionGuard.d.ts +0 -1
- package/dist/auth/TokenGuard.d.ts +6 -26
- package/dist/auth/api-token.d.ts +16 -148
- package/dist/auth/context.d.ts +5 -10
- package/dist/auth/email-verification.d.ts +29 -127
- package/dist/auth/index.js +1 -1
- package/dist/auth/oauth/index.d.ts +35 -57
- package/dist/auth/password/DefaultHasher.d.ts +5 -14
- package/dist/auth/password/PasswordHasher.d.ts +5 -13
- package/dist/auth/password/hash-format.d.ts +5 -13
- package/dist/auth/password-reset.d.ts +16 -42
- package/dist/auth/providers/ModelUserProvider.d.ts +3 -4
- package/dist/auth/providers/UserProvider.d.ts +4 -4
- package/dist/auth/signed-token.d.ts +18 -0
- package/dist/auth/types.d.ts +9 -32
- package/dist/auth/utils.d.ts +6 -27
- package/dist/{auth-DkYoAPVn.js → auth-Gg54ppQi.js} +279 -519
- package/dist/authorization/Gate.d.ts +9 -145
- package/dist/authorization/Policy.d.ts +6 -53
- package/dist/authorization/index.js +1 -1
- package/dist/authorization/middleware.d.ts +16 -62
- package/dist/authorization/types.d.ts +8 -64
- package/dist/{authorization-CdfbCj8J.js → authorization-CdEWZZw3.js} +44 -309
- package/dist/broadcasting/BroadcastManager.d.ts +29 -149
- package/dist/broadcasting/channels/Channel.d.ts +1 -19
- package/dist/broadcasting/channels/PresenceChannel.d.ts +1 -55
- package/dist/broadcasting/channels/PrivateChannel.d.ts +1 -23
- package/dist/broadcasting/drivers/MemoryDriver.d.ts +18 -70
- package/dist/broadcasting/drivers/RedisDriver.d.ts +3 -80
- package/dist/broadcasting/drivers/index.d.ts +1 -1
- package/dist/broadcasting/index.d.ts +1 -1
- package/dist/broadcasting/index.js +1 -1
- package/dist/broadcasting/types.d.ts +7 -88
- package/dist/{broadcasting-BwodCA4q.js → broadcasting-B5RzB0A2.js} +87 -414
- package/dist/cache/CacheManager.d.ts +8 -62
- package/dist/cache/TaggedCache.d.ts +2 -35
- package/dist/cache/index.js +1 -1
- package/dist/cache/stores/FileStore.d.ts +2 -36
- package/dist/cache/stores/MemoryStore.d.ts +2 -26
- package/dist/cache/stores/RedisStore.d.ts +1 -29
- package/dist/cache/types.d.ts +21 -128
- package/dist/{cache-BYnZf2FR.js → cache-BOOIr324.js} +19 -198
- package/dist/client-C4TEr_Dd.js +9 -0
- package/dist/console/Command.d.ts +17 -126
- package/dist/console/ConsoleKernel.d.ts +2 -74
- package/dist/console/Input.d.ts +5 -113
- package/dist/console/Output.d.ts +3 -99
- package/dist/console/types.d.ts +3 -33
- package/dist/container/Container.d.ts +12 -103
- package/dist/container/ServiceProvider.d.ts +17 -61
- package/dist/container/bindings.d.ts +5 -26
- package/dist/container/defineModule.d.ts +16 -54
- package/dist/container/definePlugin.d.ts +12 -45
- package/dist/container/types.d.ts +2 -34
- package/dist/context-CXk_umpT.js +21 -0
- package/dist/database/Factory.d.ts +4 -57
- package/dist/database/Seeder.d.ts +8 -46
- package/dist/database/SeederRunner.d.ts +3 -33
- package/dist/database/types.d.ts +3 -24
- package/dist/discovery/AutoDiscovery.d.ts +10 -82
- package/dist/{dispatch-erOS9epZ.js → dispatch-BAwzftws.js} +32 -79
- package/dist/docs-viewer/DocsViewerServiceProvider.d.ts +2 -5
- package/dist/docs-viewer/endpoint.d.ts +5 -11
- package/dist/encryption/Encrypter.d.ts +5 -71
- package/dist/encryption/Hash.d.ts +7 -57
- package/dist/encryption/Random.d.ts +6 -99
- package/dist/encryption/index.js +3 -3
- package/dist/encryption/types.d.ts +10 -72
- package/dist/{encryption-D99Vmls3.js → encryption-uwP3Di4D.js} +9 -78
- package/dist/{endpoint-D6GIqOpe.js → endpoint-BXipU2Jj.js} +6 -12
- package/dist/endpoint-Dsw3Acvq.js +26 -0
- package/dist/errors/ExceptionHandler.d.ts +3 -90
- package/dist/errors/HttpException.d.ts +2 -79
- package/dist/errors/debug-page.d.ts +3 -17
- package/dist/errors/error-page.d.ts +1 -0
- package/dist/errors/exceptions/AuthenticationException.d.ts +2 -24
- package/dist/errors/exceptions/AuthorizationException.d.ts +1 -24
- package/dist/errors/exceptions/MethodNotAllowedException.d.ts +1 -23
- package/dist/errors/exceptions/NotFoundHttpException.d.ts +1 -27
- package/dist/errors/exceptions/ValidationException.d.ts +2 -43
- package/dist/errors/types.d.ts +1 -25
- package/dist/{errors-BgeOl_DC.js → errors-JpkcCjjn.js} +3 -41
- package/dist/events/Event.d.ts +1 -28
- package/dist/events/EventManager.d.ts +5 -107
- package/dist/events/Listener.d.ts +7 -55
- package/dist/events/builtin.d.ts +0 -24
- package/dist/events/index.js +1 -1
- package/dist/events/types.d.ts +4 -22
- package/dist/{events-aIH_bWRx.js → events-DOmAHDeP.js} +11 -191
- package/dist/facades/index.d.ts +2 -14
- package/dist/health/HealthCheck.d.ts +0 -24
- package/dist/health/HealthManager.d.ts +0 -36
- package/dist/health/checks/CacheCheck.d.ts +2 -17
- package/dist/health/checks/CustomCheck.d.ts +0 -9
- package/dist/health/checks/DatabaseCheck.d.ts +2 -17
- package/dist/health/checks/MemoryCheck.d.ts +3 -12
- package/dist/health/checks/RedisCheck.d.ts +1 -13
- package/dist/health/checks/StorageCheck.d.ts +2 -17
- package/dist/health/index.js +1 -1
- package/dist/health/types.d.ts +4 -24
- package/dist/{health-VWdWXRwh.js → health-DQSvUplL.js} +1 -76
- package/dist/hot-disposables-B5BXqaIH.js +167 -0
- package/dist/hot-reload/hot-disposables.d.ts +22 -74
- package/dist/hot-reload/testing.d.ts +4 -9
- package/dist/http/Application.d.ts +77 -205
- package/dist/http/FormRequest.d.ts +4 -55
- package/dist/http/dev-assets.d.ts +13 -31
- package/dist/http/dev-banner.d.ts +2 -5
- package/dist/http/inertia-assets.d.ts +3 -6
- package/dist/http/middleware/capabilities.d.ts +27 -50
- package/dist/http/middleware/cors.d.ts +4 -29
- package/dist/http/middleware/csp.d.ts +2 -25
- package/dist/http/middleware/csrf.d.ts +28 -95
- package/dist/http/middleware/detect-locale.d.ts +7 -27
- package/dist/http/middleware/force-https.d.ts +6 -24
- package/dist/http/middleware/host-authorization.d.ts +2 -12
- package/dist/http/middleware/index.d.ts +1 -1
- package/dist/http/middleware/loopback-guard.d.ts +15 -33
- package/dist/http/middleware/rate-limit.d.ts +29 -126
- package/dist/http/middleware/redirect-safety.d.ts +2 -20
- package/dist/http/middleware/request-id.d.ts +1 -14
- package/dist/http/middleware/request-logging.d.ts +2 -13
- package/dist/http/middleware/response-headers.d.ts +5 -13
- package/dist/http/middleware/security-headers.d.ts +2 -16
- package/dist/http/middleware/session.d.ts +15 -34
- package/dist/http/middleware/validation-errors-cookie.d.ts +7 -18
- package/dist/http/middleware/validation.d.ts +8 -63
- package/dist/http/public-assets.d.ts +11 -7
- package/dist/http/request.d.ts +32 -118
- package/dist/http/resources/CursorPaginator.d.ts +5 -64
- package/dist/http/resources/Paginator.d.ts +7 -84
- package/dist/http/resources/Resource.d.ts +9 -65
- package/dist/http/resources/ResourceCollection.d.ts +5 -39
- package/dist/http/resources/types.d.ts +10 -30
- package/dist/http/static-documents.d.ts +10 -20
- package/dist/http/validation/Validator.d.ts +25 -85
- package/dist/http/validation/rules.d.ts +48 -147
- package/dist/http/validation/types.d.ts +16 -61
- package/dist/http/vite-assets.d.ts +5 -28
- package/dist/http/vite-dev-server.d.ts +6 -9
- package/dist/http/vite-manifest.d.ts +19 -33
- package/dist/i18n/I18nManager.d.ts +12 -78
- package/dist/i18n/Translator.d.ts +3 -54
- package/dist/i18n/index.js +1 -1
- package/dist/i18n/loaders/JsonLoader.d.ts +4 -31
- package/dist/i18n/loaders/MemoryLoader.d.ts +1 -21
- package/dist/i18n/pluralization.d.ts +4 -13
- package/dist/i18n/types.d.ts +17 -69
- package/dist/{i18n-mcWi7LCd.js → i18n-Cg1aajRP.js} +31 -225
- package/dist/index.d.ts +11 -4
- package/dist/index.js +1186 -3040
- package/dist/internal/agent-preflight.d.ts +9 -21
- package/dist/internal/agent-principal.d.ts +32 -0
- package/dist/internal/request.d.ts +6 -19
- package/dist/internal/request.js +1 -1
- package/dist/internal/route-path.d.ts +9 -21
- package/dist/internal/route-path.js +9 -21
- package/dist/internal/zod-compat.d.ts +55 -122
- package/dist/internal/zod-compat.js +39 -70
- package/dist/internal/zod-json-schema.d.ts +18 -54
- package/dist/internal/zod-json-schema.js +46 -123
- package/dist/jsx-runtime.d.ts +3 -8
- package/dist/lambda/index.d.ts +17 -79
- package/dist/lambda/index.js +11 -59
- package/dist/logging/LogManager.d.ts +1 -51
- package/dist/logging/Logger.d.ts +8 -47
- package/dist/logging/channels/ConsoleChannel.d.ts +1 -3
- package/dist/logging/channels/DailyFileChannel.d.ts +1 -3
- package/dist/logging/channels/FileChannel.d.ts +1 -3
- package/dist/logging/daily-file-path.d.ts +7 -16
- package/dist/logging/index.js +1 -1
- package/dist/logging/types.d.ts +13 -45
- package/dist/{logging-B-kngi3q.js → logging-zOY1XCtq.js} +52 -141
- package/dist/{loopback-guard-D0Kc7-xc.js → loopback-guard-DT9gHF0F.js} +41 -92
- package/dist/mail/Mail.d.ts +10 -106
- package/dist/mail/MailManager.d.ts +2 -60
- package/dist/mail/index.js +1 -1
- package/dist/mail/transports/LogTransport.d.ts +1 -4
- package/dist/mail/transports/MemoryTransport.d.ts +1 -63
- package/dist/mail/transports/ResendTransport.d.ts +1 -23
- package/dist/mail/transports/SmtpTransport.d.ts +1 -31
- package/dist/mail/types.d.ts +28 -150
- package/dist/{mail-DfEfSQEr.js → mail-76DWy9lj.js} +31 -289
- package/dist/mcp/McpServiceProvider.d.ts +4 -10
- package/dist/mcp/create-mcp-server.d.ts +42 -57
- package/dist/mcp/endpoint.d.ts +12 -36
- package/dist/mcp/index.js +1 -1
- package/dist/mvc/Controller.d.ts +46 -227
- package/dist/mvc/Router.d.ts +50 -129
- package/dist/mvc/inertia/InertiaEngine.d.ts +18 -48
- package/dist/mvc/inertia/shared.d.ts +6 -19
- package/dist/mvc/mount-route.d.ts +2 -6
- package/dist/mvc/view.d.ts +1 -2
- package/dist/notifications/Notification.d.ts +8 -75
- package/dist/notifications/NotificationManager.d.ts +15 -88
- package/dist/notifications/channels/DatabaseChannel.d.ts +1 -41
- package/dist/notifications/channels/MailChannel.d.ts +2 -31
- package/dist/notifications/channels/MemoryChannel.d.ts +2 -62
- package/dist/notifications/channels/SlackChannel.d.ts +3 -48
- package/dist/notifications/index.js +1 -1
- package/dist/notifications/notifiable-type.d.ts +3 -6
- package/dist/notifications/registry.d.ts +8 -27
- package/dist/notifications/types.d.ts +16 -53
- package/dist/{notifications-BGqmUNZ8.js → notifications-okWFs9ly.js} +37 -335
- package/dist/providers/AuthServiceProvider.d.ts +1 -3
- package/dist/providers/AuthorizationServiceProvider.d.ts +2 -3
- package/dist/providers/BroadcastServiceProvider.d.ts +1 -3
- package/dist/providers/CacheServiceProvider.d.ts +1 -3
- package/dist/providers/EncryptionServiceProvider.d.ts +1 -3
- package/dist/providers/ErrorServiceProvider.d.ts +1 -4
- package/dist/providers/EventServiceProvider.d.ts +1 -3
- package/dist/providers/HealthServiceProvider.d.ts +1 -3
- package/dist/providers/I18nServiceProvider.d.ts +6 -10
- package/dist/providers/InertiaServiceProvider.d.ts +1 -4
- package/dist/providers/LogServiceProvider.d.ts +1 -3
- package/dist/providers/MailServiceProvider.d.ts +1 -3
- package/dist/providers/NotificationServiceProvider.d.ts +1 -3
- package/dist/providers/OAuthServiceProvider.d.ts +1 -3
- package/dist/providers/QueueServiceProvider.d.ts +1 -3
- package/dist/providers/SchedulingServiceProvider.d.ts +1 -3
- package/dist/providers/StorageServiceProvider.d.ts +1 -3
- package/dist/queue/FailedJobReporter.d.ts +1 -24
- package/dist/queue/Job.d.ts +12 -99
- package/dist/queue/QueueManager.d.ts +6 -57
- package/dist/queue/Worker.d.ts +4 -65
- package/dist/queue/drivers/MemoryDriver.d.ts +3 -44
- package/dist/queue/drivers/RedisDriver.d.ts +7 -65
- package/dist/queue/drivers/SqsDriver.d.ts +6 -57
- package/dist/queue/drivers/SyncDriver.d.ts +10 -13
- package/dist/queue/index.js +2 -2
- package/dist/queue/types.d.ts +10 -92
- package/dist/{queue-CXrRK85G.js → queue-CcXCjuJI.js} +32 -260
- package/dist/redis/RedisApiTokenStore.d.ts +4 -56
- package/dist/redis/RedisEmailVerificationStore.d.ts +4 -37
- package/dist/redis/RedisOAuthStateStore.d.ts +2 -10
- package/dist/redis/RedisPasswordResetStore.d.ts +4 -37
- package/dist/redis/RedisRateLimitStore.d.ts +16 -49
- package/dist/redis/RedisSessionStore.d.ts +3 -44
- package/dist/redis/client.d.ts +2 -32
- package/dist/redis/index.js +47 -232
- package/dist/redis/redis-values.d.ts +6 -12
- package/dist/redis/scan-keys.d.ts +1 -4
- package/dist/request-CLOYytGP.js +68 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.js +50 -92
- package/dist/scheduling/CronParser.d.ts +0 -29
- package/dist/scheduling/Schedule.d.ts +1 -153
- package/dist/scheduling/ScheduledTask.d.ts +0 -31
- package/dist/scheduling/Scheduler.d.ts +0 -70
- package/dist/scheduling/index.js +1 -1
- package/dist/scheduling/types.d.ts +4 -65
- package/dist/{scheduling-CPiEdtQd.js → scheduling-C6tcOtUl.js} +2 -287
- package/dist/storage/StorageManager.d.ts +0 -48
- package/dist/storage/drivers/LocalDriver.d.ts +1 -25
- package/dist/storage/drivers/MemoryDriver.d.ts +5 -35
- package/dist/storage/drivers/S3Driver.d.ts +6 -36
- package/dist/storage/drivers/s3-acl.d.ts +5 -10
- package/dist/storage/index.js +1 -1
- package/dist/storage/types.d.ts +27 -265
- package/dist/{storage-TLD9t0Q2.js → storage-BB59f07j.js} +17 -157
- package/dist/support/contained-path.d.ts +10 -20
- package/dist/support/error-polyfill.d.ts +4 -6
- package/dist/support/expiry.d.ts +17 -33
- package/dist/support/expiry.js +17 -33
- package/dist/support/import-map.d.ts +3 -7
- package/dist/support/inertia-defaults.d.ts +5 -10
- package/dist/support/redirect-target.d.ts +4 -6
- package/dist/support/stack-frames.d.ts +11 -50
- package/dist/support/trim-slashes.d.ts +4 -7
- package/dist/support/warn-once.d.ts +2 -6
- package/dist/{trim-slashes-ZJ_VsY5s.js → trim-slashes-BLY9hKAa.js} +4 -7
- package/dist/{vite-manifest-w_RSOvQW.js → vite-manifest-B_Iy5183.js} +34 -58
- package/package.json +2 -2
- package/dist/client-Dd7vLcqp.js +0 -27
- package/dist/context-DoD0c7J_.js +0 -26
- package/dist/endpoint-D-20PiHY.js +0 -46
- package/dist/hot-disposables-WsTX2ySN.js +0 -281
- package/dist/request-CVQwpu2J.js +0 -129
package/dist/redis/index.js
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { toDate, toOptionalExpiry } from "../support/expiry.js";
|
|
2
|
-
import { n as createRedisClient, t as Redis } from "../client-
|
|
2
|
+
import { n as createRedisClient, t as Redis } from "../client-C4TEr_Dd.js";
|
|
3
3
|
//#region src/redis/scan-keys.ts
|
|
4
|
-
/**
|
|
5
|
-
* Scan Redis keys matching a pattern without blocking the server.
|
|
6
|
-
* Uses SCAN with cursor-based iteration to avoid the O(N) KEYS command.
|
|
7
|
-
*/
|
|
4
|
+
/** Cursor-based SCAN rather than the O(N), server-blocking KEYS. */
|
|
8
5
|
async function scanKeys(redis, pattern) {
|
|
9
6
|
const keys = [];
|
|
10
7
|
let cursor = "0";
|
|
@@ -17,19 +14,6 @@ async function scanKeys(redis, pattern) {
|
|
|
17
14
|
}
|
|
18
15
|
//#endregion
|
|
19
16
|
//#region src/redis/RedisSessionStore.ts
|
|
20
|
-
/**
|
|
21
|
-
* Redis-backed session store.
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```ts
|
|
25
|
-
* import { createRedisClient } from '@guren/server/redis'
|
|
26
|
-
*
|
|
27
|
-
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
28
|
-
* const store = new RedisSessionStore(redis)
|
|
29
|
-
*
|
|
30
|
-
* app.use(createSessionMiddleware({ store }))
|
|
31
|
-
* ```
|
|
32
|
-
*/
|
|
33
17
|
var RedisSessionStore = class {
|
|
34
18
|
redis;
|
|
35
19
|
prefix;
|
|
@@ -37,9 +21,6 @@ var RedisSessionStore = class {
|
|
|
37
21
|
this.redis = redis;
|
|
38
22
|
this.prefix = options.prefix ?? "session:";
|
|
39
23
|
}
|
|
40
|
-
/**
|
|
41
|
-
* Read session data from Redis.
|
|
42
|
-
*/
|
|
43
24
|
async read(id) {
|
|
44
25
|
const key = this.prefix + id;
|
|
45
26
|
const data = await this.redis.get(key);
|
|
@@ -50,46 +31,27 @@ var RedisSessionStore = class {
|
|
|
50
31
|
return;
|
|
51
32
|
}
|
|
52
33
|
}
|
|
53
|
-
/**
|
|
54
|
-
* Write session data to Redis with TTL.
|
|
55
|
-
*/
|
|
56
34
|
async write(id, data, ttlSeconds) {
|
|
57
35
|
const key = this.prefix + id;
|
|
58
36
|
const serialized = JSON.stringify(data);
|
|
59
37
|
await this.redis.setex(key, ttlSeconds, serialized);
|
|
60
38
|
}
|
|
61
|
-
/**
|
|
62
|
-
* Delete a session from Redis.
|
|
63
|
-
*/
|
|
64
39
|
async destroy(id) {
|
|
65
40
|
const key = this.prefix + id;
|
|
66
41
|
await this.redis.del(key);
|
|
67
42
|
}
|
|
68
|
-
/**
|
|
69
|
-
* Refresh an existing session's TTL without rewriting its data.
|
|
70
|
-
* EXPIRE on a missing key is a no-op, never a resurrection.
|
|
71
|
-
*/
|
|
43
|
+
/** EXPIRE on a missing key is a no-op, never a resurrection. */
|
|
72
44
|
async touch(id, ttlSeconds) {
|
|
73
45
|
const key = this.prefix + id;
|
|
74
46
|
await this.redis.expire(key, ttlSeconds);
|
|
75
47
|
}
|
|
76
|
-
/**
|
|
77
|
-
* Get all session keys (for debugging/admin purposes).
|
|
78
|
-
* Note: This uses SCAN to avoid blocking Redis.
|
|
79
|
-
*/
|
|
48
|
+
/** Debugging/admin. */
|
|
80
49
|
async keys() {
|
|
81
50
|
return (await scanKeys(this.redis, this.prefix + "*")).map((key) => key.slice(this.prefix.length));
|
|
82
51
|
}
|
|
83
|
-
/**
|
|
84
|
-
* Get the count of sessions (for monitoring).
|
|
85
|
-
*/
|
|
86
52
|
async size() {
|
|
87
53
|
return (await this.keys()).length;
|
|
88
54
|
}
|
|
89
|
-
/**
|
|
90
|
-
* Clear all sessions.
|
|
91
|
-
* Use with caution in production!
|
|
92
|
-
*/
|
|
93
55
|
async clear() {
|
|
94
56
|
const keys = await this.keys();
|
|
95
57
|
if (keys.length > 0) {
|
|
@@ -101,8 +63,8 @@ var RedisSessionStore = class {
|
|
|
101
63
|
//#endregion
|
|
102
64
|
//#region src/redis/RedisRateLimitStore.ts
|
|
103
65
|
/**
|
|
104
|
-
*
|
|
105
|
-
*
|
|
66
|
+
* Returns [count, resetAt]. Exported for the in-memory fake in tests, which
|
|
67
|
+
* recognises the script by identity; not part of the public surface.
|
|
106
68
|
*/
|
|
107
69
|
const INCREMENT_SCRIPT = `
|
|
108
70
|
local key = KEYS[1]
|
|
@@ -118,19 +80,25 @@ local resetAt = now + ttl
|
|
|
118
80
|
return {count, resetAt}
|
|
119
81
|
`;
|
|
120
82
|
/**
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
* import { createRedisClient } from '@guren/server/redis'
|
|
127
|
-
*
|
|
128
|
-
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
129
|
-
* const store = new RedisRateLimitStore(redis)
|
|
130
|
-
*
|
|
131
|
-
* app.use(createRateLimitMiddleware({ store, limit: 100 }))
|
|
132
|
-
* ```
|
|
83
|
+
* Trim entries that fell out of the window, record this request, count what is
|
|
84
|
+
* left, and refresh the expiry as one atomic step; returns the count. A pipeline
|
|
85
|
+
* is not a substitute: Redis still interleaves other clients' commands between
|
|
86
|
+
* its steps, so two concurrent callers could both ZADD before either ZCARD and
|
|
87
|
+
* read the same count. The caller generates the member so the script stays deterministic.
|
|
133
88
|
*/
|
|
89
|
+
const SLIDING_WINDOW_SCRIPT = `
|
|
90
|
+
local key = KEYS[1]
|
|
91
|
+
local window = tonumber(ARGV[1])
|
|
92
|
+
local now = tonumber(ARGV[2])
|
|
93
|
+
local member = ARGV[3]
|
|
94
|
+
|
|
95
|
+
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
|
|
96
|
+
redis.call('ZADD', key, now, member)
|
|
97
|
+
local count = redis.call('ZCARD', key)
|
|
98
|
+
redis.call('PEXPIRE', key, window)
|
|
99
|
+
return count
|
|
100
|
+
`;
|
|
101
|
+
/** Fixed-window rate limiting; the Lua script keeps the increment atomic. */
|
|
134
102
|
var RedisRateLimitStore = class {
|
|
135
103
|
redis;
|
|
136
104
|
prefix;
|
|
@@ -138,9 +106,6 @@ var RedisRateLimitStore = class {
|
|
|
138
106
|
this.redis = redis;
|
|
139
107
|
this.prefix = options.prefix ?? "ratelimit:";
|
|
140
108
|
}
|
|
141
|
-
/**
|
|
142
|
-
* Get current rate limit entry for a key.
|
|
143
|
-
*/
|
|
144
109
|
async get(key) {
|
|
145
110
|
const redisKey = this.prefix + key;
|
|
146
111
|
const [countStr, ttl] = await Promise.all([this.redis.get(redisKey), this.redis.pttl(redisKey)]);
|
|
@@ -150,9 +115,6 @@ var RedisRateLimitStore = class {
|
|
|
150
115
|
resetAt: Date.now() + ttl
|
|
151
116
|
};
|
|
152
117
|
}
|
|
153
|
-
/**
|
|
154
|
-
* Increment the rate limit counter atomically.
|
|
155
|
-
*/
|
|
156
118
|
async increment(key, windowMs) {
|
|
157
119
|
const redisKey = this.prefix + key;
|
|
158
120
|
const now = Date.now();
|
|
@@ -162,22 +124,14 @@ var RedisRateLimitStore = class {
|
|
|
162
124
|
resetAt: result[1]
|
|
163
125
|
};
|
|
164
126
|
}
|
|
165
|
-
/**
|
|
166
|
-
* Reset the rate limit for a key.
|
|
167
|
-
*/
|
|
168
127
|
async reset(key) {
|
|
169
128
|
const redisKey = this.prefix + key;
|
|
170
129
|
await this.redis.del(redisKey);
|
|
171
130
|
}
|
|
172
|
-
/**
|
|
173
|
-
* Get all rate limit keys (for debugging/admin purposes).
|
|
174
|
-
*/
|
|
131
|
+
/** Debugging/admin. */
|
|
175
132
|
async keys() {
|
|
176
133
|
return (await scanKeys(this.redis, this.prefix + "*")).map((key) => key.slice(this.prefix.length));
|
|
177
134
|
}
|
|
178
|
-
/**
|
|
179
|
-
* Clear all rate limits.
|
|
180
|
-
*/
|
|
181
135
|
async clear() {
|
|
182
136
|
const keys = await this.keys();
|
|
183
137
|
if (keys.length > 0) {
|
|
@@ -187,8 +141,8 @@ var RedisRateLimitStore = class {
|
|
|
187
141
|
}
|
|
188
142
|
};
|
|
189
143
|
/**
|
|
190
|
-
*
|
|
191
|
-
*
|
|
144
|
+
* Sliding window: more accurate than the fixed window, slightly more expensive.
|
|
145
|
+
* The Lua script keeps trim, insert, and count atomic.
|
|
192
146
|
*/
|
|
193
147
|
var RedisSlidingWindowRateLimitStore = class {
|
|
194
148
|
redis;
|
|
@@ -197,9 +151,6 @@ var RedisSlidingWindowRateLimitStore = class {
|
|
|
197
151
|
this.redis = redis;
|
|
198
152
|
this.prefix = options.prefix ?? "ratelimit:sw:";
|
|
199
153
|
}
|
|
200
|
-
/**
|
|
201
|
-
* Get current rate limit entry for a key.
|
|
202
|
-
*/
|
|
203
154
|
async get(key) {
|
|
204
155
|
const redisKey = this.prefix + key;
|
|
205
156
|
const count = await this.redis.zcard(redisKey);
|
|
@@ -210,34 +161,18 @@ var RedisSlidingWindowRateLimitStore = class {
|
|
|
210
161
|
resetAt: ttl > 0 ? Date.now() + ttl : Date.now()
|
|
211
162
|
};
|
|
212
163
|
}
|
|
213
|
-
/**
|
|
214
|
-
* Increment the rate limit counter using sorted set.
|
|
215
|
-
* Each request is stored with its timestamp as score.
|
|
216
|
-
*/
|
|
217
164
|
async increment(key, windowMs) {
|
|
218
165
|
const redisKey = this.prefix + key;
|
|
219
166
|
const now = Date.now();
|
|
220
|
-
const windowStart = now - windowMs;
|
|
221
|
-
const pipeline = this.redis.pipeline();
|
|
222
|
-
pipeline.zremrangebyscore(redisKey, "-inf", windowStart);
|
|
223
|
-
pipeline.zadd(redisKey, now, `${now}:${Math.random()}`);
|
|
224
|
-
pipeline.zcard(redisKey);
|
|
225
|
-
pipeline.pexpire(redisKey, windowMs);
|
|
226
167
|
return {
|
|
227
|
-
count:
|
|
168
|
+
count: await this.redis.eval(SLIDING_WINDOW_SCRIPT, 1, redisKey, windowMs.toString(), now.toString(), `${now}:${Math.random()}`),
|
|
228
169
|
resetAt: now + windowMs
|
|
229
170
|
};
|
|
230
171
|
}
|
|
231
|
-
/**
|
|
232
|
-
* Reset the rate limit for a key.
|
|
233
|
-
*/
|
|
234
172
|
async reset(key) {
|
|
235
173
|
const redisKey = this.prefix + key;
|
|
236
174
|
await this.redis.del(redisKey);
|
|
237
175
|
}
|
|
238
|
-
/**
|
|
239
|
-
* Clear all rate limits.
|
|
240
|
-
*/
|
|
241
176
|
async clear() {
|
|
242
177
|
const keys = await scanKeys(this.redis, this.prefix + "*");
|
|
243
178
|
if (keys.length > 0) await this.redis.del(...keys);
|
|
@@ -246,20 +181,14 @@ var RedisSlidingWindowRateLimitStore = class {
|
|
|
246
181
|
//#endregion
|
|
247
182
|
//#region src/redis/redis-values.ts
|
|
248
183
|
/**
|
|
249
|
-
* Decoding rules shared by the Redis-backed stores.
|
|
250
|
-
*
|
|
251
|
-
* Expiry coercion lives in `../support/expiry` — every store reads its expiry
|
|
252
|
-
* through `toDate`/`toOptionalExpiry`/`isExpired` there, so there is one rule
|
|
253
|
-
* rather than one per store.
|
|
184
|
+
* Decoding rules shared by the Redis-backed stores. Expiry coercion lives in
|
|
185
|
+
* `../support/expiry`, so there is one rule rather than one per store.
|
|
254
186
|
*/
|
|
255
187
|
/**
|
|
256
|
-
*
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
* on
|
|
260
|
-
* something other than a list of strings degrades the same way: `tokenCan`
|
|
261
|
-
* would otherwise run `String.prototype.includes` on it, so a stored `'"*"'`
|
|
262
|
-
* would grant every ability.
|
|
188
|
+
* Corrupt text degrades to no abilities (deny-by-default) rather than throwing
|
|
189
|
+
* on every verification of the affected token. Anything that decodes to a
|
|
190
|
+
* non-list degrades the same way: `tokenCan` would otherwise run
|
|
191
|
+
* `String.prototype.includes` on it, so a stored `'"*"'` would grant everything.
|
|
263
192
|
*/
|
|
264
193
|
function decodeAbilities(value) {
|
|
265
194
|
if (value == null || value === "") return [];
|
|
@@ -274,25 +203,8 @@ function decodeAbilities(value) {
|
|
|
274
203
|
//#endregion
|
|
275
204
|
//#region src/redis/RedisApiTokenStore.ts
|
|
276
205
|
/**
|
|
277
|
-
*
|
|
278
|
-
*
|
|
279
|
-
* Uses the following key structure:
|
|
280
|
-
* - `apitoken:{id}` - Token data (hash)
|
|
281
|
-
* - `apitoken:hash:{hashedToken}` - Maps hash to token ID
|
|
282
|
-
* - `apitoken:user:{userId}` - Set of token IDs for a user
|
|
283
|
-
*
|
|
284
|
-
* @example
|
|
285
|
-
* ```ts
|
|
286
|
-
* import { createRedisClient } from '@guren/server/redis'
|
|
287
|
-
*
|
|
288
|
-
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
289
|
-
* const store = new RedisApiTokenStore(redis)
|
|
290
|
-
*
|
|
291
|
-
* const { plainTextToken } = await createApiToken(store, {
|
|
292
|
-
* name: 'API Token',
|
|
293
|
-
* userId: user.id,
|
|
294
|
-
* })
|
|
295
|
-
* ```
|
|
206
|
+
* Key layout: `apitoken:{id}` Hash of token data, `apitoken:hash:{hashedToken}`
|
|
207
|
+
* hash → token ID, `apitoken:user:{userId}` Set of a user's token IDs.
|
|
296
208
|
*/
|
|
297
209
|
var RedisApiTokenStore = class {
|
|
298
210
|
redis;
|
|
@@ -301,9 +213,6 @@ var RedisApiTokenStore = class {
|
|
|
301
213
|
this.redis = redis;
|
|
302
214
|
this.prefix = options.prefix ?? "apitoken:";
|
|
303
215
|
}
|
|
304
|
-
/**
|
|
305
|
-
* Store a new API token.
|
|
306
|
-
*/
|
|
307
216
|
async store(token) {
|
|
308
217
|
const tokenKey = `${this.prefix}${token.id}`;
|
|
309
218
|
const hashKey = `${this.prefix}hash:${token.hashedToken}`;
|
|
@@ -322,18 +231,12 @@ var RedisApiTokenStore = class {
|
|
|
322
231
|
}
|
|
323
232
|
await pipeline.exec();
|
|
324
233
|
}
|
|
325
|
-
/**
|
|
326
|
-
* Find a token by its hashed value.
|
|
327
|
-
*/
|
|
328
234
|
async findByHashedToken(hashedToken) {
|
|
329
235
|
const hashKey = `${this.prefix}hash:${hashedToken}`;
|
|
330
236
|
const tokenId = await this.redis.get(hashKey);
|
|
331
237
|
if (!tokenId) return null;
|
|
332
238
|
return this.findById(tokenId);
|
|
333
239
|
}
|
|
334
|
-
/**
|
|
335
|
-
* Find all tokens for a user.
|
|
336
|
-
*/
|
|
337
240
|
async findByUserId(userId) {
|
|
338
241
|
const userKey = `${this.prefix}user:${userId}`;
|
|
339
242
|
const tokenIds = await this.redis.smembers(userKey);
|
|
@@ -344,9 +247,6 @@ var RedisApiTokenStore = class {
|
|
|
344
247
|
}
|
|
345
248
|
return tokens;
|
|
346
249
|
}
|
|
347
|
-
/**
|
|
348
|
-
* Delete a token by its ID.
|
|
349
|
-
*/
|
|
350
250
|
async delete(id) {
|
|
351
251
|
const token = await this.findById(id);
|
|
352
252
|
if (!token) return;
|
|
@@ -359,34 +259,22 @@ var RedisApiTokenStore = class {
|
|
|
359
259
|
pipeline.srem(userKey, id);
|
|
360
260
|
await pipeline.exec();
|
|
361
261
|
}
|
|
362
|
-
/**
|
|
363
|
-
* Delete all tokens for a user.
|
|
364
|
-
*/
|
|
365
262
|
async deleteForUser(userId) {
|
|
366
263
|
const tokens = await this.findByUserId(userId);
|
|
367
264
|
for (const token of tokens) await this.delete(token.id);
|
|
368
265
|
const userKey = `${this.prefix}user:${userId}`;
|
|
369
266
|
await this.redis.del(userKey);
|
|
370
267
|
}
|
|
371
|
-
/**
|
|
372
|
-
* Update the last used timestamp.
|
|
373
|
-
*/
|
|
374
268
|
async updateLastUsed(id, timestamp) {
|
|
375
269
|
const tokenKey = `${this.prefix}${id}`;
|
|
376
270
|
await this.redis.hset(tokenKey, "lastUsedAt", timestamp.toISOString());
|
|
377
271
|
}
|
|
378
|
-
/**
|
|
379
|
-
* Find a token by its ID.
|
|
380
|
-
*/
|
|
381
272
|
async findById(id) {
|
|
382
273
|
const tokenKey = `${this.prefix}${id}`;
|
|
383
274
|
const data = await this.redis.hgetall(tokenKey);
|
|
384
275
|
if (!data || Object.keys(data).length === 0) return null;
|
|
385
276
|
return this.deserializeToken(data);
|
|
386
277
|
}
|
|
387
|
-
/**
|
|
388
|
-
* Serialize a token for Redis storage.
|
|
389
|
-
*/
|
|
390
278
|
serializeToken(token) {
|
|
391
279
|
return {
|
|
392
280
|
id: token.id,
|
|
@@ -399,9 +287,6 @@ var RedisApiTokenStore = class {
|
|
|
399
287
|
createdAt: token.createdAt.toISOString()
|
|
400
288
|
};
|
|
401
289
|
}
|
|
402
|
-
/**
|
|
403
|
-
* Deserialize a token from Redis storage.
|
|
404
|
-
*/
|
|
405
290
|
deserializeToken(data) {
|
|
406
291
|
return {
|
|
407
292
|
id: data.id,
|
|
@@ -414,9 +299,7 @@ var RedisApiTokenStore = class {
|
|
|
414
299
|
createdAt: toDate(data.createdAt) ?? /* @__PURE__ */ new Date(0)
|
|
415
300
|
};
|
|
416
301
|
}
|
|
417
|
-
/**
|
|
418
|
-
* Clear all tokens (for testing).
|
|
419
|
-
*/
|
|
302
|
+
/** Testing only. */
|
|
420
303
|
async clear() {
|
|
421
304
|
const keys = await scanKeys(this.redis, this.prefix + "*");
|
|
422
305
|
if (keys.length > 0) await this.redis.del(...keys);
|
|
@@ -425,21 +308,8 @@ var RedisApiTokenStore = class {
|
|
|
425
308
|
//#endregion
|
|
426
309
|
//#region src/redis/RedisPasswordResetStore.ts
|
|
427
310
|
/**
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
* Uses the following key structure:
|
|
431
|
-
* - `pwreset:{tokenId}` - Token data (JSON with email and expiresAt)
|
|
432
|
-
* - `pwreset:email:{email}` - Set of token IDs for an email
|
|
433
|
-
*
|
|
434
|
-
* @example
|
|
435
|
-
* ```ts
|
|
436
|
-
* import { createRedisClient } from '@guren/server/redis'
|
|
437
|
-
*
|
|
438
|
-
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
439
|
-
* const store = new RedisPasswordResetStore(redis)
|
|
440
|
-
*
|
|
441
|
-
* const { token } = await createPasswordResetToken(email, store, { expiresIn: 3600000 })
|
|
442
|
-
* ```
|
|
311
|
+
* Key layout: `pwreset:{tokenId}` JSON of email + expiresAt,
|
|
312
|
+
* `pwreset:email:{email}` Set of an email's token IDs.
|
|
443
313
|
*/
|
|
444
314
|
var RedisPasswordResetStore = class {
|
|
445
315
|
redis;
|
|
@@ -448,9 +318,6 @@ var RedisPasswordResetStore = class {
|
|
|
448
318
|
this.redis = redis;
|
|
449
319
|
this.prefix = options.prefix ?? "pwreset:";
|
|
450
320
|
}
|
|
451
|
-
/**
|
|
452
|
-
* Store a password reset token.
|
|
453
|
-
*/
|
|
454
321
|
async store(tokenId, email, expiresAt) {
|
|
455
322
|
const tokenKey = `${this.prefix}${tokenId}`;
|
|
456
323
|
const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
|
|
@@ -466,9 +333,6 @@ var RedisPasswordResetStore = class {
|
|
|
466
333
|
pipeline.pexpire(emailKey, ttlMs + 6e4);
|
|
467
334
|
await pipeline.exec();
|
|
468
335
|
}
|
|
469
|
-
/**
|
|
470
|
-
* Find a token by its hash.
|
|
471
|
-
*/
|
|
472
336
|
async find(tokenId) {
|
|
473
337
|
const tokenKey = `${this.prefix}${tokenId}`;
|
|
474
338
|
const data = await this.redis.get(tokenKey);
|
|
@@ -485,9 +349,6 @@ var RedisPasswordResetStore = class {
|
|
|
485
349
|
return null;
|
|
486
350
|
}
|
|
487
351
|
}
|
|
488
|
-
/**
|
|
489
|
-
* Delete a token by its hash.
|
|
490
|
-
*/
|
|
491
352
|
async delete(tokenId) {
|
|
492
353
|
const tokenKey = `${this.prefix}${tokenId}`;
|
|
493
354
|
const data = await this.redis.get(tokenKey);
|
|
@@ -498,9 +359,6 @@ var RedisPasswordResetStore = class {
|
|
|
498
359
|
} catch {}
|
|
499
360
|
await this.redis.del(tokenKey);
|
|
500
361
|
}
|
|
501
|
-
/**
|
|
502
|
-
* Delete all tokens for an email.
|
|
503
|
-
*/
|
|
504
362
|
async deleteForEmail(email) {
|
|
505
363
|
const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
|
|
506
364
|
const tokenIds = await this.redis.smembers(emailKey);
|
|
@@ -509,9 +367,7 @@ var RedisPasswordResetStore = class {
|
|
|
509
367
|
await this.redis.del(...tokenKeys, emailKey);
|
|
510
368
|
} else await this.redis.del(emailKey);
|
|
511
369
|
}
|
|
512
|
-
/**
|
|
513
|
-
* Clear all tokens (for testing).
|
|
514
|
-
*/
|
|
370
|
+
/** Testing only. */
|
|
515
371
|
async clear() {
|
|
516
372
|
const keys = await scanKeys(this.redis, this.prefix + "*");
|
|
517
373
|
if (keys.length > 0) await this.redis.del(...keys);
|
|
@@ -520,21 +376,8 @@ var RedisPasswordResetStore = class {
|
|
|
520
376
|
//#endregion
|
|
521
377
|
//#region src/redis/RedisEmailVerificationStore.ts
|
|
522
378
|
/**
|
|
523
|
-
*
|
|
524
|
-
*
|
|
525
|
-
* Uses the following key structure:
|
|
526
|
-
* - `emailverify:{tokenId}` - Token data (JSON)
|
|
527
|
-
* - `emailverify:email:{email}` - Set of token IDs for an email
|
|
528
|
-
*
|
|
529
|
-
* @example
|
|
530
|
-
* ```ts
|
|
531
|
-
* import { createRedisClient } from '@guren/server/redis'
|
|
532
|
-
*
|
|
533
|
-
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
534
|
-
* const store = new RedisEmailVerificationStore(redis)
|
|
535
|
-
*
|
|
536
|
-
* const { token } = await createEmailVerificationToken(email, store, { expiresIn: 86400000 })
|
|
537
|
-
* ```
|
|
379
|
+
* Key layout: `emailverify:{tokenId}` JSON token data,
|
|
380
|
+
* `emailverify:email:{email}` Set of an email's token IDs.
|
|
538
381
|
*/
|
|
539
382
|
var RedisEmailVerificationStore = class {
|
|
540
383
|
redis;
|
|
@@ -543,9 +386,6 @@ var RedisEmailVerificationStore = class {
|
|
|
543
386
|
this.redis = redis;
|
|
544
387
|
this.prefix = options.prefix ?? "emailverify:";
|
|
545
388
|
}
|
|
546
|
-
/**
|
|
547
|
-
* Store an email verification token.
|
|
548
|
-
*/
|
|
549
389
|
async store(token) {
|
|
550
390
|
const tokenKey = `${this.prefix}${token.tokenId}`;
|
|
551
391
|
const emailKey = `${this.prefix}email:${token.email.toLowerCase()}`;
|
|
@@ -563,9 +403,6 @@ var RedisEmailVerificationStore = class {
|
|
|
563
403
|
pipeline.pexpire(emailKey, ttlMs + 6e4);
|
|
564
404
|
await pipeline.exec();
|
|
565
405
|
}
|
|
566
|
-
/**
|
|
567
|
-
* Find a token by its hash.
|
|
568
|
-
*/
|
|
569
406
|
async findByTokenId(tokenId) {
|
|
570
407
|
const tokenKey = `${this.prefix}${tokenId}`;
|
|
571
408
|
const data = await this.redis.get(tokenKey);
|
|
@@ -584,9 +421,6 @@ var RedisEmailVerificationStore = class {
|
|
|
584
421
|
return null;
|
|
585
422
|
}
|
|
586
423
|
}
|
|
587
|
-
/**
|
|
588
|
-
* Delete a token by its hash.
|
|
589
|
-
*/
|
|
590
424
|
async delete(tokenId) {
|
|
591
425
|
const tokenKey = `${this.prefix}${tokenId}`;
|
|
592
426
|
const data = await this.redis.get(tokenKey);
|
|
@@ -597,9 +431,6 @@ var RedisEmailVerificationStore = class {
|
|
|
597
431
|
} catch {}
|
|
598
432
|
await this.redis.del(tokenKey);
|
|
599
433
|
}
|
|
600
|
-
/**
|
|
601
|
-
* Delete all tokens for an email.
|
|
602
|
-
*/
|
|
603
434
|
async deleteForEmail(email) {
|
|
604
435
|
const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
|
|
605
436
|
const tokenIds = await this.redis.smembers(emailKey);
|
|
@@ -608,9 +439,7 @@ var RedisEmailVerificationStore = class {
|
|
|
608
439
|
await this.redis.del(...tokenKeys, emailKey);
|
|
609
440
|
} else await this.redis.del(emailKey);
|
|
610
441
|
}
|
|
611
|
-
/**
|
|
612
|
-
* Clear all tokens (for testing).
|
|
613
|
-
*/
|
|
442
|
+
/** Testing only. */
|
|
614
443
|
async clear() {
|
|
615
444
|
const keys = await scanKeys(this.redis, this.prefix + "*");
|
|
616
445
|
if (keys.length > 0) await this.redis.del(...keys);
|
|
@@ -619,21 +448,9 @@ var RedisEmailVerificationStore = class {
|
|
|
619
448
|
//#endregion
|
|
620
449
|
//#region src/redis/RedisOAuthStateStore.ts
|
|
621
450
|
/**
|
|
622
|
-
*
|
|
623
|
-
*
|
|
624
|
-
*
|
|
625
|
-
* traffic (load balancers, serverless): the default MemoryOAuthStateStore
|
|
626
|
-
* is per-process, so the callback request may land on a process that never
|
|
627
|
-
* saw the state. Entries expire automatically via Redis TTL.
|
|
628
|
-
*
|
|
629
|
-
* @example
|
|
630
|
-
* ```ts
|
|
631
|
-
* import { createOAuthManager } from '@guren/core'
|
|
632
|
-
* import { createRedisClient, RedisOAuthStateStore } from '@guren/core/redis'
|
|
633
|
-
*
|
|
634
|
-
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
635
|
-
* const oauth = createOAuthManager({ stateStore: new RedisOAuthStateStore(redis) })
|
|
636
|
-
* ```
|
|
451
|
+
* Required in production whenever more than one process handles traffic (load
|
|
452
|
+
* balancers, serverless): the default MemoryOAuthStateStore is per-process, so
|
|
453
|
+
* the callback may land on a process that never saw the state.
|
|
637
454
|
*/
|
|
638
455
|
const CONSUME_SCRIPT = `
|
|
639
456
|
local value = redis.call('GET', KEYS[1])
|
|
@@ -696,9 +513,7 @@ var RedisOAuthStateStore = class {
|
|
|
696
513
|
async delete(stateHash) {
|
|
697
514
|
await this.redis.del(`${this.prefix}${stateHash}`);
|
|
698
515
|
}
|
|
699
|
-
/**
|
|
700
|
-
* Clear all states (for testing).
|
|
701
|
-
*/
|
|
516
|
+
/** Testing only. */
|
|
702
517
|
async clear() {
|
|
703
518
|
const keys = await scanKeys(this.redis, this.prefix + "*");
|
|
704
519
|
if (keys.length > 0) await this.redis.del(...keys);
|
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Decoding rules shared by the Redis-backed stores.
|
|
3
|
-
*
|
|
4
|
-
* Expiry coercion lives in `../support/expiry` — every store reads its expiry
|
|
5
|
-
* through `toDate`/`toOptionalExpiry`/`isExpired` there, so there is one rule
|
|
6
|
-
* rather than one per store.
|
|
2
|
+
* Decoding rules shared by the Redis-backed stores. Expiry coercion lives in
|
|
3
|
+
* `../support/expiry`, so there is one rule rather than one per store.
|
|
7
4
|
*/
|
|
8
5
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* on
|
|
13
|
-
* something other than a list of strings degrades the same way: `tokenCan`
|
|
14
|
-
* would otherwise run `String.prototype.includes` on it, so a stored `'"*"'`
|
|
15
|
-
* would grant every ability.
|
|
6
|
+
* Corrupt text degrades to no abilities (deny-by-default) rather than throwing
|
|
7
|
+
* on every verification of the affected token. Anything that decodes to a
|
|
8
|
+
* non-list degrades the same way: `tokenCan` would otherwise run
|
|
9
|
+
* `String.prototype.includes` on it, so a stored `'"*"'` would grant everything.
|
|
16
10
|
*/
|
|
17
11
|
export declare function decodeAbilities(value: unknown): string[];
|
|
@@ -1,6 +1,3 @@
|
|
|
1
1
|
import type { Redis } from 'ioredis';
|
|
2
|
-
/**
|
|
3
|
-
* Scan Redis keys matching a pattern without blocking the server.
|
|
4
|
-
* Uses SCAN with cursor-based iteration to avoid the O(N) KEYS command.
|
|
5
|
-
*/
|
|
2
|
+
/** Cursor-based SCAN rather than the O(N), server-blocking KEYS. */
|
|
6
3
|
export declare function scanKeys(redis: Redis, pattern: string): Promise<string[]>;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
//#region src/http/request.ts
|
|
2
|
+
function isPlainObject(value) {
|
|
3
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Returns the parsed body as-is (a JSON array stays an array), for callers that
|
|
7
|
+
* hand it to a schema. Any unparseable body falls back to `{}` so an all-optional
|
|
8
|
+
* object schema still passes on an empty POST; a non-object schema then fails
|
|
9
|
+
* validation instead of receiving nothing. A malformed body and one consumed
|
|
10
|
+
* upstream both read as `{}`: telling them apart means matching error codes that differ on Bun, Node and Workers.
|
|
11
|
+
*/
|
|
12
|
+
async function parseRequestBody(ctx) {
|
|
13
|
+
if ((ctx.req.header("content-type") ?? "").includes("application/json")) return ctx.req.json().catch(() => ({}));
|
|
14
|
+
if (typeof ctx.req.parseBody === "function") try {
|
|
15
|
+
const form = await ctx.req.parseBody();
|
|
16
|
+
return Object.fromEntries(Object.entries(form).map(([key, value]) => [key, Array.isArray(value) ? value[0] : value]));
|
|
17
|
+
} catch {
|
|
18
|
+
return {};
|
|
19
|
+
}
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The one multipart read behind `Controller.file()`/`files()`; `{ all: true }` is
|
|
24
|
+
* the contract, which {@link parseRequestBody} (first value of a repeated field) breaks.
|
|
25
|
+
* No media-type gate: Hono lowercases it in `parseBody()`, so uppercase
|
|
26
|
+
* `MULTIPART/FORM-DATA` works here while `Request.formData()` answers `null`
|
|
27
|
+
* (Bun 1.3.14; 1.4.0 and Node accept it). try/catch as `parseBody` may throw synchronously: a bad or consumed body is no files, not a 500.
|
|
28
|
+
*/
|
|
29
|
+
async function parseRequestUploads(ctx) {
|
|
30
|
+
try {
|
|
31
|
+
return await ctx.req.parseBody({ all: true });
|
|
32
|
+
} catch {
|
|
33
|
+
return {};
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The record-shaped view of {@link parseRequestBody}, for callers reading the
|
|
38
|
+
* payload field by field. A body that is not a plain object becomes `{}`.
|
|
39
|
+
*/
|
|
40
|
+
async function parseRequestPayload(ctx) {
|
|
41
|
+
return asRecord(await parseRequestBody(ctx));
|
|
42
|
+
}
|
|
43
|
+
/** Narrow a parsed body to the record view described on {@link parseRequestPayload}. */
|
|
44
|
+
function asRecord(body) {
|
|
45
|
+
return isPlainObject(body) ? body : {};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Query parameters with repeated keys kept as arrays and single ones as strings.
|
|
49
|
+
* Use instead of `ctx.req.query()` when feeding a validation schema.
|
|
50
|
+
* Must be materialized with `Object.fromEntries`, never by assigning into an
|
|
51
|
+
* object literal: query keys are attacker-controlled, and `flat['__proto__'] = …`
|
|
52
|
+
* hits `Object.prototype`'s inherited setter instead of defining a field.
|
|
53
|
+
*/
|
|
54
|
+
function flattenRequestQueries(ctx) {
|
|
55
|
+
return Object.fromEntries(Object.entries(ctx.req.queries()).map(([key, values]) => [key, values.length === 1 ? values[0] : values]));
|
|
56
|
+
}
|
|
57
|
+
/** Converts a Zod-style validation error into a flat record usable by forms. */
|
|
58
|
+
function formatValidationErrors(error, fallbackMessage = "The provided data is invalid.") {
|
|
59
|
+
const errors = {};
|
|
60
|
+
for (const issue of error.issues ?? []) {
|
|
61
|
+
const field = issue.path?.[0];
|
|
62
|
+
if (typeof field === "string" && !errors[field]) errors[field] = issue.message;
|
|
63
|
+
}
|
|
64
|
+
if (Object.keys(errors).length === 0) errors.message = fallbackMessage;
|
|
65
|
+
return errors;
|
|
66
|
+
}
|
|
67
|
+
//#endregion
|
|
68
|
+
export { parseRequestPayload as a, parseRequestBody as i, flattenRequestQueries as n, parseRequestUploads as o, formatValidationErrors as r, asRecord as t };
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -6,3 +6,5 @@ export { logDevServerBanner, GUREN_ASCII_ART } from '../http/dev-banner.js';
|
|
|
6
6
|
export type { DevBannerOptions } from '../http/dev-banner.js';
|
|
7
7
|
export { startViteDevServer } from '../http/vite-dev-server.js';
|
|
8
8
|
export type { StartViteDevServerOptions, StartedViteDevServer } from '../http/vite-dev-server.js';
|
|
9
|
+
export { DEFAULT_ROOT_PUBLIC_ASSET_EXTENSIONS } from '../http/public-assets.js';
|
|
10
|
+
export type { RootPublicAssetsConfig, RootPublicAssetsOptions } from '../http/public-assets.js';
|