@guren/server 2.13.0 → 2.15.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 (68) hide show
  1. package/dist/{Hash-CzrwKeDp.js → Hash-C8aejmi8.js} +5 -0
  2. package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
  3. package/dist/agent/AgentApprovalRequested.d.ts +59 -0
  4. package/dist/agent/approval.d.ts +295 -0
  5. package/dist/agent/audit-emitter.d.ts +64 -0
  6. package/dist/agent/audit.d.ts +103 -0
  7. package/dist/agent/derive.d.ts +155 -0
  8. package/dist/agent/dispatch.d.ts +165 -0
  9. package/dist/agent/events.d.ts +80 -0
  10. package/dist/agent/meta-tools.d.ts +62 -0
  11. package/dist/agent/public.d.ts +33 -0
  12. package/dist/agent/public.js +2 -0
  13. package/dist/agent/redact.d.ts +55 -0
  14. package/dist/agent/scopes.d.ts +115 -0
  15. package/dist/auth/AuthManager.d.ts +64 -0
  16. package/dist/auth/RequestAuthContext.d.ts +3 -5
  17. package/dist/auth/TokenGuard.d.ts +61 -0
  18. package/dist/auth/api-token.d.ts +25 -5
  19. package/dist/auth/context.d.ts +24 -0
  20. package/dist/auth/index.d.ts +5 -2
  21. package/dist/auth/index.js +2 -2
  22. package/dist/auth/password/DefaultHasher.d.ts +18 -5
  23. package/dist/auth/password/PasswordHasher.d.ts +15 -0
  24. package/dist/auth/password/hash-format.d.ts +19 -0
  25. package/dist/auth/providers/UserProvider.d.ts +7 -0
  26. package/dist/auth/types.d.ts +6 -0
  27. package/dist/{auth-C7sVmYgc.js → auth-DkYoAPVn.js} +431 -151
  28. package/dist/authorization/index.js +1 -1
  29. package/dist/authorization/middleware.d.ts +28 -1
  30. package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
  31. package/dist/broadcasting/index.js +1 -1
  32. package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BwodCA4q.js} +2 -45
  33. package/dist/container/bindings.d.ts +19 -0
  34. package/dist/context-DoD0c7J_.js +26 -0
  35. package/dist/dispatch-erOS9epZ.js +285 -0
  36. package/dist/encryption/index.js +2 -2
  37. package/dist/{encryption-DJtkkhiw.js → encryption-D99Vmls3.js} +4 -1
  38. package/dist/http/dev-assets.d.ts +16 -0
  39. package/dist/http/middleware/auth.d.ts +2 -2
  40. package/dist/http/middleware/capabilities.d.ts +57 -0
  41. package/dist/http/middleware/csrf.d.ts +3 -0
  42. package/dist/http/public-assets.d.ts +10 -0
  43. package/dist/http/request.d.ts +139 -3
  44. package/dist/http/static-documents.d.ts +31 -0
  45. package/dist/index.d.ts +21 -4
  46. package/dist/index.js +1302 -118
  47. package/dist/internal/agent-preflight.d.ts +28 -0
  48. package/dist/internal/request.d.ts +25 -0
  49. package/dist/internal/request.js +2 -0
  50. package/dist/internal/route-path.d.ts +28 -0
  51. package/dist/internal/route-path.js +33 -0
  52. package/dist/internal/zod-compat.d.ts +201 -0
  53. package/dist/internal/zod-compat.js +193 -0
  54. package/dist/internal/zod-json-schema.d.ts +102 -0
  55. package/dist/internal/zod-json-schema.js +461 -0
  56. package/dist/logging/channels/DailyFileChannel.d.ts +0 -2
  57. package/dist/logging/daily-file-path.d.ts +24 -0
  58. package/dist/logging/index.d.ts +1 -0
  59. package/dist/logging/index.js +2 -2
  60. package/dist/{logging-CPaRMuPP.js → logging-B-kngi3q.js} +61 -18
  61. package/dist/mcp/create-mcp-server.d.ts +29 -0
  62. package/dist/mcp/index.js +1 -1
  63. package/dist/mvc/Controller.d.ts +20 -0
  64. package/dist/mvc/Router.d.ts +53 -0
  65. package/dist/request-CVQwpu2J.js +129 -0
  66. package/dist/runtime/index.js +94 -15
  67. package/dist/{vite-manifest-gdONBsM3.js → vite-manifest-w_RSOvQW.js} +1 -1
  68. package/package.json +22 -2
@@ -1,7 +1,8 @@
1
1
  import { t as HttpException } from "./HttpException-BkS3euNG.js";
2
2
  import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
3
- import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-CzrwKeDp.js";
3
+ import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-C8aejmi8.js";
4
4
  import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
5
+ import { n as getAuthContext } from "./context-DoD0c7J_.js";
5
6
  import { deleteCookie, getCookie, setCookie } from "hono/cookie";
6
7
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
7
8
  import { Model } from "@guren/orm";
@@ -323,23 +324,20 @@ var AuthenticationException = class AuthenticationException extends HttpExceptio
323
324
  //#endregion
324
325
  //#region src/auth/RequestAuthContext.ts
