@guren/server 2.10.0 → 2.11.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.
Files changed (91) hide show
  1. package/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
  2. package/dist/Hash-CzrwKeDp.js +133 -0
  3. package/dist/HttpException-BkS3euNG.js +161 -0
  4. package/dist/Job-BVT813DO.js +441 -0
  5. package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
  6. package/dist/MessageSigner-Bd25ZJAV.js +93 -0
  7. package/dist/Random-DbIJ22KQ.js +191 -0
  8. package/dist/address-D0Iq-XIH.js +20 -0
  9. package/dist/auth/index.js +2 -122
  10. package/dist/auth-C7sVmYgc.js +1954 -0
  11. package/dist/authorization/index.js +2 -38
  12. package/dist/authorization-Dbcuc5ZK.js +610 -0
  13. package/dist/broadcasting/index.js +2 -26
  14. package/dist/broadcasting-Dw-FhyjN.js +1055 -0
  15. package/dist/cache/index.js +2 -17
  16. package/dist/cache/types.d.ts +4 -4
  17. package/dist/cache-BYnZf2FR.js +812 -0
  18. package/dist/client-Dd7vLcqp.js +27 -0
  19. package/dist/console/Output.d.ts +18 -18
  20. package/dist/encryption/index.js +5 -96
  21. package/dist/encryption-fOWQaKqX.js +250 -0
  22. package/dist/endpoint-D-20PiHY.js +46 -0
  23. package/dist/endpoint-D6GIqOpe.js +31 -0
  24. package/dist/errors-quJOkkCn.js +81 -0
  25. package/dist/events/index.js +2 -28
  26. package/dist/events-aIH_bWRx.js +410 -0
  27. package/dist/health/index.js +2 -24
  28. package/dist/health-VWdWXRwh.js +345 -0
  29. package/dist/hot-disposables-WsTX2ySN.js +281 -0
  30. package/dist/hot-reload/testing.d.ts +1 -1
  31. package/dist/http/resources/Resource.d.ts +23 -3
  32. package/dist/i18n/index.js +2 -30
  33. package/dist/i18n-mcWi7LCd.js +617 -0
  34. package/dist/index.js +7515 -7276
  35. package/dist/lambda/index.js +114 -71
  36. package/dist/logging/index.js +2 -24
  37. package/dist/logging-CPaRMuPP.js +518 -0
  38. package/dist/loopback-guard-D0Kc7-xc.js +224 -0
  39. package/dist/mail/index.js +2 -27
  40. package/dist/mail-DfEfSQEr.js +699 -0
  41. package/dist/mcp/index.js +2 -10
  42. package/dist/notifications/index.js +2 -33
  43. package/dist/notifications-BGqmUNZ8.js +759 -0
  44. package/dist/queue/index.js +3 -42
  45. package/dist/queue-CXrRK85G.js +948 -0
  46. package/dist/redis/index.js +672 -642
  47. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  48. package/dist/runtime/index.js +472 -616
  49. package/dist/scheduling/index.js +2 -29
  50. package/dist/scheduling-CPiEdtQd.js +839 -0
  51. package/dist/storage/index.js +2 -15
  52. package/dist/storage-tWHMv2H_.js +841 -0
  53. package/dist/support/expiry.js +69 -12
  54. package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
  55. package/dist/vite/index.js +118 -181
  56. package/dist/vite/plugin.d.ts +1 -1
  57. package/dist/vite-dev-server-BSJkduhZ.js +131 -0
  58. package/package.json +6 -5
  59. package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
  60. package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
  61. package/dist/chunk-2SC566CD.js +0 -376
  62. package/dist/chunk-2V3YID4H.js +0 -20
  63. package/dist/chunk-3KV5X2FL.js +0 -31
  64. package/dist/chunk-63SKW5PS.js +0 -457
  65. package/dist/chunk-6J6B5KOB.js +0 -425
  66. package/dist/chunk-A5JJ7XTH.js +0 -24
  67. package/dist/chunk-AZOYI43J.js +0 -18
  68. package/dist/chunk-B5E5VBDI.js +0 -115
  69. package/dist/chunk-DAQKYKLH.js +0 -182
  70. package/dist/chunk-DRNPVBAA.js +0 -1002
  71. package/dist/chunk-EI5GYMAT.js +0 -853
  72. package/dist/chunk-H3B23O6T.js +0 -271
  73. package/dist/chunk-HPET6XY5.js +0 -853
  74. package/dist/chunk-HR2KZ3WL.js +0 -616
  75. package/dist/chunk-IOTWFHZU.js +0 -558
  76. package/dist/chunk-K6CUBJX6.js +0 -642
  77. package/dist/chunk-KTNJG7R7.js +0 -911
  78. package/dist/chunk-LAJQCSSF.js +0 -355
  79. package/dist/chunk-LHR6OHI7.js +0 -189
  80. package/dist/chunk-N7PLD7MB.js +0 -729
  81. package/dist/chunk-Q2P6YLRR.js +0 -24
  82. package/dist/chunk-QQKTH5KX.js +0 -114
  83. package/dist/chunk-SFQP6O52.js +0 -126
  84. package/dist/chunk-SQR7277M.js +0 -911
  85. package/dist/chunk-T2FFUU6J.js +0 -484
  86. package/dist/chunk-TVV5YNEC.js +0 -1842
  87. package/dist/chunk-UY3AZSYL.js +0 -14
  88. package/dist/chunk-V4DNC2ER.js +0 -114
  89. package/dist/chunk-VSA3QY5Q.js +0 -274
  90. package/dist/chunk-YSOJKAAU.js +0 -427
  91. package/dist/errors-PUNHAFL2.js +0 -34
@@ -1,100 +1,110 @@
1
- import {
2
- Redis,
3
- createRedisClient
4
- } from "../chunk-UY3AZSYL.js";
5
- import {
6
- toDate,
7
- toOptionalExpiry
8
- } from "../chunk-3KV5X2FL.js";
9
-
10
- // src/redis/scan-keys.ts
1
+ import { toDate, toOptionalExpiry } from "../support/expiry.js";
2
+ import { n as createRedisClient, t as Redis } from "../client-Dd7vLcqp.js";
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
+ */
11
8
  async function scanKeys(redis, pattern) {
12
- const keys = [];
13
- let cursor = "0";
14
- do {
15
- const [newCursor, foundKeys] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
16
- cursor = newCursor;
17
- keys.push(...foundKeys);
18
- } while (cursor !== "0");
19
- return keys;
9
+ const keys = [];
10
+ let cursor = "0";
11
+ do {
12
+ const [newCursor, foundKeys] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
13
+ cursor = newCursor;
14
+ keys.push(...foundKeys);
15
+ } while (cursor !== "0");
16
+ return keys;
20
17
  }
