@guren/server 2.21.0 → 2.23.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 (115) hide show
  1. package/dist/Job-BxioDEcS.js +165 -0
  2. package/dist/{Logger-DFifRAtc.js → Logger-DWXdtLSJ.js} +62 -2
  3. package/dist/agent/approval-status.d.ts +1 -1
  4. package/dist/agent/approval.d.ts +2 -2
  5. package/dist/agent/audit-emitter.d.ts +11 -1
  6. package/dist/agent/gate.d.ts +10 -8
  7. package/dist/agent/meta-tools.d.ts +13 -5
  8. package/dist/agent/pipeline.d.ts +10 -9
  9. package/dist/auth/AuthManager.d.ts +29 -0
  10. package/dist/auth/AuthenticatableModel.d.ts +15 -0
  11. package/dist/auth/RequestAuthContext.d.ts +10 -1
  12. package/dist/auth/SessionGuard.d.ts +2 -0
  13. package/dist/auth/api-token.d.ts +6 -0
  14. package/dist/auth/context.d.ts +32 -0
  15. package/dist/auth/index.d.ts +7 -0
  16. package/dist/auth/index.js +2 -2
  17. package/dist/auth/model-capability.d.ts +8 -0
  18. package/dist/auth/oauth/index.d.ts +5 -0
  19. package/dist/auth/password/DefaultHasher.d.ts +17 -6
  20. package/dist/auth/password/configured-hasher.d.ts +23 -0
  21. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  22. package/dist/auth/providers/unconfigured-user-provider.d.ts +12 -0
  23. package/dist/auth/types.d.ts +9 -0
  24. package/dist/{auth-CjE2oO50.js → auth-D_W1cJp3.js} +279 -84
  25. package/dist/authorization/Gate.d.ts +12 -0
  26. package/dist/authorization/index.js +1 -1
  27. package/dist/{authorization-CdEWZZw3.js → authorization-0mCGUFoI.js} +58 -12
  28. package/dist/broadcasting/BroadcastManager.d.ts +10 -0
  29. package/dist/broadcasting/index.js +1 -1
  30. package/dist/{broadcasting-B5RzB0A2.js → broadcasting-BdJnaq1O.js} +17 -3
  31. package/dist/cache/index.js +1 -1
  32. package/dist/{cache-thXRnaju.js → cache-DikxP7Bk.js} +1 -1
  33. package/dist/container/Container.d.ts +18 -1
  34. package/dist/container/bindings.d.ts +9 -4
  35. package/dist/container/index.d.ts +4 -2
  36. package/dist/container/resolve-optional.d.ts +10 -0
  37. package/dist/context-af2n5abO.js +91 -0
  38. package/dist/{Job-CvDwk2Gj.js → default-application-Chbrul_m.js} +126 -82
  39. package/dist/encryption/Encrypter.d.ts +10 -0
  40. package/dist/encryption/index.js +1 -1
  41. package/dist/{encryption-uwP3Di4D.js → encryption-BRjZnshr.js} +23 -5
  42. package/dist/errors/ExceptionHandler.d.ts +10 -0
  43. package/dist/events/Event.d.ts +18 -0
  44. package/dist/events/EventManager.d.ts +56 -4
  45. package/dist/events/index.d.ts +2 -1
  46. package/dist/events/index.js +2 -2
  47. package/dist/events/queued.d.ts +8 -0
  48. package/dist/events/serialize.d.ts +8 -0
  49. package/dist/events/types.d.ts +19 -2
  50. package/dist/events-C86rS63h.js +428 -0
  51. package/dist/health/checks/CacheCheck.d.ts +3 -5
  52. package/dist/health/checks/StorageCheck.d.ts +3 -5
  53. package/dist/health/index.js +1 -1
  54. package/dist/{health-DQSvUplL.js → health-CB0oS_UE.js} +2 -2
  55. package/dist/http/Application.d.ts +28 -0
  56. package/dist/http/default-application.d.ts +33 -0
  57. package/dist/http/middleware/detect-locale.d.ts +2 -1
  58. package/dist/http/request-container.d.ts +25 -0
  59. package/dist/i18n/I18nManager.d.ts +16 -3
  60. package/dist/i18n/index.d.ts +1 -1
  61. package/dist/i18n/index.js +2 -2
  62. package/dist/{i18n-BZ2VrSud.js → i18n-DRo1g0AN.js} +34 -10
  63. package/dist/index.d.ts +16 -11
  64. package/dist/index.js +248 -129
  65. package/dist/lambda/index.js +1 -1
  66. package/dist/logging/LogManager.d.ts +9 -0
  67. package/dist/logging/index.js +2 -2
  68. package/dist/{logging-DXmqqUl4.js → logging-CXotojgW.js} +17 -4
  69. package/dist/mail/Mail.d.ts +14 -1
  70. package/dist/mail/MailManager.d.ts +10 -2
  71. package/dist/mail/index.js +1 -1
  72. package/dist/{mail-9CrvJyBZ.js → mail-CmxO2Ttx.js} +42 -11
  73. package/dist/mvc/Controller.d.ts +1 -1
  74. package/dist/mvc/Router.d.ts +16 -5
  75. package/dist/mvc/inertia/InertiaEngine.d.ts +24 -3
  76. package/dist/mvc/inertia/shared.d.ts +7 -0
  77. package/dist/notifications/NotificationManager.d.ts +15 -0
  78. package/dist/notifications/index.js +1 -1
  79. package/dist/{notifications-D0VXkFLF.js → notifications-CE3U7uyg.js} +24 -5
  80. package/dist/providers/AuthServiceProvider.d.ts +5 -4
  81. package/dist/providers/AuthorizationServiceProvider.d.ts +2 -2
  82. package/dist/providers/BroadcastServiceProvider.d.ts +4 -1
  83. package/dist/providers/EncryptionServiceProvider.d.ts +7 -1
  84. package/dist/providers/EventServiceProvider.d.ts +1 -0
  85. package/dist/providers/LogServiceProvider.d.ts +6 -1
  86. package/dist/providers/MailServiceProvider.d.ts +7 -1
  87. package/dist/providers/NotificationServiceProvider.d.ts +4 -1
  88. package/dist/queue/Job.d.ts +39 -0
  89. package/dist/queue/QueueManager.d.ts +14 -5
  90. package/dist/queue/Worker.d.ts +2 -1
  91. package/dist/queue/index.d.ts +1 -1
  92. package/dist/queue/index.js +3 -3
  93. package/dist/queue/types.d.ts +7 -0
  94. package/dist/{queue-zPPYZdif.js → queue-B3x_RKnB.js} +24 -10
  95. package/dist/redis/RedisSchedulerLock.d.ts +17 -0
  96. package/dist/redis/index.d.ts +2 -0
  97. package/dist/redis/index.js +21 -1
  98. package/dist/runtime/index.js +1 -1
  99. package/dist/scheduling/MemorySchedulerLock.d.ts +16 -0
  100. package/dist/scheduling/ScheduledTask.d.ts +19 -2
  101. package/dist/scheduling/Scheduler.d.ts +25 -0
  102. package/dist/scheduling/index.d.ts +2 -1
  103. package/dist/scheduling/index.js +2 -2
  104. package/dist/scheduling/types.d.ts +26 -2
  105. package/dist/{scheduling-C6tcOtUl.js → scheduling-DudNXGnh.js} +178 -20
  106. package/dist/storage/index.js +1 -1
  107. package/dist/{storage-D_yNe54O.js → storage-6HLaUf9j.js} +2 -13
  108. package/dist/support/deprecate.d.ts +16 -0
  109. package/dist/support/keep-alive.d.ts +26 -0
  110. package/dist/support/request-deferrer.d.ts +10 -0
  111. package/dist/{vite-manifest-CdfPfQdj.js → vite-manifest-B8720V7w.js} +1 -1
  112. package/dist/warn-once-p-IlMjra.js +13 -0
  113. package/package.json +3 -2
  114. package/dist/context-CXk_umpT.js +0 -21
  115. package/dist/events-DOmAHDeP.js +0 -230
