@guren/server 2.2.0 → 2.4.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 (40) hide show
  1. package/dist/{DocsViewerServiceProvider-D7RGJPGM.js → DocsViewerServiceProvider-RUYDFBMW.js} +2 -2
  2. package/dist/McpServiceProvider-FRJ5O7LT.js +8 -0
  3. package/dist/auth/index.js +2 -1
  4. package/dist/broadcasting/index.js +2 -1
  5. package/dist/{chunk-SIP34GBE.js → chunk-2SC566CD.js} +14 -18
  6. package/dist/chunk-3KV5X2FL.js +31 -0
  7. package/dist/{chunk-CDZUNKI6.js → chunk-5WL2FTC4.js} +3 -3
  8. package/dist/{chunk-WIXGT4TN.js → chunk-A5JJ7XTH.js} +8 -2
  9. package/dist/{chunk-4VE3LYOM.js → chunk-DRNPVBAA.js} +20 -5
  10. package/dist/{chunk-LVJCZCAV.js → chunk-H3B23O6T.js} +10 -118
  11. package/dist/{chunk-BZMZEFRG.js → chunk-LHR6OHI7.js} +11 -0
  12. package/dist/{chunk-PZKUDFMW.js → chunk-NENDACRP.js} +20 -4
  13. package/dist/{chunk-JBG4AR24.js → chunk-Q2P6YLRR.js} +8 -2
  14. package/dist/{chunk-BUQXOZCT.js → chunk-TVV5YNEC.js} +8 -4
  15. package/dist/chunk-V4DNC2ER.js +114 -0
  16. package/dist/docs-viewer/endpoint.d.ts +11 -1
  17. package/dist/encryption/index.js +17 -15
  18. package/dist/health/index.js +1 -1
  19. package/dist/http/Application.d.ts +67 -1
  20. package/dist/http/FormRequest.d.ts +10 -7
  21. package/dist/http/dev-assets.d.ts +11 -0
  22. package/dist/http/dev-banner.d.ts +11 -0
  23. package/dist/http/inertia-assets.d.ts +9 -0
  24. package/dist/http/middleware/loopback-guard.d.ts +16 -3
  25. package/dist/http/middleware/response-headers.d.ts +18 -0
  26. package/dist/http/middleware/validation-errors-cookie.d.ts +31 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +376 -112
  29. package/dist/mcp/create-mcp-server.d.ts +8 -0
  30. package/dist/mcp/endpoint.d.ts +19 -1
  31. package/dist/mcp/index.js +3 -3
  32. package/dist/redis/index.js +43 -8
  33. package/dist/redis/redis-values.d.ts +17 -0
  34. package/dist/runtime/index.js +102 -69
  35. package/dist/support/contained-path.d.ts +26 -0
  36. package/dist/support/expiry.d.ts +47 -0
  37. package/dist/support/expiry.js +12 -0
  38. package/dist/support/inertia-defaults.d.ts +13 -0
  39. package/package.json +6 -2
  40. package/dist/McpServiceProvider-GRDYNEQG.js +0 -8
@@ -2,10 +2,10 @@ import {
2
2
  DOCS_VIEWER_PATH,
3
3
  createDocsViewerAccessGuard,
4
4
  isDocsViewerEnabled
5
- } from "./chunk-WIXGT4TN.js";
5
+ } from "./chunk-A5JJ7XTH.js";
6
6
  import {
7
7
  ServiceProvider
8
- } from "./chunk-BZMZEFRG.js";
8
+ } from "./chunk-LHR6OHI7.js";
9
9
 
10
10
  // src/docs-viewer/DocsViewerServiceProvider.ts
11
11
  import { createRequire } from "module";
@@ -0,0 +1,8 @@
1
+ import {
2
+ McpServiceProvider
3
+ } from "./chunk-5WL2FTC4.js";
4
+ import "./chunk-Q2P6YLRR.js";
5
+ import "./chunk-LHR6OHI7.js";
6
+ export {
7
+ McpServiceProvider
8
+ };
@@ -56,7 +56,8 @@ import {
56
56
  verifyEmailToken,
57
57
  verifyOAuthState,
58
58
  verifyPasswordResetToken
59
- } from "../chunk-BUQXOZCT.js";
59
+ } from "../chunk-TVV5YNEC.js";
60
+ import "../chunk-3KV5X2FL.js";
60
61
  import "../chunk-DAQKYKLH.js";
