@strutvane/redis 0.0.0-reserved.0 → 0.2.0-next.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.
@@ -0,0 +1,628 @@
1
+ /**
2
+ * `@strutvane/redis`: Redis and Valkey for Strutvane apps.
3
+ *
4
+ * - a cache store (`CACHE_STORE=redis`), which also makes the framework's `throttle` limits hold
5
+ * across servers;
6
+ * - atomic locks with owner tokens and safe release;
7
+ * - a session store (`SESSION_DRIVER=redis`);
8
+ * - fixed- and sliding-window rate limiting;
9
+ * - an idempotency store and a used-signature store for multi-server apps;
10
+ * - an experimental queue driver (`@strutvane/redis/queue`).
11
+ *
12
+ * Every key lives under the app's prefix (`REDIS_PREFIX`), optionally scoped to a tenant. Install
13
+ * with `node strut install:redis`; the provider is `@strutvane/redis/provider`.
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ import { BeginOutcome, CacheManager, CacheStore, IdempotencyStore, SessionStore, StoredResponse } from "@strutvane/framework";
18
+ import { Logger } from "@strutvane/framework/contracts";
19
+ import { Clock, ErrorDefinition, StrutvaneError, Token } from "@strutvane/framework/core";
20
+ import { a as prefixProblem, c as asArray, d as defineLua, f as deleteMatching, i as isValidTenantId, l as asInteger, n as MAX_KEY_BYTES, o as LuaScript, r as globEscape, s as RedisDriver, t as KeySpace, u as asNullableString } from "./keys-BeX5p2wm.mjs";
21
+ /**
22
+ * One Redis store in `config/cache.ts`.
23
+ *
24
+ * @example
25
+ * const store: RedisCacheStoreConfig = { driver: 'redis', area: 'reports' }
26
+ */
27
+ interface RedisCacheStoreConfig {
28
+ readonly driver: "redis";
29
+ /** The key area after the app prefix. Default `cache`. */
30
+ readonly area?: string;
31
+ }
32
+ /**
33
+ * What {@link createRedisCacheManager} needs.
34
+ *
35
+ * @example
36
+ * createRedisCacheManager({ basePath, clock, config: app.config('cache'), driver: () => redis, root })
37
+ */
38
+ interface RedisCacheManagerOptions {
39
+ readonly basePath: string;
40
+ readonly clock: Clock;
41
+ /** The `cache` config tree (unchecked). */
42
+ readonly config?: unknown;
43
+ /** The shared connection (resolved on first use of a Redis store). */
44
+ readonly driver: () => RedisDriver;
45
+ /** The app's root key space (`REDIS_PREFIX`). */
46
+ readonly root: KeySpace;
47
+ readonly logger?: Logger;
48
+ }
49
+ /**
50
+ * Build the cache manager with Redis stores.
51
+ *
52
+ * @example
53
+ * const cache = createRedisCacheManager(options)
54
+ * await cache.store('redis').put('k', 1, 60)
55
+ */
56
+ export declare function createRedisCacheManager(options: RedisCacheManagerOptions): CacheManager;
57
+ /**
58
+ * Options for {@link RedisCacheStore}.
59
+ *
60
+ * @example
61
+ * new RedisCacheStore({ driver: redis, space: KeySpace.root('blog:').area('cache') })
62
+ */
63
+ interface RedisCacheStoreOptions {
64
+ readonly driver: RedisDriver;
65
+ /** The key space (`<prefix>cache:` for the default store). */
66
+ readonly space: KeySpace;
67
+ /** Where failed background refreshes (`flexible`) are reported. */
68
+ readonly logger?: Logger;
69
+ }
70
+ /**
71
+ * A cache store in Redis or Valkey.
72
+ *
73
+ * @example
74
+ * const cache = new RedisCacheStore({ driver: redis, space: KeySpace.root('blog:').area('cache') })
75
+ * await cache.put('stats', { posts: 3 }, 60)
76
+ * await cache.forTenant('acme').get('stats') // undefined: another namespace
77
+ */
78
+ export declare class RedisCacheStore implements CacheStore {
79
+ #private;
80
+ constructor(options: RedisCacheStoreOptions);
81
+ /** The key prefix of this store (for diagnostics). */
82
+ get prefix(): string;
83
+ /**
84
+ * The same store, scoped to one tenant.
85
+ *
86
+ * @example
87
+ * await Cache.store('redis').forTenant(tenant.id).remember('dashboard', 60, build)
88
+ */
89
+ forTenant(tenantId: string): RedisCacheStore;
90
+ get(key: string): Promise<unknown>;
91
+ has(key: string): Promise<boolean>;
92
+ put(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
93
+ add(key: string, value: unknown, ttlSeconds?: number): Promise<boolean>;
94
+ increment(key: string, by?: number, ttlSeconds?: number): Promise<number>;
95
+ /**
96
+ * Subtract from a counter (see {@link RedisCacheStore.increment}).
97
+ *
98
+ * @example
99
+ * await cache.decrement('seats', 1)
100
+ */
101
+ decrement(key: string, by?: number, ttlSeconds?: number): Promise<number>;
102
+ ttl(key: string): Promise<number | undefined>;
103
+ forget(key: string): Promise<boolean>;
104
+ flush(): Promise<void>;
105
+ /**
106
+ * Several values at once (`MGET`); missing keys are `undefined`.
107
+ *
108
+ * @example
109
+ * const { a, b } = await cache.many(['a', 'b'])
110
+ */
111
+ many(keys: readonly string[]): Promise<Record<string, unknown>>;
112
+ /**
113
+ * Store several values atomically with one expiry.
114
+ *
115
+ * @example
116
+ * await cache.putMany({ a: 1, b: 2 }, 60)
117
+ */
118
+ putMany(values: Readonly<Record<string, unknown>>, ttlSeconds?: number): Promise<void>;
119
+ /**
120
+ * Store a value with no expiry.
121
+ *
122
+ * @example
123
+ * await cache.forever('settings', { theme: 'dark' })
124
+ */
125
+ forever(key: string, value: unknown): Promise<void>;
126
+ /**
127
+ * The cached value, or compute, store and return it. `undefined` results are not cached.
128
+ *
129
+ * @example
130
+ * const posts = await cache.remember('posts:count', 60, () => Post.query().count())
131
+ */
132
+ remember<TValue>(key: string, ttlSeconds: number | undefined, compute: () => TValue | Promise<TValue>): Promise<TValue>;
133
+ /**
134
+ * Stale-while-revalidate (Laravel's `Cache::flexible`): a value younger than `freshSeconds` is
135
+ * returned as is; one younger than `staleSeconds` is returned at once and refreshed in the
136
+ * background (one refresher at a time, across processes); an older or missing one is computed
137
+ * now.
138
+ *
139
+ * @example
140
+ * const stats = await cache.flexible('stats', [5, 60], () => computeStats())
141
+ */
142
+ flexible<TValue>(key: string, [freshSeconds, staleSeconds]: readonly [number, number], compute: () => TValue | Promise<TValue>): Promise<TValue>;
143
+ }
144
+ /**
145
+ * The resolved connection settings. `password` and `url` came from the environment and must never
146
+ * be logged; use {@link describeSettings} for logs.
147
+ *
148
+ * @example
149
+ * const settings = resolveRedisSettings({ env: { REDIS_HOST: 'cache.internal' } })
150
+ */
151
+ interface RedisSettings {
152
+ readonly host: string;
153
+ readonly port: number;
154
+ readonly username: string | undefined;
155
+ readonly password: string | undefined;
156
+ readonly database: number;
157
+ readonly tls: boolean;
158
+ readonly tlsCaFile: string | undefined;
159
+ readonly tlsServername: string | undefined;
160
+ readonly prefix: string;
161
+ readonly connectTimeoutMs: number;
162
+ readonly commandTimeoutMs: number;
163
+ }
164
+ /**
165
+ * The non-secret settings an app may keep in `config/redis.ts`.
166
+ *
167
+ * @example
168
+ * export default defineConfig((env) => ({ host: env.string('REDIS_HOST', '127.0.0.1') }) satisfies RedisConfig)
169
+ */
170
+ interface RedisConfig {
171
+ readonly host?: string;
172
+ readonly port?: number | string;
173
+ readonly username?: string;
174
+ readonly database?: number | string;
175
+ readonly tls?: boolean | string;
176
+ readonly tls_ca?: string;
177
+ readonly tls_servername?: string;
178
+ readonly prefix?: string;
179
+ readonly connect_timeout?: number | string;
180
+ readonly command_timeout?: number | string;
181
+ }
182
+ /**
183
+ * What {@link resolveRedisSettings} reads.
184
+ *
185
+ * @example
186
+ * resolveRedisSettings({ config: app.config('redis'), env, appName: 'Blog' })
187
+ */
188
+ interface ResolveOptions {
189
+ /** The `redis` config tree (unchecked: it is validated here). */
190
+ readonly config?: unknown;
191
+ /** The environment (`.env` merged under the process environment). */
192
+ readonly env: Readonly<Record<string, string | undefined>>;
193
+ /** The app's name, for the default prefix. */
194
+ readonly appName?: string;
195
+ }
196
+ /**
197
+ * Resolve and check the settings. Config keys win over variables (the config file usually reads
198
+ * the same variables); `REDIS_URL` wins over the separate host, port, user, password and database.
199
+ *
200
+ * @example
201
+ * resolveRedisSettings({ env: { REDIS_URL: 'rediss://app:secret@cache.example.com:6380/2' } })
202
+ * // { host: 'cache.example.com', port: 6380, username: 'app', database: 2, tls: true, … }
203
+ */
204
+ export declare function resolveRedisSettings(options: ResolveOptions): RedisSettings;
205
+ /**
206
+ * A log-safe description of the settings: no password, no URL.
207
+ *
208
+ * @example
209
+ * logger.info('redis.connecting', describeSettings(settings))
210
+ */
211
+ export declare function describeSettings(settings: RedisSettings): Readonly<Record<string, unknown>>;
212
+ /**
213
+ * The default key prefix: the app name as a lowercase slug, then `:` (`My Blog` → `my_blog:`).
214
+ *
215
+ * @example
216
+ * defaultPrefix('My Blog') // 'my_blog:'
217
+ */
218
+ export declare function defaultPrefix(appName: string | undefined): string;
219
+ /**
220
+ * The parts of a node-redis client this module uses (a seam for tests).
221
+ *
222
+ * @example
223
+ * const client: RedisClientLike = createClient({ url })
224
+ */
225
+ interface RedisClientLike {
226
+ connect(): Promise<unknown>;
227
+ sendCommand(args: readonly string[], options?: {
228
+ readonly timeout?: number;
229
+ }): Promise<unknown>;
230
+ close(): Promise<void>;
231
+ destroy(): void;
232
+ readonly isOpen: boolean;
233
+ readonly isReady: boolean;
234
+ on(event: "error", listener: (error: unknown) => void): unknown;
235
+ }
236
+ /** The options node-redis gets (a subset of its `RedisClientOptions`). */
237
+ interface RedisClientOptionsLike {
238
+ readonly socket: Readonly<Record<string, unknown>>;
239
+ readonly username?: string;
240
+ readonly password?: string;
241
+ readonly database: number;
242
+ readonly disableOfflineQueue: boolean;
243
+ }
244
+ /**
245
+ * Options for {@link RedisConnection}.
246
+ *
247
+ * @example
248
+ * new RedisConnection(settings, { logger: app.make(LoggerToken).child({ component: 'redis' }) })
249
+ */
250
+ interface RedisConnectionOptions {
251
+ /** Where connection events go (never `console`). Omitted: silent. */
252
+ readonly logger?: Logger;
253
+ /** How long {@link RedisConnection.close} waits for pending replies. Default 2000 ms. */
254
+ readonly closeTimeoutMs?: number;
255
+ /** After a failed connect, fail fast for this long before trying again. Default 1000 ms. */
256
+ readonly retryAfterMs?: number;
257
+ /** Build the client (tests). Default: node-redis `createClient`. */
258
+ readonly createClient?: (options: RedisClientOptionsLike) => RedisClientLike;
259
+ }
260
+ /**
261
+ * One lazily opened connection, shared by every store of an app.
262
+ *
263
+ * @example
264
+ * const redis = new RedisConnection(resolveRedisSettings({ env: process.env }))
265
+ * await redis.command(['SET', 'k', 'v'])
266
+ * await redis.close()
267
+ */
268
+ export declare class RedisConnection implements RedisDriver {
269
+ #private;
270
+ readonly settings: RedisSettings;
271
+ constructor(settings: RedisSettings, options?: RedisConnectionOptions);
272
+ /** Whether {@link RedisConnection.close} has been called. */
273
+ get closed(): boolean;
274
+ command(args: readonly string[]): Promise<unknown>;
275
+ script(script: LuaScript, keys: readonly string[], args: readonly string[]): Promise<unknown>;
276
+ ping(): Promise<number>;
277
+ /**
278
+ * A health check for readiness probes: never throws.
279
+ *
280
+ * @example
281
+ * const health = await redis.health() // { status: 'up', latency_ms: 0.4 }
282
+ */
283
+ health(): Promise<{
284
+ readonly status: "up";
285
+ readonly latency_ms: number;
286
+ } | {
287
+ readonly status: "down";
288
+ readonly error: string;
289
+ }>;
290
+ close(): Promise<void>;
291
+ }
292
+ /**
293
+ * Read `<basePath>/.env` (when present) under `process.env`.
294
+ *
295
+ * @example
296
+ * const env = loadRedisEnv('/srv/blog')
297
+ * env['REDIS_HOST'] // from the process environment, else from .env
298
+ */
299
+ export declare function loadRedisEnv(basePath: string, processEnv?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string | undefined>>;
300
+ /**
301
+ * The error definitions the provider registers.
302
+ *
303
+ * @example
304
+ * for (const definition of REDIS_ERRORS) registry.register(definition)
305
+ */
306
+ export declare const REDIS_ERRORS: readonly ErrorDefinition[];
307
+ /**
308
+ * The English message catalog for the codes above (RFC-0003 keys).
309
+ *
310
+ * @example
311
+ * REDIS_MESSAGES_EN['errors.lock_timeout.detail']
312
+ */
313
+ export declare const REDIS_MESSAGES_EN: Readonly<Record<string, string>>;
314
+ /**
315
+ * A 503 `redis_unavailable` error. The cause stays on the error for the log, never for the client.
316
+ *
317
+ * @example
318
+ * throw redisUnavailable('connect', cause)
319
+ */
320
+ export declare function redisUnavailable(operation: string, cause?: unknown): StrutvaneError;
321
+ /**
322
+ * A 503 `lock_timeout` error for the lock `name` (the name is the app's own key, never a secret).
323
+ *
324
+ * @example
325
+ * throw lockTimeout('reports:build', 10)
326
+ */
327
+ export declare function lockTimeout(name: string, waitedSeconds: number): StrutvaneError;
328
+ /**
329
+ * The idempotency store in Redis.
330
+ *
331
+ * @example
332
+ * app.container.value(IdempotencyStoreToken, new RedisIdempotencyStore({ driver: redis, space }))
333
+ */
334
+ export declare class RedisIdempotencyStore implements IdempotencyStore {
335
+ #private;
336
+ constructor(options: {
337
+ readonly driver: RedisDriver;
338
+ readonly space: KeySpace;
339
+ /** How long a claim and its response live. Default 24 h (the framework's). */
340
+ readonly ttlMs?: number;
341
+ });
342
+ begin(key: string, fingerprint: string, _now: number): Promise<BeginOutcome>;
343
+ complete(key: string, response: StoredResponse, _now: number): Promise<void>;
344
+ release(key: string): Promise<void>;
345
+ }
346
+ /**
347
+ * Creates and restores locks in one key space.
348
+ *
349
+ * @example
350
+ * const locks = new RedisLocks({ driver: redis, space: KeySpace.root('blog:').area('lock') })
351
+ * await locks.create('reports:build', 120).block(10, () => buildReports())
352
+ */
353
+ export declare class RedisLocks {
354
+ #private;
355
+ constructor(options: {
356
+ readonly driver: RedisDriver;
357
+ readonly space: KeySpace;
358
+ });
359
+ /**
360
+ * The same locks, scoped to one tenant (tenant A's `import` lock never blocks tenant B's).
361
+ *
362
+ * @example
363
+ * locks.forTenant('acme').create('import', 60)
364
+ */
365
+ forTenant(tenantId: string): RedisLocks;
366
+ /**
367
+ * A lock handle (not acquired yet) that expires `seconds` after it is acquired.
368
+ *
369
+ * @example
370
+ * const lock = locks.create('invoices:send', 30)
371
+ * if (await lock.acquire()) try { … } finally { await lock.release() }
372
+ */
373
+ create(name: string, seconds: number, owner?: string): RedisLock;
374
+ /**
375
+ * A handle for a lock acquired elsewhere (another process) with a known owner token, so it can
376
+ * be released or extended here.
377
+ *
378
+ * @example
379
+ * await locks.restore('invoices:send', job.lockOwner).release()
380
+ */
381
+ restore(name: string, owner: string): RedisLock;
382
+ }
383
+ /**
384
+ * One named lock and this handle's owner token.
385
+ *
386
+ * @example
387
+ * const lock = locks.create('export', 60)
388
+ * await lock.block(5, () => runExport())
389
+ */
390
+ export declare class RedisLock {
391
+ #private;
392
+ /** The lock's name (the caller's, without prefix). */
393
+ readonly name: string;
394
+ /** This handle's owner token: pass it to another process to release the lock there. */
395
+ readonly owner: string;
396
+ /** @internal Use {@link RedisLocks.create}. */
397
+ constructor(driver: RedisDriver, name: string, key: string, ttlMs: number, owner: string);
398
+ /**
399
+ * Try once; `true` when this handle now holds the lock. Re-acquiring a lock this owner already
400
+ * holds is `false` (locks are not re-entrant).
401
+ *
402
+ * @example
403
+ * if (await lock.acquire()) { … }
404
+ */
405
+ acquire(): Promise<boolean>;
406
+ /**
407
+ * Wait up to `seconds` for the lock (polling with jittered backoff), then, when `work` is given,
408
+ * run it and always release afterwards. Throws the 503 `lock_timeout` problem when the wait
409
+ * runs out.
410
+ *
411
+ * @example
412
+ * const total = await lock.block(5, () => recalculate())
413
+ */
414
+ block<TResult>(seconds: number, work?: () => TResult | Promise<TResult>): Promise<TResult | undefined>;
415
+ /**
416
+ * Run `work` only if the lock is free right now (no waiting); `undefined` when it was taken.
417
+ *
418
+ * @example
419
+ * await lock.run(() => sendDigest()) // skipped if another worker is sending it
420
+ */
421
+ run<TResult>(work: () => TResult | Promise<TResult>): Promise<TResult | undefined>;
422
+ /**
423
+ * Release the lock if this owner still holds it; `false` when it had expired or belongs to
424
+ * someone else (nothing is removed then).
425
+ *
426
+ * @example
427
+ * await lock.release()
428
+ */
429
+ release(): Promise<boolean>;
430
+ /**
431
+ * Reset the lifetime to `seconds` from now if this owner still holds the lock.
432
+ *
433
+ * @example
434
+ * await lock.extend(60) // a long import keeps its lock
435
+ */
436
+ extend(seconds: number): Promise<boolean>;
437
+ /**
438
+ * Remove the lock whoever holds it (an operator's escape hatch).
439
+ *
440
+ * @example
441
+ * await locks.create('stuck-job', 1).forceRelease()
442
+ */
443
+ forceRelease(): Promise<void>;
444
+ /**
445
+ * Whether this owner holds the lock right now.
446
+ *
447
+ * @example
448
+ * if (!(await lock.isOwned())) throw new Error('lost the lock')
449
+ */
450
+ isOwned(): Promise<boolean>;
451
+ }
452
+ /**
453
+ * A limit: at most `max` hits per `windowSeconds`.
454
+ *
455
+ * @example
456
+ * const limit: RateLimit = { max: 60, windowSeconds: 60, algorithm: 'sliding' }
457
+ */
458
+ interface RateLimit {
459
+ readonly max: number;
460
+ readonly windowSeconds: number;
461
+ /** Default `fixed`. */
462
+ readonly algorithm?: "fixed" | "sliding";
463
+ }
464
+ /**
465
+ * The outcome of one hit.
466
+ *
467
+ * @example
468
+ * if (!result.allowed) throw new RateLimitedError({ retryAfter: result.retryAfterSeconds })
469
+ */
470
+ interface RateLimitResult {
471
+ readonly allowed: boolean;
472
+ readonly limit: number;
473
+ /** Hits left in the current window (0 when refused). */
474
+ readonly remaining: number;
475
+ /** Seconds until a hit can succeed again (0 when allowed). */
476
+ readonly retryAfterSeconds: number;
477
+ }
478
+ /**
479
+ * A rate limiter in one key space.
480
+ *
481
+ * @example
482
+ * const limiter = new RedisRateLimiter({ driver: redis, space: KeySpace.root('blog:').area('rate') })
483
+ * const result = await limiter.hit(`login:${email}`, { max: 5, windowSeconds: 60, algorithm: 'sliding' })
484
+ */
485
+ export declare class RedisRateLimiter {
486
+ #private;
487
+ constructor(options: {
488
+ readonly driver: RedisDriver;
489
+ readonly space: KeySpace;
490
+ });
491
+ /**
492
+ * The same limiter, scoped to one tenant.
493
+ *
494
+ * @example
495
+ * limiter.forTenant('acme').hit('exports', { max: 10, windowSeconds: 3600 })
496
+ */
497
+ forTenant(tenantId: string): RedisRateLimiter;
498
+ /**
499
+ * Count one hit and say whether it is within the limit.
500
+ *
501
+ * @example
502
+ * const { allowed, retryAfterSeconds } = await limiter.hit('api:42', { max: 60, windowSeconds: 60 })
503
+ */
504
+ hit(key: string, limit: RateLimit): Promise<RateLimitResult>;
505
+ /**
506
+ * Run `work` only when the hit is allowed; returns the result, or `undefined` when limited.
507
+ *
508
+ * @example
509
+ * await limiter.attempt(`digest:${user.id}`, { max: 1, windowSeconds: 3600 }, () => sendDigest(user))
510
+ */
511
+ attempt<TResult>(key: string, limit: RateLimit, work: () => TResult | Promise<TResult>): Promise<TResult | undefined>;
512
+ /**
513
+ * Reset a key's counters (both algorithms), for example after a successful login.
514
+ *
515
+ * @example
516
+ * await limiter.clear(`login:${email}`)
517
+ */
518
+ clear(key: string): Promise<void>;
519
+ }
520
+ /**
521
+ * Options for {@link RedisSessionStore}.
522
+ *
523
+ * @example
524
+ * new RedisSessionStore({ driver: redis, space: KeySpace.root('blog:').area('session'), lifetimeSeconds: 7200 })
525
+ */
526
+ interface RedisSessionStoreOptions {
527
+ readonly driver: RedisDriver;
528
+ readonly space: KeySpace;
529
+ /** Idle lifetime (`SESSION_LIFETIME` minutes × 60). Default 7200 s. */
530
+ readonly lifetimeSeconds?: number;
531
+ /** The largest session accepted, in bytes of JSON. Default 256 KiB. */
532
+ readonly maxBytes?: number;
533
+ }
534
+ /**
535
+ * A session store in Redis.
536
+ *
537
+ * @example
538
+ * await sessions.write(id, { userId: 7 })
539
+ * const data = await sessions.read(id) // { userId: 7 }
540
+ */
541
+ export declare class RedisSessionStore implements SessionStore {
542
+ #private;
543
+ constructor(options: RedisSessionStoreOptions);
544
+ /**
545
+ * The session's data, or `undefined` when it doesn't exist, expired, or the id is malformed.
546
+ *
547
+ * @example
548
+ * const data = await sessions.read(cookieValue)
549
+ */
550
+ read(id: string): Promise<Record<string, unknown> | undefined>;
551
+ /**
552
+ * Store the session's data and reset its idle expiry. Throws a `TypeError` for a malformed id and
553
+ * a `RangeError` for data over the size limit.
554
+ *
555
+ * @example
556
+ * await sessions.write(id, { userId: 7, csrf: token })
557
+ */
558
+ write(id: string, data: Readonly<Record<string, unknown>>): Promise<void>;
559
+ /**
560
+ * Reset the idle expiry without rewriting the data; `false` when the session is gone.
561
+ *
562
+ * @example
563
+ * await sessions.touch(id)
564
+ */
565
+ touch(id: string): Promise<boolean>;
566
+ /**
567
+ * Remove one session (sign-out, id rotation); `true` when it existed.
568
+ *
569
+ * @example
570
+ * await sessions.destroy(oldId)
571
+ */
572
+ destroy(id: string): Promise<boolean>;
573
+ /** Remove every session of this app; returns how many were removed. */
574
+ flush(): Promise<number>;
575
+ }
576
+ /**
577
+ * The framework's `UsedSignatureStore` shape.
578
+ *
579
+ * @example
580
+ * const store: UsedSignatureStoreLike = new RedisUsedSignatureStore({ driver, space })
581
+ */
582
+ interface UsedSignatureStoreLike {
583
+ claim(signature: string, expiresAt: number): Promise<boolean>;
584
+ }
585
+ /**
586
+ * Used-signature records in Redis.
587
+ *
588
+ * @example
589
+ * const first = await store.claim(signature, expiresAtMs) // true, then false for a replay
590
+ */
591
+ export declare class RedisUsedSignatureStore implements UsedSignatureStoreLike {
592
+ #private;
593
+ constructor(options: {
594
+ readonly driver: RedisDriver;
595
+ readonly space: KeySpace;
596
+ });
597
+ claim(signature: string, expiresAt: number): Promise<boolean>;
598
+ }
599
+ /**
600
+ * The app's shared Redis connection (lazily connected; closed on shutdown).
601
+ *
602
+ * @example
603
+ * const health = await app.make(RedisConnectionToken).health()
604
+ */
605
+ export declare const RedisConnectionToken: Token<RedisConnection>;
606
+ /**
607
+ * The app's root key space (`REDIS_PREFIX`).
608
+ *
609
+ * @example
610
+ * app.make(RedisKeySpaceToken).area('reports').key('daily')
611
+ */
612
+ export declare const RedisKeySpaceToken: Token<KeySpace>;
613
+ /**
614
+ * Atomic locks (`<prefix>lock:…`).
615
+ *
616
+ * @example
617
+ * await app.make(RedisLocksToken).create('reports:build', 120).block(10, build)
618
+ */
619
+ export declare const RedisLocksToken: Token<RedisLocks>;
620
+ /**
621
+ * The rate limiter (`<prefix>rate:…`).
622
+ *
623
+ * @example
624
+ * await app.make(RedisRateLimiterToken).hit(`export:${user.id}`, { max: 5, windowSeconds: 3600 })
625
+ */
626
+ export declare const RedisRateLimiterToken: Token<RedisRateLimiter>;
627
+ export { KeySpace, type LuaScript, MAX_KEY_BYTES, type RateLimit, type RateLimitResult, type RedisCacheManagerOptions, type RedisCacheStoreConfig, type RedisCacheStoreOptions, type RedisClientLike, type RedisClientOptionsLike, type RedisConfig, type RedisConnectionOptions, type RedisDriver, type RedisSessionStoreOptions, type RedisSettings, type ResolveOptions, type UsedSignatureStoreLike, asArray, asInteger, asNullableString, defineLua, deleteMatching, globEscape, isValidTenantId, prefixProblem };
628
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/cache-manager.ts","../src/cache-store.ts","../src/config.ts","../src/connection.ts","../src/env.ts","../src/errors.ts","../src/idempotency-store.ts","../src/lock.ts","../src/rate-limiter.ts","../src/session-store.ts","../src/signature-store.ts","../src/tokens.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;UAsCiB;WACN;;WAEA;;;;;;;;UASM;WACN;WACA,OAAO;;WAEP;;WAEA,cAAc;;WAEd,MAAM;WACN,SAAS;;;;;;;;;wBAUJ,wBAAwB,SAAS,2BAA2B;;;;;;;UCjC3D;WACN,QAAQ;;WAER,OAAO;;WAEP,SAAS;;;;;;;;;;qBA2CP,2BAA2B;;EAKtC,YAAY,SAAS;;MAOjB;;;;;;;EAUJ,UAAU,mBAAmB;EAQvB,IAAI,cAAc;EAIlB,IAAI,cAAc;EAIlB,IAAI,aAAa,gBAAgB,sBAAsB;EAavD,IAAI,aAAa,gBAAgB,sBAAsB;EAWvD,UAAU,aAAa,aAAQ,sBAAsB;;;;;;;EAgBrD,UAAU,aAAa,aAAQ,sBAAsB;EAIrD,IAAI,cAAc;EAKlB,OAAO,cAAc;EAIrB,SAAS;;;;;;;EAUT,KAAK,0BAA0B,QAAQ;;;;;;;EAkBvC,QAAQ,QAAQ,SAAS,0BAA0B,sBAAsB;;;;;;;EAmBzE,QAAQ,aAAa,iBAAiB;;;;;;;EAUtC,SAAS,QACb,aACA,gCACA,eAAe,SAAS,QAAQ,UAC/B,QAAQ;;;;;;;;;;EAiBL,SAAS,QACb,cACC,cAAc,0C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0,0 +1,47 @@
1
+ import { C as isValidTenantId, E as RedisCacheStore, S as globEscape, T as createRedisCacheManager, _ as defaultPrefix, a as RedisSessionStore, b as KeySpace, c as RedisLocks, d as RedisConnection, g as redisUnavailable, h as lockTimeout, i as RedisRateLimiterToken, l as RedisIdempotencyStore, m as REDIS_MESSAGES_EN, n as RedisKeySpaceToken, o as RedisRateLimiter, p as REDIS_ERRORS, r as RedisLocksToken, s as RedisLock, t as RedisConnectionToken, u as loadRedisEnv, v as describeSettings, w as prefixProblem, x as MAX_KEY_BYTES, y as resolveRedisSettings } from "./tokens-CnThleYU.mjs";
2
+ import { a as deleteMatching, i as defineLua, n as asInteger, r as asNullableString, t as asArray } from "./driver-DEW-Sggt.mjs";
3
+ import { createHash } from "node:crypto";
4
+ // src/signature-store.ts
5
+ /**
6
+ * One-time signed URLs across processes: a Redis implementation of the framework's
7
+ * `UsedSignatureStore` (`claim` = "record this signature as used; `true` only the first time").
8
+ *
9
+ * `SET <sha256(signature)> 1 NX PXAT <expiresAt>`: only one claim can win, and the record expires
10
+ * with the URL itself, so the set never grows past the live signatures.
11
+ *
12
+ * The framework does not export `UsedSignatureStoreToken` from its public entry yet, so an app
13
+ * can't bind this store through the container today (see NEXT.md, framework proposals). It is
14
+ * shipped and tested so the binding is one line once the token is public.
15
+ *
16
+ * @module
17
+ */
18
+ /**
19
+ * Used-signature records in Redis.
20
+ *
21
+ * @example
22
+ * const first = await store.claim(signature, expiresAtMs) // true, then false for a replay
23
+ */
24
+ var RedisUsedSignatureStore = class {
25
+ #driver;
26
+ #space;
27
+ constructor(options) {
28
+ this.#driver = options.driver;
29
+ this.#space = options.space;
30
+ }
31
+ async claim(signature, expiresAt) {
32
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now()) return false;
33
+ const key = this.#space.key(createHash("sha256").update(signature).digest("hex"));
34
+ const reply = await this.#driver.command([
35
+ "SET",
36
+ key,
37
+ "1",
38
+ "NX",
39
+ "PXAT",
40
+ String(expiresAt)
41
+ ]);
42
+ return reply !== null && reply !== void 0;
43
+ }
44
+ };
45
+ export { KeySpace, MAX_KEY_BYTES, REDIS_ERRORS, REDIS_MESSAGES_EN, RedisCacheStore, RedisConnection, RedisConnectionToken, RedisIdempotencyStore, RedisKeySpaceToken, RedisLock, RedisLocks, RedisLocksToken, RedisRateLimiter, RedisRateLimiterToken, RedisSessionStore, RedisUsedSignatureStore, asArray, asInteger, asNullableString, createRedisCacheManager, defaultPrefix, defineLua, deleteMatching, describeSettings, globEscape, isValidTenantId, loadRedisEnv, lockTimeout, prefixProblem, redisUnavailable, resolveRedisSettings };
46
+
47
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/signature-store.ts"],"sourcesContent":["/**\n * One-time signed URLs across processes: a Redis implementation of the framework's\n * `UsedSignatureStore` (`claim` = \"record this signature as used; `true` only the first time\").\n *\n * `SET <sha256(signature)> 1 NX PXAT <expiresAt>`: only one claim can win, and the record expires\n * with the URL itself, so the set never grows past the live signatures.\n *\n * The framework does not export `UsedSignatureStoreToken` from its public entry yet, so an app\n * can't bind this store through the container today (see NEXT.md, framework proposals). It is\n * shipped and tested so the binding is one line once the token is public.\n *\n * @module\n */\nimport { createHash } from 'node:crypto'\nimport type { RedisDriver } from './driver.ts'\nimport type { KeySpace } from './keys.ts'\n\n/**\n * The framework's `UsedSignatureStore` shape.\n *\n * @example\n * const store: UsedSignatureStoreLike = new RedisUsedSignatureStore({ driver, space })\n */\nexport interface UsedSignatureStoreLike {\n claim(signature: string, expiresAt: number): Promise<boolean>\n}\n\n/**\n * Used-signature records in Redis.\n *\n * @example\n * const first = await store.claim(signature, expiresAtMs) // true, then false for a replay\n */\nexport class RedisUsedSignatureStore implements UsedSignatureStoreLike {\n readonly #driver: RedisDriver\n readonly #space: KeySpace\n\n constructor(options: { readonly driver: RedisDriver; readonly space: KeySpace }) {\n this.#driver = options.driver\n this.#space = options.space\n }\n\n async claim(signature: string, expiresAt: number): Promise<boolean> {\n // An expired (or nonsensical) expiry is refused: fail closed, never \"first use\".\n if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now()) return false\n const key = this.#space.key(createHash('sha256').update(signature).digest('hex'))\n const reply = await this.#driver.command(['SET', key, '1', 'NX', 'PXAT', String(expiresAt)])\n return reply !== null && reply !== undefined\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,0BAAb,MAAuE;CAC5D;CACA;CAET,YAAY,SAAqE;EAC/E,KAAK,UAAU,QAAQ;EACvB,KAAK,SAAS,QAAQ;CACxB;CAEA,MAAM,MAAM,WAAmB,WAAqC;EAElE,IAAI,CAAC,OAAO,cAAc,SAAS,KAAK,aAAa,KAAK,IAAI,GAAG,OAAO;EACxE,MAAM,MAAM,KAAK,OAAO,IAAI,WAAW,QAAQ,CAAC,CAAC,OAAO,SAAS,CAAC,CAAC,OAAO,KAAK,CAAC;EAChF,MAAM,QAAQ,MAAM,KAAK,QAAQ,QAAQ;GAAC;GAAO;GAAK;GAAK;GAAM;GAAQ,OAAO,SAAS;EAAC,CAAC;EAC3F,OAAO,UAAU,QAAQ,UAAU,KAAA;CACrC;AACF"}