@guren/server 2.22.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 (104) hide show
  1. package/dist/Job-BxioDEcS.js +165 -0
  2. package/dist/auth/AuthManager.d.ts +29 -0
  3. package/dist/auth/AuthenticatableModel.d.ts +15 -0
  4. package/dist/auth/RequestAuthContext.d.ts +10 -1
  5. package/dist/auth/SessionGuard.d.ts +2 -0
  6. package/dist/auth/api-token.d.ts +6 -0
  7. package/dist/auth/context.d.ts +32 -0
  8. package/dist/auth/index.d.ts +7 -0
  9. package/dist/auth/index.js +2 -2
  10. package/dist/auth/model-capability.d.ts +8 -0
  11. package/dist/auth/oauth/index.d.ts +5 -0
  12. package/dist/auth/password/DefaultHasher.d.ts +17 -6
  13. package/dist/auth/password/configured-hasher.d.ts +23 -0
  14. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  15. package/dist/auth/providers/unconfigured-user-provider.d.ts +12 -0
  16. package/dist/auth/types.d.ts +9 -0
  17. package/dist/{auth-CjE2oO50.js → auth-D_W1cJp3.js} +279 -84
  18. package/dist/authorization/Gate.d.ts +12 -0
  19. package/dist/authorization/index.js +1 -1
  20. package/dist/{authorization-CdEWZZw3.js → authorization-0mCGUFoI.js} +58 -12
  21. package/dist/broadcasting/BroadcastManager.d.ts +10 -0
  22. package/dist/broadcasting/index.js +1 -1
  23. package/dist/{broadcasting-B5RzB0A2.js → broadcasting-BdJnaq1O.js} +17 -3
  24. package/dist/container/Container.d.ts +18 -1
  25. package/dist/container/bindings.d.ts +5 -0
  26. package/dist/container/index.d.ts +4 -2
  27. package/dist/container/resolve-optional.d.ts +10 -0
  28. package/dist/context-af2n5abO.js +91 -0
  29. package/dist/{Job-CvDwk2Gj.js → default-application-Chbrul_m.js} +126 -82
  30. package/dist/encryption/Encrypter.d.ts +10 -0
  31. package/dist/encryption/index.js +1 -1
  32. package/dist/{encryption-uwP3Di4D.js → encryption-BRjZnshr.js} +23 -5
  33. package/dist/errors/ExceptionHandler.d.ts +10 -0
  34. package/dist/events/Event.d.ts +18 -0
  35. package/dist/events/EventManager.d.ts +56 -4
  36. package/dist/events/index.d.ts +2 -1
  37. package/dist/events/index.js +2 -2
  38. package/dist/events/queued.d.ts +8 -0
  39. package/dist/events/serialize.d.ts +8 -0
  40. package/dist/events/types.d.ts +19 -2
  41. package/dist/events-C86rS63h.js +428 -0
  42. package/dist/health/checks/CacheCheck.d.ts +3 -5
  43. package/dist/health/checks/StorageCheck.d.ts +3 -5
  44. package/dist/health/index.js +1 -1
  45. package/dist/{health-DQSvUplL.js → health-CB0oS_UE.js} +2 -2
  46. package/dist/http/Application.d.ts +28 -0
  47. package/dist/http/default-application.d.ts +33 -0
  48. package/dist/http/middleware/detect-locale.d.ts +2 -1
  49. package/dist/http/request-container.d.ts +25 -0
  50. package/dist/i18n/I18nManager.d.ts +16 -3
  51. package/dist/i18n/index.d.ts +1 -1
  52. package/dist/i18n/index.js +2 -2
  53. package/dist/{i18n-BZ2VrSud.js → i18n-DRo1g0AN.js} +34 -10
  54. package/dist/index.d.ts +14 -9
  55. package/dist/index.js +179 -84
  56. package/dist/lambda/index.js +1 -1
  57. package/dist/logging/LogManager.d.ts +9 -0
  58. package/dist/logging/index.js +1 -1
  59. package/dist/{logging-Dmzdb6mL.js → logging-CXotojgW.js} +16 -3
  60. package/dist/mail/Mail.d.ts +14 -1
  61. package/dist/mail/MailManager.d.ts +10 -2
  62. package/dist/mail/index.js +1 -1
  63. package/dist/{mail-9CrvJyBZ.js → mail-CmxO2Ttx.js} +42 -11
  64. package/dist/mvc/Controller.d.ts +1 -1
  65. package/dist/mvc/Router.d.ts +16 -5
  66. package/dist/mvc/inertia/InertiaEngine.d.ts +18 -3
  67. package/dist/mvc/inertia/shared.d.ts +7 -0
  68. package/dist/notifications/NotificationManager.d.ts +15 -0
  69. package/dist/notifications/index.js +1 -1
  70. package/dist/{notifications-D0VXkFLF.js → notifications-CE3U7uyg.js} +24 -5
  71. package/dist/providers/AuthServiceProvider.d.ts +5 -4
  72. package/dist/providers/AuthorizationServiceProvider.d.ts +2 -2
  73. package/dist/providers/BroadcastServiceProvider.d.ts +4 -1
  74. package/dist/providers/EncryptionServiceProvider.d.ts +7 -1
  75. package/dist/providers/EventServiceProvider.d.ts +1 -0
  76. package/dist/providers/LogServiceProvider.d.ts +6 -1
  77. package/dist/providers/MailServiceProvider.d.ts +7 -1
  78. package/dist/providers/NotificationServiceProvider.d.ts +4 -1
  79. package/dist/queue/Job.d.ts +39 -0
  80. package/dist/queue/QueueManager.d.ts +14 -5
  81. package/dist/queue/Worker.d.ts +2 -1
  82. package/dist/queue/index.d.ts +1 -1
  83. package/dist/queue/index.js +3 -3
  84. package/dist/queue/types.d.ts +7 -0
  85. package/dist/{queue-zPPYZdif.js → queue-B3x_RKnB.js} +24 -10
  86. package/dist/redis/RedisSchedulerLock.d.ts +17 -0
  87. package/dist/redis/index.d.ts +2 -0
  88. package/dist/redis/index.js +21 -1
  89. package/dist/runtime/index.js +1 -1
  90. package/dist/scheduling/MemorySchedulerLock.d.ts +16 -0
  91. package/dist/scheduling/ScheduledTask.d.ts +19 -2
  92. package/dist/scheduling/Scheduler.d.ts +25 -0
  93. package/dist/scheduling/index.d.ts +2 -1
  94. package/dist/scheduling/index.js +2 -2
  95. package/dist/scheduling/types.d.ts +26 -2
  96. package/dist/{scheduling-C6tcOtUl.js → scheduling-DudNXGnh.js} +178 -20
  97. package/dist/storage/index.js +1 -1
  98. package/dist/{storage-D_yNe54O.js → storage-6HLaUf9j.js} +2 -13
  99. package/dist/support/deprecate.d.ts +16 -0
  100. package/dist/{vite-manifest-D295_7-_.js → vite-manifest-B8720V7w.js} +1 -1
  101. package/dist/warn-once-p-IlMjra.js +13 -0
  102. package/package.json +2 -2
  103. package/dist/context-CXk_umpT.js +0 -21
  104. package/dist/events-DOmAHDeP.js +0 -230