61
62
  import "../chunk-SFQP6O52.js";
62
63
  import "../chunk-QQKTH5KX.js";
@@ -9,8 +9,9 @@ import {
9
9
  createTypedBroadcaster,
10
10
  getBroadcastManager,
11
11
  setBroadcastManager
12
- } from "../chunk-4VE3LYOM.js";
12
+ } from "../chunk-DRNPVBAA.js";
13
13
  import "../chunk-B5E5VBDI.js";
14
+ import "../chunk-V4DNC2ER.js";
14
15
  export {
15
16
  BroadcastManager,
16
17
  Channel,
@@ -105,26 +105,22 @@ var HealthManager = class {
105
105
  return async (ctx, next) => {
106
106
  const report = options.checks ? await this.checkOnly(options.checks) : await this.check();
107
107
  const statusCode = report.status === "healthy" ? 200 : report.status === "degraded" ? 200 : 503;
108
- if (options.detailed === false) {
109
- ctx.status(statusCode);
110
- ctx.json({
111
- status: report.status,
112
- timestamp: report.timestamp.toISOString()
113
- });
114
- } else {
115
- ctx.status(statusCode);
116
- ctx.json({
108
+ ctx.res = ctx.json(
109
+ {
117
110
  status: report.status,
118
111
  timestamp: report.timestamp.toISOString(),
119
- checks: report.checks.map((check) => ({
120
- name: check.name,
121
- status: check.status,
122
- message: check.message,
123
- duration: check.duration,
124
- meta: check.meta
125
- }))
126
- });
127
- }
112
+ ...options.detailed === false ? {} : {
113
+ checks: report.checks.map((check) => ({
114
+ name: check.name,
115
+ status: check.status,
116
+ message: check.message,
117
+ duration: check.duration,
118
+ meta: check.meta
119
+ }))
120
+ }
121
+ },
122
+ statusCode
123
+ );
128
124
  };
129
125
  }
130
126
  /**
@@ -0,0 +1,31 @@
1
+ // src/support/expiry.ts
2
+ function toDate(value) {
3
+ const date = coerceDate(value);
4
+ return date !== null && !Number.isNaN(date.getTime()) ? date : null;
5
+ }
6
+ function coerceDate(value) {
7
+ if (value == null) return null;
8
+ if (value instanceof Date) return value;
9
+ if (typeof value === "number" || typeof value === "bigint") return new Date(Number(value));
10
+ if (typeof value === "string") return new Date(/^\d+$/.test(value) ? Number(value) : value);
11
+ return null;
12
+ }
13
+ function isExpired(value, now = Date.now()) {
14
+ const date = toDate(value);
15
+ return date === null || date.getTime() <= now;
16
+ }
17
+ function isOptionalExpiryPast(value, now = Date.now()) {
18
+ if (value == null) return false;
19
+ return isExpired(value, now);
20
+ }
21
+ function toOptionalExpiry(value) {
22
+ if (value == null) return null;
23
+ return toDate(value) ?? /* @__PURE__ */ new Date(0);
24
+ }
25
+
26
+ export {
27
+ toDate,
28
+ isExpired,
29
+ isOptionalExpiryPast,
30
+ toOptionalExpiry
31
+ };
@@ -2,10 +2,10 @@ import {
2
2
  MCP_ENDPOINT_PATH,
3
3
  createMcpAccessGuard,
4
4
  isMcpEndpointEnabled
5
- } from "./chunk-JBG4AR24.js";
5
+ } from "./chunk-Q2P6YLRR.js";
6
6
  import {
7
7
  ServiceProvider
8
- } from "./chunk-BZMZEFRG.js";
8
+ } from "./chunk-LHR6OHI7.js";
9
9
 
10
10
  // src/mcp/create-mcp-server.ts