@@ -1,9 +1,8 @@
1
- import { t as HttpException } from "./HttpException-BlQ2yEmT.js";
2
1
  import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
3
2
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
3
+ import { a as setResolvedPrincipal, i as getResolvedPrincipal, n as createPrincipalAuthContext, o as AuthenticationException, r as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-af2n5abO.js";
4
4
  import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
5
5
  import { isExpired, isOptionalExpiryPast } from "./support/expiry.js";
6
- import { n as getAuthContext } from "./context-CXk_umpT.js";
7
6
  import { deleteCookie, getCookie, setCookie } from "hono/cookie";
8
7
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
9
8
  import { Model } from "@guren/orm";
@@ -457,38 +456,20 @@ var AgentPrincipalGuard = class {
457
456
  session() {}
458
457
  };
459
458
  //#endregion
460
- //#region src/errors/exceptions/AuthenticationException.ts
461
- /** 401: the user is not authenticated, or the credentials were invalid. */
462
- var AuthenticationException = class AuthenticationException extends HttpException {
463
- /** The guard that threw. */
464
- guard;
465
- redirectTo;
466
- constructor(message = "Unauthenticated.", guard, redirectTo) {
467
- super(401, message);
468
- this.name = "AuthenticationException";
469
- this.guard = guard;
470
- this.redirectTo = redirectTo;
471
- }
472
- static withRedirect(redirectTo, message) {
473
- return new AuthenticationException(message, void 0, redirectTo);
474
- }
475
- static forGuard(guard, message) {
476
- return new AuthenticationException(message, guard);
477
- }
478
- };
479
- //#endregion
480
459
  //#region src/auth/RequestAuthContext.ts
481
460
  var RequestAuthContext = class {
482
461
  resolveName;
483
462
  ctx;
484
463
  resolveSession;
485
464
  resolveGuard;
465
+ resolvePrincipal;
486
466
  guardCache = /* @__PURE__ */ new Map();
487
- constructor(resolveName, ctx, resolveSession, resolveGuard) {
467
+ constructor(resolveName, ctx, resolveSession, resolveGuard, resolvePrincipal = () => void 0) {
488
468
  this.resolveName = resolveName;
489
469
  this.ctx = ctx;
490
470
  this.resolveSession = resolveSession;
491
471
  this.resolveGuard = resolveGuard;
472
+ this.resolvePrincipal = resolvePrincipal;
492
473
  }
493
474
  guard(name) {
494
475
  const key = this.resolveName(name);
@@ -499,12 +480,18 @@ var RequestAuthContext = class {
499
480
  return this.resolveSession();
500
481
  }
501
482
  async check() {
483
+ const principal = this.resolvePrincipal();
484
+ if (principal) return principal.user != null;
502
485
  return this.guard().check();
503
486
  }
504
487
  async guest() {
488
+ const principal = this.resolvePrincipal();
489
+ if (principal) return principal.user == null;
505
490
  return this.guard().guest();
506
491
  }
507
492
  async user() {
493
+ const principal = this.resolvePrincipal();
494
+ if (principal) return principal.user ?? null;
508
495
  return this.guard().user();
509
496
  }
510
497
  async userOrFail() {
@@ -513,17 +500,36 @@ var RequestAuthContext = class {
513
500
  return u;
514
501
  }
515
502
  async id() {
503
+ const principal = this.resolvePrincipal();
504
+ if (principal) return principal.user == null ? null : principal.id;
516
505
  return this.guard().id();
517
506
  }
518
507
  async login(user, remember) {
519
508
  await this.guard().login(user, remember);
509
+ this.forgetPrincipal();
520
510
  }
521
511
  async attempt(credentials, remember) {
522
- return this.guard().attempt(credentials, remember);
512
+ const succeeded = await this.guard().attempt(credentials, remember);
513
+ if (succeeded) this.forgetPrincipal();
514
+ return succeeded;
523
515
  }
524
516
  async logout() {
517
+ const principal = this.resolvePrincipal();
518
+ if (principal) {
519
+ await principal.revoke?.();
520
+ this.forgetPrincipal();
521
+ return;
522
+ }
525
523
  await this.guard().logout();
526
524
  }
525
+ /**
526
+ * The request's identity is whatever just logged in, so a principal a
527
+ * middleware resolved stops answering. A later `logout()` therefore ends the
528
+ * new session rather than revoking the credential the request arrived with.
529
+ */
530
+ forgetPrincipal() {
531
+ setResolvedPrincipal(this.ctx, void 0);
532
+ }
527
533
  };
528
534
  /**
529
535
  * Prefixes of every hash format the built-in hashers produce: Bun's argon2
@@ -652,54 +658,114 @@ function testingHashCost() {
652
658
  return typeof process !== "undefined" && Boolean(process.env.GUREN_TESTING);
653
659
  }
654
660
  /**
655
- * Runtime-detecting password hasher behind `Hash`, the default for
656
- * `AuthenticatableModel` and `ModelUserProvider`: `Bun.password` on Bun (Argon2id,
657
- * despite `ScryptHasher`'s name), `crypto.scrypt` otherwise. **Verification routes
658
- * on the stored hash, not the runtime**, or a column written elsewhere would 500 on
659
- * every login; `$scrypt$` verifies anywhere, Argon2id/bcrypt needs `Bun.password`.
661
+ * The hasher behind `Hash`, the default for `AuthenticatableModel` and
662
+ * `ModelUserProvider`. Writes the configured algorithm, scrypt unless told
663
+ * otherwise, so a row seeded under Bun still verifies on Node or Workers.
664
+ * Verification routes on the stored hash, not the writer: `$scrypt$` verifies
665
+ * anywhere, Argon2id/bcrypt needs `Bun.password`; the other format reports `needsRehash()`.
660
666
  */
661
667
  var DefaultHasher = class {
668
+ algorithm;
662
669
  bun;
663
670
  node;
671
+ writer;
664
672
  testing;
665
- constructor() {
666
- const onBun = typeof Bun !== "undefined";
667
- this.bun = onBun ? new ScryptHasher() : null;
673
+ constructor(options = {}) {
674
+ this.algorithm = options.algorithm ?? "scrypt";
675
+ const bun = typeof Bun !== "undefined" ? new ScryptHasher() : null;
676
+ this.bun = bun;
668
677
  this.node = new NodeHasher();
669
- this.testing = onBun ? new ScryptHasher(TESTING_ARGON2_OPTIONS) : new NodeHasher({ cost: TESTING_SCRYPT_COST });
678
+ if (this.algorithm === "argon2") {
679
+ if (!bun) throw new Error("The 'argon2' password hasher hashes through Bun.password, which this runtime does not have. Use the default ('scrypt'), which works everywhere.");
680
+ this.writer = bun;
681
+ this.testing = new ScryptHasher(TESTING_ARGON2_OPTIONS);
682
+ } else {
683
+ this.writer = this.node;
684
+ this.testing = new NodeHasher({ cost: TESTING_SCRYPT_COST });
685
+ }
670
686
  }
671
687
  hash(plain) {
672
- return (testingHashCost() ? this.testing : this.bun ?? this.node).hash(plain);
688
+ return (testingHashCost() ? this.testing : this.writer).hash(plain);
673
689
  }
674
690
  verify(hashed, plain) {
675
691
  return this.delegateFor(hashed).verify(hashed, plain);
676
692
  }
677
693
  needsRehash(hashed) {
678
- if (hashed.startsWith("$scrypt$") !== (this.bun === null)) return true;
694
+ if (hashed.startsWith("$scrypt$") !== (this.algorithm === "scrypt")) return true;
679
695
  if (!this.testing.needsRehash(hashed)) return !testingHashCost();
680
- return this.delegateFor(hashed).needsRehash(hashed);
696
+ return this.writer.needsRehash(hashed);
681
697
  }
682
698
  delegateFor(hashed) {
683
699
  if (hashed.startsWith("$scrypt$")) return this.node;
684
700
  if (!this.bun) {
685
701
  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().");
686
- 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.");
702
+ throw new Error("This password hash was written by Bun.password (Argon2id or bcrypt) and cannot be verified on a runtime without Bun. Such rows are rehashed to scrypt on their next successful login under Bun, so log the affected accounts in there once (or reset their passwords) before a Node or Workers deploy has to read them.");
687
703
  }
688
704
  return this.bun;
689
705
  }
690
706
  };
691
707
  //#endregion
692
- //#region src/auth/providers/ModelUserProvider.ts
708
+ //#region src/auth/model-capability.ts
693
709
  /**
694
- * Capability check, not `instanceof AuthenticatableModel`: a nominal check
695
- * silently fails when two copies of @guren/server are loaded (src and dist
696
- * coexist through workspace symlinks), which would ignore a renamed
697
- * passwordHashField without any signal. Same duck-typing idiom as
698
- * BaseUserProvider's remember-token support.
710
+ * The capability `T` a model class implements, or null. A capability check
711
+ * rather than `instanceof`: two copies of @guren/server coexist through
712
+ * workspace symlinks (src and dist), and a nominal test answers "no" for the
713
+ * copy it was not built from, silently ignoring a renamed credential column or
714
+ * a hasher the app bound.
699
715
  */
700
- function credentialColumnSource(model) {
716
+ function capabilityOf(model, ...methods) {
701
717
  const candidate = model;
702
- return typeof candidate.resolvePasswordHashField === "function" && typeof candidate.resolveRememberTokenField === "function" ? candidate : null;
718
+ if (!candidate) return null;
719
+ return methods.every((method) => typeof candidate[method] === "function") ? candidate : null;
720
+ }
721
+ //#endregion
722
+ //#region src/auth/password/configured-hasher.ts
723
+ function createPasswordHasher(option) {
724
+ if (option === void 0) return defaultPasswordHasher();
725
+ return typeof option === "string" ? new DefaultHasher({ algorithm: option }) : option;
726
+ }
727
+ let sharedDefaultHasher = null;
728
+ /**
729
+ * The scrypt default, constructed once. `DefaultHasher` holds no per-instance
730
+ * state (the testing cost is read per call), and each one allocates three
731
+ * hashers, which an unbound model write would otherwise pay per row.
732
+ */
733
+ function defaultPasswordHasher() {
734
+ sharedDefaultHasher ??= new DefaultHasher();
735
+ return sharedDefaultHasher;
736
+ }
737
+ function passwordHasherSlot(model) {
738
+ return capabilityOf(model, "explicitPasswordHasher");
739
+ }
740
+ /**
741
+ * Hand the app's hasher to a model class at bind time, rather than letting the
742
+ * class read a process-wide container per hash. A model that declares `static
743
+ * passwordHasher` keeps the author's choice. The slot is a static, so a model
744
+ * class shared by two Applications carries the last binding.
745
+ */
746
+ function bindPasswordHasher(model, hasher) {
747
+ const slot = passwordHasherSlot(model);
748
+ if (!slot || slot.explicitPasswordHasher()) return;
749
+ slot.configuredPasswordHasher = hasher;
750
+ }
751
+ /**
752
+ * The one hasher precedence, read by the model class and by its provider: the
753
+ * author's `static passwordHasher`, then the caller's override, then what
754
+ * `useModel()` bound, then scrypt. A second spelling of this order is how a
755
+ * model and its provider come to write at different parameters, and every
756
+ * login then asks for a rehash the previous one already made.
757
+ */
758
+ function resolveModelHasher(model, override) {
759
+ const slot = passwordHasherSlot(model);
760
+ return slot?.explicitPasswordHasher() ?? override ?? slot?.configuredPasswordHasher ?? defaultPasswordHasher();
761
+ }
762
+ //#endregion
763
+ //#region src/auth/providers/ModelUserProvider.ts
764
+ function passwordHashWriter(model) {
765
+ return capabilityOf(model, "storePasswordHash");
766
+ }
767
+ function credentialColumnSource(model) {
768
+ return capabilityOf(model, "resolvePasswordHashField", "resolveRememberTokenField");
703
769
  }
704
770
  var ModelUserProvider = class extends BaseUserProvider {
705
771
  model;
@@ -717,7 +783,7 @@ var ModelUserProvider = class extends BaseUserProvider {
717
783
  this.usernameColumn = options.usernameColumn ?? "email";
718
784
  this.passwordColumn = options.passwordColumn ?? authModel?.resolvePasswordHashField() ?? "passwordHash";
719
785
  this.rememberTokenColumn = options.rememberTokenColumn ?? authModel?.resolveRememberTokenField() ?? "rememberToken";
720
- this.hasher = options.hasher ?? new DefaultHasher();
786
+ this.hasher = resolveModelHasher(model, options.hasher);
721
787
  this.credentialsPasswordField = options.credentialsPasswordField ?? "password";
722
788
  }
723
789
  cast(record) {
@@ -752,6 +818,20 @@ var ModelUserProvider = class extends BaseUserProvider {
752
818
  getId(user) {
753
819
  return user[this.idColumn];
754
820
  }
821
+ async rehashPasswordIfRequired(user, credentials) {
822
+ const plain = credentials[this.credentialsPasswordField];
823
+ const hashed = user[this.passwordColumn];
824
+ if (typeof plain !== "string" || typeof hashed !== "string" || !this.hasher.needsRehash?.(hashed)) return;
825
+ const rehashed = await this.hasher.hash(plain);
826
+ user[this.passwordColumn] = rehashed;
827
+ const writer = passwordHashWriter(this.model);
828
+ if (writer) await writer.storePasswordHash({ [this.idColumn]: this.getId(user) }, this.passwordColumn, rehashed);
829
+ else await this.writeColumn(user, this.passwordColumn, rehashed);
830
+ }
831
+ /** forceUpdate keyed on the id column: both credential columns are denied to mass assignment. */
832
+ async writeColumn(user, column, value) {
833
+ await this.model.forceUpdate({ [this.idColumn]: this.getId(user) }, { [column]: value });
834
+ }
755
835
  /**
756
836
  * Strip the password hash, remember token, and the model's `hidden` fields
757
837
  * before the record leaves the auth layer. Credential validation runs on the
@@ -772,7 +852,7 @@ var ModelUserProvider = class extends BaseUserProvider {
772
852
  async setRememberToken(user, token) {
773
853
  if (typeof user[this.rememberTokenColumn] !== "undefined") {
774
854
  user[this.rememberTokenColumn] = token;
775
- await this.model.forceUpdate({ [this.idColumn]: this.getId(user) }, { [this.rememberTokenColumn]: token });
855
+ await this.writeColumn(user, this.rememberTokenColumn, token);
776
856
  }
777
857
  }
778
858
  async getRememberToken(user) {
@@ -951,8 +1031,21 @@ var SessionGuard = class {
951
1031
  return null;
952
1032
  }
953
1033
  if (!await this.provider.validateCredentials(user, credentials)) return null;
1034
+ try {
1035
+ await this.provider.rehashPasswordIfRequired?.(user, credentials);
1036
+ } catch (error) {
1037
+ console.warn(`[guren] Rehashing the password for user ${this.describeUser(user)} failed; the login continues.`, error);
1038
+ }
954
1039
  return user;
955
1040
  }
1041
+ /** Never the plaintext or the hash: a warning is a log line, and both belong in neither. */
1042
+ describeUser(user) {
1043
+ try {
1044
+ return String(this.provider.getId(user));
1045
+ } catch {
1046
+ return "unknown";
1047
+ }
1048
+ }
956
1049
  session() {
957
1050
  return this.currentSession;
958
1051
  }
@@ -1127,6 +1220,15 @@ async function getUserApiTokens(userId, store) {
1127
1220
  */
1128
1221
  const API_TOKEN_KEY = "guren:api-token";
1129
1222
  /**
1223
+ * Revoke the token a request presented, and clear it from the request context
1224
+ * so `getApiToken()` / `getApiTokenOrFail()` cannot succeed after a logout on
1225
+ * the same request. The slot is cleared whether or not a token still verified.
1226
+ */
1227
+ async function revokePresentedToken(ctx, tokenId, store) {
1228
+ if (tokenId) await revokeApiToken(tokenId, store);
1229
+ ctx.set(API_TOKEN_KEY, void 0);
1230
+ }
1231
+ /**
1130
1232
  * Create middleware that authenticates requests using Bearer tokens.
1131
1233
  * @example
1132
1234
  * ```ts
@@ -1164,6 +1266,12 @@ function createBearerTokenMiddleware(options) {
1164
1266
  if (loadUser) {
1165
1267
  const user = await loadUser(result.userId);
1166
1268
  ctx.set("guren:user", user);
1269
+ setResolvedPrincipal(ctx, {
1270
+ user,
1271
+ id: result.userId,
1272
+ revoke: () => revokePresentedToken(ctx, result.token.id, store)
1273
+ });
1274
+ if (!getAuthContext(ctx)) ctx.set(AUTH_CONTEXT_KEY, createPrincipalAuthContext(ctx));
1167
1275
  }
1168
1276
  return next();
1169
1277
  };
@@ -1248,16 +1356,13 @@ var TokenGuard = class {
1248
1356
  /** Revokes the presented token. Subsequent requests with it fail verification. */
1249
1357
  async logout() {
1250
1358
  const result = await this.verify();
1251
- if (result) await revokeApiToken(result.token.id, this.store);
1359
+ await revokePresentedToken(this.ctx, result?.token.id, this.store);
1252
1360
  this.verification = Promise.resolve(null);
1253
1361
  this.resolvedUser = Promise.resolve(null);
1254
- this.ctx.set(API_TOKEN_KEY, void 0);
1255
1362
  }
1256
1363
  session() {}
1257
1364
  };
1258
- //#endregion
1259
- //#region src/auth/AuthManager.ts
1260
- const DEFAULT_GUARD = "web";
1365
+ const DEFAULT_PROVIDER = "users";
1261
1366
  /**
1262
1367
  * The guard name an unqualified lookup resolves to on a request the pipeline
1263
1368
  * installed a principal on (RFC 0017 §2). Deliberately **not** registered:
@@ -1273,8 +1378,19 @@ var AuthManager = class {
1273
1378
  tokenGuard = null;
1274
1379
  apiTokenStore = null;
1275
1380
  apiTokenOptions = {};
1381
+ passwordHasher;
1276
1382
  constructor(options = {}) {
1277
- this.defaultGuard = options.defaultGuard ?? DEFAULT_GUARD;
1383
+ this.defaultGuard = options.defaultGuard ?? "web";
1384
+ this.passwordHasher = createPasswordHasher(options.hasher);
1385
+ }
1386
+ /**
1387
+ * The one password hasher this app writes with: `AuthPluginOptions.hasher`
1388
+ * resolved, scrypt by default. `useModel()` hands it to the provider, and
1389
+ * `AuthenticatableModel` reads it through the container, so a row the model
1390
+ * hashes and a login the provider verifies never disagree on the format.
1391
+ */
1392
+ hasher() {
1393
+ return this.passwordHasher;
1278
1394
  }
1279
1395
  registerGuard(name, factory) {
1280
1396
  this.guards.set(name, { factory });
@@ -1282,6 +1398,14 @@ var AuthManager = class {
1282
1398
  registerProvider(name, factory) {
1283
1399
  this.providers.set(name, { factory });
1284
1400
  }
1401
+ /** The guard `useTokens()` registered, or null. On this class rather than the contract, like `getApiTokenOptions()`. */
1402
+ getTokenGuard() {
1403
+ return this.tokenGuard;
1404
+ }
1405
+ /** Whether a provider factory is registered under `name`; `getProvider()` throws where this is false. */
1406
+ hasProvider(name) {
1407
+ return this.providers.has(name);
1408
+ }
1285
1409
  getProvider(name) {
1286
1410
  const entry = this.providers.get(name);
1287
1411
  if (!entry) throw new Error(`AuthManager: provider "${name}" has not been registered.`);
@@ -1294,10 +1418,13 @@ var AuthManager = class {
1294
1418
  createGuard(name, context) {
1295
1419
  if (name === AGENT_PRINCIPAL_GUARD) {
1296
1420
  const installed = readAgentPrincipal(context.ctx.req.raw);
1297
- if (installed) return new AgentPrincipalGuard({
1298
- installed,
1299
- ...this.apiTokenOptions.provider ? { provider: this.getProvider(this.apiTokenOptions.provider) } : {}
1300
- });
1421
+ if (installed) {
1422
+ const provider = this.tokenUserProvider();
1423
+ return new AgentPrincipalGuard({
1424
+ installed,
1425
+ ...provider ? { provider } : {}
1426
+ });
1427
+ }
1301
1428
  }
1302
1429
  const entry = this.guards.get(name);
1303
1430
  if (!entry) throw new Error(`AuthManager: guard "${name}" has not been registered.`);
@@ -1336,7 +1463,33 @@ var AuthManager = class {
1336
1463
  manager: this
1337
1464
  });
1338
1465
  };
1339
- return new RequestAuthContext(resolveName, ctx, resolveSession, guardFactory);
1466
+ return new RequestAuthContext(resolveName, ctx, resolveSession, guardFactory, () => this.resolvePrincipal(ctx));
1467
+ }
1468
+ /**
1469
+ * The user provider `useTokens({ provider })` configured, and no other.
1470
+ * Every surface that turns a token's or a principal's id into a user record
1471
+ * reads this one: a second rule would mean a policy reading a user field
1472
+ * behaved differently depending on which surface the call arrived on.
1473
+ */
1474
+ tokenUserProvider() {
1475
+ const name = this.apiTokenOptions.provider;
1476
+ return name ? this.getProvider(name) : void 0;
1477
+ }
1478
+ /**
1479
+ * The principal a middleware resolved for this request, sanitized the way the
1480
+ * token guard sanitizes its own. Read at call time, so a context built before
1481
+ * the authenticating middleware ran still answers with it.
1482
+ */
1483
+ resolvePrincipal(ctx) {
1484
+ if (readAgentPrincipal(ctx.req.raw)) return void 0;
1485
+ const principal = getResolvedPrincipal(ctx);
1486
+ if (!principal || principal.user == null) return principal;
1487
+ const provider = this.tokenUserProvider();
1488
+ if (!provider) return principal;
1489
+ return {
1490
+ ...principal,
1491
+ user: sanitizeUser(provider, principal.user)
1492
+ };
1340
1493
  }
1341
1494
  async attempt(name, ctx, credentials, remember) {
1342
1495
  return this.createAuthContext(ctx, { guard: name }).guard(name).attempt(credentials, remember);
@@ -1348,13 +1501,15 @@ var AuthManager = class {
1348
1501
  * @param providerName - Defaults to 'users'
1349
1502
  * @param guardName - Defaults to 'web'
1350
1503
  */
1351
- useModel(model, options = {}, providerName = "users", guardName = "web") {
1504
+ useModel(model, options = {}, providerName = DEFAULT_PROVIDER, guardName = "web") {
1505
+ const hasher = options.hasher ?? this.hasher();
1352
1506
  const defaultOptions = {
1353
1507
  usernameColumn: "email",
1354
1508
  credentialsPasswordField: "password",
1355
- hasher: new DefaultHasher(),
1356
- ...options
1509
+ ...options,
1510
+ hasher
1357
1511
  };
1512
+ bindPasswordHasher(model, hasher);
1358
1513
  this.registerProvider(providerName, () => new ModelUserProvider(model, defaultOptions));
1359
1514
  this.registerGuard(guardName, ({ session, manager }) => {
1360
1515
  return new SessionGuard({
@@ -1451,16 +1606,15 @@ function warnOnceAboutUnboundState() {
1451
1606
  warnedAboutUnboundState = true;
1452
1607
  console.warn("[guren] OAuth authorize() was called without `session` or `bindTo`, so `state` is not tied to the browser that started the flow. An attacker can then complete their own authorization in a victim's browser and log the victim into the attacker's account. Pass the current session (`this.auth.session()`) as `session` to both authorize() and handleCallback(), or manage a per-browser value yourself via `bindTo`. See: https://guren.dev/docs/guides/oauth");
1453
1608
  }
1454
- let warnedAboutDroppedBinding = false;
1455
1609
  /**
1456
- * The flow was bound at authorize time but the state came back without one,
1457
- * so the configured `OAuthStateStore` is not persisting `binding` — which
1458
- * silently reverts the protection to the transferable state it replaced.
1610
+ * The state came back without the binding the flow was created with, so the
1611
+ * configured `OAuthStateStore` is not persisting `binding`. This names the
1612
+ * cause, since "Invalid or expired OAuth state" reads as a user problem.
1613
+ * Printed per rejected login, each of which a store author has to trace;
1614
+ * reaching the branch costs a caller a state the store already consumed.
1459
1615
  */
1460
- function warnOnceAboutDroppedBinding() {
1461
- if (warnedAboutDroppedBinding) return;
1462
- warnedAboutDroppedBinding = true;
1463
- console.warn("[guren] An OAuth state was created with `bindTo` but came back from the state store without its binding, so the callback could not be tied to the browser that started the flow. The configured OAuthStateStore is dropping `OAuthStatePayload.binding` — for DatabaseOAuthStateStore this usually means the `oauth_states` table has no `binding` column. See: https://guren.dev/docs/guides/oauth");
1616
+ function warnAboutDroppedBinding() {
1617
+ console.warn("[guren] A bound OAuth state came back from the state store without its binding, so the callback was rejected: it cannot be tied to the browser that started the flow. The configured OAuthStateStore is dropping `OAuthStatePayload.binding` — for DatabaseOAuthStateStore this usually means the `oauth_states` table has no `binding` column. See: https://guren.dev/docs/guides/oauth");
1464
1618
  }
1465
1619
  function readPendingBindings(session) {
1466
1620
  const stored = session.get(OAUTH_SESSION_BINDING_KEY);
@@ -1499,6 +1653,14 @@ function consumeSessionBinding(session, stateHash) {
1499
1653
  session.set(OAUTH_SESSION_BINDING_KEY, pending.filter((entry) => entry.stateHash !== stateHash));
1500
1654
  return match?.binding;
1501
1655
  }
1656
+ /**
1657
+ * Prefix a bound state carries. `verifyOAuthState` reads boundness off the
1658
+ * state itself, so a store that drops `binding` cannot turn a bound flow back
1659
+ * into a transferable one. The store key is the hash of the whole state, so
1660
+ * adding or stripping the prefix changes the key and the lookup misses: the
1661
+ * marker needs no signature of its own.
1662
+ */
1663
+ const BOUND_STATE_PREFIX = "gb1~";
1502
1664
  const DEFAULT_STATE_EXPIRES_IN = 6e5;
1503
1665
  const DEFAULT_STATE_LENGTH = 24;
1504
1666
  const DEFAULT_STATE_HASH_ALGORITHM = "sha256";
@@ -1607,7 +1769,8 @@ function createOAuthManager(options = {}) {
1607
1769
  return new OAuthManager(options);
1608
1770
  }
1609
1771
  async function createOAuthState(provider, store, config = {}, redirectTo, fixedState, bindTo) {
1610
- const state = fixedState ?? generateToken(config.stateLength ?? DEFAULT_STATE_LENGTH);
1772
+ const minted = fixedState ?? generateToken(config.stateLength ?? DEFAULT_STATE_LENGTH);
1773
+ const state = bindTo ? `${BOUND_STATE_PREFIX}${minted}` : minted;
1611
1774
  const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
1612
1775
  const expiresAt = new Date(Date.now() + (config.expiresIn ?? DEFAULT_STATE_EXPIRES_IN));
1613
1776
  const stateHash = hashToken(state, hashAlgorithm);
@@ -1628,7 +1791,7 @@ async function verifyOAuthState(state, provider, store, config = {}, bindTo) {
1628
1791
  const payload = typeof store.consume === "function" ? await store.consume(stateHash) : await findAndDeleteState(store, stateHash);
1629
1792
  if (!payload) return null;
1630
1793
  if (payload.provider !== provider) return null;
1631
- if (!bindingMatches(payload.binding, bindTo, hashAlgorithm)) return null;
1794
+ if (!bindingMatches(payload.binding, bindTo, hashAlgorithm, state.startsWith(BOUND_STATE_PREFIX))) return null;
1632
1795
  return {
1633
1796
  ...payload,
1634
1797
  redirectTo: sanitizeOAuthRedirect(payload.redirectTo, config.allowedRedirectHosts)
@@ -1636,14 +1799,15 @@ async function verifyOAuthState(state, provider, store, config = {}, bindTo) {
1636
1799
  }
1637
1800
  /**
1638
1801
  * Whether the presented value matches the binding recorded at authorize time.
1639
- * A state created without a binding still verifies, so an app that has not
1640
- * adopted `bindTo` keeps working; a state created *with* one is useless to a
1641
- * browser that cannot present it, so a missing or wrong value fails.
1802
+ * A flow bound on neither side verifies, so an app that has not adopted
1803
+ * `bindTo` keeps working. A bound flow fails on a missing value on either side:
1804
+ * a browser that cannot present the binding, or a store that did not keep it.
1642
1805
  */
1643
- function bindingMatches(stored, presented, hashAlgorithm) {
1806
+ function bindingMatches(stored, presented, hashAlgorithm, stateWasBound) {
1644
1807
  if (!stored) {
1645
- if (presented) warnOnceAboutDroppedBinding();
1646
- return true;
1808
+ if (!stateWasBound && !presented) return true;
1809
+ warnAboutDroppedBinding();
1810
+ return false;
1647
1811
  }
1648
1812
  if (!presented) return false;
1649
1813
  return secureCompare(stored, hashToken(presented, hashAlgorithm));
@@ -1817,6 +1981,17 @@ function parseOAuthRedirectUrl(url) {
1817
1981
  }
1818
1982
  //#endregion
1819
1983
  //#region src/auth/AuthenticatableModel.ts
1984
+ /**
1985
+ * Marks a payload whose password value is already hashed, out of band because
1986
+ * an in-place model has only one column to read. Stripped before the payload
1987
+ * reaches the database; `storePasswordHash()` is the only writer.
1988
+ */
1989
+ const PRECOMPUTED_HASH = Symbol("guren.auth.precomputedPasswordHash");
1990
+ function withoutMarker(data) {
1991
+ const copy = { ...data };
1992
+ Reflect.deleteProperty(copy, PRECOMPUTED_HASH);
1993
+ return copy;
1994
+ }
1820
1995
  var AuthenticatableModel = class extends Model {
1821
1996
  static createType = void 0;
1822
1997
  static passwordField = "password";
@@ -1846,16 +2021,36 @@ var AuthenticatableModel = class extends Model {
1846
2021
  denied.push(this.resolveRememberTokenField());
1847
2022
  return denied;
1848
2023
  }
2024
+ /** The model author's own choice, read by `ModelUserProvider` so one model and its provider cannot write at different parameters. */
2025
+ static explicitPasswordHasher() {
2026
+ return this.passwordHasher ?? null;
2027
+ }
2028
+ /**
2029
+ * Assigned by `AuthManager.useModel()` at bind time, never by the model's
2030
+ * author. A class evaluating before `createApp()` therefore pins nothing, and
2031
+ * a model no app ever bound falls through to scrypt (a seeder run bare, a unit test).
2032
+ */
2033
+ static configuredPasswordHasher = null;
1849
2034
  static resolvePasswordHasher() {
1850
- if (this.passwordHasher) return this.passwordHasher;
1851
- const hasher = new DefaultHasher();
1852
- this.passwordHasher = hasher;
1853
- return hasher;
2035
+ return resolveModelHasher(this);
2036
+ }
2037
+ /**
2038
+ * Persist an already-hashed password without hashing it again. A model that
2039
+ * hashes in place (`passwordField === passwordHashField`) cannot tell a hash
2040
+ * from a plaintext by column name, so a rehash written through `update()`
2041
+ * would be hashed a second time and lock the account out.
2042
+ */
2043
+ static async storePasswordHash(where, column, hash) {
2044
+ await this.forceUpdate(where, {
2045
+ [column]: hash,
2046
+ [PRECOMPUTED_HASH]: true
2047
+ });
1854
2048
  }
1855
2049
  static async preparePersistencePayload(data) {
1856
- const basePayload = await super.preparePersistencePayload(data);
2050
+ const precomputed = Reflect.get(data, PRECOMPUTED_HASH) === true;
2051
+ const basePayload = await super.preparePersistencePayload(precomputed ? withoutMarker(data) : data);
1857
2052
  const passwordField = this.resolvePasswordField();
1858
- if (!(passwordField in basePayload)) return basePayload;
2053
+ if (precomputed || !(passwordField in basePayload)) return basePayload;
1859
2054
  const payload = { ...basePayload };
1860
2055
  const plainPassword = payload[passwordField];
1861
2056
  const hashField = this.resolvePasswordHashField();
@@ -2093,4 +2288,4 @@ function requireVerifiedEmail(options = {}) {
2093
2288
  };
2094
2289
  }
2095
2290
  //#endregion
2096
- 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 _, getSessionFromContext as _t, isEmailVerified as a, secureStringCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c, NodeHasher as ct, completePasswordReset as d, BaseUserProvider as dt, generateId as et, createPasswordResetToken as f, installAgentPrincipal as ft, MemoryOAuthStateStore as g, defaultCookieSecure as gt, AuthenticatableModel as h, createSessionMiddleware as ht, createEmailVerificationToken as i, secureCompare as it, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, ScryptHasher as lt, verifyPasswordResetToken as m, MemorySessionStore as mt, buildVerificationUrl as n, hashToken as nt, parseVerificationUrl as o, ModelUserProvider as ot, parsePasswordResetUrl as p, readAgentPrincipal as pt, revokeApiToken as q, completeEmailVerification as r, parseTokenUrl as rt, requireVerifiedEmail as s, DefaultHasher as st, MemoryEmailVerificationStore as t, generateToken as tt, buildPasswordResetUrl as u, AuthenticationException as ut, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, createBearerTokenMiddleware as z };
2291
+ export { SessionGuard as $, verifyOAuthState as A, createBearerTokenMiddleware as B, createGoogleOAuthProviderConfig as C, fetchOAuthUserProfile as D, exchangeOAuthCode as E, DEFAULT_PROVIDER as F, parseApiToken as G, getApiTokenOrFail as H, TokenGuard as I, revokeApiToken as J, readBearerToken as K, API_TOKEN_KEY as L, isAppRelativePath as M, normalizeRedirectTarget as N, parseOAuthRedirectUrl as O, AuthManager as P, verifyApiToken as Q, MemoryApiTokenStore as R, createGitHubOAuthProviderConfig as S, createOAuthState as T, getUserApiTokens as U, getApiToken as V, hasBearerHeader as W, tokenCanAll as X, tokenCan as Y, tokenCanAny as Z, OAUTH_SESSION_BINDING_KEY as _, getSessionFromContext as _t, isEmailVerified as a, secureCompare as at, buildOAuthRedirectUrl as b, verifyEmailToken as c, DefaultHasher as ct, completePasswordReset as d, BaseUserProvider as dt, buildTokenUrl as et, createPasswordResetToken as f, installAgentPrincipal as ft, MemoryOAuthStateStore as g, defaultCookieSecure as gt, AuthenticatableModel as h, createSessionMiddleware as ht, createEmailVerificationToken as i, parseTokenUrl as it, hostMatchesAllowlist as j, sanitizeOAuthRedirect as k, MemoryPasswordResetStore as l, NodeHasher as lt, verifyPasswordResetToken as m, MemorySessionStore as mt, buildVerificationUrl as n, generateToken as nt, parseVerificationUrl as o, secureStringCompare as ot, parsePasswordResetUrl as p, readAgentPrincipal as pt, revokeAllApiTokens as q, completeEmailVerification as r, hashToken as rt, requireVerifiedEmail as s, ModelUserProvider as st, MemoryEmailVerificationStore as t, generateId as tt, buildPasswordResetUrl as u, ScryptHasher as ut, OAuthManager as v, createOAuthManager as w, createDiscordOAuthProviderConfig as x, buildOAuthAuthorizeUrl as y, createApiToken as z };
@@ -47,8 +47,20 @@ export declare class Gate {
47
47
  getPolicyFor(model: unknown): Policy | undefined;
48
48
  }
49
49
  export declare function createGate(options?: GateOptions): Gate;
50
+ /**
51
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the gate on the
52
+ * app's container instead — `AuthorizationServiceProvider` already does, and a
53
+ * provider of your own reaches it as `this.container.instance('gate', gate)`.
54
+ */
50
55
  export declare function setGate(gate: Gate): void;
56
+ /**
57
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use `this.make('gate')`
58
+ * in a controller, `getRequestContainer(ctx).make('gate')` in middleware, or
59
+ * `defaultContainer().make('gate')`.
60
+ */
51
61
  export declare function getGate(): Gate;
62
+ /** @internal The default application's `gate`, else the one `setGate()` installed, without the warning. */
63
+ export declare function resolveGate(): Gate;
52
64
  /** Define a gate on the global instance. */
53
65
  export declare function defineGate(ability: string, callback: GateCallback): void;
54
66
  export declare function can(ability: string, ...args: unknown[]): Promise<boolean>;
@@ -1,2 +1,2 @@
1
- import { _ as setGate, a as withAuthorization, c as Gate, d as can, f as cannot, g as isAuthorizationResponse, h as getGate, l as Response, m as defineGate, n as authorizeMiddleware, o as Policy, p as createGate, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as authorize } from "../authorization-CdEWZZw3.js";
1
+ import { a as withAuthorization, c as Gate, d as can, f as cannot, g as isAuthorizationResponse, h as getGate, l as Response, m as defineGate, n as authorizeMiddleware, o as Policy, p as createGate, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as authorize, v as setGate } from "../authorization-0mCGUFoI.js";
2
2
  export { Gate, Policy, Response, authorize, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, can, cannot, createGate, defineGate, definePolicy, getGate, isAuthorizationResponse, setGate, withAuthorization };