@@ -0,0 +1,165 @@
1
+ import { h as warnDeprecatedSetter, m as warnDeprecatedGetter, n as ambientBinding, o as defaultContainer, r as ambientContainer } from "./default-application-Chbrul_m.js";
2
+ import { randomBytes } from "node:crypto";
3
+ //#region src/container/resolve-optional.ts
4
+ function resolveOptional(container, key) {
5
+ if (!container) return;
6
+ const optional = container.makeOptional;
7
+ if (typeof optional === "function") return optional.call(container, key);
8
+ return container.has?.(key) ? container.make(key) : void 0;
9
+ }
10
+ //#endregion
11
+ //#region src/queue/Job.ts
12
+ /**
13
+ * The pin `setQueueDriver()` writes, and nothing else does. A manager that
14
+ * published its own driver here pinned the first booted app's queue for every
15
+ * later `Application` in the process.
16
+ */
17
+ let globalDriver = null;
18
+ /**
19
+ * Pins the driver `Job.dispatch()` sends through, ahead of the container's
20
+ * `queue` manager. An explicit override rather than a fallback: `@guren/testing`'s
21
+ * `fakeQueue()` and the tutorial's queue test inject through it (RFC 0023 §3).
22
+ * The pin survives its deprecation window because nothing else expresses it; it
23
+ * goes with this setter in Part 3.
24
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the manager on the
25
+ * app's container — `QueueServiceProvider` already does — and inject a fake with
26
+ * `app.container.fake('queue', manager)`.
27
+ */
28
+ function setQueueDriver(driver) {
29
+ warnDeprecatedSetter("setQueueDriver");
30
+ globalDriver = driver;
31
+ }
32
+ /** Drops the pin, so `getQueueDriver()` falls back to the container again. */
33
+ function clearQueueDriver() {
34
+ globalDriver = null;
35
+ }
36
+ /** @internal The driver `setQueueDriver()` pinned, for a dispatcher with a container of its own to honour first. */
37
+ function pinnedQueueDriver() {
38
+ return globalDriver;
39
+ }
40
+ /** The `queue` manager bound in the default application, or null when there is neither. */
41
+ function boundQueueManager() {
42
+ return ambientBinding("queue") ?? null;
43
+ }
44
+ /**
45
+ * The driver `Job.dispatch()` sends through: the pin when set, else the default
46
+ * driver of the `queue` manager the default application binds, else null.
47
+ * Total by contract — every caller treats it as `QueueDriver | null`, so a
48
+ * manager bound with no factory for its default must read as absent rather
49
+ * than throw.
50
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Resolve the manager
51
+ * from the container that owns the call — `this.make('queue')` in a controller,
52
+ * job or command — and take `manager.driver()`.
53
+ */
54
+ function getQueueDriver() {
55
+ warnDeprecatedGetter("getQueueDriver");
56
+ return resolveQueueDriver();
57
+ }
58
+ /** @internal `getQueueDriver()` without the warning, for the framework's own dispatch paths. */
59
+ function resolveQueueDriver() {
60
+ if (globalDriver) return globalDriver;
61
+ const manager = boundQueueManager();
62
+ if (!manager || !manager.hasDriver(manager.getDefaultDriverName())) return null;
63
+ return manager.driver();
64
+ }
65
+ /** Why `getQueueDriver()` came back null: a manager bound with no driver reads differently from no manager at all. */
66
+ function missingQueueDriverMessage() {
67
+ const manager = boundQueueManager();
68
+ if (manager) return `Queue driver not configured: the "queue" manager has no driver named "${manager.getDefaultDriverName()}". Register one with manager.registerDriver(name, factory), or pass createQueueManager({ drivers }) a factory for it.`;
69
+ return "Queue driver not configured. Register a provider that binds a QueueManager as \"queue\" (QueueServiceProvider, or your own), or call setQueueDriver() first.";
70
+ }
71
+ function generateJobId() {
72
+ return randomBytes(16).toString("hex");
73
+ }
74
+ /**
75
+ * The one enqueue behind `Job.dispatch()` and `QueueManager.dispatch()`, so the
76
+ * two forms cannot write different messages.
77
+ */
78
+ async function enqueueJob(driver, JobClass, payload, options = {}) {
79
+ const jobId = generateJobId();
80
+ const now = /* @__PURE__ */ new Date();
81
+ const delay = options.delay ?? 0;
82
+ const job = {
83
+ id: jobId,
84
+ name: resolveJobName(JobClass),
85
+ payload,
86
+ queue: options.queue ?? JobClass.queue,
87
+ attempts: 0,
88
+ maxAttempts: options.maxAttempts ?? JobClass.maxAttempts,
89
+ availableAt: new Date(now.getTime() + delay),
90
+ createdAt: now,
91
+ reservedAt: null
92
+ };
93
+ await driver.push(job);
94
+ return jobId;
95
+ }
96
+ var Job = class {
97
+ /**
98
+ * Stable wire name: queued messages record it and the worker resolves the
99
+ * class back from it. Defaults to the class name, which breaks under
100
+ * identifier mangling or a rename with messages still in flight.
101
+ * @default the class name
102
+ */
103
+ static jobName;
104
+ /** @default 'default' */
105
+ static queue = "default";
106
+ /** @default 3 */
107
+ static maxAttempts = 3;
108
+ /**
109
+ * 'exponential' = 2^attempt * 1000ms, 'linear' = attempt * 1000ms, a number
110
+ * is a fixed delay in milliseconds.
111
+ * @default 'exponential'
112
+ */
113
+ static backoff = "exponential";
114
+ container;
115
+ /** @internal Called by the Worker with the container of the app it drains, before `handle()`. */
116
+ setContainer(container) {
117
+ this.container = container;
118
+ }
119
+ make(key) {
120
+ return (this.container ?? defaultContainer()).make(key);
121
+ }
122
+ makeOptional(key) {
123
+ return resolveOptional(this.container ?? ambientContainer(), key);
124
+ }
125
+ static async dispatch(payload, options = {}) {
126
+ const driver = resolveQueueDriver();
127
+ if (!driver) throw new Error(missingQueueDriverMessage());
128
+ return enqueueJob(driver, this, payload, options);
129
+ }
130
+ static async dispatchAfter(delayMs, payload, options = {}) {
131
+ return this.dispatch(payload, {
132
+ ...options,
133
+ delay: delayMs
134
+ });
135
+ }
136
+ static calculateRetryDelay(attempts) {
137
+ if (typeof this.backoff === "number") return this.backoff;
138
+ if (this.backoff === "linear") return attempts * 1e3;
139
+ return Math.pow(2, attempts) * 1e3;
140
+ }
141
+ };
142
+ /**
143
+ * Only an *own* `jobName` counts: statics are inherited, so reading the
144
+ * prototype chain would make every subclass of a pinned job claim its
145
+ * parent's identity and overwrite it in the registry.
146
+ */
147
+ function resolveJobName(jobClass) {
148
+ return (Object.prototype.hasOwnProperty.call(jobClass, "jobName") ? jobClass.jobName : void 0) ?? jobClass.name;
149
+ }
150
+ const jobRegistry = /* @__PURE__ */ new Map();
151
+ function registerJob(jobClass) {
152
+ jobRegistry.set(resolveJobName(jobClass), jobClass);
153
+ }
154
+ function getJob(name) {
155
+ return jobRegistry.get(name);
156
+ }
157
+ function getRegisteredJobs() {
158
+ return new Map(jobRegistry);
159
+ }
160
+ /** Testing only. */
161
+ function clearJobRegistry() {
162
+ jobRegistry.clear();
163
+ }
164
+ //#endregion
165
+ export { getJob as a, pinnedQueueDriver as c, resolveQueueDriver as d, setQueueDriver as f, enqueueJob as i, registerJob as l, clearJobRegistry as n, getQueueDriver as o, resolveOptional as p, clearQueueDriver as r, getRegisteredJobs as s, Job as t, resolveJobName as u };
@@ -2,7 +2,11 @@ import type { Context } from 'hono';
2
2
  import type { Model, PlainObject } from '@guren/orm';