21
-
22
- // src/redis/RedisSessionStore.ts
18
+ //#endregion
19
+ //#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
+ */
23
33
  var RedisSessionStore = class {
24
- constructor(redis, options = {}) {
25
- this.redis = redis;
26
- this.prefix = options.prefix ?? "session:";
27
- }
28
- redis;
29
- prefix;
30
- /**
31
- * Read session data from Redis.
32
- */
33
- async read(id) {
34
- const key = this.prefix + id;
35
- const data = await this.redis.get(key);
36
- if (!data) {
37
- return void 0;
38
- }
39
- try {
40
- return JSON.parse(data);
41
- } catch {
42
- return void 0;
43
- }
44
- }
45
- /**
46
- * Write session data to Redis with TTL.
47
- */
48
- async write(id, data, ttlSeconds) {
49
- const key = this.prefix + id;
50
- const serialized = JSON.stringify(data);
51
- await this.redis.setex(key, ttlSeconds, serialized);
52
- }
53
- /**
54
- * Delete a session from Redis.
55
- */
56
- async destroy(id) {
57
- const key = this.prefix + id;
58
- await this.redis.del(key);
59
- }
60
- /**
61
- * Refresh an existing session's TTL without rewriting its data.
62
- * EXPIRE on a missing key is a no-op, never a resurrection.
63
- */
64
- async touch(id, ttlSeconds) {
65
- const key = this.prefix + id;
66
- await this.redis.expire(key, ttlSeconds);
67
- }
68
- /**
69
- * Get all session keys (for debugging/admin purposes).
70
- * Note: This uses SCAN to avoid blocking Redis.
71
- */
72
- async keys() {
73
- const keys = await scanKeys(this.redis, this.prefix + "*");
74
- return keys.map((key) => key.slice(this.prefix.length));
75
- }
76
- /**
77
- * Get the count of sessions (for monitoring).
78
- */
79
- async size() {
80
- const keys = await this.keys();
81
- return keys.length;
82
- }
83
- /**
84
- * Clear all sessions.
85
- * Use with caution in production!
86
- */
87
- async clear() {
88
- const keys = await this.keys();
89
- if (keys.length > 0) {
90
- const prefixedKeys = keys.map((key) => this.prefix + key);
91
- await this.redis.del(...prefixedKeys);
92
- }
93
- }
34
+ redis;
35
+ prefix;
36
+ constructor(redis, options = {}) {
37
+ this.redis = redis;
38
+ this.prefix = options.prefix ?? "session:";
39
+ }
40
+ /**
41
+ * Read session data from Redis.
42
+ */
43
+ async read(id) {
44
+ const key = this.prefix + id;
45
+ const data = await this.redis.get(key);
46
+ if (!data) return;
47
+ try {
48
+ return JSON.parse(data);
49
+ } catch {
50
+ return;
51
+ }
52
+ }
53
+ /**
54
+ * Write session data to Redis with TTL.
55
+ */
56
+ async write(id, data, ttlSeconds) {
57
+ const key = this.prefix + id;
58
+ const serialized = JSON.stringify(data);
59
+ await this.redis.setex(key, ttlSeconds, serialized);
60
+ }
61
+ /**
62
+ * Delete a session from Redis.
63
+ */
64
+ async destroy(id) {
65
+ const key = this.prefix + id;
66
+ await this.redis.del(key);
67
+ }
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
+ */
72
+ async touch(id, ttlSeconds) {
73
+ const key = this.prefix + id;
74
+ await this.redis.expire(key, ttlSeconds);
75
+ }
76
+ /**
77
+ * Get all session keys (for debugging/admin purposes).
78
+ * Note: This uses SCAN to avoid blocking Redis.
79
+ */
80
+ async keys() {
81
+ return (await scanKeys(this.redis, this.prefix + "*")).map((key) => key.slice(this.prefix.length));
82
+ }
83
+ /**
84
+ * Get the count of sessions (for monitoring).
85
+ */
86
+ async size() {
87
+ return (await this.keys()).length;
88
+ }
89
+ /**
90
+ * Clear all sessions.
91
+ * Use with caution in production!
92
+ */
93
+ async clear() {
94
+ const keys = await this.keys();
95
+ if (keys.length > 0) {
96
+ const prefixedKeys = keys.map((key) => this.prefix + key);
97
+ await this.redis.del(...prefixedKeys);
98
+ }
99
+ }
94
100
  };
95
-
96
- // src/redis/RedisRateLimitStore.ts
97
- var INCREMENT_SCRIPT = `
101
+ //#endregion
102
+ //#region src/redis/RedisRateLimitStore.ts
103
+ /**
104
+ * Lua script for atomic increment with expiration.
105
+ * Returns [count, resetAt] where resetAt is the timestamp when the window resets.
106
+ */
107
+ const INCREMENT_SCRIPT = `
98
108
  local key = KEYS[1]
99
109
  local window = tonumber(ARGV[1])
100
110
  local now = tonumber(ARGV[2])
@@ -107,477 +117,525 @@ local ttl = redis.call('PTTL', key)
107
117
  local resetAt = now + ttl
108
118
  return {count, resetAt}
