@pithy-sh/auth 0.8.0 → 0.9.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 (85) hide show
  1. package/README.md +4 -0
  2. package/dist/caller/certificate.d.ts +83 -0
  3. package/dist/caller/certificate.d.ts.map +1 -0
  4. package/dist/caller/certificate.js +92 -0
  5. package/dist/caller/request.d.ts +66 -0
  6. package/dist/caller/request.d.ts.map +1 -0
  7. package/dist/caller/request.js +71 -0
  8. package/dist/caller/token.d.ts +130 -0
  9. package/dist/caller/token.d.ts.map +1 -0
  10. package/dist/caller/token.js +207 -0
  11. package/dist/capability.d.ts +44 -1
  12. package/dist/capability.d.ts.map +1 -1
  13. package/dist/capability.js +7 -4
  14. package/dist/data/betterAuth.d.ts +1 -1
  15. package/dist/data/betterAuth.d.ts.map +1 -1
  16. package/dist/data/betterAuth.js +1 -1
  17. package/dist/data/tables.d.ts +1 -1
  18. package/dist/http/credentialResign.d.ts +46 -0
  19. package/dist/http/credentialResign.d.ts.map +1 -0
  20. package/dist/http/credentialResign.js +203 -0
  21. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  22. package/dist/http/errorCallbackUrl.js +15 -9
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +66 -15
  25. package/dist/http/providerRefusal.d.ts +8 -7
  26. package/dist/http/providerRefusal.d.ts.map +1 -1
  27. package/dist/http/providerRefusal.js +29 -32
  28. package/dist/http/resolve.d.ts.map +1 -1
  29. package/dist/http/resolve.js +18 -3
  30. package/dist/instance/auth.d.ts +1225 -2
  31. package/dist/instance/auth.d.ts.map +1 -1
  32. package/dist/instance/auth.js +6 -2
  33. package/dist/instance/jwksReencryption.d.ts +75 -0
  34. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  35. package/dist/instance/jwksReencryption.js +160 -0
  36. package/dist/instance/providerSignInGate.d.ts +7 -6
  37. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  38. package/dist/instance/providerSignInGate.js +16 -14
  39. package/dist/instance/secrets.d.ts +168 -1
  40. package/dist/instance/secrets.d.ts.map +1 -1
  41. package/dist/instance/secrets.js +86 -3
  42. package/dist/instance/sessionSecrets.d.ts +45 -0
  43. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  44. package/dist/instance/sessionSecrets.js +29 -0
  45. package/dist/migrations/0001_init.d.ts.map +1 -1
  46. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  47. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  48. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  49. package/dist/migrations/set.d.ts +2 -1
  50. package/dist/migrations/set.d.ts.map +1 -1
  51. package/dist/migrations/set.js +4 -2
  52. package/dist/test-utils/liveApp.d.ts +5 -0
  53. package/dist/test-utils/liveApp.d.ts.map +1 -1
  54. package/dist/test-utils/schemaDrift.d.ts +49 -0
  55. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  56. package/dist/test-utils/schemaDrift.js +35 -0
  57. package/dist/test-utils/scopedBackend.d.ts +183 -0
  58. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  59. package/dist/test-utils/scopedBackend.js +160 -0
  60. package/dist/version.generated.d.ts +1 -1
  61. package/dist/version.generated.js +1 -1
  62. package/docs/server-authoritative.md +182 -0
  63. package/package.json +11 -8
  64. package/src/caller/certificate.ts +133 -0
  65. package/src/caller/request.ts +84 -0
  66. package/src/caller/token.ts +276 -0
  67. package/src/capability.ts +65 -4
  68. package/src/data/betterAuth.ts +2 -1
  69. package/src/http/credentialResign.ts +268 -0
  70. package/src/http/errorCallbackUrl.ts +21 -13
  71. package/src/http/middleware.ts +100 -35
  72. package/src/http/providerRefusal.ts +30 -32
  73. package/src/http/resolve.ts +27 -3
  74. package/src/http/routes.ts +1 -1
  75. package/src/instance/auth.ts +22 -4
  76. package/src/instance/jwksReencryption.ts +206 -0
  77. package/src/instance/providerSignInGate.ts +23 -21
  78. package/src/instance/secrets.ts +94 -1
  79. package/src/instance/sessionSecrets.ts +64 -0
  80. package/src/migrations/0001_init.ts +8 -10
  81. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  82. package/src/migrations/set.ts +3 -1
  83. package/src/test-utils/schemaDrift.ts +82 -0
  84. package/src/test-utils/scopedBackend.ts +136 -0
  85. package/src/version.generated.ts +1 -1
