@guren/server 2.19.0 → 2.21.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,114 @@
1
+ //#region src/logging/Logger.ts
2
+ const DEFAULT_FILTER_KEYS = [
3
+ "password",
4
+ "password_confirmation",
5
+ "token",
6
+ "secret",
7
+ "credit_card",
8
+ "creditCard",
9
+ "card_number",
10
+ "cardNumber",
11
+ "cvv",
12
+ "ssn",
13
+ "authorization"
14
+ ];
15
+ /** Recursively replace values of sensitive keys in a log context object. */
16
+ function filterSensitiveData(data, filterKeys, replacement = "[FILTERED]") {
17
+ if (filterKeys.length === 0) return data;
18
+ return filterObject(data, new Set(filterKeys.map((k) => k.toLowerCase())), replacement);
19
+ }
20
+ function filterObject(obj, keySet, replacement) {
21
+ const result = {};
22
+ for (const [key, value] of Object.entries(obj)) if (keySet.has(key.toLowerCase())) result[key] = replacement;
23
+ else if (value !== null && typeof value === "object" && !Array.isArray(value)) result[key] = filterObject(value, keySet, replacement);
24
+ else if (Array.isArray(value)) result[key] = value.map((item) => item !== null && typeof item === "object" && !Array.isArray(item) ? filterObject(item, keySet, replacement) : item);
25
+ else result[key] = value;
26
+ return result;
27
+ }
28
+ const reportLoggingError = (error) => {
29
+ console.error("Logging error:", error);
30
+ };
31
+ /**
32
+ * Whether a channel's `log()` handed back something to wait on. A duck-typed
33
+ * check rather than `instanceof Promise`: a promise created in another realm
34
+ * (a `node:vm` context, a worker's module graph) satisfies the channel
35
+ * contract and would otherwise slip past the reporter as an unhandled rejection.
36
+ */
37
+ function isPromiseLike(value) {
38
+ return typeof value === "object" && value !== null && typeof value.then === "function";
39
+ }
40
+ /** Logger instance for writing log entries. */
41
+ var Logger = class Logger {
42
+ channels;
43
+ baseContext;
44
+ filterKeys;
45
+ replacement;
46
+ constructor(channels, context = {}, options = {}) {
47
+ this.channels = channels;
48
+ this.baseContext = context;
49
+ this.filterKeys = options.filterKeys ?? DEFAULT_FILTER_KEYS;
50
+ this.replacement = options.replacement ?? "[FILTERED]";
51
+ }
52
+ emergency(message, context = {}) {
53
+ this.log("emergency", message, context);
54
+ }
55
+ alert(message, context = {}) {
56
+ this.log("alert", message, context);
57
+ }
58
+ critical(message, context = {}) {
59
+ this.log("critical", message, context);
60
+ }
61
+ error(message, context = {}) {
62
+ this.log("error", message, context);
63
+ }
64
+ warning(message, context = {}) {
65
+ this.log("warning", message, context);
66
+ }
67
+ warn(message, context = {}) {
68
+ this.warning(message, context);
69
+ }
70
+ notice(message, context = {}) {
71
+ this.log("notice", message, context);
72
+ }
73
+ info(message, context = {}) {
74
+ this.log("info", message, context);
75
+ }
76
+ debug(message, context = {}) {
77
+ this.log("debug", message, context);
78
+ }
79
+ log(level, message, context = {}) {
80
+ const merged = {
81
+ ...this.baseContext,
82
+ ...context
83
+ };
84
+ const entry = {
85
+ level,
86
+ message,
87
+ context: this.filterKeys.length > 0 ? filterSensitiveData(merged, this.filterKeys, this.replacement) : merged,
88
+ timestamp: /* @__PURE__ */ new Date()
89
+ };
90
+ for (const channel of this.channels) try {
91
+ const pending = channel.log(entry);
92
+ if (isPromiseLike(pending)) Promise.resolve(pending).catch(reportLoggingError);
93
+ } catch (error) {
94
+ reportLoggingError(error);
95
+ }
96
+ }
97
+ withContext(context) {
98
+ return new Logger(this.channels, {
99
+ ...this.baseContext,
100
+ ...context
101
+ }, {
102
+ filterKeys: this.filterKeys,
103
+ replacement: this.replacement
104
+ });
105
+ }
106
+ child(context) {
107
+ return this.withContext(context);
108
+ }
109
+ async close() {
110
+ for (const channel of this.channels) if (channel.close) await channel.close();
111
+ }
112
+ };
113
+ //#endregion
114
+ export { filterSensitiveData as n, isPromiseLike as r, Logger as t };
@@ -1,2 +1,2 @@
1
- import { $ as buildTokenUrl, A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-DrbFuxoW.js";
1
+ import { $ as buildTokenUrl, A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-CjE2oO50.js";
2
2
  export { API_TOKEN_KEY, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, ScryptHasher, SessionGuard, TokenGuard, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildTokenUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createApiToken, createBearerTokenMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createOAuthManager, createOAuthState, createPasswordResetToken, exchangeOAuthCode, fetchOAuthUserProfile, generateId, generateToken, getApiToken, getApiTokenOrFail, getUserApiTokens, hashToken, isEmailVerified, parseApiToken, parseOAuthRedirectUrl, parsePasswordResetUrl, parseTokenUrl, parseVerificationUrl, readBearerToken, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };
@@ -9,6 +9,7 @@ import type { PasswordHasher } from './PasswordHasher.js';
9
9
  export declare class DefaultHasher implements PasswordHasher {
10
10
  private readonly bun;
11
11
  private readonly node;
12
+ private readonly testing;
12
13
  constructor();
13
14
  hash(plain: string): Promise<string>;
14
15
  verify(hashed: string, plain: string): Promise<boolean>;
@@ -41,6 +41,8 @@ var MemorySessionStore = class {
41
41
  };
42
42
  const DEFAULT_COOKIE_NAME = "guren.session";
43
43
  const DEFAULT_TTL_SECONDS = 7200;
44
+ /** What browsers keep per cookie; a larger one is dropped, which reads as a logout. */
45
+ const DEFAULT_MAX_COOKIE_BYTES = 4096;
44
46
  /**
45
47
  * Read when a middleware is built, not when this module loads: an app that
46
48
  * sets NODE_ENV after importing the framework (tests, some serverless
@@ -239,8 +241,62 @@ function warnAboutMemoryStore(store) {
239
241
  if (!runtime || runtime.emulator === "vercel-dev") return;
240
242
  console.warn(`[guren] Sessions use MemorySessionStore on ${SERVERLESS_RUNTIME_LABELS[runtime.id]}, which shares no memory between requests, so a login is lost on the very next request. Configure a persistent store: DatabaseSessionStore from @guren/core, or a SessionManager whose default store is database- or Redis-backed.`);
241
243
  }
244
+ function keyedTransport(store, signer, ttlSeconds) {
245
+ return {
246
+ async load(cookieValue) {
247
+ const id = signer.verify(cookieValue);
248
+ return id === null ? null : {
249
+ id,
250
+ data: await store.read(id) ?? {}
251
+ };
252
+ },
253
+ async refresh(id, session) {
254
+ if (store.touch) await store.touch(id, ttlSeconds);
255
+ else await store.write(id, session.snapshot(), ttlSeconds);
256
+ return signer.sign(id);
257
+ },
258
+ async persist(id, data, { regeneratedFrom }) {
259
+ await store.write(id, data, ttlSeconds);
260
+ if (regeneratedFrom !== null && regeneratedFrom !== id) await store.destroy(regeneratedFrom);
261
+ return signer.sign(id);
262
+ },
263
+ async discard(id) {
264
+ await store.destroy(id);
265
+ }
266
+ };
267
+ }
268
+ function inlineTransport(codec, ttlSeconds) {
269
+ return {
270
+ async load(cookieValue) {
271
+ return codec.decode(cookieValue);
272
+ },
273
+ async refresh(id, session) {
274
+ return codec.encode(id, session.snapshot(), ttlSeconds);
275
+ },
276
+ async persist(id, data) {
277
+ return codec.encode(id, data, ttlSeconds);
278
+ },
279
+ async discard() {}
280
+ };
281
+ }
282
+ /**
283
+ * What the `Set-Cookie` header will cost, name and attributes included. The
284
+ * browser limit applies to the whole thing, so measuring only the value is how
285
+ * a session passes its own check and is then dropped without a word.
286
+ */
287
+ function assembledCookieBytes(name, value, options, maxAge) {
288
+ const attributes = [
289
+ options.path ? `; Path=${options.path}` : "",
290
+ options.domain ? `; Domain=${options.domain}` : "",
291
+ `; Max-Age=${maxAge}`,
292
+ options.httpOnly ? "; HttpOnly" : "",
293
+ options.secure ? "; Secure" : "",
294
+ options.sameSite ? `; SameSite=${options.sameSite}` : ""
295
+ ].join("");
296
+ return Buffer.byteLength(`${name}=${encodeURIComponent(value)}${attributes}`, "utf8");
297
+ }
242
298
  function createSessionMiddleware(options = {}) {
243
- const { cookieName = DEFAULT_COOKIE_NAME, cookiePath = "/", cookieDomain, cookieSecure = defaultCookieSecure(), cookieSameSite = "Lax", cookieHttpOnly = true, cookieMaxAgeSeconds, ttlSeconds = DEFAULT_TTL_SECONDS, store: storeOrFactory = new MemorySessionStore() } = options;
299
+ const { cookieName = DEFAULT_COOKIE_NAME, cookiePath = "/", cookieDomain, cookieSecure = defaultCookieSecure(), cookieSameSite = "Lax", cookieHttpOnly = true, cookieMaxAgeSeconds, ttlSeconds = DEFAULT_TTL_SECONDS, maxCookieBytes = DEFAULT_MAX_COOKIE_BYTES, store: storeOrFactory = new MemorySessionStore() } = options;
244
300
  const signer = createCookieSigner(cookieName, cookiePath);
245
301
  let checkedStore = false;
246
302
  return async (ctx, next) => {
@@ -249,10 +305,12 @@ function createSessionMiddleware(options = {}) {
249
305
  checkedStore = true;
250
306
  warnAboutMemoryStore(store);
251
307
  }
252
- const existingId = signer.verify(getCookie(ctx, cookieName));
308
+ const transport = store.inline ? inlineTransport(store.inline, ttlSeconds) : keyedTransport(store, signer, ttlSeconds);
309
+ const loaded = await transport.load(getCookie(ctx, cookieName));
310
+ const existingId = loaded?.id ?? null;
253
311
  const sessionId = existingId ?? globalThis.crypto.randomUUID();
254
312
  const isNew = !existingId;
255
- const storedData = existingId ? await store.read(existingId) ?? {} : {};
313
+ const storedData = loaded?.data ?? {};
256
314
  const testingData = resolveTestingSession(ctx);
257
315
  const session = new SessionImpl(sessionId, testingData ? {
258
316
  ...storedData,
@@ -260,45 +318,42 @@ function createSessionMiddleware(options = {}) {
260
318
  } : storedData, isNew);
261
319
  session.ageFlashData();
262
320
  ctx.set(SESSION_CONTEXT_KEY, session);
263
- try {
264
- await next();
265
- } finally {
321
+ await next();
322
+ const cookieOptions = {
323
+ path: cookiePath,
324
+ domain: cookieDomain,
325
+ secure: cookieSecure,
326
+ sameSite: cookieSameSite,
327
+ httpOnly: cookieHttpOnly
328
+ };
329
+ const persistSession = async () => {
266
330
  if (session.wasDestroyed()) {
267
- await store.destroy(session.originalSessionId());
268
- deleteCookie(ctx, cookieName, {
269
- path: cookiePath,
270
- domain: cookieDomain,
271
- secure: cookieSecure,
272
- sameSite: cookieSameSite,
273
- httpOnly: cookieHttpOnly
274
- });
275
- } else if (!session.shouldPersist()) {
276
- if (existingId) {
277
- if (store.touch) await store.touch(existingId, ttlSeconds);
278
- else await store.write(existingId, session.snapshot(), ttlSeconds);
279
- setCookie(ctx, cookieName, signer.sign(existingId), {
280
- path: cookiePath,
281
- domain: cookieDomain,
282
- secure: cookieSecure,
283
- sameSite: cookieSameSite,
284
- httpOnly: cookieHttpOnly,
285
- maxAge: cookieMaxAgeSeconds ?? ttlSeconds
286
- });
287
- }
288
- } else {
289
- const nextId = session.id;
290
- await store.write(nextId, session.snapshot(), ttlSeconds);
291
- if (session.wasRegenerated() && session.originalSessionId() !== nextId) await store.destroy(session.originalSessionId());
292
- setCookie(ctx, cookieName, signer.sign(nextId), {
293
- path: cookiePath,
294
- domain: cookieDomain,
295
- secure: cookieSecure,
296
- sameSite: cookieSameSite,
297
- httpOnly: cookieHttpOnly,
331
+ await transport.discard(session.originalSessionId());
332
+ deleteCookie(ctx, cookieName, cookieOptions);
333
+ return;
334
+ }
335
+ if (!session.shouldPersist()) {
336
+ if (existingId) setCookie(ctx, cookieName, await write(transport.refresh(existingId, session)), {
337
+ ...cookieOptions,
298
338
  maxAge: cookieMaxAgeSeconds ?? ttlSeconds
299
339
  });
340
+ return;
300
341
  }
301
- }
342
+ const nextId = session.id;
343
+ const value = await transport.persist(nextId, session.snapshot(), { regeneratedFrom: session.wasRegenerated() ? session.originalSessionId() : null });
344
+ setCookie(ctx, cookieName, await write(value), {
345
+ ...cookieOptions,
346
+ maxAge: cookieMaxAgeSeconds ?? ttlSeconds
347
+ });
348
+ };
349
+ /** Refuses a value whose `Set-Cookie` would exceed what a browser keeps. */
350
+ const write = async (value) => {
351
+ const resolved = await value;
352
+ const bytes = assembledCookieBytes(cookieName, resolved, cookieOptions, cookieMaxAgeSeconds ?? ttlSeconds);
353
+ if (bytes > maxCookieBytes) throw new Error(`The session cookie would be ${bytes} bytes, over the ${maxCookieBytes}-byte limit browsers keep. A cookie session carries the whole session — keep large or revocable values in the database and only their ids in the session, or raise \`maxCookieBytes\`.`);
354
+ return resolved;
355
+ };
356
+ await persistSession();
302
357
  };
303
358
  }
304
359
  function getSessionFromContext(ctx) {
@@ -582,6 +637,21 @@ var NodeHasher = class {
582
637
  //#endregion
583
638
  //#region src/auth/password/DefaultHasher.ts
584
639
  /**
640
+ * Parameters used while `GUREN_TESTING` is set (by `TestApp` and `guren tool:call --as`).
641
+ * The production defaults cost ~136 ms per hash (Bun 1.3, Apple M-series), the whole
642
+ * 180 ms of every test creating a user; these measure ~1 ms. Verification reads the
643
+ * parameters the hash carries, so a hash written here verifies at that cost anywhere.
644
+ */
645
+ const TESTING_ARGON2_OPTIONS = {
646
+ memoryCost: 1024,
647
+ timeCost: 1
648
+ };
649
+ const TESTING_SCRYPT_COST = 1024;
650
+ /** Read per call, not at construction: the provider owning this hasher is built at boot, and `TestApp` may set the variable later. */
651
+ function testingHashCost() {
652
+ return typeof process !== "undefined" && Boolean(process.env.GUREN_TESTING);
653
+ }
654
+ /**
585
655
  * Runtime-detecting password hasher behind `Hash`, the default for
586
656
  * `AuthenticatableModel` and `ModelUserProvider`: `Bun.password` on Bun (Argon2id,
587
657
  * despite `ScryptHasher`'s name), `crypto.scrypt` otherwise. **Verification routes
@@ -591,18 +661,22 @@ var NodeHasher = class {
591
661
  var DefaultHasher = class {
592
662
  bun;
593
663
  node;
664
+ testing;
594
665
  constructor() {
595
- this.bun = typeof Bun !== "undefined" ? new ScryptHasher() : null;
666
+ const onBun = typeof Bun !== "undefined";
667
+ this.bun = onBun ? new ScryptHasher() : null;
596
668
  this.node = new NodeHasher();
669
+ this.testing = onBun ? new ScryptHasher(TESTING_ARGON2_OPTIONS) : new NodeHasher({ cost: TESTING_SCRYPT_COST });
597
670
  }
598
671
  hash(plain) {
599
- return (this.bun ?? this.node).hash(plain);
672
+ return (testingHashCost() ? this.testing : this.bun ?? this.node).hash(plain);
600
673
  }
601
674
  verify(hashed, plain) {
602
675
  return this.delegateFor(hashed).verify(hashed, plain);
603
676
  }
604
677
  needsRehash(hashed) {
605
678
  if (hashed.startsWith("$scrypt$") !== (this.bun === null)) return true;
679
+ if (!this.testing.needsRehash(hashed)) return !testingHashCost();
606
680
  return this.delegateFor(hashed).needsRehash(hashed);
607
681
  }
608
682
  delegateFor(hashed) {
@@ -1,2 +1,2 @@
1
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-BOOIr324.js";
1
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-thXRnaju.js";
2
2
  export { CacheManager, FileStore, MemoryStore, RedisStore, TaggedCache, createCacheManager };
@@ -45,7 +45,11 @@ export interface MemoryStoreOptions {
45
45
  now?: () => number;
46
46
  }
47
47
  export interface RedisStoreOptions {
48
- /** Redis client instance (ioredis). */
48
+ /**
49
+ * An ioredis client, or a function returning one *synchronously* (ioredis
50
+ * connects lazily on its own). A function runs when the store is first
51
+ * built, so a store declared in `stores` but never selected opens no socket.
52
+ */
49
53
  client: unknown;
50
54
  /** @default 'cache:' */
51
55
  prefix?: string;
@@ -1,8 +1,23 @@
1
+ import { r as isPromiseLike } from "./Logger-DFifRAtc.js";
1
2
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
2
3
  import { createHash } from "node:crypto";
3
- import { mkdir, readFile, readdir, rm, unlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
+ import { mkdir, readFile, readdir, rm, unlink, writeFile } from "node:fs/promises";
5
6
  import { existsSync } from "node:fs";
7
+ //#region src/redis/lazy-client.ts
8
+ /**
9
+ * The one rule for a `client` option that may be an ioredis instance or a
10
+ * function returning one: the function runs here, not where the config object
11
+ * was declared, so a declared-but-unselected store never dials. Cache and
12
+ * session both resolve through it — a second copy is how the two subsystems
13
+ * come to disagree about what `client` accepts.
14
+ */
15
+ function resolveLazyRedisClient(client, label) {
16
+ const resolved = typeof client === "function" ? client() : client;
17
+ if (isPromiseLike(resolved)) throw new Error(`${label}: \`client\` returned a Promise. Return the ioredis client synchronously; it connects lazily on first use.`);
18
+ return resolved;
19
+ }
20
+ //#endregion
6
21
  //#region src/cache/stores/MemoryStore.ts
7
22
  /** In-memory cache store. */
8
23
  var MemoryStore = class {
@@ -131,7 +146,7 @@ var RedisStore = class {
131
146
  client;
132
147
  prefix;
133
148
  constructor(options) {
134
- this.client = options.client;
149
+ this.client = resolveLazyRedisClient(options.client, "Redis cache store");
135
150
  this.prefix = options.prefix ?? "cache:";
136
151
  }
137
152
  prefixKey(key) {
@@ -592,7 +607,7 @@ var CacheManager = class {
592
607
  const cached = this.resolvedStores.get(storeName);
593
608
  if (cached) return cached;
594
609
  const factory = this.storeFactories.get(storeName);
595
- if (!factory) throw new Error(`Cache store not found: ${storeName}`);
610
+ if (!factory) throw new Error(`Cache store not found: ${storeName} (declared: ${this.getStoreNames().join(", ")})`);
596
611
  const raw = factory();
597
612
  this.stopPreviousStore(storeName, raw);
598
613
  const store = new TaggableCacheStoreWrapper(raw);
@@ -630,4 +645,4 @@ function createCacheManager(config) {
630
645
  return new CacheManager(config);
631
646
  }
632
647
  //#endregion
633
- export { RedisStore as a, FileStore as i, createCacheManager as n, MemoryStore as o, TaggedCache as r, CacheManager as t };
648
+ export { RedisStore as a, FileStore as i, createCacheManager as n, MemoryStore as o, TaggedCache as r, resolveLazyRedisClient as s, CacheManager as t };
@@ -1,6 +1,7 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { MiddlewareHandler, ExecutionContext } from 'hono';
3
3
  import { Router } from '../mvc/Router.js';
4
+ import { type PrototypeFixtureLoader } from '../mvc/prototype.js';
4
5
  import { Container, type GurenModule } from '../container/index.js';
5
6
  import { type ServiceProviderConstructor } from '../container/ServiceProvider.js';
6
7
  import { AuthManager } from '../auth/AuthManager.js';
@@ -67,6 +68,12 @@ export interface ApplicationOptions {
67
68
  readonly securityHeaders?: SecurityHeadersOptions | false;
68
69
  /** DNS rebinding protection. Off unless configured; the template configures it. */
69
70
  readonly hostAuthorization?: HostAuthorizationOptions | false;
71
+ /**
72
+ * The fixture module routes registered with the `prototype` handler answer
73
+ * from (RFC 0021): `() => import('../resources/js/prototype/index.js')`.
74
+ * Loaded at boot only when such a route exists.
75
+ */
76
+ readonly prototype?: PrototypeFixtureLoader;
70
77
  }
71
78
  export interface I18nPluginOptions {
72
79
  /** Detection only resolves to one of these; all are preloaded during `boot()`. */
@@ -164,6 +171,14 @@ export declare class Application {
164
171
  /** Matched by exact path — see {@link declareCookielessAuthPath}. */
165
172
  getCookielessAuthPaths(): ReadonlySet<string>;
166
173
  mountRoutes(): Promise<void>;
174
+ /**
175
+ * Every failure here is one a request would otherwise surface as a 500:
176
+ * an unnamed prototype route cannot be looked up, a named one the fixture
177
+ * does not answer, no loader to answer from at all. Process-shared fixture
178
+ * state is a developer's own `bun run dev`, not a deployment, hence the
179
+ * production refusal; `GUREN_PROTOTYPE_ROUTES=1` overrides it deliberately.
180
+ */
181
+ private preparePrototypeRoutes;
167
182
  use(path: string, ...middleware: MiddlewareHandler[]): void;
168
183
  /**
169
184
  * Registers providers, runs the boot callback, mounts routes, boots providers.
@@ -0,0 +1,38 @@
1
+ import { type AppKeyring } from '../../encryption/app-key.js';
2
+ import type { SessionData, SessionStore } from './session.js';
3
+ export interface CookieSessionStoreOptions {
4
+ /** Clock for expiry, injectable for tests. @default Date.now */
5
+ now?: () => number;
6
+ /** Overrides the keyring derived from `APP_KEY` / `APP_PREVIOUS_KEYS`; for tests and direct construction. */
7
+ keyring?: AppKeyring;
8
+ }
9
+ /**
10
+ * The whole session, encrypted inside the cookie under the app key: the one
11
+ * store needing no server-side resource (RFC 0020 §3). Two limits the docs
12
+ * state outright — everything in the session travels in the cookie, so the
13
+ * middleware caps it; and a logout cannot revoke a copy the client already
14
+ * has, so anything revocable belongs in the database with only its id here.
15
+ */
16
+ export declare class CookieSessionStore implements SessionStore {
17
+ private readonly keyring;
18
+ private readonly now;
19
+ constructor(options?: CookieSessionStoreOptions);
20
+ readonly inline: {
21
+ /**
22
+ * `base64url(iv ‖ tag ‖ ciphertext)` rather than `Encrypter`'s envelope,
23
+ * which base64s the ciphertext into JSON and base64s that again: measured
24
+ * 2.27x the plaintext against 1.52x here, and a cookie's budget is this
25
+ * store's whole constraint. Same primitives, same 12-byte IV and 16-byte tag.
26
+ */
27
+ encode: (id: string, data: SessionData, ttlSeconds: number) => string;
28
+ decode: (cookieValue: string | undefined) => {
29
+ id: string;
30
+ data: SessionData;
31
+ } | null;
32
+ };
33
+ private open;
34
+ read(): Promise<SessionData | undefined>;
35
+ write(): Promise<void>;
36
+ destroy(): Promise<void>;
37
+ private keyedStoreError;
38
+ }
@@ -3,9 +3,11 @@ export type Middleware = MiddlewareHandler;
3
3
  export declare function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler;
4
4
  export declare function jsonResponse(data: unknown, status?: number): Response;
5
5
  export { createSessionMiddleware, MemorySessionStore, getSessionFromContext } from './session.js';
6
- export { DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, SessionManager } from './session-manager.js';
7
- export type { SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, MemorySessionDriverOptions, RedisSessionDriverOptions, } from './session-manager.js';
8
- export type { SessionCookieOptions } from './session.js';
6
+ export { BUILT_IN_SESSION_DRIVERS, DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, SessionManager } from './session-manager.js';
7
+ export { CookieSessionStore } from './cookie-session-store.js';
8
+ export type { CookieSessionStoreOptions } from './cookie-session-store.js';
9
+ export type { CookieSessionDriverOptions, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, MemorySessionDriverOptions, RedisSessionDriverOptions, } from './session-manager.js';
10
+ export type { SessionCookieOptions, SessionInlineCodec } from './session.js';
9
11
  export { defaultCookieSecure } from './session.js';
10
12
  export type { Session, SessionData, SessionStore } from './session.js';
11
13
  export { requireAuthenticated, requireGuest, attachAuthContext, type AuthContext, type RequireAuthOptions, } from './auth.js';
@@ -23,6 +23,15 @@ export interface RedisSessionDriverOptions {
23
23
  export interface SessionDrivers {
24
24
  memory: MemorySessionDriverOptions;
25
25
  redis: RedisSessionDriverOptions;
26
+ cookie: CookieSessionDriverOptions;
27
+ }
28
+ /**
29
+ * The cookie driver takes no app-facing options: its key comes from `APP_KEY`
30
+ * and its size budget from the middleware. `keyring` and `now` stay on
31
+ * {@link CookieSessionStoreOptions}, for direct construction in tests — a
32
+ * committed `config/session.ts` is the wrong home for key material.
33
+ */
34
+ export interface CookieSessionDriverOptions {
26
35
  }
27
36
  export type SessionStoreConfig = {
28
37
  [K in keyof SessionDrivers]: {
@@ -32,6 +41,13 @@ export type SessionStoreConfig = {
32
41
  /** The store `SessionConfig.default` names when it names none, and the one driver that shares no state between requests. */
33
42
  export declare const DEFAULT_SESSION_STORE_NAME = "memory";
34
43
  export declare const PER_PROCESS_SESSION_DRIVERS: ReadonlySet<string>;
44
+ /**
45
+ * Every driver the framework itself registers, and whether it survives a
46
+ * runtime that shares no memory between requests. Read by static checks that
47
+ * cannot boot the app; a plugin's driver is declared in its `gurenPlugin`
48
+ * manifest instead, and a name in neither is unverifiable, not absent.
49
+ */
50
+ export declare const BUILT_IN_SESSION_DRIVERS: ReadonlyMap<string, boolean>;
35
51
  /** Cookie and TTL settings plus the named stores one of which is the default. */
36
52
  export interface SessionConfig extends SessionCookieOptions {
37
53
  /** @default 'memory' */
@@ -13,6 +13,22 @@ export interface SessionStore {
13
13
  * session that does not exist must be a no-op, not a resurrection.
14
14
  */
15
15
  touch?(id: string, ttlSeconds: number): Promise<void>;
16
+ /**
17
+ * Present on stores that keep the session *inside* the cookie (RFC 0020 §3).
18
+ * The middleware then writes `encode()`'s value as the cookie instead of a
19
+ * signed id and reads the next request's back through `decode()`, so
20
+ * `read`/`write`/`destroy` are never called: there is no keyed store behind it.
21
+ */
22
+ inline?: SessionInlineCodec;
23
+ }
24
+ export interface SessionInlineCodec {
25
+ /** Throws when the session cannot fit the cookie, rather than emitting one a browser drops. */
26
+ encode(id: string, data: SessionData, ttlSeconds: number): string;
27
+ /** Null for a missing, expired, tampered, or undecryptable cookie. */
28
+ decode(cookieValue: string | undefined): {
29
+ id: string;
30
+ data: SessionData;
31
+ } | null;
16
32
  }
17
33
  export declare class MemorySessionStore implements SessionStore {
18
34
  private readonly now;
@@ -35,6 +51,12 @@ export interface SessionCookieOptions {
35
51
  ttlSeconds?: number;
36
52
  }
37
53
  export interface SessionOptions extends SessionCookieOptions {
54
+ /**
55
+ * Bytes the whole `Set-Cookie` may occupy before the middleware refuses it.
56
+ * Browsers drop a larger one, and a dropped session cookie is a silent logout.
57
+ * @default 4096
58
+ */
59
+ maxCookieBytes?: number;
38
60
  /**
39
61
  * The store, or a function returning it, called on every request and never
40
62
  * at construction: a Workers binding does not exist before the first request
@@ -1,2 +1,2 @@
1
- import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "../i18n-Cg1aajRP.js";
1
+ import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "../i18n-BZ2VrSud.js";
2
2
  export { I18nManager, JsonLoader, MemoryLoader, Translator, createI18n, getI18n, getPluralizationRule, pluralizationRules, selectPluralForm, setI18n, t, tc, tryGetI18n };
package/dist/index.d.ts CHANGED
@@ -10,6 +10,8 @@ export type { ContentfulStatusCode } from 'hono/utils/http-status';
10
10
  export { viteAsset } from './http/vite-assets.js';
11
11
  export type { ViteAssetOptions } from './http/vite-assets.js';
12
12
  export { Router } from './mvc/Router.js';
13
+ export { prototype } from './mvc/prototype.js';
14
+ export type { PrototypeFixture, PrototypeFixtureLoader, PrototypeResult, PrototypeRouteHandler, PrototypeServerContext, } from './mvc/prototype.js';
13
15
  export type { BindableModel, AgentRouteMetadata, RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteModelBinding, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
14
16
  export { deriveAgentTools } from './agent/derive.js';
15
17
  export type { AgentToolInputSource, AgentToolSchema, DeriveAgentToolsResult, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, } from './agent/derive.js';
@@ -43,9 +45,9 @@ export { InertiaServiceProvider, AuthServiceProvider, OAuthServiceProvider, Even
43
45
  export { FormRequest } from './http/FormRequest.js';
44
46
  export { AuthManager, SessionGuard, TokenGuard, ModelUserProvider, BaseUserProvider, AuthenticatableModel, ScryptHasher, createPasswordResetToken, verifyPasswordResetToken, completePasswordReset, buildPasswordResetUrl, parsePasswordResetUrl, MemoryPasswordResetStore, createEmailVerificationToken, verifyEmailToken, completeEmailVerification, buildVerificationUrl, parseVerificationUrl, isEmailVerified, requireVerifiedEmail, MemoryEmailVerificationStore, createApiToken, parseApiToken, readBearerToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, OAuthManager, MemoryOAuthStateStore, createOAuthManager, createOAuthState, verifyOAuthState, sanitizeOAuthRedirect, OAUTH_SESSION_BINDING_KEY, buildOAuthAuthorizeUrl, exchangeOAuthCode, fetchOAuthUserProfile, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createDiscordOAuthProviderConfig, buildOAuthRedirectUrl, parseOAuthRedirectUrl, } from './auth/index.js';
45
47
  export type { AuthContext as AuthRuntimeContext, AuthCredentials, AuthManagerOptions, Authenticatable, Guard, GuardContext, GuardFactory, UserProvider, ProviderFactory, DefaultSanitizedKeys, Sanitized, PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, ApiToken, ApiTokenGuardOptions, ApiTokenStore, CreateApiTokenOptions, CreateApiTokenResult, BearerTokenMiddlewareOptions, VerifiedApiToken, TokenGuardOptions, OAuthProviderConfig, OAuthTokenResult, OAuthUserProfile, OAuthFallbackEmail, OAuthStatePayload, OAuthStateStore, OAuthStateConfig, OAuthAuthorizeOptions, OAuthCallbackPayload, OAuthManagerOptions, OAuthProviderFactoryInput, OAuthBindingSession, } from './auth/index.js';
46
- export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, getSessionFromContext, requireAuthenticated, requireGuest, attachAuthContext, createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
48
+ export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, CookieSessionStore, DEFAULT_SESSION_STORE_NAME, BUILT_IN_SESSION_DRIVERS, PER_PROCESS_SESSION_DRIVERS, getSessionFromContext, requireAuthenticated, requireGuest, attachAuthContext, createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
47
49
  export { AUTH_CONTEXT_KEY } from './http/middleware/auth.js';
48
- export type { Middleware, Session, SessionData, SessionStore, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, SessionCookieOptions, MemorySessionDriverOptions, RedisSessionDriverOptions, AuthContext, RequireAuthOptions, CsrfOptions, CookielessAuthEndpoints, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';
50
+ export type { Middleware, Session, SessionData, SessionStore, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, SessionCookieOptions, SessionInlineCodec, CookieSessionStoreOptions, CookieSessionDriverOptions, MemorySessionDriverOptions, RedisSessionDriverOptions, AuthContext, RequireAuthOptions, CsrfOptions, CookielessAuthEndpoints, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';
49
51
  export { Validator, FieldValidator, createValidator, quickValidate, quickValidateOrThrow, required, nullable, requiredIf, requiredUnless, requiredWith, requiredWithout, string as stringRule, numeric, integer, boolean as booleanRule, array as arrayRule, object as objectRule, email as emailRule, url as urlRule, uuid as uuidRule, ip, ipv4, ipv6, json as jsonRule, alpha, alphaNum, alphaDash, regex, min, max, between, size, inValues, notIn, confirmed, same, different, date as dateRule, dateFormat, after, afterOrEqual, before, beforeOrEqual, startsWith, endsWith, file as fileRule, image as imageRule, mimes, maxFileSize, minFileSize, custom, unique, exists, } from './http/validation/index.js';
50
52
  export type { ValidationRule, RuleDefinition, ValidationResult, FileValidationOptions, ImageValidationOptions, ValidatorOptions, FileLike, } from './http/validation/index.js';
51
53
  export { Event, EventManager, createEventManager, Listener, RequestReceived, RequestFinished, UserAuthenticated, UserLoggedOut, JobProcessed, JobFailed, ApplicationStarted, ApplicationShutdown, } from './events/index.js';