109
119
  `;
120
+ /**
121
+ * Redis-backed rate limit store using fixed window algorithm.
122
+ * Uses Lua script for atomic increment operations.
123
+ *
124
+ * @example
125
+ * ```ts
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
+ * ```
133
+ */
110
134
  var RedisRateLimitStore = class {
111
- constructor(redis, options = {}) {
112
- this.redis = redis;
113
- this.prefix = options.prefix ?? "ratelimit:";
114
- }
115
- redis;
116
- prefix;
117
- /**
118
- * Get current rate limit entry for a key.
119
- */
120
- async get(key) {
121
- const redisKey = this.prefix + key;
122
- const [countStr, ttl] = await Promise.all([
123
- this.redis.get(redisKey),
124
- this.redis.pttl(redisKey)
125
- ]);
126
- if (!countStr || ttl <= 0) {
127
- return null;
128
- }
129
- return {
130
- count: parseInt(countStr, 10),
131
- resetAt: Date.now() + ttl
132
- };
133
- }
134
- /**
135
- * Increment the rate limit counter atomically.
136
- */
137
- async increment(key, windowMs) {
138
- const redisKey = this.prefix + key;
139
- const now = Date.now();
140
- const result = await this.redis.eval(
141
- INCREMENT_SCRIPT,
142
- 1,
143
- redisKey,
144
- windowMs.toString(),
145
- now.toString()
146
- );
147
- return {
148
- count: result[0],
149
- resetAt: result[1]
150
- };
151
- }
152
- /**
153
- * Reset the rate limit for a key.
154
- */
155
- async reset(key) {
156
- const redisKey = this.prefix + key;
157
- await this.redis.del(redisKey);
158
- }
159
- /**
160
- * Get all rate limit keys (for debugging/admin purposes).
161
- */
162
- async keys() {
163
- const keys = await scanKeys(this.redis, this.prefix + "*");
164
- return keys.map((key) => key.slice(this.prefix.length));
165
- }
166
- /**
167
- * Clear all rate limits.
168
- */
169
- async clear() {
170
- const keys = await this.keys();
171
- if (keys.length > 0) {
172
- const prefixedKeys = keys.map((key) => this.prefix + key);
173
- await this.redis.del(...prefixedKeys);
174
- }
175
- }
135
+ redis;
136
+ prefix;
137
+ constructor(redis, options = {}) {
138
+ this.redis = redis;
139
+ this.prefix = options.prefix ?? "ratelimit:";
140
+ }
141
+ /**
142
+ * Get current rate limit entry for a key.
143
+ */
144
+ async get(key) {
145
+ const redisKey = this.prefix + key;
146
+ const [countStr, ttl] = await Promise.all([this.redis.get(redisKey), this.redis.pttl(redisKey)]);
147
+ if (!countStr || ttl <= 0) return null;
148
+ return {
149
+ count: parseInt(countStr, 10),
150
+ resetAt: Date.now() + ttl
151
+ };
152
+ }
153
+ /**
154
+ * Increment the rate limit counter atomically.
155
+ */
156
+ async increment(key, windowMs) {
157
+ const redisKey = this.prefix + key;
158
+ const now = Date.now();
159
+ const result = await this.redis.eval(INCREMENT_SCRIPT, 1, redisKey, windowMs.toString(), now.toString());
160
+ return {
161
+ count: result[0],
162
+ resetAt: result[1]
163
+ };
164
+ }
165
+ /**
166
+ * Reset the rate limit for a key.
167
+ */
168
+ async reset(key) {
169
+ const redisKey = this.prefix + key;
170
+ await this.redis.del(redisKey);
171
+ }
172
+ /**
173
+ * Get all rate limit keys (for debugging/admin purposes).
174
+ */
175
+ async keys() {
176
+ return (await scanKeys(this.redis, this.prefix + "*")).map((key) => key.slice(this.prefix.length));
177
+ }
178
+ /**
179
+ * Clear all rate limits.
180
+ */
181
+ async clear() {
182
+ const keys = await this.keys();
183
+ if (keys.length > 0) {
184
+ const prefixedKeys = keys.map((key) => this.prefix + key);
185
+ await this.redis.del(...prefixedKeys);
186
+ }
187
+ }
176
188
  };
189
+ /**
190
+ * Redis-backed rate limit store using sliding window algorithm.
191
+ * More accurate than fixed window but slightly more expensive.
192
+ */
177
193
  var RedisSlidingWindowRateLimitStore = class {
178
- constructor(redis, options = {}) {
179
- this.redis = redis;
180
- this.prefix = options.prefix ?? "ratelimit:sw:";
181
- }
182
- redis;
183
- prefix;
184
- /**
185
- * Get current rate limit entry for a key.
186
- */
187
- async get(key) {
188
- const redisKey = this.prefix + key;
189
- const count = await this.redis.zcard(redisKey);
190
- if (count === 0) {
191
- return null;
192
- }
193
- const ttl = await this.redis.pttl(redisKey);
194
- return {
195
- count,
196
- resetAt: ttl > 0 ? Date.now() + ttl : Date.now()
197
- };
198
- }
199
- /**
200
- * Increment the rate limit counter using sorted set.
201
- * Each request is stored with its timestamp as score.
202
- */
203
- async increment(key, windowMs) {
204
- const redisKey = this.prefix + key;
205
- const now = Date.now();
206
- const windowStart = now - windowMs;
207
- const pipeline = this.redis.pipeline();
208
- pipeline.zremrangebyscore(redisKey, "-inf", windowStart);
209
- pipeline.zadd(redisKey, now, `${now}:${Math.random()}`);
210
- pipeline.zcard(redisKey);
211
- pipeline.pexpire(redisKey, windowMs);
212
- const results = await pipeline.exec();
213
- const count = results?.[2]?.[1] ?? 1;
214
- return {
215
- count,
216
- resetAt: now + windowMs
217
- };
218
- }
219
- /**
220
- * Reset the rate limit for a key.
221
- */
222
- async reset(key) {
223
- const redisKey = this.prefix + key;
224
- await this.redis.del(redisKey);
225
- }
226
- /**
227
- * Clear all rate limits.
228
- */
229
- async clear() {
230
- const keys = await scanKeys(this.redis, this.prefix + "*");
231
- if (keys.length > 0) {
232
- await this.redis.del(...keys);
233
- }
234
- }
194
+ redis;
195
+ prefix;
196
+ constructor(redis, options = {}) {
197
+ this.redis = redis;
198
+ this.prefix = options.prefix ?? "ratelimit:sw:";
199
+ }
200
+ /**
201
+ * Get current rate limit entry for a key.
202
+ */
203
+ async get(key) {
204
+ const redisKey = this.prefix + key;
205
+ const count = await this.redis.zcard(redisKey);
206
+ if (count === 0) return null;
207
+ const ttl = await this.redis.pttl(redisKey);
208
+ return {
209
+ count,
210
+ resetAt: ttl > 0 ? Date.now() + ttl : Date.now()
211
+ };
212
+ }
213
+ /**
214
+ * Increment the rate limit counter using sorted set.
215
+ * Each request is stored with its timestamp as score.
216
+ */
217
+ async increment(key, windowMs) {
218
+ const redisKey = this.prefix + key;
219
+ 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
+ return {
227
+ count: (await pipeline.exec())?.[2]?.[1] ?? 1,
228
+ resetAt: now + windowMs
229
+ };
230
+ }
231
+ /**
232
+ * Reset the rate limit for a key.
233
+ */
234
+ async reset(key) {
235
+ const redisKey = this.prefix + key;
236
+ await this.redis.del(redisKey);
237
+ }
238
+ /**
239
+ * Clear all rate limits.
240
+ */
241
+ async clear() {
242
+ const keys = await scanKeys(this.redis, this.prefix + "*");
243
+ if (keys.length > 0) await this.redis.del(...keys);
244
+ }
235
245
  };
236
-
237
- // src/redis/redis-values.ts
246
+ //#endregion
247
+ //#region src/redis/redis-values.ts
248
+ /**
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.
254
+ */
255
+ /**
256
+ * Decode a JSON-encoded ability list.
257
+ *
258
+ * Corrupt text degrades to no abilities (deny-by-default) instead of throwing
259
+ * on every verification of the affected token. A value that decodes to
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.
263
+ */
238
264
  function decodeAbilities(value) {
239
- if (value == null || value === "") return [];
240
- let parsed = value;
241
- if (typeof value === "string") {
242
- try {
243
- parsed = JSON.parse(value);
244
- } catch {
245
- return [];
246
- }
247
- }
248
- return Array.isArray(parsed) ? parsed.filter((ability) => typeof ability === "string") : [];
265
+ if (value == null || value === "") return [];
266
+ let parsed = value;
267
+ if (typeof value === "string") try {
268
+ parsed = JSON.parse(value);
269
+ } catch {
270
+ return [];
271
+ }
272
+ return Array.isArray(parsed) ? parsed.filter((ability) => typeof ability === "string") : [];
249
273
  }
250
-
251
- // src/redis/RedisApiTokenStore.ts
274
+ //#endregion
275
+ //#region src/redis/RedisApiTokenStore.ts
276
+ /**
277
+ * Redis-backed API token store.
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
+ * ```
296
+ */
252
297
  var RedisApiTokenStore = class {
253
- constructor(redis, options = {}) {
254
- this.redis = redis;
255
- this.prefix = options.prefix ?? "apitoken:";
256
- }
257
- redis;
258
- prefix;
259
- /**
260
- * Store a new API token.
261
- */
262
- async store(token) {
263
- const tokenKey = `${this.prefix}${token.id}`;
264
- const hashKey = `${this.prefix}hash:${token.hashedToken}`;
265
- const userKey = `${this.prefix}user:${token.userId}`;
266
- const serialized = this.serializeToken(token);
267
- const pipeline = this.redis.pipeline();
268
- pipeline.hset(tokenKey, serialized);
269
- pipeline.set(hashKey, token.id);
270
- pipeline.sadd(userKey, token.id);
271
- if (token.expiresAt) {
272
- const ttl = Math.max(0, token.expiresAt.getTime() - Date.now());
273
- if (ttl > 0) {
274
- pipeline.pexpire(tokenKey, ttl);
275
- pipeline.pexpire(hashKey, ttl);
276
- }
277
- }
278
- await pipeline.exec();
279
- }
280
- /**
281
- * Find a token by its hashed value.
282
- */
283
- async findByHashedToken(hashedToken) {
284
- const hashKey = `${this.prefix}hash:${hashedToken}`;
285
- const tokenId = await this.redis.get(hashKey);
286
- if (!tokenId) {
287
- return null;
288
- }
289
- return this.findById(tokenId);
290
- }
291
- /**
292
- * Find all tokens for a user.
293
- */
294
- async findByUserId(userId) {
295
- const userKey = `${this.prefix}user:${userId}`;
296
- const tokenIds = await this.redis.smembers(userKey);
297
- const tokens = [];
298
- for (const id of tokenIds) {
299
- const token = await this.findById(id);
300
- if (token) {
301
- tokens.push(token);
302
- }
303
- }
304
- return tokens;
305
- }
306
- /**
307
- * Delete a token by its ID.
308
- */
309
- async delete(id) {
310
- const token = await this.findById(id);
311
- if (!token) return;
312
- const tokenKey = `${this.prefix}${id}`;
313
- const hashKey = `${this.prefix}hash:${token.hashedToken}`;
314
- const userKey = `${this.prefix}user:${token.userId}`;
315
- const pipeline = this.redis.pipeline();
316
- pipeline.del(tokenKey);
317
- pipeline.del(hashKey);
318
- pipeline.srem(userKey, id);
319
- await pipeline.exec();
320
- }
321
- /**
322
- * Delete all tokens for a user.
323
- */
324
- async deleteForUser(userId) {
325
- const tokens = await this.findByUserId(userId);
326
- for (const token of tokens) {
327
- await this.delete(token.id);
328
- }
329
- const userKey = `${this.prefix}user:${userId}`;
330
- await this.redis.del(userKey);
331
- }
332
- /**
333
- * Update the last used timestamp.
334
- */
335
- async updateLastUsed(id, timestamp) {
336
- const tokenKey = `${this.prefix}${id}`;
337
- await this.redis.hset(tokenKey, "lastUsedAt", timestamp.toISOString());
338
- }
339
- /**
340
- * Find a token by its ID.
341
- */
342
- async findById(id) {
343
- const tokenKey = `${this.prefix}${id}`;
344
- const data = await this.redis.hgetall(tokenKey);
345
- if (!data || Object.keys(data).length === 0) {
346
- return null;
347
- }
348
- return this.deserializeToken(data);
349
- }
350
- /**
351
- * Serialize a token for Redis storage.
352
- */
353
- serializeToken(token) {
354
- return {
355
- id: token.id,
356
- name: token.name,
357
- hashedToken: token.hashedToken,
358
- userId: String(token.userId),
359
- abilities: JSON.stringify(token.abilities),
360
- lastUsedAt: token.lastUsedAt?.toISOString() ?? "",
361
- expiresAt: token.expiresAt?.toISOString() ?? "",
362
- createdAt: token.createdAt.toISOString()
363
- };
364
- }
365
- /**
366
- * Deserialize a token from Redis storage.
367
- */
368
- deserializeToken(data) {
369
- return {
370
- id: data.id,
371
- name: data.name,
372
- hashedToken: data.hashedToken,
373
- userId: data.userId,
374
- abilities: decodeAbilities(data.abilities),
375
- lastUsedAt: toDate(data.lastUsedAt),
376
- // A never-expiring token serializes `expiresAt` as '' (a Redis hash has no
377
- // null), so an empty string is "absent" here, not a corrupt value. Map it
378
- // to undefined before `toOptionalExpiry`, which would otherwise degrade ''
379
- // to epoch and reject every non-expiring token. A genuinely unparseable
380
- // value still degrades to epoch and reads as expired.
381
- expiresAt: toOptionalExpiry(data.expiresAt === "" ? void 0 : data.expiresAt),
382
- createdAt: toDate(data.createdAt) ?? /* @__PURE__ */ new Date(0)
383
- };
384
- }
385
- /**
386
- * Clear all tokens (for testing).
387
- */
388
- async clear() {
389
- const keys = await scanKeys(this.redis, this.prefix + "*");
390
- if (keys.length > 0) {
391
- await this.redis.del(...keys);
392
- }
393
- }
298
+ redis;
299
+ prefix;
300
+ constructor(redis, options = {}) {
301
+ this.redis = redis;
302
+ this.prefix = options.prefix ?? "apitoken:";
303
+ }
304
+ /**
305
+ * Store a new API token.
306
+ */
307
+ async store(token) {
308
+ const tokenKey = `${this.prefix}${token.id}`;
309
+ const hashKey = `${this.prefix}hash:${token.hashedToken}`;
310
+ const userKey = `${this.prefix}user:${token.userId}`;
311
+ const serialized = this.serializeToken(token);
312
+ const pipeline = this.redis.pipeline();
313
+ pipeline.hset(tokenKey, serialized);
314
+ pipeline.set(hashKey, token.id);
315
+ pipeline.sadd(userKey, token.id);
316
+ if (token.expiresAt) {
317
+ const ttl = Math.max(0, token.expiresAt.getTime() - Date.now());
318
+ if (ttl > 0) {
319
+ pipeline.pexpire(tokenKey, ttl);
320
+ pipeline.pexpire(hashKey, ttl);
321
+ }
322
+ }
323
+ await pipeline.exec();
324
+ }
325
+ /**
326
+ * Find a token by its hashed value.
327
+ */
328
+ async findByHashedToken(hashedToken) {
329
+ const hashKey = `${this.prefix}hash:${hashedToken}`;
330
+ const tokenId = await this.redis.get(hashKey);
331
+ if (!tokenId) return null;
332
+ return this.findById(tokenId);
333
+ }
334
+ /**
335
+ * Find all tokens for a user.
336
+ */
337
+ async findByUserId(userId) {
338
+ const userKey = `${this.prefix}user:${userId}`;
339
+ const tokenIds = await this.redis.smembers(userKey);
340
+ const tokens = [];
341
+ for (const id of tokenIds) {
342
+ const token = await this.findById(id);
343
+ if (token) tokens.push(token);
344
+ }
345
+ return tokens;
346
+ }
347
+ /**
348
+ * Delete a token by its ID.
349
+ */
350
+ async delete(id) {
351
+ const token = await this.findById(id);
352
+ if (!token) return;
353
+ const tokenKey = `${this.prefix}${id}`;
354
+ const hashKey = `${this.prefix}hash:${token.hashedToken}`;
355
+ const userKey = `${this.prefix}user:${token.userId}`;
356
+ const pipeline = this.redis.pipeline();
357
+ pipeline.del(tokenKey);
358
+ pipeline.del(hashKey);
359
+ pipeline.srem(userKey, id);
360
+ await pipeline.exec();
361
+ }
362
+ /**
363
+ * Delete all tokens for a user.
364
+ */
365
+ async deleteForUser(userId) {
366
+ const tokens = await this.findByUserId(userId);
367
+ for (const token of tokens) await this.delete(token.id);
368
+ const userKey = `${this.prefix}user:${userId}`;
369
+ await this.redis.del(userKey);
370
+ }
371
+ /**
372
+ * Update the last used timestamp.
373
+ */
374
+ async updateLastUsed(id, timestamp) {
375
+ const tokenKey = `${this.prefix}${id}`;
376
+ await this.redis.hset(tokenKey, "lastUsedAt", timestamp.toISOString());
377
+ }
378
+ /**
379
+ * Find a token by its ID.
380
+ */
381
+ async findById(id) {
382
+ const tokenKey = `${this.prefix}${id}`;
383
+ const data = await this.redis.hgetall(tokenKey);
384
+ if (!data || Object.keys(data).length === 0) return null;
385
+ return this.deserializeToken(data);
386
+ }
387
+ /**
388
+ * Serialize a token for Redis storage.
389
+ */
390
+ serializeToken(token) {
391
+ return {
392
+ id: token.id,
393
+ name: token.name,
394
+ hashedToken: token.hashedToken,
395
+ userId: String(token.userId),
396
+ abilities: JSON.stringify(token.abilities),
397
+ lastUsedAt: token.lastUsedAt?.toISOString() ?? "",
398
+ expiresAt: token.expiresAt?.toISOString() ?? "",
399
+ createdAt: token.createdAt.toISOString()
400
+ };
401
+ }
402
+ /**
403
+ * Deserialize a token from Redis storage.
404
+ */
405
+ deserializeToken(data) {
406
+ return {
407
+ id: data.id,
408
+ name: data.name,
409
+ hashedToken: data.hashedToken,
410
+ userId: data.userId,
411
+ abilities: decodeAbilities(data.abilities),
412
+ lastUsedAt: toDate(data.lastUsedAt),
413
+ expiresAt: toOptionalExpiry(data.expiresAt === "" ? void 0 : data.expiresAt),
414
+ createdAt: toDate(data.createdAt) ?? /* @__PURE__ */ new Date(0)
415
+ };
416
+ }
417
+ /**
418
+ * Clear all tokens (for testing).
419
+ */
420
+ async clear() {
421
+ const keys = await scanKeys(this.redis, this.prefix + "*");
422
+ if (keys.length > 0) await this.redis.del(...keys);
423
+ }
394
424
  };
