@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
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The scope grammar an API token's `abilities` use to reach agent tools
3
+ * (RFC 0016 §5.1).
4
+ *
5
+ * Four forms, and deliberately no more — a grammar an agent-facing consent
6
+ * screen has to render is only useful if a human can read a scope and say
7
+ * which tools it grants:
8
+ *
9
+ * - `tool:<name>` one tool, by exact name
10
+ * - `tools:read` every tool whose resolved `readOnlyHint` is true
11
+ * - `tools:*` every tool
12
+ * - `tools:<prefix>.*` every tool named `<prefix>.…`
13
+ *
14
+ * **Only `tool:` / `tools:` entries are considered.** Every other ability an
15
+ * `ApiToken` carries — including the store's default `['*']` — is ignored, so
16
+ * it matches nothing. This is the fail-closed half of a deliberate split:
17
+ *
18
+ * - A token issued before agent tools existed, for an app's own API, holds
19
+ * `['*']`. Reading that as "all agent tools" would silently hand every
20
+ * already-issued token the whole agent surface the moment an app declares
21
+ * its first `.agent()` route. Access to the agent surface is granted by an
22
+ * explicit tool scope or not at all (default deny, RFC §5.1); `tools:*` is
23
+ * the explicit way to say "everything".
24
+ * - A malformed entry is likewise ignored here rather than throwing: this
25
+ * module judges an already-issued token, and a token that cannot be parsed
26
+ * must grant less, never more. Rejecting a bad scope belongs to the
27
+ * *issuer* (`token:issue`, a later PR), which runs {@link parseToolScope}
28
+ * over what it was asked for and refuses a `null`.
29
+ *
30
+ * Matching is case-sensitive and entries are not trimmed. A stored ability
31
+ * with stray whitespace is an issuance bug; normalizing it here would make
32
+ * the judge more permissive than the issuer, which is the wrong direction.
33
+ */
34
+ /**
35
+ * The MCP tool-name grammar (SEP-986), which a `tool:` scope names and a
36
+ * `tools:<prefix>.*` scope has to stay inside — a scope that could not
37
+ * possibly name a legal tool is not a scope.
38
+ *
39
+ * `packages/cli/src/agent-route-check.ts` holds the same pattern for the
40
+ * check that fails a build over an illegal tool name. Collapsing the two onto
41
+ * this export is a later change, not this one: the CLI reaches `@guren/server`
42
+ * through `dist/`, so the collapse needs a built server and belongs with the
43
+ * PR that does the build-order work.
44
+ *
45
+ * Note what the charset gives for free: `*` is not in it, so `tool:posts.*`
46
+ * fails the test and needs no special case to be rejected.
47
+ */
48
+ export declare const AGENT_TOOL_NAME_PATTERN: RegExp;
49
+ /** One well-formed scope entry, discriminated by what it grants. */
50
+ export type ParsedToolScope =
51
+ /** `tool:<name>` — exactly the tool with this name. */
52
+ {
53
+ kind: 'tool';
54
+ name: string;
55
+ }
56
+ /** `tools:read` — every tool whose resolved `readOnlyHint` is true. */
57
+ | {
58
+ kind: 'read';
59
+ }
60
+ /** `tools:*` — every tool. */
61
+ | {
62
+ kind: 'all';
63
+ }
64
+ /** `tools:<prefix>.*` — every tool named `<prefix>.…`. `prefix` excludes the dot. */
65
+ | {
66
+ kind: 'prefix';
67
+ prefix: string;
68
+ };
69
+ /**
70
+ * The shape a tool has to present to be judged: its name, and whether it
71
+ * resolved to read-only. Deliberately not `DerivedAgentTool` — the token
72
+ * guard, the consent screen and a test fixture all supply this, and none of
73
+ * them should have to build a whole derived tool to ask a question about two
74
+ * fields. `DerivedAgentTool` is structurally compatible via
75
+ * `{ name: tool.toolName, readOnly: tool.annotations.readOnlyHint }`.
76
+ */
77
+ export interface ScopedTool {
78
+ name: string;
79
+ readOnly: boolean;
80
+ }
81
+ /**
82
+ * Parse one `abilities` entry.
83
+ *
84
+ * @returns The scope it denotes, or `null` for an entry that is not a tool
85
+ * scope at all (`'*'`, an app's own ability name) and for one that is
86
+ * malformed (`tools:`, `tools:.*`, `tools:*.store`, a prefix outside the
87
+ * tool-name grammar). Callers cannot tell those apart on purpose: both mean
88
+ * "grants no tool", and a judge that distinguished them would be inventing
89
+ * a third answer for a two-valued question.
90
+ *
91
+ * Note the two reserved `tools:` words are matched before the wildcard form,
92
+ * so a tool family literally named `read.…` is still reachable as
93
+ * `tools:read.*`, while a tool named exactly `read` is reachable only as
94
+ * `tool:read` — the reserved word wins its own spelling.
95
+ */
96
+ export declare function parseToolScope(entry: string): ParsedToolScope | null;
97
+ /**
98
+ * Whether a token's abilities grant a tool. Any one entry suffices — scopes
99
+ * are additive, and there is no deny form.
100
+ */
101
+ export declare function scopesAllowTool(abilities: readonly string[], tool: ScopedTool): boolean;
102
+ /**
103
+ * The concrete tool names a token's abilities grant, for the surfaces that
104
+ * have to show a human what a scope means: the OAuth consent screen, the
105
+ * `token:issue` confirmation, and the issuance-time lint.
106
+ *
107
+ * Literally a filter over {@link scopesAllowTool}, and it must stay one. A
108
+ * second matcher that walked entries and accumulated names is how a consent
109
+ * screen comes to list a tool the dispatcher then denies — the two answers
110
+ * have to be the same answer, not two implementations of one rule.
111
+ *
112
+ * @returns Names in the order the tools were given, so a caller controls the
113
+ * display order by ordering its input.
114
+ */
115
+ export declare function expandToolScopes(abilities: readonly string[], tools: readonly ScopedTool[]): string[];
@@ -1,11 +1,24 @@
1
1
  import type { Context } from 'hono';