@@ -0,0 +1,207 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
4
+ import { z } from "zod";
5
+ //#region src/caller/token.ts
6
+ /**
7
+ * **A short-lived, audience-restricted caller token — the portable way to prove a request came from the
8
+ * adopter's own backend (#560).**
9
+ *
10
+ * `resolveScopes` asks one question: is this request's caller the adopter's trusted backend, or a device?
11
+ * Where that backend is a Worker, a service binding answers it with no credential at all, and where the
12
+ * zone can run mTLS a client certificate answers it at the edge. Neither works everywhere — a service
13
+ * binding needs both ends on Cloudflare, mTLS needs a proxied zone and an exact hostname, so not
14
+ * `workers.dev`. This is what works on day one anywhere, and it is shipped because the alternative every
15
+ * adopter otherwise reaches for is a long-lived shared secret compared in a header, which fails every
16
+ * control RFC 9700 names at once.
17
+ *
18
+ * So it holds to those controls, each on its own line below:
19
+ *
20
+ * - **Audience-restricted.** `aud` is the origin the token was minted for, and it verifies there and nowhere
21
+ * else — a staging token presented to production is refused, and so is one Worker's token replayed at
22
+ * another that happens to share the key.
23
+ * - **Short-lived.** Five minutes by default, and a ceiling of fifteen that no token and no configuration
24
+ * gets past. A token whose `exp` is a day after its `iat` is refused even when it is otherwise perfect,
25
+ * because honoring it would make it a shared secret with extra steps.
26
+ * - **Signed with a key the Worker reads from `@pithy-sh/secrets`.** The operator supplies it and the
27
+ * backend holds the same value. The `kid` names the stored version the token was signed with, and a kid
28
+ * the store does not hold is refused.
29
+ *
30
+ * What it is not is **sender-constrained**: a token lifted off the wire is usable by whoever lifted it, for
31
+ * the minutes it has left. RFC 9700 says a token SHOULD be bound to its sender, and the two answers are
32
+ * mTLS (`readClientCertificate`) and DPoP, which the kit does not ship yet. Short lifetime is what limits
33
+ * the damage here, which is why the ceiling is not negotiable.
34
+ *
35
+ * **HS256 and nothing else.** One algorithm, one key type, one token shape — the header is validated
36
+ * against a literal, so `alg: none` and an asymmetric algorithm are malformed rather than negotiated. No
37
+ * JWT library: the algorithm agility one brings is where the JWT vulnerabilities live.
38
+ */
39
+ /** The header a caller token travels on. Not `Authorization`, which carries the player's forwarded session. */
40
+ const CALLER_TOKEN_HEADER = "pithy-caller";
41
+ /** How long a minted token lives unless the minter asks for less: five minutes. */
42
+ const DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS = 300;
43
+ /**
44
+ * The longest a caller token may live, from its `iat` to its `exp` — fifteen minutes, minted or verified.
45
+ *
46
+ * A ceiling rather than a default, and it refuses above rather than clamping: a verifier configured past it
47
+ * is a configuration error, and a token claiming more is refused. Minutes because the token is a bearer
48
+ * credential with no sender binding, and its lifetime is the whole of what bounds a stolen one.
49
+ */
50
+ const MAX_CALLER_TOKEN_LIFETIME_SECONDS = 900;
51
+ /** How far in the future an `iat` may sit before the token is refused — clocks disagree by seconds, not minutes. */
52
+ const CALLER_TOKEN_CLOCK_SKEW_SECONDS = 30;
53
+ /** The protected header of a caller token. */
54
+ const CallerTokenHeader = z.object({
55
+ alg: z.literal("HS256").describe("The signature algorithm. HMAC-SHA-256, and nothing else is accepted."),
56
+ typ: z.literal("JWT").optional().describe("The media type, `JWT` when present."),
57
+ kid: z.string().min(1).describe("The version of the caller-token key this token was signed with.")
58
+ }).describe("The protected header of a caller token: HS256, and which key version signed it.");
59
+ /** The claims a caller token carries. */
60
+ const CallerTokenClaims = z.object({
61
+ aud: z.string().describe("The origin this token was minted for. It verifies at that origin and nowhere else."),
62
+ iat: z.number().int().describe("When it was minted, in Unix seconds."),
63
+ exp: z.number().int().describe("When it stops verifying, in Unix seconds. At most fifteen minutes after `iat`."),
64
+ sub: z.string().optional().describe("Which backend minted it, for the adopter's own logs. The verifier grants nothing on it.")
65
+ }).describe("The claims of a caller token: where it is valid, and for how long.");
66
+ const encoder = new TextEncoder();
67
+ const decoder = new TextDecoder();
68
+ /** The url alphabet, unpadded. Padding and the standard alphabet are refused, so a token has one spelling. */
69
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
70
+ function encodeSegment(bytes) {
71
+ let binary = "";
72
+ for (const byte of bytes) binary += String.fromCharCode(byte);
73
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
74
+ }
75
+ /** Decode one unpadded base64url segment, or `null` — strict, because every segment is attacker-supplied. */
76
+ function decodeSegment(segment) {
77
+ if (!BASE64URL.test(segment) || segment.length % 4 === 1) return null;
78
+ try {
79
+ const binary = atob(segment.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - segment.length % 4) % 4));
80
+ const bytes = new Uint8Array(binary.length);
81
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
82
+ return bytes;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ /** Decode a JSON segment through its schema, or `null` for any failure at all. */
88
+ function decodeJson(segment, schema) {
89
+ const bytes = decodeSegment(segment);
90
+ if (bytes === null) return null;
91
+ let json;
92
+ try {
93
+ json = JSON.parse(decoder.decode(bytes));
94
+ } catch {
95
+ return null;
96
+ }
97
+ const parsed = schema.safeParse(json);
98
+ return parsed.success ? parsed.data : null;
99
+ }
100
+ /** The origin a URL names, or the string unchanged when it is not one — so it can only fail to match. */
101
+ function originOf(audience) {
102
+ try {
103
+ return new URL(audience).origin;
104
+ } catch {
105
+ return audience;
106
+ }
107
+ }
108
+ function hmacKey(key, usage) {
109
+ return crypto.subtle.importKey("raw", encoder.encode(key), {
110
+ name: "HMAC",
111
+ hash: "SHA-256"
112
+ }, false, [usage]);
113
+ }
114
+ /** Refuse a lifetime outside `(0, MAX]` — a configuration error, raised loudly rather than clamped. */
115
+ function assertLifetime(seconds, what) {
116
+ if (!Number.isInteger(seconds) || seconds <= 0 || seconds > 900) throw new InternalError({
117
+ message: `A caller token's ${what} must be a whole number of seconds from 1 to 900.`,
118
+ action: `Use a lifetime of minutes, not hours — at most 900 seconds.`,
119
+ detail: `got ${String(seconds)}`
120
+ });
121
+ }
122
+ /**
123
+ * Mint a caller token — on the **trusted backend**, never on a device.
124
+ *
125
+ * Mint one per call, or per few minutes, and present it on {@link CALLER_TOKEN_HEADER}. A backend that is
126
+ * another Worker in this project reads the key the way the verifier does, through `@pithy-sh/secrets`.
127
+ */
128
+ async function mintCallerToken(options) {
129
+ const lifetime = options.lifetimeSeconds ?? 300;
130
+ assertLifetime(lifetime, "lifetime");
131
+ const iat = Math.floor((options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
132
+ const header = {
133
+ alg: "HS256",
134
+ typ: "JWT",
135
+ kid: options.kid
136
+ };
137
+ const claims = {
138
+ aud: originOf(options.audience),
139
+ iat,
140
+ exp: iat + lifetime,
141
+ ...options.subject === void 0 ? {} : { sub: options.subject }
142
+ };
143
+ const input = `${encodeSegment(encoder.encode(JSON.stringify(header)))}.${encodeSegment(encoder.encode(JSON.stringify(claims)))}`;
144
+ return `${input}.${encodeSegment(new Uint8Array(await crypto.subtle.sign("HMAC", await hmacKey(options.key, "sign"), encoder.encode(input))))}`;
145
+ }
146
+ /**
147
+ * Decide whether a caller token is one to trust, and why not when it is not.
148
+ *
149
+ * **In this order, and the order is the security model:** structure, then the key, then the signature,
150
+ * then the audience, then the lifetime, then expiry. Nothing about the claims is read as a fact until the
151
+ * signature has verified, so a forgery learns nothing from the answer about how far it got.
152
+ *
153
+ * Returns a verdict rather than throwing, so a resolver can answer `[]` and log the reason. It throws only
154
+ * for its own misconfiguration — a ceiling past the maximum — which `resolveScopes` turns into no scopes.
155
+ */
156
+ async function verifyCallerToken(token, options) {
157
+ const ceiling = options.maxLifetimeSeconds ?? 900;
158
+ assertLifetime(ceiling, "lifetime ceiling");
159
+ const segments = token.split(".");
160
+ const [encodedHeader, encodedClaims, encodedSignature] = segments;
161
+ if (segments.length !== 3 || !encodedHeader || !encodedClaims || !encodedSignature) return {
162
+ trusted: false,
163
+ reason: "malformed"
164
+ };
165
+ const header = decodeJson(encodedHeader, CallerTokenHeader);
166
+ const claims = decodeJson(encodedClaims, CallerTokenClaims);
167
+ const signature = decodeSegment(encodedSignature);
168
+ if (header === null || claims === null || signature === null) return {
169
+ trusted: false,
170
+ reason: "malformed"
171
+ };
172
+ const versions = options.keys.versions;
173
+ const key = Object.hasOwn(versions, header.kid) ? versions[header.kid] : void 0;
174
+ if (typeof key !== "string") return {
175
+ trusted: false,
176
+ reason: "unknown_key"
177
+ };
178
+ let verified;
179
+ try {
180
+ verified = await crypto.subtle.verify("HMAC", await hmacKey(key, "verify"), new Uint8Array(signature), encoder.encode(`${encodedHeader}.${encodedClaims}`));
181
+ } catch {
182
+ verified = false;
183
+ }
184
+ if (!verified) return {
185
+ trusted: false,
186
+ reason: "signature"
187
+ };
188
+ if (claims.aud !== originOf(options.audience)) return {
189
+ trusted: false,
190
+ reason: "audience"
191
+ };
192
+ const now = Math.floor((options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
193
+ if (claims.exp - claims.iat > ceiling || claims.iat > now + 30) return {
194
+ trusted: false,
195
+ reason: "lifetime"
196
+ };
197
+ if (claims.exp <= now) return {
198
+ trusted: false,
199
+ reason: "expired"
200
+ };
201
+ return {
202
+ trusted: true,
203
+ claims
204
+ };
205
+ }
206
+ //#endregion
207
+ export { CALLER_TOKEN_CLOCK_SKEW_SECONDS, CALLER_TOKEN_HEADER, CallerTokenClaims, CallerTokenHeader, DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS, MAX_CALLER_TOKEN_LIFETIME_SECONDS, mintCallerToken, verifyCallerToken };
@@ -1,9 +1,10 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import type { D1Database } from "@cloudflare/workers-types";
4
- import type { Capability } from "@pithy-sh/core/src/capability/capability";
4
+ import type { Capability, PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
5
  import type { EmailCapability } from "@pithy-sh/email/src/capability";
6
6
  import { type TurnstileMode } from "@pithy-sh/turnstile/src/config/config";
7
+ import type { Context } from "hono";
7
8
  import { z } from "zod";
8
9
  import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
9
10
  import { type AuthPeer } from "./peer";
@@ -32,6 +33,7 @@ export declare const AuthConfig: z.ZodObject<{
32
33
  }, z.core.$strip>>;
33
34
  sessionExpiresIn: z.ZodDefault<z.ZodNumber>;
34
35
  sessionUpdateAge: z.ZodDefault<z.ZodNumber>;
36
+ sessionSecretRotateEveryDays: z.ZodOptional<z.ZodNumber>;
35
37
  verificationExpiresIn: z.ZodDefault<z.ZodNumber>;
36
38
  otpLength: z.ZodDefault<z.ZodNumber>;
37
39
  disableSignUp: z.ZodDefault<z.ZodBoolean>;
@@ -61,7 +63,29 @@ export interface AuthWiring {
61
63
  * is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
62
64
  */
63
65
  onSessionRevoked?: SessionRevokedListener | undefined;
66
+ /**
67
+ * The adopter's scope resolver, or absent. See {@link AuthOptions.resolveScopes}.
68
+ *
69
+ * Optional on the wiring for the reason `onSessionRevoked` is: no resolver is the ordinary composition.
70
+ */
71
+ resolveScopes?: ScopeResolver | undefined;
64
72
  }
73
+ /** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
74
+ export interface ScopeResolverSession {
75
+ /** The signed-in user the session belongs to. */
76
+ userId: string;
77
+ /** The session this request presented. */
78
+ sessionId: string;
79
+ }
80
+ /**
81
+ * Decide what this request's caller is, and answer the scopes that attests to (#560).
82
+ *
83
+ * Called by the session middleware on every authenticated request, after Better Auth has resolved the
84
+ * session and before any route runs. What it returns becomes `AuthContext.scopes`. It reads the **request**,
85
+ * which is where the proof is — a service binding the call arrived over, `request.cf.tlsClientAuth`, a
86
+ * short-lived token on its own header — and never anything the request merely claims about itself.
87
+ */
88
+ export type ScopeResolver = (c: Context<PithyHonoEnv>, session: ScopeResolverSession) => readonly string[] | Promise<readonly string[]>;
65
89
  /**
66
90
  * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
67
91
  *
@@ -114,6 +138,25 @@ export type AuthOptions = AuthConfigInput & {
114
138
  * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
115
139
  */
116
140
  onSessionRevoked?: SessionRevokedListener;
141
+ /**
142
+ * Decide, per request, what this request's caller is — and so which scope gates it opens (#560).
143
+ *
144
+ * `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
145
+ * the caller, not permissions granted to the user**: each says *this write came from the adopter's own
146
+ * trusted backend, not from a device*. This is where that is decided, and the seam does not dictate how.
147
+ * A backend calling over a service binding, one presenting a client certificate, and one presenting a
148
+ * short-lived token all answer the same question here. `verifyCallerToken` and `readClientCertificate`
149
+ * are the kit's helpers for the last two; `docs/server-authoritative.md` ranks the three.
150
+ *
151
+ * **Resolved per request, never cached** — a cached scope is a revocation that has not taken effect.
152
+ * **Failure is closed and never fatal**: a resolver that throws, or answers anything but a list of
153
+ * strings, leaves the request with no scopes and logs at warn, and the request goes on to whatever gate
154
+ * it was headed for. **No default**: without one the array is empty and nothing extra runs, so composing
155
+ * this changes nothing until an adopter opts in.
156
+ *
157
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
158
+ */
159
+ resolveScopes?: ScopeResolver;
117
160
  };
118
161
  /** The auth capability, with its resolved config attached for inspection. */
119
162
  export interface AuthCapability extends Capability {
@@ -1 +1 @@
1
- {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,0CAA0C,CAAC;AAG5F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCA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E,QAAQ,CAAC;CACpB;AAiCD;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,cAAc,CAqKzD;AAED,0DAA0D;AAC1D,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,cAAc,CAErF"}
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { authTables } from "./data/tables.js";
4
4
  import { publishSameOrigin } from "./http/csrf.js";
5
- import { authSecretsRegistry, inapplicableProviderSecrets } from "./instance/secrets.js";
5
+ import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets.js";
6
6
  import { authDevSessionSeed } from "./seeds/devSession.js";
7
7
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins.js";
8
8
  import { registerDevLoginRoute } from "./http/devLoginRoute.js";
@@ -50,6 +50,7 @@ const AuthConfig = z.object({
50
50
  github: ProviderToggle.prefault({}).describe("GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md."),
51
51
  sessionExpiresIn: z.number().int().default(604800).describe("Session (refresh credential) lifetime in seconds. Defaults to 7 days. Expiry slides forward on use."),
52
52
  sessionUpdateAge: z.number().int().default(86400).describe("How often (seconds) an active session's expiry slides forward. Defaults to 1 day."),
53
+ sessionSecretRotateEveryDays: z.number().int().positive().optional().describe("How often, in days, the secrets manager rotates `auth-session-secret` by itself. Unset by default, so nothing rotates it unattended. The previous version keeps verifying for the session lifetime, so nobody is signed out, and is retired once the JWKS keys sealed under it are re-encrypted. Must be longer than `sessionExpiresIn`."),
53
54
  verificationExpiresIn: z.number().int().default(300).describe("Magic-link and OTP lifetime in seconds. Defaults to 5 minutes. Single-use regardless."),
54
55
  otpLength: z.number().int().default(6).describe("The number of digits in an email OTP. Defaults to 6."),
55
56
  disableSignUp: z.boolean().default(false).describe("When true, sign-in never provisions a new user — existing accounts only. Unknown emails get no email (anti-enumeration)."),
@@ -86,7 +87,7 @@ function assertPluginTablesUnclaimed(capabilities, binding, extensions) {
86
87
  * and emits `auth/*` through `audit` when those are composed.
87
88
  */
88
89
  function auth(options) {
89
- const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
90
+ const { resolveGithubUserInfo, onSessionRevoked, resolveScopes, ...config } = options;
90
91
  const resolved = AuthConfig.parse(config);
91
92
  assertAdditivePlugins(resolved.plugins);
92
93
  const pluginPlan = authPluginPlan(resolved.plugins);
@@ -95,7 +96,8 @@ function auth(options) {
95
96
  resolveGithubUserInfo,
96
97
  enqueueEmail: void 0,
97
98
  turnstile: void 0,
98
- onSessionRevoked
99
+ onSessionRevoked,
100
+ resolveScopes
99
101
  };
100
102
  const rateLimitMiddleware = (app) => {
101
103
  app.use(`${resolved.basePath}/*`, createRateLimitMiddleware(resolved.rateLimiterBinding));
@@ -106,7 +108,8 @@ function auth(options) {
106
108
  package: PACKAGE_NAME,
107
109
  config: AuthConfig,
108
110
  dependsOn: ["secrets", "email"],
109
- secretRegistry: authSecretsRegistry,
111
+ providesScopes: resolveScopes !== void 0,
112
+ secretRegistry: authSecretsRegistryFor(resolved),
110
113
  inapplicableSecrets: inapplicableProviderSecrets(resolved),
111
114
  requiredBindings: [{
112
115
  type: "d1",
@@ -31,7 +31,7 @@ export type Session = z.output<typeof Session>;
31
31
  /** `pithy_auth_accounts` — a credential/identity link for a user (one row per social provider). */
32
32
  export declare const Account: z.ZodObject<{
33
33
  id: z.ZodString;
34
- issuer: z.ZodString;
34
+ issuer: z.ZodNullable<z.ZodString>;
35
35
  accountId: z.ZodString;
36
36
  providerId: z.ZodString;
37
37
  userId: z.ZodString;
@@ -1 +1 @@
1
- {"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/data/betterAuth.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB,2FAA2F;AAC3F,eAAO,MAAM,IAAI;;;;;;;;;iBA0BwF,CAAC;AAC1G,MAAM,MAAM,IAA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AAM,OAAO;;;;;;;;;;;;;;;iBA0CqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,8FAA8F;AAC9F,eAAO,MAAM,YAAY;;;;;;;iBAmBtB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,gGAAgG;AAChG,eAAO,MAAM,IAAI;;;;;;;;iBA8Bd,CAAC;AACJ,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,sHAAsH;AACtH,eAAO,MAAM,SAAS;;;;;iBAcnB,CAAC;AACJ,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC"}
@@ -51,7 +51,7 @@ const Session = z.object({
51
51
  /** `pithy_auth_accounts` — a credential/identity link for a user (one row per social provider). */
52
52
  const Account = z.object({
53
53
  id: z.string().describe("Primary key. A random/UUID text id."),
54
- issuer: z.string().describe("Who asserted this identity, as the identity provider names itself: an OIDC issuer URL (`https://accounts.google.com`), `local:oauth:<id>` for an OAuth provider that publishes none, or `local:credential` for a password. With `accountId` it is the account's identity and carries a unique index — a provider slug is a name this project chose, so two providers pointed at one directory could assert the same `accountId` and land on two rows."),
54
+ issuer: z.string().nullable().describe("A relic of Better Auth 1.7.0–1.7.2, which identified an account by `(issuer, accountId)` and wrote who asserted the identity here: an OIDC issuer URL, `local:oauth:<id>`, or `local:credential`. 1.7.3 went back to `(providerId, accountId)` and writes nothing here, so a row created since is null. Kept, with the values a Worker migrated under 1.7.1 holds, and read by nothing (#787)."),
55
55
  accountId: z.string().describe("The provider's stable id for this user (e.g. the Google `sub` claim)."),
56
56
  providerId: z.string().describe("The provider slug, e.g. `google`. Identifies which OAuth/credential provider this row links."),
57
57
  userId: z.string().describe("The owning user's id. Foreign key to `pithy_auth_users(id)`, ON DELETE CASCADE."),
@@ -38,7 +38,7 @@ export declare const authTables: {
38
38
  }, import("zod/v4/core").$strip>;
39
39
  pithyAuthAccounts: import("zod").ZodObject<{
40
40
  id: import("zod").ZodString;
41
- issuer: import("zod").ZodString;
41
+ issuer: import("zod").ZodNullable<import("zod").ZodString>;
42
42
  accountId: import("zod").ZodString;
43
43
  providerId: import("zod").ZodString;
44
44
  userId: import("zod").ZodString;
@@ -0,0 +1,46 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import type { Context } from "hono";
5
+ import type { AuthInstance } from "../instance/auth";
6
+ /** Sign `value` the way better-call's `signCookieValue` does, before its URL encoding: `value.signature`. */
7
+ export declare function signCredential(value: string, secret: string): Promise<string>;
8
+ /**
9
+ * Which of `keys` a signed credential verifies under, by index, and the value it signs — or `null` when it
10
+ * is not a signed credential or verifies under none. Takes the decoded form, `value.signature`.
11
+ */
12
+ export declare function verifyCredential(signed: string, keys: readonly string[]): Promise<{
13
+ value: string;
14
+ key: number;
15
+ } | null>;
16
+ /** What was re-signed: the request's new headers, each re-signed cookie, and the re-signed bearer credential. */
17
+ export interface ResignedCredentials {
18
+ /** The request headers with every re-signed credential in place of the one that arrived. */
19
+ headers: Headers;
20
+ /** Each cookie re-signed, by name, with its new value in decoded form. */
21
+ cookies: {
22
+ name: string;
23
+ value: string;
24
+ }[];
25
+ /** The bearer credential re-signed, in decoded form, when one was. */
26
+ bearer?: string;
27
+ }
28
+ /**
29
+ * Re-sign every credential in `headers` that verifies under a prior key: the cookies named in `names`, and
30
+ * a signed bearer token. Answers `null` when nothing needed it — including always when there is no prior
31
+ * key, so a deployment that has never rotated parses nothing.
32
+ */
33
+ export declare function resignCredentials(headers: Headers, keys: {
34
+ current: string;
35
+ prior: readonly string[];
36
+ }, names: readonly string[]): Promise<ResignedCredentials | null>;
37
+ /**
38
+ * Carry this request's credentials across a rotation, then run the rest of the chain, then hand the
39
+ * re-signed credentials back on the response.
40
+ *
41
+ * Swaps `c.req.raw` for a request carrying the re-signed credentials, so the session middleware, the auth
42
+ * handler and every route that reads the request see one consistent set. A response that already sets the
43
+ * cookie — a sign-out, a refresh — keeps its own; this only fills the silence.
44
+ */
45
+ export declare function withResignedCredentials(c: Context<PithyHonoEnv>, instance: AuthInstance, next: () => Promise<void>): Promise<void>;
46
+ //# sourceMappingURL=credentialResign.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentialResign.d.ts","sourceRoot":"","sources":["../../src/http/credentialResign.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAmDrD,6GAA6G;AAC7G,wBAAsB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEnF;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,SAAS,MAAM,EAAE,GACtB,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAWhD;AAuBD,iHAAiH;AACjH,MAAM,WAAW,mBAAmB;IAClC,4FAA4F;IAC5F,OAAO,EAAE,OAAO,CAAC;IACjB,0EAA0E;IAC1E,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC3C,sEAAsE;IACtE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,EACnD,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAyCrC;AA0CD;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAC3C,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EACxB,QAAQ,EAAE,YAAY,EACtB,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GACxB,OAAO,CAAC,IAAI,CAAC,CAkDf"}
@@ -0,0 +1,203 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { resolveSessionSecrets } from "../instance/secrets.js";
4
+ import { priorSessionSecrets } from "../instance/sessionSecrets.js";
5
+ //#region src/http/credentialResign.ts
6
+ /**
7
+ * **A session signed before a rotation, carried across it (#602).**
8
+ *
9
+ * Better Auth signs the session cookie — and the signed token a bearer client holds — with one secret,
10
+ * `ctx.secret`, which is the first entry of the version set and nothing else (`cookies/index.mjs:172`,
11
+ * `plugins/bearer/index.mjs`). So the moment `auth-session-secret` rotates, every credential issued under
12
+ * the previous version fails verification, and everyone is signed out at once. The overlap the registry
13
+ * declares would protect nothing.
14
+ *
15
+ * This closes that gap in front of Better Auth: before a request reaches it, a credential that fails under
16
+ * the current version and verifies under a **retained** prior one is re-signed under the current version.
17
+ * Better Auth then sees a credential it accepts, and the response carries the re-signed one back — a
18
+ * `Set-Cookie` for a browser, `set-auth-token` for a bearer client — so the next request needs no help.
19
+ *
20
+ * **It extends no trust.** A credential is re-signed only when it verifies under a version this deployment
21
+ * still holds, which is exactly the set Better Auth would accept if it verified signatures by version. The
22
+ * session it names is still looked up, still expired, still revoked by Better Auth as before. And the
23
+ * window closes on its own: once the rotation retires the previous version, nothing verifies under it.
24
+ *
25
+ * **The session's lifetime is the overlap.** A session in use is re-signed on its next request, inside the
26
+ * overlap; one not used for the whole overlap has expired anyway, because `auth-session-secret`'s overlap
27
+ * is declared at least as long as `sessionExpiresIn`, which slides on use.
28
+ */
29
+ /** HMAC-SHA256 under `secret`, in standard base64 — the 44 characters better-call writes and checks. */
30
+ async function signature(value, secret) {
31
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
32
+ name: "HMAC",
33
+ hash: "SHA-256"
34
+ }, false, ["sign"]);
35
+ const bytes = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value)));
36
+ let binary = "";
37
+ for (const byte of bytes) binary += String.fromCharCode(byte);
38
+ return btoa(binary);
39
+ }
40
+ /** Constant-time comparison of two strings of equal length; unequal lengths are unequal. */
41
+ function sameSignature(left, right) {
42
+ if (left.length !== right.length) return false;
43
+ let difference = 0;
44
+ for (let index = 0; index < left.length; index++) difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
45
+ return difference === 0;
46
+ }
47
+ /** Sign `value` the way better-call's `signCookieValue` does, before its URL encoding: `value.signature`. */
48
+ async function signCredential(value, secret) {
49
+ return `${value}.${await signature(value, secret)}`;
50
+ }
51
+ /**
52
+ * Which of `keys` a signed credential verifies under, by index, and the value it signs — or `null` when it
53
+ * is not a signed credential or verifies under none. Takes the decoded form, `value.signature`.
54
+ */
55
+ async function verifyCredential(signed, keys) {
56
+ const dot = signed.lastIndexOf(".");
57
+ if (dot < 1) return null;
58
+ const value = signed.slice(0, dot);
59
+ const presented = signed.slice(dot + 1);
60
+ if (presented.length !== 44 || !presented.endsWith("=")) return null;
61
+ for (let index = 0; index < keys.length; index++) {
62
+ const key = keys[index];
63
+ if (sameSignature(await signature(value, key), presented)) return {
64
+ value,
65
+ key: index
66
+ };
67
+ }
68
+ return null;
69
+ }
70
+ /** `decodeURIComponent`, answering the input itself when it is not valid percent-encoding. */
71
+ function decoded(text) {
72
+ try {
73
+ return decodeURIComponent(text);
74
+ } catch {
75
+ return text;
76
+ }
77
+ }
78
+ /**
79
+ * Re-sign under `current` whichever of a credential's two forms was signed under a key in `prior`.
80
+ *
81
+ * Takes the decoded credential and answers the re-signed one, or `null` when it verifies under the current
82
+ * key already, under no key at all, or is not a signed credential.
83
+ */
84
+ async function carried(signed, keys) {
85
+ const verified = await verifyCredential(signed, [keys.current, ...keys.prior]);
86
+ if (verified === null || verified.key === 0) return null;
87
+ return await signCredential(verified.value, keys.current);
88
+ }
89
+ /**
90
+ * Re-sign every credential in `headers` that verifies under a prior key: the cookies named in `names`, and
91
+ * a signed bearer token. Answers `null` when nothing needed it — including always when there is no prior
92
+ * key, so a deployment that has never rotated parses nothing.
93
+ */
94
+ async function resignCredentials(headers, keys, names) {
95
+ if (keys.prior.length === 0) return null;
96
+ const cookies = [];
97
+ let bearer;
98
+ const header = headers.get("cookie");
99
+ let cookieHeader = header;
100
+ if (header !== null) {
101
+ const parts = header.split(";").map((part) => part.trim());
102
+ cookieHeader = (await Promise.all(parts.map(async (part) => {
103
+ const equals = part.indexOf("=");
104
+ if (equals < 1) return part;
105
+ const name = part.slice(0, equals);
106
+ if (!names.includes(name)) return part;
107
+ const fresh = await carried(decoded(part.slice(equals + 1)), keys);
108
+ if (fresh === null) return part;
109
+ cookies.push({
110
+ name,
111
+ value: fresh
112
+ });
113
+ return `${name}=${encodeURIComponent(fresh)}`;
114
+ }))).join("; ");
115
+ }
116
+ const authorization = headers.get("authorization");
117
+ let authorizationHeader = authorization;
118
+ if (authorization !== null && authorization.slice(0, 7).toLowerCase() === "bearer ") {
119
+ const token = decoded(authorization.slice(7).trim());
120
+ const fresh = token.includes(".") ? await carried(token, keys) : null;
121
+ if (fresh !== null) {
122
+ bearer = fresh;
123
+ authorizationHeader = `Bearer ${fresh}`;
124
+ }
125
+ }
126
+ if (cookies.length === 0 && bearer === void 0) return null;
127
+ const next = new Headers(headers);
128
+ if (cookieHeader !== null) next.set("cookie", cookieHeader);
129
+ if (authorizationHeader !== null) next.set("authorization", authorizationHeader);
130
+ return {
131
+ headers: next,
132
+ cookies,
133
+ ...bearer === void 0 ? {} : { bearer }
134
+ };
135
+ }
136
+ /** One `Set-Cookie` value, with the attributes Better Auth itself would have written. */
137
+ function setCookie(name, value, attributes, maxAge) {
138
+ const parts = [`${name}=${encodeURIComponent(value)}`];
139
+ if (maxAge !== void 0) parts.push(`Max-Age=${Math.floor(maxAge)}`);
140
+ if (attributes.domain) parts.push(`Domain=${attributes.domain}`);
141
+ parts.push(`Path=${attributes.path ?? "/"}`);
142
+ if (attributes.httpOnly) parts.push("HttpOnly");
143
+ if (attributes.secure || attributes.partitioned) parts.push("Secure");
144
+ if (attributes.sameSite) parts.push(`SameSite=${attributes.sameSite.charAt(0).toUpperCase()}${attributes.sameSite.slice(1).toLowerCase()}`);
145
+ if (attributes.partitioned) parts.push("Partitioned");
146
+ return parts.join("; ");
147
+ }
148
+ /**
149
+ * The credentials this request needs re-signed, with the instance context their cookies are written from —
150
+ * or `null` when there is no prior version, or nothing to re-sign.
151
+ */
152
+ async function resignedFor(c, instance) {
153
+ const versions = await resolveSessionSecrets(c.env);
154
+ const current = versions.versions[versions.currentVersion];
155
+ const prior = priorSessionSecrets(versions);
156
+ if (current === void 0 || prior.length === 0) return null;
157
+ const context = await instance.$context;
158
+ const names = [context.authCookies.sessionToken.name, context.authCookies.dontRememberToken.name];
159
+ const resigned = await resignCredentials(c.req.raw.headers, {
160
+ current,
161
+ prior
162
+ }, names);
163
+ return resigned === null ? null : {
164
+ resigned,
165
+ context
166
+ };
167
+ }
168
+ /**
169
+ * Carry this request's credentials across a rotation, then run the rest of the chain, then hand the
170
+ * re-signed credentials back on the response.
171
+ *
172
+ * Swaps `c.req.raw` for a request carrying the re-signed credentials, so the session middleware, the auth
173
+ * handler and every route that reads the request see one consistent set. A response that already sets the
174
+ * cookie — a sign-out, a refresh — keeps its own; this only fills the silence.
175
+ */
176
+ async function withResignedCredentials(c, instance, next) {
177
+ const prepared = await resignedFor(c, instance).catch(() => null);
178
+ if (prepared === null) return await next();
179
+ const { resigned, context } = prepared;
180
+ const session = context.authCookies.sessionToken;
181
+ const dontRemember = context.authCookies.dontRememberToken;
182
+ c.req.raw = new Request(c.req.raw, { headers: resigned.headers });
183
+ await next();
184
+ const response = new Response(c.res.body, c.res);
185
+ const setting = response.headers.getSetCookie().map((line) => line.slice(0, line.indexOf("=")));
186
+ const remembered = !(resigned.headers.get("cookie") ?? "").split(";").some((part) => part.trim().startsWith(`${dontRemember.name}=`));
187
+ for (const cookie of resigned.cookies) {
188
+ if (setting.includes(cookie.name)) continue;
189
+ const isSession = cookie.name === session.name;
190
+ const attributes = isSession ? session.attributes : dontRemember.attributes;
191
+ response.headers.append("set-cookie", setCookie(cookie.name, cookie.value, attributes, isSession && remembered ? context.sessionConfig.expiresIn : void 0));
192
+ }
193
+ if (resigned.bearer !== void 0 && !response.headers.has("set-auth-token")) {
194
+ response.headers.set("set-auth-token", encodeURIComponent(resigned.bearer));
195
+ const exposed = new Set((response.headers.get("access-control-expose-headers") ?? "").split(",").map((header) => header.trim()).filter(Boolean));
196
+ exposed.add("set-auth-token");
197
+ response.headers.set("access-control-expose-headers", [...exposed].join(", "));
198
+ }
199
+ c.res = void 0;
200
+ c.res = response;
201
+ }
202
+ //#endregion
203
+ export { resignCredentials, signCredential, verifyCredential, withResignedCredentials };
@@ -1 +1 @@
1
- {"version":3,"file":"errorCallbackUrl.d.ts","sourceRoot":"","sources":["../../src/http/errorCallbackUrl.ts"],"names":[],"mappings":"AAiKA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CA8CnF;AA0ED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAkBlG"}
1
+ {"version":3,"file":"errorCallbackUrl.d.ts","sourceRoot":"","sources":["../../src/http/errorCallbackUrl.ts"],"names":[],"mappings":"AAuKA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAgDnF;AA0ED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAkBlG"}