395
-
396
- // src/redis/RedisPasswordResetStore.ts
425
+ //#endregion
426
+ //#region src/redis/RedisPasswordResetStore.ts
427
+ /**
428
+ * Redis-backed password reset token store.
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
+ * ```
443
+ */
397
444
  var RedisPasswordResetStore = class {
398
- constructor(redis, options = {}) {
399
- this.redis = redis;
400
- this.prefix = options.prefix ?? "pwreset:";
401
- }
402
- redis;
403
- prefix;
404
- /**
405
- * Store a password reset token.
406
- */
407
- async store(tokenId, email, expiresAt) {
408
- const tokenKey = `${this.prefix}${tokenId}`;
409
- const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
410
- const ttlMs = Math.max(0, expiresAt.getTime() - Date.now());
411
- if (ttlMs <= 0) {
412
- return;
413
- }
414
- const data = JSON.stringify({ email, expiresAt: expiresAt.toISOString() });
415
- const pipeline = this.redis.pipeline();
416
- pipeline.psetex(tokenKey, ttlMs, data);
417
- pipeline.sadd(emailKey, tokenId);
418
- pipeline.pexpire(emailKey, ttlMs + 6e4);
419
- await pipeline.exec();
420
- }
421
- /**
422
- * Find a token by its hash.
423
- */
424
- async find(tokenId) {
425
- const tokenKey = `${this.prefix}${tokenId}`;
426
- const data = await this.redis.get(tokenKey);
427
- if (!data) {
428
- return null;
429
- }
430
- try {
431
- const parsed = JSON.parse(data);
432
- const expiresAt = toDate(parsed.expiresAt);
433
- if (expiresAt === null) {
434
- return null;
435
- }
436
- return {
437
- email: parsed.email,
438
- expiresAt
439
- };
440
- } catch {
441
- return null;
442
- }
443
- }
444
- /**
445
- * Delete a token by its hash.
446
- */
447
- async delete(tokenId) {
448
- const tokenKey = `${this.prefix}${tokenId}`;
449
- const data = await this.redis.get(tokenKey);
450
- if (data) {
451
- try {
452
- const parsed = JSON.parse(data);
453
- const emailKey = `${this.prefix}email:${parsed.email.toLowerCase()}`;
454
- await this.redis.srem(emailKey, tokenId);
455
- } catch {
456
- }
457
- }
458
- await this.redis.del(tokenKey);
459
- }
460
- /**
461
- * Delete all tokens for an email.
462
- */
463
- async deleteForEmail(email) {
464
- const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
465
- const tokenIds = await this.redis.smembers(emailKey);
466
- if (tokenIds.length > 0) {
467
- const tokenKeys = tokenIds.map((tokenId) => `${this.prefix}${tokenId}`);
468
- await this.redis.del(...tokenKeys, emailKey);
469
- } else {
470
- await this.redis.del(emailKey);
471
- }
472
- }
473
- /**
474
- * Clear all tokens (for testing).
475
- */
476
- async clear() {
477
- const keys = await scanKeys(this.redis, this.prefix + "*");
478
- if (keys.length > 0) {
479
- await this.redis.del(...keys);
480
- }
481
- }
445
+ redis;
446
+ prefix;
447
+ constructor(redis, options = {}) {
448
+ this.redis = redis;
449
+ this.prefix = options.prefix ?? "pwreset:";
450
+ }
451
+ /**
452
+ * Store a password reset token.
453
+ */
454
+ async store(tokenId, email, expiresAt) {
455
+ const tokenKey = `${this.prefix}${tokenId}`;
456
+ const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
457
+ const ttlMs = Math.max(0, expiresAt.getTime() - Date.now());
458
+ if (ttlMs <= 0) return;
459
+ const data = JSON.stringify({
460
+ email,
461
+ expiresAt: expiresAt.toISOString()
462
+ });
463
+ const pipeline = this.redis.pipeline();
464
+ pipeline.psetex(tokenKey, ttlMs, data);
465
+ pipeline.sadd(emailKey, tokenId);
466
+ pipeline.pexpire(emailKey, ttlMs + 6e4);
467
+ await pipeline.exec();
468
+ }
469
+ /**
470
+ * Find a token by its hash.
471
+ */
472
+ async find(tokenId) {
473
+ const tokenKey = `${this.prefix}${tokenId}`;
474
+ const data = await this.redis.get(tokenKey);
475
+ if (!data) return null;
476
+ try {
477
+ const parsed = JSON.parse(data);
478
+ const expiresAt = toDate(parsed.expiresAt);
479
+ if (expiresAt === null) return null;
480
+ return {
481
+ email: parsed.email,
482
+ expiresAt
483
+ };
484
+ } catch {
485
+ return null;
486
+ }
487
+ }
488
+ /**
489
+ * Delete a token by its hash.
490
+ */
491
+ async delete(tokenId) {
492
+ const tokenKey = `${this.prefix}${tokenId}`;
493
+ const data = await this.redis.get(tokenKey);
494
+ if (data) try {
495
+ const parsed = JSON.parse(data);
496
+ const emailKey = `${this.prefix}email:${parsed.email.toLowerCase()}`;
497
+ await this.redis.srem(emailKey, tokenId);
498
+ } catch {}
499
+ await this.redis.del(tokenKey);
500
+ }
501
+ /**
502
+ * Delete all tokens for an email.
503
+ */
504
+ async deleteForEmail(email) {
505
+ const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
506
+ const tokenIds = await this.redis.smembers(emailKey);
507
+ if (tokenIds.length > 0) {
508
+ const tokenKeys = tokenIds.map((tokenId) => `${this.prefix}${tokenId}`);
509
+ await this.redis.del(...tokenKeys, emailKey);
510
+ } else await this.redis.del(emailKey);
511
+ }
512
+ /**
513
+ * Clear all tokens (for testing).
514
+ */
515
+ async clear() {
516
+ const keys = await scanKeys(this.redis, this.prefix + "*");
517
+ if (keys.length > 0) await this.redis.del(...keys);
518
+ }
482
519
  };