325
326
  var RequestAuthContext = class {
326
- manager;
327
+ resolveName;
327
328
  ctx;
328
329
  resolveSession;
329
330
  resolveGuard;
330
331
  guardCache = /* @__PURE__ */ new Map();
331
- constructor(manager, ctx, resolveSession, resolveGuard) {
332
- this.manager = manager;
332
+ constructor(resolveName, ctx, resolveSession, resolveGuard) {
333
+ this.resolveName = resolveName;
333
334
  this.ctx = ctx;
334
335
  this.resolveSession = resolveSession;
335
336
  this.resolveGuard = resolveGuard;
336
337
  }
337
338
  guard(name) {
338
- const key = name ?? this.manager.getDefaultGuard();
339
- if (!this.guardCache.has(key)) {
340
- const guard = this.resolveGuard(name);
341
- this.guardCache.set(key, guard);
342
- }
339
+ const key = this.resolveName(name);
340
+ if (!this.guardCache.has(key)) this.guardCache.set(key, this.resolveGuard(key));
343
341
  return this.guardCache.get(key);
344
342
  }
345
343
  session() {
@@ -372,6 +370,49 @@ var RequestAuthContext = class {
372
370
  await this.guard().logout();
373
371
  }
374
372
  };
373
+ /**
374
+ * Prefixes of every hash format the built-in hashers produce: Bun's argon2
375
+ * family (`$argon2id$`, `$argon2i$`, `$argon2d$`), bcrypt (`$2a$`, `$2b$`,
376
+ * `$2y$`), and the Node fallback's scrypt.
377
+ *
378
+ * This is a *shape* test, not a validity test. It answers "could this string
379
+ * be a password hash at all", which is all the argument-order check below
380
+ * needs; whether the hash is well-formed stays the implementation's job.
381
+ *
382
+ * Full prefixes rather than the `$argon2` / `$2` stems they share: a password
383
+ * of `$2fast4u` is not bcrypt, and treating it as one turns a correct call
384
+ * against a non-hash credential column into a false accusation.
385
+ */
386
+ const HASH_PREFIXES = [
387
+ "$argon2id$",
388
+ "$argon2i$",
389
+ "$argon2d$",
390
+ "$2a$",
391
+ "$2b$",
392
+ "$2y$",
393
+ "$scrypt$"
394
+ ];
395
+ function looksLikePasswordHash(value) {
396
+ return HASH_PREFIXES.some((prefix) => value.startsWith(prefix));
397
+ }
398
+ /**
399
+ * Throws when `verify()` was called as `verify(plain, hashed)`.
400
+ *
401
+ * Two-sided on purpose: it fires only when the second argument looks like a
402
+ * hash *and* the first does not. A one-sided "the first argument must look
403
+ * like a hash" precondition would misdiagnose a legitimate non-hash
404
+ * credential column - `passwordHash: 'oauth:...'`, the sentinel this repo
405
+ * documents for OAuth-only accounts - as a caller mistake. Those keep falling
406
+ * through to the implementation, which rejects them as before.
407
+ *
408
+ * Neither argument is included in the message: one of them is a plaintext
409
+ * password, and this throw is reached on a live login attempt.
410
+ *
411
+ * See `PasswordHasher.verify` for why the order is easy to get wrong.
412
+ */
413
+ function assertVerifyArgumentOrder(hashed, plain) {
414
+ if (!looksLikePasswordHash(hashed) && looksLikePasswordHash(plain)) throw new TypeError("PasswordHasher.verify(hashed, plain) received its arguments in the wrong order: the second argument looks like a password hash and the first does not. Note this order is the inverse of Bun.password.verify(plain, hashed) and of verifyPassword(plain, hashed).");
415
+ }
375
416
  //#endregion
376
417
  //#region src/auth/password/ScryptHasher.ts
377
418
  var ScryptHasher = class {
@@ -397,6 +438,7 @@ var ScryptHasher = class {
397
438
  });
398
439
  }
399
440
  async verify(hashed, plain) {
441
+ assertVerifyArgumentOrder(hashed, plain);
400
442
  return Bun.password.verify(plain, hashed);
401
443
  }
402
444
  needsRehash(hashed) {
@@ -425,7 +467,87 @@ var ScryptHasher = class {
425
467
  }
426
468
  };
427
469
  //#endregion
470
+ //#region src/auth/password/NodeHasher.ts
471
+ /**
472
+ * Node.js-compatible password hasher using crypto.scrypt.
473
+ * Use this instead of ScryptHasher when deploying to non-Bun runtimes (e.g. AWS Lambda).
474
+ */
475
+ var NodeHasher = class {
476
+ options;
477
+ constructor(options = {}) {
478
+ this.options = {
479
+ cost: options.cost,
480
+ memory: options.memory,
481
+ saltLength: options.saltLength,
482
+ keyLength: options.keyLength
483
+ };
484
+ }
485
+ async hash(plain) {
486
+ return hashPassword(plain, this.options);
487
+ }
488
+ async verify(hashed, plain) {
489
+ assertVerifyArgumentOrder(hashed, plain);
490
+ return verifyPassword(plain, hashed);
491
+ }
492
+ needsRehash(hashed) {
493
+ return needsRehash(hashed, this.options);
494
+ }
495
+ };
496
+ //#endregion
497
+ //#region src/auth/password/DefaultHasher.ts
498
+ /**
499
+ * Runtime-detecting password hasher: hashes with `Bun.password` when running
500
+ * on Bun (Argon2id by default, despite `ScryptHasher`'s name) and with Node's
501
+ * `crypto.scrypt` otherwise (e.g. AWS Lambda or Cloudflare Workers). This is
502
+ * the hasher behind the `Hash` export, and the default for
503
+ * `AuthenticatableModel` and `ModelUserProvider`.
504
+ *
505
+ * **Verification routes on the stored hash, not on the runtime.** The two
506
+ * delegates write different formats, and neither can read the other's, so
507
+ * picking a delegate by runtime alone would 500 on every login for an app
508
+ * whose password column was written elsewhere - a seeder run on Bun against a
509
+ * database a Node deploy then serves. Bun implements `node:crypto`, so a
510
+ * `$scrypt$` hash verifies on either runtime; an Argon2id or bcrypt hash needs
511
+ * `Bun.password` and cannot be read off Bun at all, which this reports as
512
+ * itself rather than as an opaque parse failure.
513
+ */
514
+ var DefaultHasher = class {
515
+ bun;
516
+ node;
517
+ constructor() {
518
+ this.bun = typeof Bun !== "undefined" ? new ScryptHasher() : null;
519
+ this.node = new NodeHasher();
520
+ }
521
+ hash(plain) {
522
+ return (this.bun ?? this.node).hash(plain);
523
+ }
524
+ verify(hashed, plain) {
525
+ return this.delegateFor(hashed).verify(hashed, plain);
526
+ }
527
+ needsRehash(hashed) {
528
+ if (hashed.startsWith("$scrypt$") !== (this.bun === null)) return true;
529
+ return this.delegateFor(hashed).needsRehash(hashed);
530
+ }
531
+ delegateFor(hashed) {
532
+ if (hashed.startsWith("$scrypt$")) return this.node;
533
+ if (!this.bun) {
534
+ if (!looksLikePasswordHash(hashed)) throw new Error("This value is not a password hash in any format the built-in hashers produce, so it cannot be verified. A credential column holding a sentinel for a passwordless account should not reach verify().");
535
+ throw new Error("This password hash was written by Bun.password (Argon2id or bcrypt) and cannot be verified on a runtime without Bun. Hash formats follow the runtime that wrote them, so a column seeded under Bun has to be rehashed before a Node or Workers deploy can read it.");
536
+ }
537
+ return this.bun;
538
+ }
539
+ };
540
+ //#endregion
428
541
  //#region src/auth/providers/UserProvider.ts
542
+ /**
543
+ * Run a user record through the provider's optional `sanitize` before it
544
+ * leaves the auth layer. Every guard must call this on anything it returns
545
+ * from `user()` — a guard that forgets the optional-chaining ternary leaks
546
+ * password hashes, so the ternary lives here, once.
547
+ */
548
+ function sanitizeUser(provider, user) {
549
+ return provider.sanitize ? provider.sanitize(user) : user;
550
+ }
429
551
  var BaseUserProvider = class {
430
552
  async setRememberToken(user, token) {
431
553
  if (typeof user.setRememberToken === "function") await user.setRememberToken(token);
@@ -464,7 +586,7 @@ var ModelUserProvider = class extends BaseUserProvider {
464
586
  this.usernameColumn = options.usernameColumn ?? "email";
465
587
  this.passwordColumn = options.passwordColumn ?? authModel?.resolvePasswordHashField() ?? "passwordHash";
466
588
  this.rememberTokenColumn = options.rememberTokenColumn ?? authModel?.resolveRememberTokenField() ?? "rememberToken";
467
- this.hasher = options.hasher ?? new ScryptHasher();
589
+ this.hasher = options.hasher ?? new DefaultHasher();
468
590
  this.credentialsPasswordField = options.credentialsPasswordField ?? "password";
469
591
  }
470
592
  cast(record) {
@@ -490,7 +612,7 @@ var ModelUserProvider = class extends BaseUserProvider {
490
612
  const plain = credentials[this.credentialsPasswordField];
491
613
  if (typeof plain !== "string") return false;
492
614
  const hashed = user[this.passwordColumn];
493
- if (typeof hashed !== "string") {
615
+ if (typeof hashed !== "string" || !looksLikePasswordHash(hashed)) {
494
616
  await this.hasher.hash("dummy-timing-equalization");
495
617
  return false;
496
618
  }
@@ -645,7 +767,7 @@ var SessionGuard = class {
645
767
  }
646
768
  /** Strip auth-internal fields before a record is cached or exposed. */
647
769
  sanitizeUser(user) {
648
- return this.provider.sanitize ? this.provider.sanitize(user) : user;
770
+ return sanitizeUser(this.provider, user);
649
771
  }
650
772
  async resolveUser() {
651
773
  if (this.cachedUser !== void 0) return this.cachedUser;
@@ -728,113 +850,6 @@ var SessionGuard = class {
728
850
  }
729
851
  };
730
852
  //#endregion
731
- //#region src/auth/AuthManager.ts
732
- const DEFAULT_GUARD = "web";
733
- var AuthManager = class {
734
- guards = /* @__PURE__ */ new Map();
735
- providers = /* @__PURE__ */ new Map();
736
- defaultGuard;
737
- constructor(options = {}) {
738
- this.defaultGuard = options.defaultGuard ?? DEFAULT_GUARD;
739
- }
740
- registerGuard(name, factory) {
741
- this.guards.set(name, { factory });
742
- }
743
- registerProvider(name, factory) {
744
- this.providers.set(name, { factory });
745
- }
746
- getProvider(name) {
747
- const entry = this.providers.get(name);
748
- if (!entry) throw new Error(`AuthManager: provider "${name}" has not been registered.`);
749
- if (!entry.instance) {
750
- entry.instance = entry.factory(this);
751
- this.providers.set(name, entry);
752
- }
753
- return entry.instance;
754
- }
755
- createGuard(name, context) {
756
- const entry = this.guards.get(name);
757
- if (!entry) throw new Error(`AuthManager: guard "${name}" has not been registered.`);
758
- return entry.factory(context);
759
- }
760
- guardNames() {
761
- return Array.from(this.guards.keys());
762
- }
763
- setDefaultGuard(name) {
764
- if (!this.guards.has(name)) throw new Error(`AuthManager: cannot set default guard to unregistered guard "${name}".`);
765
- this.defaultGuard = name;
766
- }
767
- getDefaultGuard() {
768
- return this.defaultGuard;
769
- }
770
- createAuthContext(ctx, options = {}) {
771
- const guardName = options.guard ?? this.defaultGuard;
772
- const resolveSession = () => getSessionFromContext(ctx);
773
- const guardFactory = (name) => {
774
- const targetName = name ?? guardName;
775
- return this.createGuard(targetName, {
776
- ctx,
777
- session: resolveSession(),
778
- manager: this
779
- });
780
- };
781
- return new RequestAuthContext(this, ctx, resolveSession, guardFactory);
782
- }
783
- async attempt(name, ctx, credentials, remember) {
784
- return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
785
- }
786
- /**
787
- * Shorthand method to register a model-based authentication provider and session guard.
788
- * This simplifies the common case of authenticating users via a database model.
789
- *
790
- * @param model - The model class to use for user authentication
791
- * @param options - Options for the ModelUserProvider (partial, with defaults)
792
- * @param providerName - Name for the provider (defaults to 'users')
793
- * @param guardName - Name for the guard (defaults to 'web')
794
- */
795
- useModel(model, options = {}, providerName = "users", guardName = "web") {
796
- const defaultOptions = {
797
- usernameColumn: "email",
798
- credentialsPasswordField: "password",
799
- hasher: new ScryptHasher(),
800
- ...options
801
- };
802
- this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
803
- this.registerGuard(guardName, ({ session, manager }) => {
804
- return new SessionGuard({
805
- provider: manager.getProvider(providerName),
806
- session
807
- });
808
- });
809
- this.setDefaultGuard(guardName);
810
- }
811
- };
812
- //#endregion
813
- //#region src/support/redirect-target.ts
814
- /**
815
- * Shared open-redirect classification primitives, used by both the
816
- * redirect-safety middleware and the OAuth `redirectTo` sanitizer. Keep every
817
- * hardening fix here so the two layers cannot drift.
818
- */
819
- /** Normalize backslash tricks (e.g. `/\evil.com`) before classifying. */
820
- function normalizeRedirectTarget(value) {
821
- return value.replace(/\\/g, "/");
822
- }
823
- /** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
824
- function isAppRelativePath(value) {
825
- return value.startsWith("/") && !value.startsWith("//");
826
- }
827
- /** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
828
- function hostMatchesAllowlist(target, allowedHosts) {
829
- const hostname = target.hostname.toLowerCase();
830
- const host = target.host.toLowerCase();
831
- for (const allowed of allowedHosts) if (allowed.startsWith("*.")) {
832
- const suffix = allowed.slice(1).toLowerCase();
833
- if (hostname.endsWith(suffix) && hostname.length > suffix.length) return true;
834
- } else if (host === allowed.toLowerCase()) return true;
835
- return false;
836
- }
837
- //#endregion
838
853
  //#region src/auth/api-token.ts
839
854
  /**
840
855
  * In-memory token store for testing.
@@ -940,6 +955,27 @@ function parseApiToken(plainTextToken) {
940
955
  };
941
956
  }
942
957
  /**
958
+ * Extract the bearer token from an Authorization header value. The one
959
+ * parsing rule shared by `createBearerTokenMiddleware`, `TokenGuard`, and
960
+ * `hasBearerHeader` below — three readers of the same header must not
961
+ * disagree about what a bearer request is.
962
+ */
963
+ function readBearerToken(header) {
964
+ if (!header) return null;
965
+ const match = header.match(/^Bearer\s+(.+)$/i);
966
+ return match ? match[1] : null;
967
+ }
968
+ /**
969
+ * The one answer to "is this request bearer-authenticated?" — the parsing
970
+ * rule above applied to the header it is read from. Shared by guard selection
971
+ * (`AuthManager.resolveGuardName`) and the CSRF skip for cookie-less bearer
972
+ * requests: both must classify a request identically, and a second copy of
973
+ * the header name is how they would drift apart.
974
+ */
975
+ function hasBearerHeader(ctx) {
976
+ return readBearerToken(ctx.req.header("Authorization")) !== null;
977
+ }
978
+ /**
943
979
  * Verify an API token and return the associated user ID.
944
980
  *
945
981
  * @example
@@ -1061,12 +1097,11 @@ function createBearerTokenMiddleware(options) {
1061
1097
  if (onUnauthorized) return onUnauthorized(ctx);
1062
1098
  return ctx.json({ error: "Authentication required" }, 401);
1063
1099
  }
1064
- const match = authHeader.match(/^Bearer\s+(.+)$/i);
1065
- if (!match) {
1100
+ const plainTextToken = readBearerToken(authHeader);
1101
+ if (!plainTextToken) {
1066
1102
  if (onUnauthorized) return onUnauthorized(ctx);
1067
1103
  return ctx.json({ error: "Invalid authorization format" }, 401);
1068
1104
  }
1069
- const plainTextToken = match[1];
1070
1105
  const result = await verifyApiToken(plainTextToken, store, { updateLastUsed });
1071
1106
  if (!result) {
1072
1107
  if (onUnauthorized) return onUnauthorized(ctx);
@@ -1122,6 +1157,277 @@ function getApiTokenOrFail(ctx) {
1122
1157
  return result;
1123
1158
  }
1124
1159
  //#endregion
1160
+ //#region src/auth/TokenGuard.ts
1161
+ /**
1162
+ * Bearer-token implementation of the Guard contract (RFC 0016 Phase 0).
1163
+ *
1164
+ * Reads `Authorization: Bearer <token>`, verifies it against the configured
1165
+ * ApiTokenStore, and exposes the result through the same Guard surface the
1166
+ * SessionGuard implements — so `requireAuthenticated()`, `Controller.auth`,
1167
+ * and Gate resolution treat session- and token-authenticated requests
1168
+ * identically. On successful verification the result is also written to
1169
+ * `ctx[API_TOKEN_KEY]`, keeping `getApiToken(ctx)` and `tokenCan*` working
1170
+ * exactly as they do behind `createBearerTokenMiddleware` — and when that
1171
+ * middleware already verified this request's token, the guard reuses its
1172
+ * result instead of paying a second store read and lastUsedAt write.
1173
+ *
1174
+ * Credential flows do not apply to bearer tokens: `attempt()`, `login()` and
1175
+ * `validate()` throw. `logout()` is not a no-op — it revokes the presented
1176
+ * token, the closest meaningful analogue to ending a session. On a request
1177
+ * that carries a session cookie *and* a Bearer header, only the token is
1178
+ * revoked; end the session explicitly via `auth.guard('web').logout()`.
1179
+ *
1180
+ * This guard answers authentication only. Token *abilities* are not
1181
+ * consulted here or by Gate/policies — enforce them where the operation is
1182
+ * dispatched (`tokenCan*`, `createBearerTokenMiddleware({ abilities })`, or
1183
+ * the RFC 0016 scope gate), per the RFC's scope-before-policy layering.
1184
+ */
1185
+ var TokenGuard = class {
1186
+ ctx;
1187
+ store;
1188
+ provider;
1189
+ updateLastUsed;
1190
+ verification;
1191
+ resolvedUser;
1192
+ constructor(options) {
1193
+ this.ctx = options.ctx;
1194
+ this.store = options.store;
1195
+ this.provider = options.provider;
1196
+ this.updateLastUsed = options.updateLastUsed ?? true;
1197
+ }
1198
+ verify() {
1199
+ if (!this.verification) this.verification = (async () => {
1200
+ const plainTextToken = readBearerToken(this.ctx.req.header("Authorization"));
1201
+ if (!plainTextToken) return null;
1202
+ const existing = this.ctx.get(API_TOKEN_KEY);
1203
+ if (existing && existing.token.id === parseApiToken(plainTextToken)?.id) return existing;
1204
+ const result = await verifyApiToken(plainTextToken, this.store, { updateLastUsed: this.updateLastUsed });
1205
+ if (result) this.ctx.set(API_TOKEN_KEY, result);
1206
+ return result;
1207
+ })();
1208
+ return this.verification;
1209
+ }
1210
+ async check() {
1211
+ return await this.user() !== null;
1212
+ }
1213
+ async guest() {
1214
+ return !await this.check();
1215
+ }
1216
+ user() {
1217
+ if (!this.resolvedUser) this.resolvedUser = (async () => {
1218
+ const result = await this.verify();
1219
+ if (!result) return null;
1220
+ if (!this.provider) return { id: result.userId };
1221
+ const record = await this.provider.retrieveById(result.userId);
1222
+ return record ? sanitizeUser(this.provider, record) : null;
1223
+ })();
1224
+ return this.resolvedUser;
1225
+ }
1226
+ async id() {
1227
+ return (await this.verify())?.userId ?? null;
1228
+ }
1229
+ async login() {
1230
+ throw new Error("TokenGuard does not support login(); issue a token with createApiToken() instead.");
1231
+ }
1232
+ async attempt(_credentials, _remember) {
1233
+ throw new Error("TokenGuard does not support attempt(); bearer tokens are not credential-based.");
1234
+ }
1235
+ async validate(_credentials) {
1236
+ throw new Error("TokenGuard does not support validate(); bearer tokens are not credential-based.");
1237
+ }
1238
+ /** Revokes the presented token. Subsequent requests with it fail verification. */
1239
+ async logout() {
1240
+ const result = await this.verify();
1241
+ if (result) await revokeApiToken(result.token.id, this.store);
1242
+ this.verification = Promise.resolve(null);
1243
+ this.resolvedUser = Promise.resolve(null);
1244
+ this.ctx.set(API_TOKEN_KEY, void 0);
1245
+ }
1246
+ session() {}
1247
+ };
1248
+ //#endregion
1249
+ //#region src/auth/AuthManager.ts
1250
+ const DEFAULT_GUARD = "web";
1251
+ var AuthManager = class {
1252
+ guards = /* @__PURE__ */ new Map();
1253
+ providers = /* @__PURE__ */ new Map();
1254
+ defaultGuard;
1255
+ tokenGuard = null;
1256
+ apiTokenStore = null;
1257
+ apiTokenOptions = {};
1258
+ constructor(options = {}) {
1259
+ this.defaultGuard = options.defaultGuard ?? DEFAULT_GUARD;
1260
+ }
1261
+ registerGuard(name, factory) {
1262
+ this.guards.set(name, { factory });
1263
+ }
1264
+ registerProvider(name, factory) {
1265
+ this.providers.set(name, { factory });
1266
+ }
1267
+ getProvider(name) {
1268
+ const entry = this.providers.get(name);
1269
+ if (!entry) throw new Error(`AuthManager: provider "${name}" has not been registered.`);
1270
+ if (!entry.instance) {
1271
+ entry.instance = entry.factory(this);
1272
+ this.providers.set(name, entry);
1273
+ }
1274
+ return entry.instance;
1275
+ }
1276
+ createGuard(name, context) {
1277
+ const entry = this.guards.get(name);
1278
+ if (!entry) throw new Error(`AuthManager: guard "${name}" has not been registered.`);
1279
+ return entry.factory(context);
1280
+ }
1281
+ guardNames() {
1282
+ return Array.from(this.guards.keys());
1283
+ }
1284
+ setDefaultGuard(name) {
1285
+ if (!this.guards.has(name)) throw new Error(`AuthManager: cannot set default guard to unregistered guard "${name}".`);
1286
+ this.defaultGuard = name;
1287
+ }
1288
+ getDefaultGuard() {
1289
+ return this.defaultGuard;
1290
+ }
1291
+ /**
1292
+ * The guard name an unqualified `auth.guard()` / `auth.user()` call resolves
1293
+ * to for this request. Explicit names always win; otherwise a registered
1294
+ * token guard is selected when the request carries a Bearer Authorization
1295
+ * header, falling back to the default (session) guard. This is the
1296
+ * composite-guard rule from RFC 0016: session- and token-authenticated
1297
+ * requests flow through the same auth surface without configuration.
1298
+ */
1299
+ resolveGuardName(ctx, name) {
1300
+ if (name) return name;
1301
+ if (this.tokenGuard && hasBearerHeader(ctx)) return this.tokenGuard;
1302
+ return this.defaultGuard;
1303
+ }
1304
+ createAuthContext(ctx, options = {}) {
1305
+ const resolveSession = () => getSessionFromContext(ctx);
1306
+ const resolveName = (name) => this.resolveGuardName(ctx, name ?? options.guard);
1307
+ const guardFactory = (resolvedName) => {
1308
+ return this.createGuard(resolvedName, {
1309
+ ctx,
1310
+ session: resolveSession(),
1311
+ manager: this
1312
+ });
1313
+ };
1314
+ return new RequestAuthContext(resolveName, ctx, resolveSession, guardFactory);
1315
+ }
1316
+ async attempt(name, ctx, credentials, remember) {
1317
+ return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
1318
+ }
1319
+ /**
1320
+ * Shorthand method to register a model-based authentication provider and session guard.
1321
+ * This simplifies the common case of authenticating users via a database model.
1322
+ *
1323
+ * @param model - The model class to use for user authentication
1324
+ * @param options - Options for the ModelUserProvider (partial, with defaults)
1325
+ * @param providerName - Name for the provider (defaults to 'users')
1326
+ * @param guardName - Name for the guard (defaults to 'web')
1327
+ */
1328
+ useModel(model, options = {}, providerName = "users", guardName = "web") {
1329
+ const defaultOptions = {
1330
+ usernameColumn: "email",
1331
+ credentialsPasswordField: "password",
1332
+ hasher: new DefaultHasher(),
1333
+ ...options
1334
+ };
1335
+ this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
1336
+ this.registerGuard(guardName, ({ session, manager }) => {
1337
+ return new SessionGuard({
1338
+ provider: manager.getProvider(providerName),
1339
+ session
1340
+ });
1341
+ });
1342
+ this.setDefaultGuard(guardName);
1343
+ }
1344
+ /**
1345
+ * Register a bearer-token guard backed by an ApiTokenStore and enable
1346
+ * header-based guard selection: requests carrying `Authorization: Bearer`
1347
+ * resolve to this guard, everything else keeps the default (session)
1348
+ * guard. The default guard itself is unchanged — session apps keep
1349
+ * working exactly as before.
1350
+ *
1351
+ * @param store - Where issued tokens live (see createApiToken)
1352
+ * @param options.provider - Registered provider name used to load the full
1353
+ * user record from the token's userId. Without it, `auth.user()` resolves
1354
+ * to a minimal `{ id }` record (enough for Gate/policy evaluation).
1355
+ * @param options.guardName - Guard registry name (defaults to 'token')
1356
+ */
1357
+ useTokens(store, options = {}) {
1358
+ const guardName = options.guardName ?? "token";
1359
+ if (this.guards.has(guardName) && this.tokenGuard !== guardName) throw new Error(`AuthManager: guard "${guardName}" is already registered. Pass a different guardName to useTokens() instead of shadowing it.`);
1360
+ this.registerGuard(guardName, ({ ctx, manager }) => {
1361
+ return new TokenGuard({
1362
+ store,
1363
+ ctx,
1364
+ provider: options.provider ? manager.getProvider(options.provider) : void 0,
1365
+ updateLastUsed: options.updateLastUsed
1366
+ });
1367
+ });
1368
+ this.tokenGuard = guardName;
1369
+ this.apiTokenStore = store;
1370
+ this.apiTokenOptions = { ...options };
1371
+ }
1372
+ /**
1373
+ * The options the last `useTokens()` call configured its guard with.
1374
+ *
1375
+ * Read by machinery that has to *replace* the store without changing
1376
+ * anything else about how tokens authenticate — `guren tool:dev` installs an
1377
+ * ephemeral store over the app's, and doing that with a bare `useTokens(store)`
1378
+ * silently dropped the app's `provider`, so a token resolved to a bare
1379
+ * `{ id }` instead of the real user record and every policy reading a user
1380
+ * field behaved differently for no stated reason.
1381
+ */
1382
+ getApiTokenOptions() {
1383
+ return { ...this.apiTokenOptions };
1384
+ }
1385
+ /**
1386
+ * The token store {@link useTokens} was configured with, or `undefined`
1387
+ * when this app never called it.
1388
+ *
1389
+ * This is the one path by which out-of-request machinery — `guren
1390
+ * token:issue`, the App MCP adapter's principal lookup — reaches the same
1391
+ * store the guard verifies against. `useTokens` otherwise closes over
1392
+ * `store` inside the guard factory, where nothing outside a live request
1393
+ * can see it, so an issuance command could only write tokens into a store
1394
+ * of its own making, which no running app would ever read.
1395
+ *
1396
+ * Deliberately on this class rather than on `AuthManagerContract`: the
1397
+ * contract describes what a *request* needs from auth, and handing out the
1398
+ * raw store is not part of that. Callers reach it through the concrete
1399
+ * manager (`Application.auth`).
1400
+ */
1401
+ getApiTokenStore() {
1402
+ return this.apiTokenStore ?? void 0;
1403
+ }
1404
+ };
1405
+ //#endregion
1406
+ //#region src/support/redirect-target.ts
1407
+ /**
1408
+ * Shared open-redirect classification primitives, used by both the
1409
+ * redirect-safety middleware and the OAuth `redirectTo` sanitizer. Keep every
1410
+ * hardening fix here so the two layers cannot drift.
1411
+ */
1412
+ /** Normalize backslash tricks (e.g. `/\evil.com`) before classifying. */
1413
+ function normalizeRedirectTarget(value) {
1414
+ return value.replace(/\\/g, "/");
1415
+ }
1416
+ /** App-relative paths (`/path`, but not protocol-relative `//host`) are always safe. */
1417
+ function isAppRelativePath(value) {
1418
+ return value.startsWith("/") && !value.startsWith("//");
1419
+ }
1420
+ /** Match a URL's host against an allowlist supporting `*.example.com` wildcards. */
1421
+ function hostMatchesAllowlist(target, allowedHosts) {
1422
+ const hostname = target.hostname.toLowerCase();
1423
+ const host = target.host.toLowerCase();
1424
+ for (const allowed of allowedHosts) if (allowed.startsWith("*.")) {
1425
+ const suffix = allowed.slice(1).toLowerCase();
1426
+ if (hostname.endsWith(suffix) && hostname.length > suffix.length) return true;
1427
+ } else if (host === allowed.toLowerCase()) return true;
1428
+ return false;
1429
+ }
1430
+ //#endregion
1125
1431
  //#region src/auth/oauth/index.ts
1126
1432
  /** Session key holding the per-browser bindings between authorize and callback. */
1127
1433
  const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
@@ -1519,32 +1825,6 @@ function parseOAuthRedirectUrl(url) {
1519
1825
  return parseTokenUrl(url);
1520
1826
  }
1521
1827
  //#endregion
1522
- //#region src/auth/password/NodeHasher.ts
1523
- /**
1524
- * Node.js-compatible password hasher using crypto.scrypt.
1525
- * Use this instead of ScryptHasher when deploying to non-Bun runtimes (e.g. AWS Lambda).
1526
- */
1527
- var NodeHasher = class {
1528
- options;
1529
- constructor(options = {}) {
1530
- this.options = {
1531
- cost: options.cost,
1532
- memory: options.memory,
1533
- saltLength: options.saltLength,
1534
- keyLength: options.keyLength
1535
- };
1536
- }
1537
- async hash(plain) {
1538
- return hashPassword(plain, this.options);
1539
- }
1540
- async verify(hashed, plain) {
1541
- return verifyPassword(plain, hashed);
1542
- }
1543
- needsRehash(hashed) {
1544
- return needsRehash(hashed, this.options);
1545
- }
1546
- };
1547
- //#endregion
1548
1828
  //#region src/auth/AuthenticatableModel.ts
1549
1829
  var AuthenticatableModel = class extends Model {
1550
1830
  static createType = void 0;
@@ -1577,7 +1857,7 @@ var AuthenticatableModel = class extends Model {
1577
1857
  }
1578
1858
  static resolvePasswordHasher() {
1579
1859
  if (this.passwordHasher) return this.passwordHasher;
1580
- const hasher = new ScryptHasher();
1860
+ const hasher = new DefaultHasher();
1581
1861
  this.passwordHasher = hasher;
1582
1862
  return hasher;
1583
1863
  }
@@ -1945,10 +2225,10 @@ function requireVerifiedEmail(options = {}) {
1945
2225
  const { redirectTo = "/verify-email" } = options;
1946
2226
  return async (ctx, next) => {
1947
2227
  if (!isEmailVerified(await (options.getUser ?? (async (c) => {
1948
- return c.get("guren:auth")?.user?.() ?? null;
2228
+ return await getAuthContext(c)?.user() ?? null;
1949
2229
  }))(ctx))) return ctx.redirect(redirectTo);
1950
2230
  await next();
1951
2231
  };
1952
2232
  }
1953
2233
  //#endregion
1954
- export { generateToken as $, sanitizeOAuthRedirect as A, revokeAllApiTokens as B, createGitHubOAuthProviderConfig as C, exchangeOAuthCode as D, createOAuthState as E, createBearerTokenMiddleware as F, verifyApiToken as G, tokenCan as H, getApiToken as I, normalizeRedirectTarget as J, hostMatchesAllowlist as K, getApiTokenOrFail as L, API_TOKEN_KEY as M, MemoryApiTokenStore as N, fetchOAuthUserProfile as O, createApiToken as P, generateId as Q, getUserApiTokens as R, createDiscordOAuthProviderConfig as S, createOAuthManager as T, tokenCanAll as U, revokeApiToken as V, tokenCanAny as W, SessionGuard as X, AuthManager as Y, buildTokenUrl as Z, MemoryOAuthStateStore as _, isEmailVerified as a, BaseUserProvider as at, buildOAuthAuthorizeUrl as b, verifyEmailToken as c, MemorySessionStore as ct, completePasswordReset as d, hashToken as et, createPasswordResetToken as f, NodeHasher as g, AuthenticatableModel as h, createEmailVerificationToken as i, ModelUserProvider as it, verifyOAuthState as j, parseOAuthRedirectUrl as k, MemoryPasswordResetStore as l, createSessionMiddleware as lt, verifyPasswordResetToken as m, buildVerificationUrl as n, secureCompare as nt, parseVerificationUrl as o, ScryptHasher as ot, parsePasswordResetUrl as p, isAppRelativePath as q, completeEmailVerification as r, secureStringCompare as rt, requireVerifiedEmail as s, AuthenticationException as st, MemoryEmailVerificationStore as t, parseTokenUrl as tt, buildPasswordResetUrl as u, getSessionFromContext as ut, OAUTH_SESSION_BINDING_KEY as v, createGoogleOAuthProviderConfig as w, buildOAuthRedirectUrl as x, OAuthManager as y, parseApiToken as z };
2234
+ export { buildTokenUrl as $, verifyOAuthState as A, getApiToken as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, TokenGuard as F, readBearerToken as G, getUserApiTokens as H, API_TOKEN_KEY as I, tokenCan as J, revokeAllApiTokens as K, MemoryApiTokenStore as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, SessionGuard as Q, createApiToken as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, hasBearerHeader as U, getApiTokenOrFail as V, parseApiToken as W, tokenCanAny as X, tokenCanAll as Y, verifyApiToken as Z, OAUTH_SESSION_BINDING_KEY as _, isEmailVerified as a, secureStringCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c, DefaultHasher as ct, completePasswordReset as d, AuthenticationException as dt, generateId as et, createPasswordResetToken as f, MemorySessionStore as ft, MemoryOAuthStateStore as g, AuthenticatableModel as h, createEmailVerificationToken as i, secureCompare as it, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, NodeHasher as lt, verifyPasswordResetToken as m, getSessionFromContext as mt, buildVerificationUrl as n, hashToken as nt, parseVerificationUrl as o, ModelUserProvider as ot, parsePasswordResetUrl as p, createSessionMiddleware as pt, revokeApiToken as q, completeEmailVerification as r, parseTokenUrl as rt, requireVerifiedEmail as s, BaseUserProvider as st, MemoryEmailVerificationStore as t, generateToken as tt, buildPasswordResetUrl as u, ScryptHasher as ut, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, createBearerTokenMiddleware as z };