3
3
  import { type ModelUserProviderOptions } from './providers/ModelUserProvider.js';
4
4
  import { type ApiTokenStore } from './api-token.js';
5
+ import type { PasswordHasher } from './password/PasswordHasher.js';
5
6
  import type { AttachContextOptions, AuthContext, AuthManagerContract, AuthManagerOptions, AuthCredentials, Guard, GuardContext, GuardFactory, ProviderFactory, UserProvider } from './types.js';
7
+ /** The guard and provider names an app gets without naming either: `createApp()` registers them, `useModel()` fills them. */
8
+ export declare const DEFAULT_GUARD = "web";
9
+ export declare const DEFAULT_PROVIDER = "users";
6
10
  /** How `useTokens()` configures the guard it registers. */
7
11
  export interface ApiTokenGuardOptions {
8
12
  /** Registered provider name that loads the full user record from a token's userId. */
@@ -19,9 +23,21 @@ export declare class AuthManager implements AuthManagerContract {
19
23
  private tokenGuard;
20
24
  private apiTokenStore;
21
25
  private apiTokenOptions;
26
+ private readonly passwordHasher;
22
27
  constructor(options?: AuthManagerOptions);
28
+ /**
29
+ * The one password hasher this app writes with: `AuthPluginOptions.hasher`
30
+ * resolved, scrypt by default. `useModel()` hands it to the provider, and
31
+ * `AuthenticatableModel` reads it through the container, so a row the model
32
+ * hashes and a login the provider verifies never disagree on the format.
33
+ */
34
+ hasher(): PasswordHasher;
23
35
  registerGuard<User>(name: string, factory: GuardFactory<User>): void;
24
36
  registerProvider<User>(name: string, factory: ProviderFactory<User>): void;
37
+ /** The guard `useTokens()` registered, or null. On this class rather than the contract, like `getApiTokenOptions()`. */
38
+ getTokenGuard(): string | null;
39
+ /** Whether a provider factory is registered under `name`; `getProvider()` throws where this is false. */
40
+ hasProvider(name: string): boolean;
25
41
  getProvider<User>(name: string): UserProvider<User>;
26
42
  createGuard<User>(name: string, context: GuardContext): Guard<User>;
27
43
  guardNames(): string[];
@@ -36,6 +52,19 @@ export declare class AuthManager implements AuthManagerContract {
36
52
  */
37
53
  resolveGuardName(ctx: Context, name?: string): string;
38
54
  createAuthContext(ctx: Context, options?: AttachContextOptions): AuthContext;
55
+ /**
56
+ * The user provider `useTokens({ provider })` configured, and no other.
57
+ * Every surface that turns a token's or a principal's id into a user record
58
+ * reads this one: a second rule would mean a policy reading a user field
59
+ * behaved differently depending on which surface the call arrived on.
60
+ */
61
+ private tokenUserProvider;
62
+ /**
63
+ * The principal a middleware resolved for this request, sanitized the way the
64
+ * token guard sanitizes its own. Read at call time, so a context built before
65
+ * the authenticating middleware ran still answers with it.
66
+ */
67
+ private resolvePrincipal;
39
68
  attempt(name: string, ctx: Context, credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
40
69
  /**
41
70
  * Register a model-based authentication provider and session guard — the
@@ -20,6 +20,21 @@ export declare abstract class AuthenticatableModel<TRecord extends PlainObject =
20
20
  * values such as `passwordHash: 'oauth:...'`.
21
21
  */
22
22
  protected static deniedFields(): string[];
23
+ /** The model author's own choice, read by `ModelUserProvider` so one model and its provider cannot write at different parameters. */
24
+ static explicitPasswordHasher(): PasswordHasher | null;
25
+ /**
26
+ * Assigned by `AuthManager.useModel()` at bind time, never by the model's
27
+ * author. A class evaluating before `createApp()` therefore pins nothing, and
28
+ * a model no app ever bound falls through to scrypt (a seeder run bare, a unit test).
29
+ */
30
+ static configuredPasswordHasher: PasswordHasher | null;
23
31
  protected static resolvePasswordHasher(): PasswordHasher;
32
+ /**
33
+ * Persist an already-hashed password without hashing it again. A model that
34
+ * hashes in place (`passwordField === passwordHashField`) cannot tell a hash
35
+ * from a plaintext by column name, so a rehash written through `update()`
36
+ * would be hashed a second time and lock the account out.
37
+ */
38
+ static storePasswordHash(where: PlainObject, column: string, hash: string): Promise<void>;
24
39
  protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
25
40
  }
@@ -1,14 +1,17 @@
1
1
  import type { Context } from 'hono';
2
2
  import type { Session } from '../http/middleware/index.js';
3
3
  import type { AuthContext, AuthCredentials, Guard } from './types.js';
4
+ import { type ResolvedPrincipal } from './context.js';
4
5
  export type GuardResolver = (resolvedName: string) => Guard<unknown>;
6
+ export type PrincipalResolver = () => ResolvedPrincipal | undefined;
5
7
  export declare class RequestAuthContext implements AuthContext {
6
8
  private readonly resolveName;
7
9
  private readonly ctx;
8
10
  private readonly resolveSession;
9
11
  private readonly resolveGuard;
12
+ private readonly resolvePrincipal;
10
13
  private readonly guardCache;
11
- constructor(resolveName: (name?: string) => string, ctx: Context, resolveSession: () => Session | undefined, resolveGuard: GuardResolver);
14
+ constructor(resolveName: (name?: string) => string, ctx: Context, resolveSession: () => Session | undefined, resolveGuard: GuardResolver, resolvePrincipal?: PrincipalResolver);
12
15
  guard<T = unknown>(name?: string): Guard<T>;
13
16
  session<T extends Session = Session>(): T | undefined;
14
17
  check(): Promise<boolean>;
@@ -19,4 +22,10 @@ export declare class RequestAuthContext implements AuthContext {
19
22
  login<T = unknown>(user: T, remember?: boolean): Promise<void>;
20
23
  attempt(credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
21
24
  logout(): Promise<void>;
25
+ /**
26
+ * The request's identity is whatever just logged in, so a principal a
27
+ * middleware resolved stops answering. A later `logout()` therefore ends the
28
+ * new session rather than revoking the credential the request arrived with.
29
+ */
30
+ private forgetPrincipal;
22
31
  }
@@ -26,5 +26,7 @@ export declare class SessionGuard<User extends Authenticatable = Authenticatable
26
26
  logout(): Promise<void>;
27
27
  attempt(credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
28
28
  validate(credentials: AuthCredentials): Promise<User | null>;
29
+ /** Never the plaintext or the hash: a warning is a log line, and both belong in neither. */
30
+ private describeUser;
29
31
  session<T extends Session = Session>(): T | undefined;
30
32
  }
@@ -144,6 +144,12 @@ export declare function getUserApiTokens(userId: string | number, store: ApiToke
144
144
  * Context key for storing the authenticated token.
145
145
  */
146
146
  export declare const API_TOKEN_KEY = "guren:api-token";
147
+ /**
148
+ * Revoke the token a request presented, and clear it from the request context
149
+ * so `getApiToken()` / `getApiTokenOrFail()` cannot succeed after a logout on
150
+ * the same request. The slot is cleared whether or not a token still verified.
151
+ */
152
+ export declare function revokePresentedToken(ctx: Context, tokenId: string | undefined, store: ApiTokenStore): Promise<void>;
147
153
  /**
148
154
  * Options for the bearer token middleware.
149
155
  */
@@ -1,3 +1,4 @@
1
+ import type { Context } from 'hono';
1
2
  import type { AuthContext } from './types.js';
2
3
  /**
3
4
  * Context key the framework auth context is stored under.
@@ -7,6 +8,26 @@ import type { AuthContext } from './types.js';
7
8
  * re-exports it, and it stays a public root export.
8
9
  */
9
10
  export declare const AUTH_CONTEXT_KEY = "guren:auth";
11
+ /**
12
+ * Context key the principal a middleware already resolved is stored under.
13
+ *
14
+ * The framework auth context answers from this slot before it reaches a guard,
15
+ * so a middleware that authenticates a request (the bearer-token middleware,
16
+ * or an app's own) reaches the Gate whatever order it is mounted in.
17
+ */
18
+ export declare const RESOLVED_PRINCIPAL_KEY = "guren:resolved-principal";
19
+ /**
20
+ * An identity a middleware established for this one request.
21
+ *
22
+ * `user` is null when the credential verified but its user cannot be loaded:
23
+ * the request is then unauthenticated, not merely unresolved.
24
+ */
25
+ export interface ResolvedPrincipal {
26
+ user: unknown;
27
+ id: unknown;
28
+ /** Invalidate the presented credential. `logout()` calls it. */
29
+ revoke?: () => Promise<void>;
30
+ }
10
31
  /**
11
32
  * Read the framework auth context off a request context. `ctx.get` returns
12
33
  * arbitrary values for unknown keys, so the cast is a claim, not a check. A
@@ -17,3 +38,14 @@ export declare const AUTH_CONTEXT_KEY = "guren:auth";
17
38
  export declare function getAuthContext(ctx: {
18
39
  get: (key: string) => unknown;
19
40
  }): AuthContext | undefined;
41
+ export declare function getResolvedPrincipal(ctx: {
42
+ get: (key: string) => unknown;
43
+ }): ResolvedPrincipal | undefined;
44
+ export declare function setResolvedPrincipal(ctx: Context, principal: ResolvedPrincipal | undefined): void;
45
+ /**
46
+ * The auth context a request carries when a middleware resolved a principal and
47
+ * nothing attached a framework context — a bearer-authenticated route on a
48
+ * plain Hono app. Credential flows throw rather than pretending to succeed;
49
+ * `logout()` revokes the presented credential.
50
+ */
51
+ export declare function createPrincipalAuthContext(ctx: Context): AuthContext;
@@ -5,12 +5,19 @@ export { TokenGuard } from './TokenGuard.js';
5
5
  export type { TokenGuardOptions } from './TokenGuard.js';
6
6
  export { BaseUserProvider } from './providers/UserProvider.js';
7
7
  export { ModelUserProvider } from './providers/ModelUserProvider.js';
8
+ export { ScryptHasher as Argon2Hasher } from './password/ScryptHasher.js';
9
+ /**
10
+ * @deprecated Renamed to `Argon2Hasher`, which is what it writes: `Bun.password`'s
11
+ * Argon2id, never scrypt. The name predates the implementation. Removed in 3.0.0.
12
+ */
8
13
  export { ScryptHasher } from './password/ScryptHasher.js';
9
14
  export { NodeHasher } from './password/NodeHasher.js';
10
15
  export { AuthenticatableModel } from './AuthenticatableModel.js';
11
16
  export { createPasswordResetToken, verifyPasswordResetToken, completePasswordReset, buildPasswordResetUrl, parsePasswordResetUrl, MemoryPasswordResetStore, } from './password-reset.js';
12
17
  export { createEmailVerificationToken, verifyEmailToken, completeEmailVerification, buildVerificationUrl, parseVerificationUrl, isEmailVerified, requireVerifiedEmail, MemoryEmailVerificationStore, } from './email-verification.js';
13
18
  export type { PasswordHasher } from './password/PasswordHasher.js';
19
+ export type { PasswordHasherOption } from './password/configured-hasher.js';
20
+ export type { PasswordHashAlgorithm, DefaultHasherOptions } from './password/DefaultHasher.js';
14
21
  export type { PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, } from './password-reset.js';
15
22
  export type { EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, } from './email-verification.js';
16
23
  export { createApiToken, parseApiToken, readBearerToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, } from './api-token.js';
@@ -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-CjE2oO50.js";
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 };
1
+ import { $ as SessionGuard, A as verifyOAuthState, B as createBearerTokenMiddleware, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, G as parseApiToken, H as getApiTokenOrFail, I as TokenGuard, J as revokeApiToken, K as readBearerToken, L as API_TOKEN_KEY, O as parseOAuthRedirectUrl, P as AuthManager, Q as verifyApiToken, R as MemoryApiTokenStore, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as getUserApiTokens, V as getApiToken, X as tokenCanAll, Y as tokenCan, Z as tokenCanAny, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, dt as BaseUserProvider, et as buildTokenUrl, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as parseTokenUrl, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as NodeHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as generateToken, o as parseVerificationUrl, ot as secureStringCompare, p as parsePasswordResetUrl, q as revokeAllApiTokens, r as completeEmailVerification, rt as hashToken, s as requireVerifiedEmail, st as ModelUserProvider, t as MemoryEmailVerificationStore, tt as generateId, u as buildPasswordResetUrl, ut as ScryptHasher, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createApiToken } from "../auth-D_W1cJp3.js";
2
+ export { API_TOKEN_KEY, ScryptHasher as Argon2Hasher, ScryptHasher, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, 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 };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The capability `T` a model class implements, or null. A capability check
3
+ * rather than `instanceof`: two copies of @guren/server coexist through
4
+ * workspace symlinks (src and dist), and a nominal test answers "no" for the
5
+ * copy it was not built from, silently ignoring a renamed credential column or
6
+ * a hasher the app bound.
7
+ */
8
+ export declare function capabilityOf<T>(model: unknown, ...methods: Array<keyof T & string>): T | null;
@@ -107,6 +107,11 @@ export declare const OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
107
107
  export interface OAuthAuthorizeOptions {
108
108
  scope?: string[];
109
109
  redirectTo?: string;
110
+ /**
111
+ * Use this value rather than a minted one. A bound flow returns it carrying
112
+ * the boundness marker, so send the `state` `authorize()` returns, not the
113
+ * one passed in.
114
+ */
110
115
  state?: string;
111
116
  extraParams?: Record<string, string>;
112
117
  /**
@@ -1,16 +1,27 @@
1
1
  import type { PasswordHasher } from './PasswordHasher.js';
2
2
  /**
3
- * Runtime-detecting password hasher behind `Hash`, the default for
4
- * `AuthenticatableModel` and `ModelUserProvider`: `Bun.password` on Bun (Argon2id,
5
- * despite `ScryptHasher`'s name), `crypto.scrypt` otherwise. **Verification routes
6
- * on the stored hash, not the runtime**, or a column written elsewhere would 500 on
7
- * every login; `$scrypt$` verifies anywhere, Argon2id/bcrypt needs `Bun.password`.
3
+ * The format new hashes are written in. `scrypt` is `node:crypto`'s and verifies
4
+ * on every runtime; `argon2` is `Bun.password`'s and needs Bun to read back.
5
+ */
6
+ export type PasswordHashAlgorithm = 'scrypt' | 'argon2';
7
+ export interface DefaultHasherOptions {
8
+ /** Defaults to `scrypt`. */
9
+ algorithm?: PasswordHashAlgorithm;
10
+ }
11
+ /**
12
+ * The hasher behind `Hash`, the default for `AuthenticatableModel` and
13
+ * `ModelUserProvider`. Writes the configured algorithm, scrypt unless told
14
+ * otherwise, so a row seeded under Bun still verifies on Node or Workers.
15
+ * Verification routes on the stored hash, not the writer: `$scrypt$` verifies
16
+ * anywhere, Argon2id/bcrypt needs `Bun.password`; the other format reports `needsRehash()`.
8
17
  */
9
18
  export declare class DefaultHasher implements PasswordHasher {
19
+ readonly algorithm: PasswordHashAlgorithm;
10
20
  private readonly bun;
11
21
  private readonly node;
22
+ private readonly writer;
12
23
  private readonly testing;
13
- constructor();
24
+ constructor(options?: DefaultHasherOptions);
14
25
  hash(plain: string): Promise<string>;
15
26
  verify(hashed: string, plain: string): Promise<boolean>;
16
27
  needsRehash(hashed: string): boolean;
@@ -0,0 +1,23 @@
1
+ import { type PasswordHashAlgorithm } from './DefaultHasher.js';
2
+ import type { PasswordHasher } from './PasswordHasher.js';
3
+ /**
4
+ * What `createApp({ auth: { hasher } })` accepts: an algorithm name for the
5
+ * built-in `DefaultHasher`, or a `PasswordHasher` of the app's own.
6
+ */
7
+ export type PasswordHasherOption = PasswordHashAlgorithm | PasswordHasher;
8
+ export declare function createPasswordHasher(option: PasswordHasherOption | undefined): PasswordHasher;
9
+ /**
10
+ * Hand the app's hasher to a model class at bind time, rather than letting the
11
+ * class read a process-wide container per hash. A model that declares `static
12
+ * passwordHasher` keeps the author's choice. The slot is a static, so a model
13
+ * class shared by two Applications carries the last binding.
14
+ */
15
+ export declare function bindPasswordHasher(model: unknown, hasher: PasswordHasher): void;
16
+ /**
17
+ * The one hasher precedence, read by the model class and by its provider: the
18
+ * author's `static passwordHasher`, then the caller's override, then what
19
+ * `useModel()` bound, then scrypt. A second spelling of this order is how a
20
+ * model and its provider come to write at different parameters, and every
21
+ * login then asks for a rehash the previous one already made.
22
+ */
23
+ export declare function resolveModelHasher(model: unknown, override?: PasswordHasher): PasswordHasher;
@@ -24,6 +24,9 @@ export declare class ModelUserProvider<User extends Authenticatable = Authentica
24
24
  retrieveByCredentials(credentials: AuthCredentials): Promise<User | null>;
25
25
  validateCredentials(user: User, credentials: AuthCredentials): Promise<boolean>;
26
26
  getId(user: User): unknown;
27
+ rehashPasswordIfRequired(user: User, credentials: AuthCredentials): Promise<void>;
28
+ /** forceUpdate keyed on the id column: both credential columns are denied to mass assignment. */
29
+ private writeColumn;
27
30
  /**
28
31
  * Strip the password hash, remember token, and the model's `hidden` fields
29
32
  * before the record leaves the auth layer. Credential validation runs on the
@@ -0,0 +1,12 @@
1
+ import type { UserProvider } from '../types.js';
2
+ /** The remediation both the thrown message and the boot warning end on. */
3
+ export declare const REGISTER_USER_PROVIDER_HINT: string;
4
+ export declare const NO_USER_PROVIDER_MESSAGE: string;
5
+ /**
6
+ * The provider behind the default guard until an app registers `users`. An
7
+ * anonymous request on an app with no auth is legitimately unauthenticated, so
8
+ * `retrieveById` answers null; a credential check with nothing to check
9
+ * against is a misconfiguration, so it throws rather than answering "wrong
10
+ * password" forever. One object: the guard is built per request.
11
+ */
12
+ export declare const unconfiguredUserProvider: UserProvider;
@@ -1,5 +1,6 @@
1
1
  import type { Context } from 'hono';
2
2
  import type { Session } from '../http/middleware/index.js';
3
+ import type { PasswordHasherOption } from './password/configured-hasher.js';
3
4
  export type AuthCredentials = Record<string, unknown>;
4
5
  export interface Authenticatable {
5
6
  getAuthIdentifier(): unknown;
@@ -30,6 +31,12 @@ export interface UserProvider<User = Authenticatable> {
30
31
  * remember tokens, model `hidden` fields) before caching or exposing a user.
31
32
  */
32
33
  sanitize?(user: User): User;
34
+ /**
35
+ * Called by a guard after `validateCredentials()` succeeded, never after it
36
+ * failed: re-hash the password in the current format and cost when the stored
37
+ * hash needs it, and persist the new value.
38
+ */
39
+ rehashPasswordIfRequired?(user: User, credentials: AuthCredentials): Promise<void> | void;
33
40
  }
34
41
  /** The conventional credential column names `ModelUserProvider.sanitize()` strips. */
35
42
  export type DefaultSanitizedKeys = 'password' | 'passwordHash' | 'password_hash' | 'rememberToken' | 'remember_token';
@@ -52,6 +59,8 @@ export interface ProviderFactory<User = Authenticatable> {
52
59
  }
53
60
  export interface AuthManagerOptions {
54
61
  defaultGuard?: string;
62
+ /** See `AuthPluginOptions.hasher`. Defaults to `'scrypt'`. */
63
+ hasher?: PasswordHasherOption;
55
64
  }
56
65
  export interface AttachContextOptions {
57
66
  guard?: string;