483
-
484
- // src/redis/RedisEmailVerificationStore.ts
520
+ //#endregion
521
+ //#region src/redis/RedisEmailVerificationStore.ts
522
+ /**
523
+ * Redis-backed email verification token store.
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
+ * ```
538
+ */
485
539
  var RedisEmailVerificationStore = class {
486
- constructor(redis, options = {}) {
487
- this.redis = redis;
488
- this.prefix = options.prefix ?? "emailverify:";
489
- }
490
- redis;
491
- prefix;
492
- /**
493
- * Store an email verification token.
494
- */
495
- async store(token) {
496
- const tokenKey = `${this.prefix}${token.tokenId}`;
497
- const emailKey = `${this.prefix}email:${token.email.toLowerCase()}`;
498
- const ttlMs = Math.max(0, token.expiresAt.getTime() - Date.now());
499
- if (ttlMs <= 0) {
500
- return;
501
- }
502
- const data = JSON.stringify({
503
- tokenId: token.tokenId,
504
- email: token.email,
505
- expiresAt: token.expiresAt.toISOString(),
506
- createdAt: token.createdAt.toISOString()
507
- });
508
- const pipeline = this.redis.pipeline();
509
- pipeline.psetex(tokenKey, ttlMs, data);
510
- pipeline.sadd(emailKey, token.tokenId);
511
- pipeline.pexpire(emailKey, ttlMs + 6e4);
512
- await pipeline.exec();
513
- }
514
- /**
515
- * Find a token by its hash.
516
- */
517
- async findByTokenId(tokenId) {
518
- const tokenKey = `${this.prefix}${tokenId}`;
519
- const data = await this.redis.get(tokenKey);
520
- if (!data) {
521
- return null;
522
- }
523
- try {
524
- const parsed = JSON.parse(data);
525
- const expiresAt = toDate(parsed.expiresAt);
526
- if (expiresAt === null) {
527
- return null;
528
- }
529
- return {
530
- tokenId: parsed.tokenId,
531
- email: parsed.email,
532
- expiresAt,
533
- createdAt: toDate(parsed.createdAt) ?? /* @__PURE__ */ new Date(0)
534
- };
535
- } catch {
536
- return null;
537
- }
538
- }
539
- /**
540
- * Delete a token by its hash.
541
- */
542
- async delete(tokenId) {
543
- const tokenKey = `${this.prefix}${tokenId}`;
544
- const data = await this.redis.get(tokenKey);
545
- if (data) {
546
- try {
547
- const parsed = JSON.parse(data);
548
- const emailKey = `${this.prefix}email:${parsed.email.toLowerCase()}`;
549
- await this.redis.srem(emailKey, tokenId);
550
- } catch {
551
- }
552
- }
553
- await this.redis.del(tokenKey);
554
- }
555
- /**
556
- * Delete all tokens for an email.
557
- */
558
- async deleteForEmail(email) {
559
- const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
560
- const tokenIds = await this.redis.smembers(emailKey);
561
- if (tokenIds.length > 0) {
562
- const tokenKeys = tokenIds.map((tokenId) => `${this.prefix}${tokenId}`);
563
- await this.redis.del(...tokenKeys, emailKey);
564
- } else {
565
- await this.redis.del(emailKey);
566
- }
567
- }
568
- /**
569
- * Clear all tokens (for testing).
570
- */
571
- async clear() {
572
- const keys = await scanKeys(this.redis, this.prefix + "*");
573
- if (keys.length > 0) {
574
- await this.redis.del(...keys);
575
- }
576
- }
540
+ redis;
541
+ prefix;
542
+ constructor(redis, options = {}) {
543
+ this.redis = redis;
544
+ this.prefix = options.prefix ?? "emailverify:";
545
+ }
546
+ /**
547
+ * Store an email verification token.
548
+ */
549
+ async store(token) {
550
+ const tokenKey = `${this.prefix}${token.tokenId}`;
551
+ const emailKey = `${this.prefix}email:${token.email.toLowerCase()}`;
552
+ const ttlMs = Math.max(0, token.expiresAt.getTime() - Date.now());
553
+ if (ttlMs <= 0) return;
554
+ const data = JSON.stringify({
555
+ tokenId: token.tokenId,
556
+ email: token.email,
557
+ expiresAt: token.expiresAt.toISOString(),
558
+ createdAt: token.createdAt.toISOString()
559
+ });
560
+ const pipeline = this.redis.pipeline();
561
+ pipeline.psetex(tokenKey, ttlMs, data);
562
+ pipeline.sadd(emailKey, token.tokenId);
563
+ pipeline.pexpire(emailKey, ttlMs + 6e4);
564
+ await pipeline.exec();
565
+ }
566
+ /**
567
+ * Find a token by its hash.
568
+ */
569
+ async findByTokenId(tokenId) {
570
+ const tokenKey = `${this.prefix}${tokenId}`;
571
+ const data = await this.redis.get(tokenKey);
572
+ if (!data) return null;
573
+ try {
574
+ const parsed = JSON.parse(data);
575
+ const expiresAt = toDate(parsed.expiresAt);
576
+ if (expiresAt === null) return null;
577
+ return {
578
+ tokenId: parsed.tokenId,
579
+ email: parsed.email,
580
+ expiresAt,
581
+ createdAt: toDate(parsed.createdAt) ?? /* @__PURE__ */ new Date(0)
582
+ };
583
+ } catch {
584
+ return null;
585
+ }
586
+ }
587
+ /**
588
+ * Delete a token by its hash.
589
+ */
590
+ async delete(tokenId) {
591
+ const tokenKey = `${this.prefix}${tokenId}`;
592
+ const data = await this.redis.get(tokenKey);
593
+ if (data) try {
594
+ const parsed = JSON.parse(data);
595
+ const emailKey = `${this.prefix}email:${parsed.email.toLowerCase()}`;
596
+ await this.redis.srem(emailKey, tokenId);
597
+ } catch {}
598
+ await this.redis.del(tokenKey);
599
+ }
600
+ /**
601
+ * Delete all tokens for an email.
602
+ */
603
+ async deleteForEmail(email) {
604
+ const emailKey = `${this.prefix}email:${email.toLowerCase()}`;
605
+ const tokenIds = await this.redis.smembers(emailKey);
606
+ if (tokenIds.length > 0) {
607
+ const tokenKeys = tokenIds.map((tokenId) => `${this.prefix}${tokenId}`);
608
+ await this.redis.del(...tokenKeys, emailKey);
609
+ } else await this.redis.del(emailKey);
610
+ }
611
+ /**
612
+ * Clear all tokens (for testing).
613
+ */
614
+ async clear() {
615
+ const keys = await scanKeys(this.redis, this.prefix + "*");
616
+ if (keys.length > 0) await this.redis.del(...keys);
617
+ }
577
618
  };