2
2
  import type { Model, PlainObject } from '@guren/orm';
3
3
  import { type ModelUserProviderOptions } from './providers/ModelUserProvider.js';
4
+ import { type ApiTokenStore } from './api-token.js';
4
5
  import type { AttachContextOptions, AuthContext, AuthManagerContract, AuthManagerOptions, AuthCredentials, Guard, GuardContext, GuardFactory, ProviderFactory, UserProvider } from './types.js';
6
+ /** How `useTokens()` configures the guard it registers. */
7
+ export interface ApiTokenGuardOptions {
8
+ /** Registered provider name used to load the full user record from a token's userId. */
9
+ provider?: string;
10
+ /** Guard registry name (defaults to 'token'). */
11
+ guardName?: string;
12
+ /** Whether verifying a bearer writes the token's `lastUsedAt`. */
13
+ updateLastUsed?: boolean;
14
+ }
5
15
  export declare class AuthManager implements AuthManagerContract {
6
16
  private readonly guards;
7
17
  private readonly providers;
8
18
  private defaultGuard;
19
+ private tokenGuard;
20
+ private apiTokenStore;
21
+ private apiTokenOptions;
9
22
  constructor(options?: AuthManagerOptions);
10
23
  registerGuard<User>(name: string, factory: GuardFactory<User>): void;
11
24
  registerProvider<User>(name: string, factory: ProviderFactory<User>): void;
@@ -14,6 +27,15 @@ export declare class AuthManager implements AuthManagerContract {
14
27
  guardNames(): string[];
15
28
  setDefaultGuard(name: string): void;
16
29
  getDefaultGuard(): string;
30
+ /**
31
+ * The guard name an unqualified `auth.guard()` / `auth.user()` call resolves
32
+ * to for this request. Explicit names always win; otherwise a registered
33
+ * token guard is selected when the request carries a Bearer Authorization
34
+ * header, falling back to the default (session) guard. This is the
35
+ * composite-guard rule from RFC 0016: session- and token-authenticated
36
+ * requests flow through the same auth surface without configuration.
37
+ */
38
+ resolveGuardName(ctx: Context, name?: string): string;
17
39
  createAuthContext(ctx: Context, options?: AttachContextOptions): AuthContext;
18
40
  attempt(name: string, ctx: Context, credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
19
41
  /**
@@ -26,5 +48,47 @@ export declare class AuthManager implements AuthManagerContract {
26
48
  * @param guardName - Name for the guard (defaults to 'web')
27
49
  */
28
50
  useModel(model: typeof Model<PlainObject>, options?: Partial<ModelUserProviderOptions>, providerName?: string, guardName?: string): void;
51
+ /**
52
+ * Register a bearer-token guard backed by an ApiTokenStore and enable
53
+ * header-based guard selection: requests carrying `Authorization: Bearer`
54
+ * resolve to this guard, everything else keeps the default (session)
55
+ * guard. The default guard itself is unchanged — session apps keep
56
+ * working exactly as before.
57
+ *
58
+ * @param store - Where issued tokens live (see createApiToken)
59
+ * @param options.provider - Registered provider name used to load the full
60
+ * user record from the token's userId. Without it, `auth.user()` resolves
61
+ * to a minimal `{ id }` record (enough for Gate/policy evaluation).
62
+ * @param options.guardName - Guard registry name (defaults to 'token')
63
+ */
64
+ useTokens(store: ApiTokenStore, options?: ApiTokenGuardOptions): void;
65
+ /**
66
+ * The options the last `useTokens()` call configured its guard with.
67
+ *
68
+ * Read by machinery that has to *replace* the store without changing
69
+ * anything else about how tokens authenticate — `guren tool:dev` installs an
70
+ * ephemeral store over the app's, and doing that with a bare `useTokens(store)`
71
+ * silently dropped the app's `provider`, so a token resolved to a bare
72
+ * `{ id }` instead of the real user record and every policy reading a user
73
+ * field behaved differently for no stated reason.
74
+ */
75
+ getApiTokenOptions(): ApiTokenGuardOptions;
76
+ /**
77
+ * The token store {@link useTokens} was configured with, or `undefined`
78
+ * when this app never called it.
79
+ *
80
+ * This is the one path by which out-of-request machinery — `guren
81
+ * token:issue`, the App MCP adapter's principal lookup — reaches the same
82
+ * store the guard verifies against. `useTokens` otherwise closes over
83
+ * `store` inside the guard factory, where nothing outside a live request
84
+ * can see it, so an issuance command could only write tokens into a store
85
+ * of its own making, which no running app would ever read.
86
+ *
87
+ * Deliberately on this class rather than on `AuthManagerContract`: the
88
+ * contract describes what a *request* needs from auth, and handing out the
89
+ * raw store is not part of that. Callers reach it through the concrete
90
+ * manager (`Application.auth`).
91
+ */
92
+ getApiTokenStore(): ApiTokenStore | undefined;
29
93
  }
30
94
  export type { AuthCredentials } from './types.js';
@@ -1,16 +1,14 @@
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
- export type GuardResolver = (name?: string) => Guard<unknown>;
4
+ export type GuardResolver = (resolvedName: string) => Guard<unknown>;
5
5
  export declare class RequestAuthContext implements AuthContext {
6
- private readonly manager;
6
+ private readonly resolveName;
7
7
  private readonly ctx;
8
8
  private readonly resolveSession;
9
9
  private readonly resolveGuard;
10
10
  private readonly guardCache;
11
- constructor(manager: {
12
- getDefaultGuard(): string;
13
- }, ctx: Context, resolveSession: () => Session | undefined, resolveGuard: GuardResolver);
11
+ constructor(resolveName: (name?: string) => string, ctx: Context, resolveSession: () => Session | undefined, resolveGuard: GuardResolver);
14
12
  guard<T = unknown>(name?: string): Guard<T>;
15
13
  session<T extends Session = Session>(): T | undefined;
16
14
  check(): Promise<boolean>;
@@ -0,0 +1,61 @@
1
+ import type { Context } from 'hono';
2
+ import type { AuthCredentials, Guard, UserProvider } from './types.js';
3
+ import type { Session } from '../http/middleware/index.js';
4
+ import { type ApiTokenStore } from './api-token.js';
5
+ export interface TokenGuardOptions<User = unknown> {
6
+ store: ApiTokenStore;
7
+ ctx: Context;
8
+ /**
9
+ * Resolves the token's userId to a full user record (sanitized through the
10
+ * provider's `sanitize` when present). Without a provider the guard still
11
+ * authenticates: `user()` resolves to a minimal `{ id }` record so
12
+ * Gate/policy evaluation (which keys on `id`) works out of the box.
13
+ */
14
+ provider?: UserProvider<User>;
15
+ /** Update the token's lastUsedAt on successful verification. Default true. */
16
+ updateLastUsed?: boolean;
17
+ }
18
+ /**
19
+ * Bearer-token implementation of the Guard contract (RFC 0016 Phase 0).
20
+ *
21
+ * Reads `Authorization: Bearer <token>`, verifies it against the configured
22
+ * ApiTokenStore, and exposes the result through the same Guard surface the
23
+ * SessionGuard implements — so `requireAuthenticated()`, `Controller.auth`,
24
+ * and Gate resolution treat session- and token-authenticated requests
25
+ * identically. On successful verification the result is also written to
26
+ * `ctx[API_TOKEN_KEY]`, keeping `getApiToken(ctx)` and `tokenCan*` working
27
+ * exactly as they do behind `createBearerTokenMiddleware` — and when that
28
+ * middleware already verified this request's token, the guard reuses its
29
+ * result instead of paying a second store read and lastUsedAt write.
30
+ *
31
+ * Credential flows do not apply to bearer tokens: `attempt()`, `login()` and
32
+ * `validate()` throw. `logout()` is not a no-op — it revokes the presented
33
+ * token, the closest meaningful analogue to ending a session. On a request
34
+ * that carries a session cookie *and* a Bearer header, only the token is
35
+ * revoked; end the session explicitly via `auth.guard('web').logout()`.
36
+ *
37
+ * This guard answers authentication only. Token *abilities* are not
38
+ * consulted here or by Gate/policies — enforce them where the operation is
39
+ * dispatched (`tokenCan*`, `createBearerTokenMiddleware({ abilities })`, or
40
+ * the RFC 0016 scope gate), per the RFC's scope-before-policy layering.
41
+ */
42
+ export declare class TokenGuard<User = unknown> implements Guard<User> {
43
+ private readonly ctx;
44
+ private readonly store;
45
+ private readonly provider?;
46
+ private readonly updateLastUsed;
47
+ private verification?;
48
+ private resolvedUser?;
49
+ constructor(options: TokenGuardOptions<User>);
50
+ private verify;
51
+ check(): Promise<boolean>;
52
+ guest(): Promise<boolean>;
53
+ user<T = User>(): Promise<T | null>;
54
+ id(): Promise<unknown>;
55
+ login(): Promise<void>;
56
+ attempt(_credentials: AuthCredentials, _remember?: boolean): Promise<boolean>;
57
+ validate(_credentials: AuthCredentials): Promise<User | null>;
58
+ /** Revokes the presented token. Subsequent requests with it fail verification. */
59
+ logout(): Promise<void>;
60
+ session<T extends Session = Session>(): T | undefined;
61
+ }
@@ -131,6 +131,30 @@ export declare function parseApiToken(plainTextToken: string): {
131
131
  id: string;
132
132
  token: string;
133
133
  } | null;
134
+ /**
135
+ * Extract the bearer token from an Authorization header value. The one
136
+ * parsing rule shared by `createBearerTokenMiddleware`, `TokenGuard`, and
137
+ * `hasBearerHeader` below — three readers of the same header must not
138
+ * disagree about what a bearer request is.
139
+ */
140
+ export declare function readBearerToken(header: string | undefined | null): string | null;
141
+ /**
142
+ * The one answer to "is this request bearer-authenticated?" — the parsing
143
+ * rule above applied to the header it is read from. Shared by guard selection
144
+ * (`AuthManager.resolveGuardName`) and the CSRF skip for cookie-less bearer
145
+ * requests: both must classify a request identically, and a second copy of
146
+ * the header name is how they would drift apart.
147
+ */
148
+ export declare function hasBearerHeader(ctx: Context): boolean;
149
+ /**
150
+ * The result of a successful bearer-token verification: the stored token
151
+ * record plus the fields most callers need directly.
152
+ */
153
+ export interface VerifiedApiToken {
154
+ token: ApiToken;
155
+ userId: string | number;
156
+ abilities: string[];
157
+ }
134
158
  /**
135
159
  * Verify an API token and return the associated user ID.
136
160
  *
@@ -147,11 +171,7 @@ export declare function parseApiToken(plainTextToken: string): {
147
171
  */
148
172
  export declare function verifyApiToken(plainTextToken: string, store: ApiTokenStore, options?: {
149
173
  updateLastUsed?: boolean;
150
- }): Promise<{
151
- token: ApiToken;
152
- userId: string | number;
153
- abilities: string[];
154
- } | null>;
174
+ }): Promise<VerifiedApiToken | null>;
155
175
  /**
156
176
  * Check if a token has a specific ability.
157
177
  */
@@ -0,0 +1,24 @@
1
+ import type { AuthContext } from './types.js';
2
+ /**
3
+ * Context key the framework auth context is stored under.
4
+ *
5
+ * Lives here rather than in `http/middleware/auth` so that `auth/` modules can
6
+ * import it without reaching back into the middleware layer. The middleware
7
+ * re-exports it, and it stays a public root export.
8
+ */
9
+ export declare const AUTH_CONTEXT_KEY = "guren:auth";
10
+ /**
11
+ * Read the framework auth context off a request context.
12
+ *
13
+ * The lookup and its cast, in one place — nothing more. `ctx.get` returns
14
+ * arbitrary values for unknown keys (test doubles and exotic contexts
15
+ * included), so the cast is a claim, not a check. A caller whose behavior
16
+ * turns on the value really being an auth context probes the member it is
17
+ * about to call; `Gate.resolveUser` does exactly that, because a stray value
18
+ * there decides whether the legacy `ctx.get('user')` fallback runs. Probing
19
+ * here instead would reject contexts that `requireAuthenticated` and
20
+ * `requireGuest` can use — they only ever read `check()` / `guest()`.
21
+ */
22
+ export declare function getAuthContext(ctx: {
23
+ get: (key: string) => unknown;
24
+ }): AuthContext | undefined;
@@ -1,5 +1,8 @@
1
1
  export { AuthManager } from './AuthManager.js';
2
+ export type { ApiTokenGuardOptions } from './AuthManager.js';
2
3
  export { SessionGuard } from './SessionGuard.js';
4
+ export { TokenGuard } from './TokenGuard.js';
5
+ export type { TokenGuardOptions } from './TokenGuard.js';
3
6
  export { BaseUserProvider } from './providers/UserProvider.js';
4
7
  export { ModelUserProvider } from './providers/ModelUserProvider.js';
5
8
  export { ScryptHasher } from './password/ScryptHasher.js';
@@ -10,9 +13,9 @@ export { createEmailVerificationToken, verifyEmailToken, completeEmailVerificati
10
13
  export type { PasswordHasher } from './password/PasswordHasher.js';
11
14
  export type { PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, } from './password-reset.js';
12
15
  export type { EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, } from './email-verification.js';
13
- export { createApiToken, parseApiToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, } from './api-token.js';
16
+ export { createApiToken, parseApiToken, readBearerToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, } from './api-token.js';
14
17
  export { OAuthManager, MemoryOAuthStateStore, createOAuthManager, createOAuthState, verifyOAuthState, buildOAuthAuthorizeUrl, exchangeOAuthCode, fetchOAuthUserProfile, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createDiscordOAuthProviderConfig, buildOAuthRedirectUrl, parseOAuthRedirectUrl, sanitizeOAuthRedirect, OAUTH_SESSION_BINDING_KEY, } from './oauth/index.js';
15
- export type { ApiToken, ApiTokenStore, CreateApiTokenOptions, CreateApiTokenResult, BearerTokenMiddlewareOptions, } from './api-token.js';
18
+ export type { ApiToken, ApiTokenStore, CreateApiTokenOptions, CreateApiTokenResult, BearerTokenMiddlewareOptions, VerifiedApiToken, } from './api-token.js';
16
19
  export type { OAuthProviderConfig, OAuthTokenResult, OAuthUserProfile, OAuthFallbackEmail, OAuthStatePayload, OAuthStateStore, OAuthStateConfig, OAuthAuthorizeOptions, OAuthCallbackPayload, OAuthManagerOptions, OAuthProviderFactoryInput, OAuthBindingSession, } from './oauth/index.js';
17
20
  export type { AuthContext, AuthCredentials, AuthManagerOptions, AuthManagerContract, Authenticatable, Guard, GuardContext, GuardFactory, UserProvider, ProviderFactory, AttachContextOptions, DefaultSanitizedKeys, Sanitized, } from './types.js';
18
21
  export { hashToken, generateToken, generateId, secureCompare, secureStringCompare, buildTokenUrl, parseTokenUrl, } from './utils.js';
@@ -1,2 +1,2 @@
1
- import { $ as generateToken, A as sanitizeOAuthRedirect, B as revokeAllApiTokens, C as createGitHubOAuthProviderConfig, D as exchangeOAuthCode, E as createOAuthState, F as createBearerTokenMiddleware, G as verifyApiToken, H as tokenCan, I as getApiToken, L as getApiTokenOrFail, M as API_TOKEN_KEY, N as MemoryApiTokenStore, O as fetchOAuthUserProfile, P as createApiToken, Q as generateId, R as getUserApiTokens, S as createDiscordOAuthProviderConfig, T as createOAuthManager, U as tokenCanAll, V as revokeApiToken, W as tokenCanAny, X as SessionGuard, Y as AuthManager, Z as buildTokenUrl, _ as MemoryOAuthStateStore, a as isEmailVerified, at as BaseUserProvider, b as buildOAuthAuthorizeUrl, c as verifyEmailToken, d as completePasswordReset, et as hashToken, f as createPasswordResetToken, g as NodeHasher, h as AuthenticatableModel, i as createEmailVerificationToken, it as ModelUserProvider, j as verifyOAuthState, k as parseOAuthRedirectUrl, l as MemoryPasswordResetStore, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as secureCompare, o as parseVerificationUrl, ot as ScryptHasher, p as parsePasswordResetUrl, r as completeEmailVerification, rt as secureStringCompare, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as parseTokenUrl, u as buildPasswordResetUrl, v as OAUTH_SESSION_BINDING_KEY, w as createGoogleOAuthProviderConfig, x as buildOAuthRedirectUrl, y as OAuthManager, z as parseApiToken } from "../auth-C7sVmYgc.js";
2
- export { API_TOKEN_KEY, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, ScryptHasher, SessionGuard, 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, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };
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, d as completePasswordReset, 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 NodeHasher, 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, st as BaseUserProvider, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, ut as ScryptHasher, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-DkYoAPVn.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,13 +1,26 @@
1
1
  import type { PasswordHasher } from './PasswordHasher.js';
2
2
  /**
3
- * Runtime-detecting password hasher: uses Bun's native scrypt implementation
4
- * when running on Bun, and the Node.js crypto implementation otherwise
5
- * (e.g. AWS Lambda on the Node runtime). This is the hasher behind the
6
- * `Hash` export, so code written against `Hash` runs on both runtimes.
3
+ * Runtime-detecting password hasher: hashes with `Bun.password` when running
4
+ * on Bun (Argon2id by default, despite `ScryptHasher`'s name) and with Node's
5
+ * `crypto.scrypt` otherwise (e.g. AWS Lambda or Cloudflare Workers). This is
6
+ * the hasher behind the `Hash` export, and the default for
7
+ * `AuthenticatableModel` and `ModelUserProvider`.
8
+ *
9
+ * **Verification routes on the stored hash, not on the runtime.** The two
10
+ * delegates write different formats, and neither can read the other's, so
11
+ * picking a delegate by runtime alone would 500 on every login for an app
12
+ * whose password column was written elsewhere - a seeder run on Bun against a
13
+ * database a Node deploy then serves. Bun implements `node:crypto`, so a
14
+ * `$scrypt$` hash verifies on either runtime; an Argon2id or bcrypt hash needs
15
+ * `Bun.password` and cannot be read off Bun at all, which this reports as
16
+ * itself rather than as an opaque parse failure.
7
17
  */
8
18
  export declare class DefaultHasher implements PasswordHasher {
9
- private readonly delegate;
19
+ private readonly bun;
20
+ private readonly node;
10
21
  constructor();
11
22
  hash(plain: string): Promise<string>;
12
23
  verify(hashed: string, plain: string): Promise<boolean>;
24
+ needsRehash(hashed: string): boolean;
25
+ private delegateFor;
13
26
  }
@@ -1,5 +1,20 @@
1
1
  export interface PasswordHasher {
2
2
  hash(plain: string): Promise<string>;
3
+ /**
4
+ * Checks a plaintext password against a stored hash.
5
+ *
6
+ * **The stored hash comes first.** This order is the inverse of both
7
+ * `Bun.password.verify(plain, hashed)` (which `ScryptHasher` delegates to)
8
+ * and `verifyPassword(plain, hashed)` (exported from this package's
9
+ * `encryption/Hash`), so the two conventions coexist in one codebase.
10
+ *
11
+ * Both parameters are `string`, so a swapped call type-checks. The built-in
12
+ * hashers detect the obvious case at runtime and throw a `TypeError` naming
13
+ * the order; a custom implementation gets no such help.
14
+ *
15
+ * @param hashed - The stored password hash, e.g. from a `passwordHash` column.
16
+ * @param plain - The plaintext password supplied by the request.
17
+ */
3
18
  verify(hashed: string, plain: string): Promise<boolean>;
4
19
  needsRehash?(hashed: string): boolean;
5
20
  }
@@ -0,0 +1,19 @@
1
+ /** The prefix every hash `NodeHasher` (and `hashPassword()`) writes. */
2
+ export declare const NODE_SCRYPT_PREFIX = "$scrypt$";
3
+ export declare function looksLikePasswordHash(value: string): boolean;
4
+ /**
5
+ * Throws when `verify()` was called as `verify(plain, hashed)`.
6
+ *
7
+ * Two-sided on purpose: it fires only when the second argument looks like a
8
+ * hash *and* the first does not. A one-sided "the first argument must look
9
+ * like a hash" precondition would misdiagnose a legitimate non-hash
10
+ * credential column - `passwordHash: 'oauth:...'`, the sentinel this repo
11
+ * documents for OAuth-only accounts - as a caller mistake. Those keep falling
12
+ * through to the implementation, which rejects them as before.
13
+ *
14
+ * Neither argument is included in the message: one of them is a plaintext
15
+ * password, and this throw is reached on a live login attempt.
16
+ *
17
+ * See `PasswordHasher.verify` for why the order is easy to get wrong.
18
+ */
19
+ export declare function assertVerifyArgumentOrder(hashed: string, plain: string): void;
@@ -1,4 +1,11 @@
1
1
  import type { AuthCredentials, Authenticatable, UserProvider } from '../types.js';
2
+ /**
3
+ * Run a user record through the provider's optional `sanitize` before it
4
+ * leaves the auth layer. Every guard must call this on anything it returns
5
+ * from `user()` — a guard that forgets the optional-chaining ternary leaks
6
+ * password hashes, so the ternary lives here, once.
7
+ */
8
+ export declare function sanitizeUser<User>(provider: UserProvider<User>, user: User): User;
2
9
  export declare abstract class BaseUserProvider<User extends Authenticatable = Authenticatable> implements UserProvider<User> {
3
10
  abstract retrieveById(identifier: unknown): Promise<User | null>;
4
11
  abstract retrieveByCredentials(credentials: AuthCredentials): Promise<User | null>;
@@ -99,4 +99,10 @@ export interface AuthManagerContract {
99
99
  setDefaultGuard(name: string): void;
100
100
  getDefaultGuard(): string;
101
101
  createAuthContext(ctx: Context, options?: AttachContextOptions): AuthContext;
102
+ /**
103
+ * The guard name an unqualified guard() call resolves to for a request.
104
+ * Optional for backward compatibility; implementations without it behave
105
+ * as if it always returned the default guard.
106
+ */
107
+ resolveGuardName?(ctx: Context, name?: string): string;
102
108
  }