11
11
  import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -195,7 +195,7 @@ function createMcpServer(options) {
195
195
  try {
196
196
  const result = await generate();
197
197
  if (result?.outputPath === "") {
198
- skipped.push({ artifacts, reason: "nothing to generate" });
198
+ skipped.push({ artifacts, reason: result.skipped?.message ?? "nothing to generate" });
199
199
  } else {
200
200
  generated.push(...artifacts);
201
201
  }
@@ -1,11 +1,17 @@
1
1
  import {
2
2
  createLoopbackGuard
3
- } from "./chunk-BZMZEFRG.js";
3
+ } from "./chunk-LHR6OHI7.js";
4
4
 
5
5
  // src/docs-viewer/endpoint.ts
6
6
  var DOCS_VIEWER_PATH = "/_guren/docs";
7
7
  function isDocsViewerEnabled() {
8
- return typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && process.env?.GUREN_DOCS === "1";
8
+ if (typeof process === "undefined") {
9
+ return false;
10
+ }
11
+ if (process.env.NODE_ENV === "production") {
12
+ return false;
13
+ }
14
+ return process.env.GUREN_DOCS === "1";
9
15
  }
10
16
  function createDocsViewerAccessGuard() {
11
17
  return createLoopbackGuard("the docs viewer");
@@ -2,6 +2,9 @@ import {
2
2
  claimHotDisposable,
3
3
  isHotReloadRuntime
4
4
  } from "./chunk-B5E5VBDI.js";
5
+ import {
6
+ randomHex
7
+ } from "./chunk-V4DNC2ER.js";
5
8
 
6
9
  // src/broadcasting/channels/Channel.ts
7
10
  var Channel = class {
@@ -520,6 +523,14 @@ function formatValidationErrors(error, fallbackMessage = "The provided data is i
520
523
  }
521
524
 
522
525
  // src/broadcasting/BroadcastManager.ts
526
+ function resolveClientUserId(user) {
527
+ if (typeof user !== "object" || user === null) return void 0;
528
+ const candidate = user;
529
+ for (const value of [candidate.id, candidate.sub, candidate.userId]) {
530
+ if (typeof value === "string" || typeof value === "number") return value;
531
+ }
532
+ return void 0;
533
+ }
523
534
  var BroadcastManager = class {
524
535
  /**
525
536
  * Default driver name.
@@ -689,6 +700,7 @@ var BroadcastManager = class {
689
700
  authorizedChannels.push(channelName);
690
701
  }
691
702
  }
703
+ const clientUserId = resolveClientUserId(user);
692
704
  let controller = null;
693
705
  let client = null;
694
706
  let pingTimer = null;
@@ -718,7 +730,9 @@ var BroadcastManager = class {
718
730
  controller = streamController;
719
731
  client = {
720
732
  id: clientId,
721
- userId: void 0,
733
+ // Recorded so `POST /broadcasting/auth` can refuse to attach
734
+ // channels to a stream belonging to someone else.
735
+ userId: clientUserId,
722
736
  channels: /* @__PURE__ */ new Set(),
723
737
  send: (event, data) => {
724
738
  const message = `event: ${event}
@@ -774,13 +788,16 @@ data: ${JSON.stringify(data)}
774
788
  }
775
789
  const clientId = typeof payload.clientId === "string" ? payload.clientId : void 0;
776
790
  const results = {};
791
+ const requesterId = resolveClientUserId(user);
792
+ const target = clientId ? this.sseClients.get(clientId) : void 0;
793
+ const attachTo = target && (target.userId === void 0 || target.userId === requesterId) ? target : void 0;
777
794
  for (const ch of channels) {
778
795
  const authResult = await this.authorize(ch, user);
779
796
  if (authResult === false || authResult === null) {
780
797
  results[ch] = { authorized: false };
781
798
  continue;
782
799
  }
783
- const subscribed = clientId ? this.subscribeClient(clientId, ch) : false;
800
+ const subscribed = attachTo ? this.subscribeClient(attachTo.id, ch) : false;
784
801
  if (authResult === true) {
785
802
  results[ch] = { authorized: true, subscribed };
786
803
  } else {
@@ -918,9 +935,7 @@ data: ${JSON.stringify(data)}
918
935
  * Generate a unique client ID.
919
936
  */
920
937
  generateClientId(prefix = "sse") {
921
- const timestamp = Date.now().toString(36);
922
- const random = Math.random().toString(36).substring(2, 10);
923
- return `${prefix}_${timestamp}${random}`;
938
+ return `${prefix}_${randomHex(16)}`;
924
939
  }
925
940
  };
926
941
  var globalBroadcastManager = null;
@@ -6,6 +6,7 @@ import {
6
6
 
7
7
  // src/encryption/Encrypter.ts
8
8
  import { createCipheriv, createDecipheriv, randomBytes, createHmac } from "crypto";
9
+ var GCM_TAG_BYTES = 16;
9
10
  var Encrypter = class {
10
11
  /**
11
12
  * Encryption key.
@@ -79,7 +80,7 @@ var Encrypter = class {
79
80
  */
80
81
  encryptGcm(data) {
81
82
  const iv = randomBytes(12);
82
- const cipher = createCipheriv("aes-256-gcm", this.key, iv);
83
+ const cipher = createCipheriv("aes-256-gcm", this.key, iv, { authTagLength: GCM_TAG_BYTES });
83
84
  const encrypted = Buffer.concat([
84
85
  cipher.update(data, "utf8"),
85
86
  cipher.final()
@@ -96,11 +97,14 @@ var Encrypter = class {
96
97
  * Decrypt using AES-256-GCM.
97
98
  */
98
99
  decryptGcm(payload) {
100
+ const iv = Buffer.from(payload.iv, "base64");
101
+ const encrypted = Buffer.from(payload.value, "base64");
102
+ const tag = Buffer.from(payload.tag, "base64");
103
+ if (tag.length !== GCM_TAG_BYTES) {
104
+ throw new Error("Invalid authentication tag length.");
105
+ }
99
106
  return this.tryDecryptWithKeys((key) => {
100
- const iv = Buffer.from(payload.iv, "base64");
101
- const encrypted = Buffer.from(payload.value, "base64");
102
- const tag = Buffer.from(payload.tag, "base64");
103
- const decipher = createDecipheriv("aes-256-gcm", key, iv);
107
+ const decipher = createDecipheriv("aes-256-gcm", key, iv, { authTagLength: GCM_TAG_BYTES });
104
108
  decipher.setAuthTag(tag);
105
109
  const decrypted = Buffer.concat([
106
110
  decipher.update(encrypted),
@@ -254,104 +258,6 @@ function verifySignedUrl(value, keyring, options = {}) {
254
258
  return payload?.url === canonical;
255
259
  }
256
260
 
257
- // src/encryption/Random.ts
258
- import { randomBytes as randomBytes2, randomUUID, randomInt as cryptoRandomInt } from "crypto";
259
- var CHARSETS = {
260
- alphanumeric: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
261
- alphabetic: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
262
- numeric: "0123456789",
263
- hex: "0123456789abcdef",
264
- "base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
265
- "url-safe": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
266
- };
267
- function unbiasedRandomChars(length, chars) {
268
- if (!Number.isInteger(length) || length < 0) {
269
- throw new RangeError(`Random string length must be a non-negative integer, received ${length}.`);
270
- }
271
- const limit = 256 - 256 % chars.length;
272
- let result = "";
273
- while (result.length < length) {
274
- const remaining = length - result.length;
275
- const bytes = randomBytes2(Math.ceil(remaining * 256 / limit) + 8);
276
- for (const byte of bytes) {
277
- if (byte < limit) {
278
- result += chars[byte % chars.length];
279
- if (result.length === length) break;
280
- }
281
- }
282
- }
283
- return result;
284
- }
285
- function randomString(length, options = {}) {
286
- const { charset = "alphanumeric" } = options;
287
- return unbiasedRandomChars(length, CHARSETS[charset]);
288
- }
289
- function random(length) {
290
- return randomBytes2(length);
291
- }
292
- function randomHex(length) {
293
- return randomBytes2(length).toString("hex");
294
- }
295
- function randomBase64(length) {
296
- return randomBytes2(length).toString("base64");
297
- }
298
- function randomBase64Url(length) {
299
- return randomBytes2(length).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
300
- }
301
- function uuid() {
302
- return randomUUID();
303
- }
304
- function randomInt(min, max) {
305
- return cryptoRandomInt(min, max + 1);
306
- }
307
- function urlSafeToken(length = 32) {
308
- return randomBase64Url(Math.ceil(length * 0.75)).slice(0, length);
309
- }
310
- function generatePassword(length = 16, options = {}) {
311
- const {
312
- uppercase = true,
313
- lowercase = true,
314
- numbers = true,
315
- symbols = true
316
- } = options;
317
- let chars = "";
318
- if (uppercase) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
319
- if (lowercase) chars += "abcdefghijklmnopqrstuvwxyz";
320
- if (numbers) chars += "0123456789";
321
- if (symbols) chars += "!@#$%^&*()-_=+[]{}|;:,.<>?";
322
- if (chars.length === 0) {
323
- chars = CHARSETS.alphanumeric;
324
- }
325
- return unbiasedRandomChars(length, chars);
326
- }
327
- function generateOtp(length = 6) {
328
- return randomString(length, { charset: "numeric" });
329
- }
330
- function generateSlug(length = 10) {
331
- return randomString(length, { charset: "hex" });
332
- }
333
- function shuffle(array) {
334
- const result = [...array];
335
- for (let i = result.length - 1; i > 0; i--) {
336
- const j = randomInt(0, i);
337
- [result[i], result[j]] = [result[j], result[i]];
338
- }
339
- return result;
340
- }
341
- function pick(array) {
342
- if (array.length === 0) {
343
- throw new Error("Cannot pick from empty array.");
344
- }
345
- return array[randomInt(0, array.length - 1)];
346
- }
347
- function sample(array, count) {
348
- if (count > array.length) {
349
- throw new Error("Sample count exceeds array length.");
350
- }
351
- const shuffled = shuffle(array);
352
- return shuffled.slice(0, count);
353
- }
354
-
355
261
  export {
356
262
  Encrypter,
357
263
  generateKey,
@@ -361,19 +267,5 @@ export {
361
267
  encrypt,
362
268
  decrypt,
363
269
  signUrl,
364
- verifySignedUrl,
365
- randomString,
366
- random,
367
- randomHex,
368
- randomBase64,
369
- randomBase64Url,
370
- uuid,
371
- randomInt,
372
- urlSafeToken,
373
- generatePassword,
374
- generateOtp,
375
- generateSlug,
376
- shuffle,
377
- pick,
378
- sample
270
+ verifySignedUrl
379
271
  };
@@ -157,6 +157,9 @@ function clientAddress(ctx) {
157
157
  }
158
158
  return env.server.requestIP(ctx.req.raw)?.address;
159
159
  }
160
+ function allowsUnverifiedPeer() {
161
+ return typeof process !== "undefined" && process.env.GUREN_ALLOW_UNVERIFIED_PEER === "1";
162
+ }
160
163
  function createLoopbackGuard(resource) {
161
164
  return async (ctx, next) => {
162
165
  const origin = ctx.req.header("origin");
@@ -167,6 +170,14 @@ function createLoopbackGuard(resource) {
167
170
  if (address !== void 0 && !isLoopbackAddress(address)) {
168
171
  return ctx.json({ message: `Forbidden: remote request to ${resource}` }, 403);
169
172
  }
173
+ if (address === void 0 && !allowsUnverifiedPeer()) {
174
+ return ctx.json(
175
+ {
176
+ message: `Forbidden: this runtime does not report the peer address, so ${resource} cannot confirm the request came from this machine. Serve the app with Application.listen() on Bun, or set GUREN_ALLOW_UNVERIFIED_PEER=1 to accept requests from anywhere the process is reachable.`
177
+ },
178
+ 403
179
+ );
180
+ }
170
181
  await next();
171
182
  };
172
183
  }
@@ -6,7 +6,7 @@ import standard from "figlet/importable-fonts/Standard.js";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@guren/server",
9
- version: "2.2.0",
9
+ version: "2.4.0",
10
10
  type: "module",
11
11
  license: "MIT",
12
12
  repository: {
@@ -106,6 +106,10 @@ var package_default = {
106
106
  "./redis": {
107
107
  types: "./dist/redis/index.d.ts",
108
108
  default: "./dist/redis/index.js"
109
+ },
110
+ "./support/expiry": {
111
+ types: "./dist/support/expiry.d.ts",
112
+ default: "./dist/support/expiry.js"
109
113
  }
110
114
  },
111
115
  scripts: {
@@ -115,7 +119,7 @@ var package_default = {
115
119
  test: "bun test"
116
120
  },
117
121
  dependencies: {
118
- "@guren/orm": "^2.2.0",
122
+ "@guren/orm": "^2.2.2",
119
123
  "@modelcontextprotocol/sdk": "^1.30.0",
120
124
  chalk: "^5.3.0",
121
125
  consola: "^3.4.2",
@@ -172,14 +176,20 @@ function generateAsciiArt(text) {
172
176
  }
173
177
  var GUREN_ASCII_ART = chalk.redBright.bold(generateAsciiArt("GUREN"));
174
178
  var GUREN_VERSION = package_default.version;
179
+ function isWildcardHost(hostname) {
180
+ return hostname === "0.0.0.0" || hostname === "::";
181
+ }
182
+ function formatHostPort(hostname, port) {
183
+ return `${hostname.includes(":") ? `[${hostname}]` : hostname}:${port}`;
184
+ }
175
185
  function logDevServerBanner({
176
186
  hostname,
177
187
  port,
178
188
  assetsUrl = "http://localhost:5173"
179
189
  }) {
180
190
  const localUrl = `http://localhost:${port}`;
181
- const boundUrl = `http://${hostname}:${port}`;
182
- const boundLabel = hostname === "0.0.0.0" || hostname === "::" ? " (all interfaces)" : "";
191
+ const boundUrl = `http://${formatHostPort(hostname, port)}`;
192
+ const boundLabel = isWildcardHost(hostname) ? " (all interfaces)" : "";
183
193
  const header = [
184
194
  GUREN_ASCII_ART,
185
195
  chalk.magentaBright.bold(
@@ -250,9 +260,15 @@ function parseImportMap(value, options = {}) {
250
260
  }
251
261
  }
252
262
 
263
+ // src/support/inertia-defaults.ts
264
+ var DEFAULT_DEV_STYLES_ENTRY = "/resources/css/app.css";
265
+
253
266
  export {
254
267
  parseImportMap,
268
+ DEFAULT_DEV_STYLES_ENTRY,
255
269
  GUREN_ASCII_ART,
270
+ isWildcardHost,
271
+ formatHostPort,
256
272
  logDevServerBanner,
257
273
  startViteDevServer
258
274
  };
@@ -1,11 +1,17 @@
1
1
  import {
2
2
  createLoopbackGuard
3
- } from "./chunk-BZMZEFRG.js";
3
+ } from "./chunk-LHR6OHI7.js";
4
4
 
5
5
  // src/mcp/endpoint.ts
6
6
  var MCP_ENDPOINT_PATH = "/_guren/mcp";
7
7
  function isMcpEndpointEnabled() {
8
- return typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && process.env?.GUREN_MCP === "1";
8
+ if (typeof process === "undefined") {
9
+ return false;
10
+ }
11
+ if (process.env.NODE_ENV === "production") {
12
+ return false;
13
+ }
14
+ return process.env.GUREN_MCP === "1";
9
15
  }
10
16
  function createMcpAccessGuard() {
11
17
  return createLoopbackGuard("the MCP endpoint");
@@ -1,3 +1,7 @@
1
+ import {
2
+ isExpired,
3
+ isOptionalExpiryPast
4
+ } from "./chunk-3KV5X2FL.js";
1
5
  import {
2
6
  AuthenticationException
3
7
  } from "./chunk-DAQKYKLH.js";
@@ -1259,7 +1263,7 @@ async function verifyApiToken(plainTextToken, store, options = {}) {
1259
1263
  const token = await store.findByHashedToken(hashedToken);
1260
1264
  if (!token) return null;
1261
1265
  if (token.id !== parsed.id) return null;
1262
- if (token.expiresAt && /* @__PURE__ */ new Date() > token.expiresAt) {
1266
+ if (isOptionalExpiryPast(token.expiresAt)) {
1263
1267
  return null;
1264
1268
  }
1265
1269
  if (!secureCompare(token.hashedToken, hashedToken)) {
@@ -1444,7 +1448,7 @@ var MemoryOAuthStateStore = class {
1444
1448
  sweepExpired() {
1445
1449
  const now = Date.now();
1446
1450
  for (const [hash, payload] of this.states) {
1447
- if (payload.expiresAt.getTime() <= now) {
1451
+ if (isExpired(payload.expiresAt, now)) {
1448
1452
  this.states.delete(hash);
1449
1453
  }
1450
1454
  }
@@ -1452,7 +1456,7 @@ var MemoryOAuthStateStore = class {
1452
1456
  async find(stateHash) {
1453
1457
  const payload = this.states.get(stateHash);
1454
1458
  if (!payload) return null;
1455
- if (payload.expiresAt.getTime() <= Date.now()) {
1459
+ if (isExpired(payload.expiresAt)) {
1456
1460
  this.states.delete(stateHash);
1457
1461
  return null;
1458
1462
  }
@@ -1465,7 +1469,7 @@ var MemoryOAuthStateStore = class {
1465
1469
  const payload = this.states.get(stateHash);
1466
1470
  if (!payload) return null;
1467
1471
  this.states.delete(stateHash);
1468
- if (payload.expiresAt.getTime() <= Date.now()) return null;
1472
+ if (isExpired(payload.expiresAt)) return null;
1469
1473
  return payload;
1470
1474
  }
1471
1475
  clear() {
@@ -0,0 +1,114 @@
1
+ // src/encryption/Random.ts
2
+ import { randomBytes, randomUUID, randomInt as cryptoRandomInt } from "crypto";
3
+ var CHARSETS = {
4
+ alphanumeric: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
5
+ alphabetic: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
6
+ numeric: "0123456789",
7
+ hex: "0123456789abcdef",
8
+ "base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
9
+ "url-safe": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
10
+ };
11
+ function unbiasedRandomChars(length, chars) {
12
+ if (!Number.isInteger(length) || length < 0) {
13
+ throw new RangeError(`Random string length must be a non-negative integer, received ${length}.`);
14
+ }
15
+ const limit = 256 - 256 % chars.length;
16
+ let result = "";
17
+ while (result.length < length) {
18
+ const remaining = length - result.length;
19
+ const bytes = randomBytes(Math.ceil(remaining * 256 / limit) + 8);
20
+ for (const byte of bytes) {
21
+ if (byte < limit) {
22
+ result += chars[byte % chars.length];
23
+ if (result.length === length) break;
24
+ }
25
+ }
26
+ }
27
+ return result;
28
+ }
29
+ function randomString(length, options = {}) {
30
+ const { charset = "alphanumeric" } = options;
31
+ return unbiasedRandomChars(length, CHARSETS[charset]);
32
+ }
33
+ function random(length) {
34
+ return randomBytes(length);
35
+ }
36
+ function randomHex(length) {
37
+ return randomBytes(length).toString("hex");
38
+ }
39
+ function randomBase64(length) {
40
+ return randomBytes(length).toString("base64");
41
+ }
42
+ function randomBase64Url(length) {
43
+ return randomBytes(length).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
44
+ }
45
+ function uuid() {
46
+ return randomUUID();
47
+ }
48
+ function randomInt(min, max) {
49
+ return cryptoRandomInt(min, max + 1);
50
+ }
51
+ function urlSafeToken(length = 32) {
52
+ return randomBase64Url(Math.ceil(length * 0.75)).slice(0, length);
53
+ }
54
+ function generatePassword(length = 16, options = {}) {
55
+ const {
56
+ uppercase = true,
57
+ lowercase = true,
58
+ numbers = true,
59
+ symbols = true
60
+ } = options;
61
+ let chars = "";
62
+ if (uppercase) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
63
+ if (lowercase) chars += "abcdefghijklmnopqrstuvwxyz";
64
+ if (numbers) chars += "0123456789";
65
+ if (symbols) chars += "!@#$%^&*()-_=+[]{}|;:,.<>?";
66
+ if (chars.length === 0) {
67
+ chars = CHARSETS.alphanumeric;
68
+ }
69
+ return unbiasedRandomChars(length, chars);
70
+ }
71
+ function generateOtp(length = 6) {
72
+ return randomString(length, { charset: "numeric" });
73
+ }
74
+ function generateSlug(length = 10) {
75
+ return randomString(length, { charset: "hex" });
76
+ }
77
+ function shuffle(array) {
78
+ const result = [...array];
79
+ for (let i = result.length - 1; i > 0; i--) {
80
+ const j = randomInt(0, i);
81
+ [result[i], result[j]] = [result[j], result[i]];
82
+ }
83
+ return result;
84
+ }
85
+ function pick(array) {
86
+ if (array.length === 0) {
87
+ throw new Error("Cannot pick from empty array.");
88
+ }
89
+ return array[randomInt(0, array.length - 1)];
90
+ }
91
+ function sample(array, count) {
92
+ if (count > array.length) {
93
+ throw new Error("Sample count exceeds array length.");
94
+ }
95
+ const shuffled = shuffle(array);
96
+ return shuffled.slice(0, count);
97
+ }
98
+
99
+ export {
100
+ randomString,
101
+ random,
102
+ randomHex,
103
+ randomBase64,
104
+ randomBase64Url,
105
+ uuid,
106
+ randomInt,
107
+ urlSafeToken,
108
+ generatePassword,
109
+ generateOtp,
110
+ generateSlug,
111
+ shuffle,
112
+ pick,
113
+ sample
114
+ };