578
-
579
- // src/redis/RedisOAuthStateStore.ts
580
- var CONSUME_SCRIPT = `
619
+ //#endregion
620
+ //#region src/redis/RedisOAuthStateStore.ts
621
+ /**
622
+ * Redis-backed OAuth state store.
623
+ *
624
+ * Required in production whenever more than one server process handles
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
+ * ```
637
+ */
638
+ const CONSUME_SCRIPT = `
581
639
  local value = redis.call('GET', KEYS[1])
582
640
  if value then
583
641
  redis.call('DEL', KEYS[1])
@@ -585,94 +643,66 @@ end
585
643
  return value
586
644
  `;
587
645
  var RedisOAuthStateStore = class {
588
- constructor(redis, options = {}) {
589
- this.redis = redis;
590
- this.prefix = options.prefix ?? "oauthstate:";
591
- }
592
- redis;
593
- prefix;
594
- async store(stateHash, payload) {
595
- const ttlMs = Math.max(0, payload.expiresAt.getTime() - Date.now());
596
- if (ttlMs <= 0) {
597
- return;
598
- }
599
- const data = JSON.stringify({
600
- provider: payload.provider,
601
- redirectTo: payload.redirectTo,
602
- expiresAt: payload.expiresAt.toISOString(),
603
- // Persisted, not derived: an unbound state verifies for any browser.
604
- binding: payload.binding
605
- });
606
- await this.redis.psetex(`${this.prefix}${stateHash}`, ttlMs, data);
607
- }
608
- async find(stateHash) {
609
- const data = await this.redis.get(`${this.prefix}${stateHash}`);
610
- if (!data) {
611
- return null;
612
- }
613
- const payload = this.parsePayload(data);
614
- if (!payload) {
615
- return null;
616
- }
617
- if (payload.expiresAt.getTime() <= Date.now()) {
618
- await this.delete(stateHash);
619
- return null;
620
- }
621
- return payload;
622
- }
623
- async consume(stateHash) {
624
- const data = await this.redis.eval(
625
- CONSUME_SCRIPT,
626
- 1,
627
- `${this.prefix}${stateHash}`
628
- );
629
- if (!data) {
630
- return null;
631
- }
632
- const payload = this.parsePayload(data);
633
- if (!payload || payload.expiresAt.getTime() <= Date.now()) {
634
- return null;
635
- }
636
- return payload;
637
- }
638
- parsePayload(data) {
639
- try {
640
- const parsed = JSON.parse(data);
641
- const expiresAt = toDate(parsed.expiresAt);
642
- if (expiresAt === null) {
643
- return null;
644
- }
645
- return {
646
- provider: parsed.provider,
647
- redirectTo: parsed.redirectTo,
648
- expiresAt,
649
- binding: parsed.binding
650
- };
651
- } catch {
652
- return null;
653
- }
654
- }
655
- async delete(stateHash) {
656
- await this.redis.del(`${this.prefix}${stateHash}`);
657
- }
658
- /**
659
- * Clear all states (for testing).
660
- */
661
- async clear() {
662
- const keys = await scanKeys(this.redis, this.prefix + "*");
663
- if (keys.length > 0) {
664
- await this.redis.del(...keys);
665
- }
666
- }
667
- };
668
- export {
669
- Redis,
670
- RedisApiTokenStore,
671
- RedisEmailVerificationStore,
672
- RedisOAuthStateStore,
673
- RedisPasswordResetStore,
674
- RedisRateLimitStore,
675
- RedisSessionStore,
676
- RedisSlidingWindowRateLimitStore,
677
- createRedisClient
646
+ redis;
647
+ prefix;
648
+ constructor(redis, options = {}) {
649
+ this.redis = redis;
650
+ this.prefix = options.prefix ?? "oauthstate:";
651
+ }
652
+ async store(stateHash, payload) {
653
+ const ttlMs = Math.max(0, payload.expiresAt.getTime() - Date.now());
654
+ if (ttlMs <= 0) return;
655
+ const data = JSON.stringify({
656
+ provider: payload.provider,
657
+ redirectTo: payload.redirectTo,
658
+ expiresAt: payload.expiresAt.toISOString(),
659
+ binding: payload.binding
660
+ });
661
+ await this.redis.psetex(`${this.prefix}${stateHash}`, ttlMs, data);
662
+ }
663
+ async find(stateHash) {
664
+ const data = await this.redis.get(`${this.prefix}${stateHash}`);
665
+ if (!data) return null;
666
+ const payload = this.parsePayload(data);
667
+ if (!payload) return null;
668
+ if (payload.expiresAt.getTime() <= Date.now()) {
669
+ await this.delete(stateHash);
670
+ return null;
671
+ }
672
+ return payload;
673
+ }
674
+ async consume(stateHash) {
675
+ const data = await this.redis.eval(CONSUME_SCRIPT, 1, `${this.prefix}${stateHash}`);
676
+ if (!data) return null;
677
+ const payload = this.parsePayload(data);
678
+ if (!payload || payload.expiresAt.getTime() <= Date.now()) return null;
679
+ return payload;
680
+ }
681
+ parsePayload(data) {
682
+ try {
683
+ const parsed = JSON.parse(data);
684
+ const expiresAt = toDate(parsed.expiresAt);
685
+ if (expiresAt === null) return null;
686
+ return {
687
+ provider: parsed.provider,
688
+ redirectTo: parsed.redirectTo,
689
+ expiresAt,
690
+ binding: parsed.binding
691
+ };
692
+ } catch {
693
+ return null;
694
+ }
695
+ }
696
+ async delete(stateHash) {
697
+ await this.redis.del(`${this.prefix}${stateHash}`);
698
+ }
699
+ /**
700
+ * Clear all states (for testing).
701
+ */
702
+ async clear() {
703
+ const keys = await scanKeys(this.redis, this.prefix + "*");
704
+ if (keys.length > 0) await this.redis.del(...keys);
705
+ }
678
706
  };
707
+ //#endregion
708
+ export { Redis, RedisApiTokenStore, RedisEmailVerificationStore, RedisOAuthStateStore, RedisPasswordResetStore, RedisRateLimitStore, RedisSessionStore, RedisSlidingWindowRateLimitStore, createRedisClient };