@pithy-sh/auth 0.7.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 (108) 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/adminRoutes.d.ts.map +1 -1
  19. package/dist/http/adminRoutes.js +39 -8
  20. package/dist/http/credentialResign.d.ts +46 -0
  21. package/dist/http/credentialResign.d.ts.map +1 -0
  22. package/dist/http/credentialResign.js +203 -0
  23. package/dist/http/devLoginRoute.d.ts.map +1 -1
  24. package/dist/http/devLoginRoute.js +12 -5
  25. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  26. package/dist/http/errorCallbackUrl.js +15 -9
  27. package/dist/http/middleware.d.ts.map +1 -1
  28. package/dist/http/middleware.js +66 -15
  29. package/dist/http/providerRefusal.d.ts +8 -7
  30. package/dist/http/providerRefusal.d.ts.map +1 -1
  31. package/dist/http/providerRefusal.js +29 -32
  32. package/dist/http/resolve.d.ts.map +1 -1
  33. package/dist/http/resolve.js +18 -3
  34. package/dist/http/responses.d.ts +52 -0
  35. package/dist/http/responses.d.ts.map +1 -1
  36. package/dist/http/responses.js +25 -1
  37. package/dist/http/routes.d.ts.map +1 -1
  38. package/dist/http/routes.js +60 -9
  39. package/dist/http/schemas.d.ts +1 -1
  40. package/dist/http/schemas.js +1 -1
  41. package/dist/instance/auth.d.ts +1225 -2
  42. package/dist/instance/auth.d.ts.map +1 -1
  43. package/dist/instance/auth.js +6 -2
  44. package/dist/instance/jwksReencryption.d.ts +75 -0
  45. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  46. package/dist/instance/jwksReencryption.js +160 -0
  47. package/dist/instance/providerSignInGate.d.ts +7 -6
  48. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  49. package/dist/instance/providerSignInGate.js +16 -14
  50. package/dist/instance/providers.d.ts.map +1 -1
  51. package/dist/instance/providers.js +2 -1
  52. package/dist/instance/secrets.d.ts +168 -1
  53. package/dist/instance/secrets.d.ts.map +1 -1
  54. package/dist/instance/secrets.js +86 -3
  55. package/dist/instance/sessionSecrets.d.ts +45 -0
  56. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  57. package/dist/instance/sessionSecrets.js +29 -0
  58. package/dist/migrations/0001_init.d.ts.map +1 -1
  59. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  60. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  61. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  62. package/dist/migrations/set.d.ts +2 -1
  63. package/dist/migrations/set.d.ts.map +1 -1
  64. package/dist/migrations/set.js +4 -2
  65. package/dist/seeds/devSession.d.ts.map +1 -1
  66. package/dist/seeds/devSession.js +2 -1
  67. package/dist/test-utils/liveApp.d.ts +5 -0
  68. package/dist/test-utils/liveApp.d.ts.map +1 -1
  69. package/dist/test-utils/liveApp.js +3 -3
  70. package/dist/test-utils/schemaDrift.d.ts +49 -0
  71. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  72. package/dist/test-utils/schemaDrift.js +35 -0
  73. package/dist/test-utils/scopedBackend.d.ts +183 -0
  74. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  75. package/dist/test-utils/scopedBackend.js +160 -0
  76. package/dist/version.generated.d.ts +1 -1
  77. package/dist/version.generated.js +1 -1
  78. package/docs/server-authoritative.md +182 -0
  79. package/package.json +14 -11
  80. package/src/caller/certificate.ts +133 -0
  81. package/src/caller/request.ts +84 -0
  82. package/src/caller/token.ts +276 -0
  83. package/src/capability.ts +65 -4
  84. package/src/data/betterAuth.ts +2 -1
  85. package/src/http/adminRoutes.ts +46 -10
  86. package/src/http/credentialResign.ts +268 -0
  87. package/src/http/devLoginRoute.ts +19 -6
  88. package/src/http/errorCallbackUrl.ts +21 -13
  89. package/src/http/middleware.ts +100 -35
  90. package/src/http/providerRefusal.ts +30 -32
  91. package/src/http/resolve.ts +27 -3
  92. package/src/http/responses.ts +54 -0
  93. package/src/http/routes.ts +97 -11
  94. package/src/http/schemas.ts +1 -1
  95. package/src/instance/auth.ts +22 -4
  96. package/src/instance/jwksReencryption.ts +206 -0
  97. package/src/instance/providerSignInGate.ts +23 -21
  98. package/src/instance/providers.ts +2 -1
  99. package/src/instance/secrets.ts +94 -1
  100. package/src/instance/sessionSecrets.ts +64 -0
  101. package/src/migrations/0001_init.ts +8 -10
  102. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  103. package/src/migrations/set.ts +3 -1
  104. package/src/seeds/devSession.ts +2 -1
  105. package/src/test-utils/liveApp.ts +8 -6
  106. package/src/test-utils/schemaDrift.ts +82 -0
  107. package/src/test-utils/scopedBackend.ts +136 -0
  108. package/src/version.generated.ts +1 -1
@@ -25,6 +25,7 @@ import {
25
25
  type SocialProviderId,
26
26
  unavailableProviderFor,
27
27
  } from "./providers";
28
+ import { betterAuthSecrets, type SessionSecretVersions } from "./sessionSecrets";
28
29
 
29
30
  /**
30
31
  * Build the `socialProviders` block from whichever provider credentials were resolved. Exported so the
@@ -206,8 +207,15 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
206
207
  extends ResolvedProviders {
207
208
  /** The shared Kysely over the `pithy_auth_*` tables (carries `CamelCasePlugin`). */
208
209
  db: AuthDatabase;
209
- /** The Better-Auth signing/encryption secret, sourced from `@pithy-sh/secrets`. */
210
+ /** The Better-Auth signing/encryption secret, sourced from `@pithy-sh/secrets` — the current version. */
210
211
  secret: string;
212
+ /**
213
+ * Every retained version of the session secret, when the caller resolved them (#602). Given, Better Auth
214
+ * gets the whole version set — newest first — so a value sealed under the previous version still opens
215
+ * through a rotation's overlap; see `./sessionSecrets.ts`. Absent, it gets `secret` alone, which is what an
216
+ * instance built outside a request (a seed, a test) has always had.
217
+ */
218
+ sessionSecrets?: SessionSecretVersions;
211
219
  /** The public base URL of this environment's auth worker (no trailing slash). */
212
220
  baseURL: string;
213
221
  /** The mount path; must equal the Hono route the handler is mounted under. */
@@ -314,13 +322,23 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
314
322
  appName: "Pithy",
315
323
  baseURL: deps.baseURL,
316
324
  basePath: deps.basePath,
317
- secret: deps.secret,
325
+ ...(deps.sessionSecrets === undefined ? { secret: deps.secret } : betterAuthSecrets(deps.sessionSecrets)),
318
326
  telemetry: { enabled: false },
319
327
  trustedOrigins: deps.trustedOrigins,
320
328
  database: { db: deps.db, type: "sqlite", transaction: false },
321
329
  advanced: {
322
- // WebCrypto UUID ids for every model — anti-enumeration, Workers-safe.
323
- database: { generateId: () => crypto.randomUUID() },
330
+ database: {
331
+ // WebCrypto UUID ids for every model — anti-enumeration, Workers-safe.
332
+ generateId: () => crypto.randomUUID(),
333
+ // **Off at runtime, and checked in CI instead (#787).** Better Auth 1.7.3 compares its schema with
334
+ // the database when an instance initializes and refuses requests on a mismatch. Its verdict is
335
+ // cached per instance, and this instance is built per request (`../http/resolve.ts`), so the check
336
+ // would run on every request: eight more D1 statements on top of the five an authenticated request
337
+ // costs, measured by `http/scopes.workers.test.ts`. The kit owns these tables through its own
338
+ // migrations, and `migrations/betterAuthSchemaDrift.workers.test.ts` runs Better Auth's own check
339
+ // against them at the lockfile's version and at the newest the range admits.
340
+ validateSchema: false,
341
+ },
324
342
  },
325
343
  // Better Auth's errors bubble out of `handler` so the Hono boundary maps them to PithyError.
326
344
  //
@@ -0,0 +1,206 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import { createDatabase } from "@pithy-sh/core/src/data/db";
6
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
7
+ import { secretsTables } from "@pithy-sh/secrets/src/data/tables";
8
+ import {
9
+ claimReencryption,
10
+ currentSealedVersion,
11
+ recordReencryption,
12
+ recordSoleVersion,
13
+ } from "@pithy-sh/secrets/src/rotation/reencryption";
14
+ import { parseEnvelope, type SecretConfig, symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto";
15
+ import type { AuthDatabase } from "../data/tables";
16
+ import { AUTH_JWKS_DEPENDENT, AUTH_SESSION_SECRET } from "./secrets";
17
+ import { betterAuthSecrets, type SessionSecretVersions } from "./sessionSecrets";
18
+
19
+ /**
20
+ * **The JWKS private keys, moved under the session secret's newest version before the old one retires (#602).**
21
+ *
22
+ * Better Auth seals every key in `pithy_auth_jwks` under the session secret (`plugins/jwt/utils.mjs`), and a
23
+ * key has no expiry that would make it safe to stop being able to open it. An unattended rotation of
24
+ * `auth-session-secret` therefore waits, before it retires the previous version, for this Worker to say the
25
+ * keys have moved — the secret's registry entry names them as `auth-jwks` — and this is where they move.
26
+ *
27
+ * Each key is opened under whichever retained version it names (`$ba$<version>$…`), or — for one sealed
28
+ * before the kit handed Better Auth a version set, which carries no envelope — under each retained version
29
+ * in turn, oldest first. It is sealed again under the current version and written back only if the row
30
+ * still holds what was read, so two isolates moving the same key cannot interleave into a value neither
31
+ * wrote. Then the move is recorded in the secrets D1, where the manager reads it.
32
+ *
33
+ * **It never makes a key unopenable.** A key no retained version opens is left exactly as it is and
34
+ * counted; it was already lost, and nothing here can lose it further. It does not hold the record back,
35
+ * because waiting cannot make it open — and a retirement held forever over a key that will never be used
36
+ * is an envelope that grows on every rotation.
37
+ */
38
+
39
+ /** What one pass did, in counts. */
40
+ export interface JwksReencryption {
41
+ /** Keys sealed again under the current version. */
42
+ moved: number;
43
+ /** Keys already under it. */
44
+ current: number;
45
+ /** Keys no retained version opens. Left as they were. */
46
+ unopenable: number;
47
+ }
48
+
49
+ /** Better Auth's own key structure for a version set, built the way `buildSecretConfig` builds it. */
50
+ function secretConfig(versions: SessionSecretVersions): SecretConfig {
51
+ const { secrets } = betterAuthSecrets(versions);
52
+ return {
53
+ keys: new Map(secrets.map((one) => [one.version, one.value])),
54
+ currentVersion: Number(versions.currentVersion),
55
+ };
56
+ }
57
+
58
+ /** Open one stored private key, or `null` when no retained version opens it. */
59
+ async function opened(stored: string, versions: SessionSecretVersions, config: SecretConfig): Promise<string | null> {
60
+ if (parseEnvelope(stored) !== null) {
61
+ return await symmetricDecrypt({ key: config, data: stored }).catch(() => null);
62
+ }
63
+ // A bare ciphertext, from before the version set: sealed under whichever value was current then.
64
+ const oldestFirst = [...betterAuthSecrets(versions).secrets].sort((left, right) => left.version - right.version);
65
+ for (const candidate of oldestFirst) {
66
+ const plain = await symmetricDecrypt({ key: candidate.value, data: stored }).catch(() => null);
67
+ if (plain !== null) return plain;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /** Move every JWKS private key under the current version of the session secret. */
73
+ export async function reencryptJwks(db: AuthDatabase, versions: SessionSecretVersions): Promise<JwksReencryption> {
74
+ const config = secretConfig(versions);
75
+ const current = Number(versions.currentVersion);
76
+ const result: JwksReencryption = { moved: 0, current: 0, unopenable: 0 };
77
+ const rows = await db.selectFrom("pithyAuthJwks").select(["id", "privateKey"]).execute();
78
+ for (const row of rows) {
79
+ let stored: unknown;
80
+ try {
81
+ stored = JSON.parse(row.privateKey);
82
+ } catch {
83
+ stored = undefined;
84
+ }
85
+ if (typeof stored !== "string") {
86
+ result.unopenable += 1;
87
+ continue;
88
+ }
89
+ if (parseEnvelope(stored)?.version === current) {
90
+ result.current += 1;
91
+ continue;
92
+ }
93
+ const plain = await opened(stored, versions, config);
94
+ if (plain === null) {
95
+ result.unopenable += 1;
96
+ continue;
97
+ }
98
+ const sealed = JSON.stringify(await symmetricEncrypt({ key: config, data: plain }));
99
+ await db
100
+ .updateTable("pithyAuthJwks")
101
+ .set({ privateKey: sealed })
102
+ .where("id", "=", row.id)
103
+ .where("privateKey", "=", row.privateKey)
104
+ .execute();
105
+ result.moved += 1;
106
+ }
107
+ return result;
108
+ }
109
+
110
+ /**
111
+ * The versions this isolate has finished with — moved, or failed to — keyed by version and fingerprint, so a
112
+ * version key reused after an `update` is a new version here too.
113
+ */
114
+ const settled = new Set<string>();
115
+
116
+ /** The versions this isolate was told to wait on, with when to ask again. */
117
+ const waiting = new Map<string, number>();
118
+
119
+ /** Forget what this isolate has settled or is waiting on. For tests. */
120
+ export function resetJwksReencryption(): void {
121
+ settled.clear();
122
+ waiting.clear();
123
+ }
124
+
125
+ /** What {@link ensureJwksSealedUnderCurrent} needs. */
126
+ export interface EnsureJwksDeps {
127
+ /** The application database the JWKS keys live in. */
128
+ db: AuthDatabase;
129
+ /**
130
+ * That database's binding name — `auth({ database })`. The holder the move is recorded under, so two auth
131
+ * Workers over two databases are waited for one by one rather than one answering for both.
132
+ */
133
+ holder: string;
134
+ /** The secrets D1 the move is recorded in. */
135
+ secrets: D1Database;
136
+ /** The session secret's retained versions, as this request resolved them. */
137
+ versions: SessionSecretVersions;
138
+ /** Where a failure is said. Never fatal. */
139
+ log: Logger;
140
+ /** The clock. Defaults to now. */
141
+ now?: Date;
142
+ }
143
+
144
+ /**
145
+ * Make sure the JWKS keys are sealed under the current version, and that the secrets D1 says so — once per
146
+ * version per isolate.
147
+ *
148
+ * **Recorded with one version too.** While the secret holds one version there is nothing to move, and the
149
+ * record says the keys are under it ({@link recordSoleVersion}). That is how the manager knows this database
150
+ * holds keys before the first rotation: a holder it has never heard from is one it cannot wait for.
151
+ *
152
+ * **Not on the first request that sees the version.** Another isolate may still hold the envelope it cached
153
+ * before the append, with no key for the new version; a key re-sealed under it now would fail there. So the
154
+ * first sight is recorded, and the move waits until every cache filled before it has expired
155
+ * (`claimReencryption`, `REENCRYPTION_SETTLE_MS`). An isolate told to wait does not ask again until then.
156
+ *
157
+ * **Never fatal.** It runs on a request, and the request it rides on is somebody signing in; a failure here
158
+ * leaves the keys where they were — still opening, since the previous version is still held — and the
159
+ * retirement waiting. The next isolate tries again.
160
+ */
161
+ export async function ensureJwksSealedUnderCurrent(deps: EnsureJwksDeps): Promise<void> {
162
+ const { versions } = deps;
163
+ const sole = Object.keys(versions.versions).length < 2;
164
+ const now = deps.now ?? new Date();
165
+ try {
166
+ const sealed = await currentSealedVersion(versions);
167
+ const key = `${deps.holder}:${sole ? "sole" : "rotating"}:${sealed.version}:${sealed.fingerprint}`;
168
+ if (settled.has(key) || (waiting.get(key) ?? 0) > now.getTime()) return;
169
+ try {
170
+ const secretsDb = createDatabase(deps.secrets, secretsTables);
171
+ const where = { name: AUTH_SESSION_SECRET, dependent: AUTH_JWKS_DEPENDENT, holder: deps.holder };
172
+ if (sole) {
173
+ settled.add(key);
174
+ await recordSoleVersion(secretsDb, { ...where, sealed, now });
175
+ return;
176
+ }
177
+ const claim = await claimReencryption(secretsDb, { ...where, sealed, now });
178
+ if (claim.state === "moved") {
179
+ settled.add(key);
180
+ return;
181
+ }
182
+ if (claim.state === "settling") {
183
+ waiting.set(key, claim.until.getTime());
184
+ return;
185
+ }
186
+ settled.add(key);
187
+ const moved = await reencryptJwks(deps.db, versions);
188
+ await recordReencryption(secretsDb, { ...where, ...sealed, now });
189
+ deps.log.info("jwks re-encrypted under the current session secret", { version: sealed.version, ...moved });
190
+ if (moved.unopenable > 0) {
191
+ deps.log.warn("jwks keys no retained session secret opens were left as they were", {
192
+ unopenable: moved.unopenable,
193
+ });
194
+ }
195
+ } catch (error) {
196
+ // Settled for this isolate, so a failing database is not asked again on every request it serves.
197
+ // Another isolate tries; until one finishes, retirement waits and the previous version keeps opening.
198
+ settled.add(key);
199
+ throw error;
200
+ }
201
+ } catch (error) {
202
+ deps.log.warn("jwks re-encryption did not finish; the previous session secret stays until it does", {
203
+ reason: error instanceof Error ? error.message : String(error),
204
+ });
205
+ }
206
+ }
@@ -25,9 +25,10 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
25
25
  * The mitigating fact is that it requires a provider-signed, audience-bound assertion of the address,
26
26
  * so it is not an address an attacker picks — which is why the claim above says *the redirect
27
27
  * callback* and not *provider sign-in*.
28
- * - **A plugin that calls `handleOAuthUserInfo` without going through `provider.getUserInfo`.**
29
- * `plugins/one-tap/index.mjs:45-70` builds the user info straight from a verified Google id token;
30
- * `plugins/oauth-proxy/index.mjs:110` lifts it out of an encrypted proxy payload. The kit composes
28
+ * - **A plugin that calls `handleOAuthUserInfo` outside the redirect callback.** `plugins/one-tap/index.mjs:64`
29
+ * resolves a verified Google id token through Google's own `getUserInfo` with no OAuth state, which
30
+ * this gate passes through, or builds the user info itself when Google is not configured;
31
+ * `plugins/oauth-proxy/index.mjs:127` lifts it out of an encrypted proxy payload. The kit composes
31
32
  * neither. `./refusalTransport` is where a composed plugin is ruled on.
32
33
  * - **An adopter plugin that replaces `ctx.socialProviders` in its own `init`.** Kit plugins run first
33
34
  * by contract (`./auth.ts` composes them ahead of the adopter's), so the wrap is installed before
@@ -47,8 +48,8 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
47
48
  * | 4 | Not attached, no account at that address | Refused |
48
49
  *
49
50
  * Rows 3 and 4 differ only in whether a row exists at an address **the caller chose**, and Better Auth
50
- * answers them with two different codes — `account_not_linked` (`oauth2/link-account.mjs:86`, returned
51
- * only inside `if (dbUser)`) and `signup_disabled` (`:202`, the `else` of that same branch). Both reach
51
+ * answers them with two different codes — `account_not_linked` (`oauth2/link-account.mjs:142`, returned
52
+ * only inside `if (dbUser)`) and `signup_disabled` (`:257`, the `else` of that same branch). Both reach
52
53
  * the browser as `?error=<code>`. That is an account-enumeration oracle needing one provider account,
53
54
  * none on the target, and no page render.
54
55
  *
@@ -58,7 +59,7 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
58
59
  * another, and the last keyed on a value `callbackURL` supplies, so it rewrote *successful* sign-ins.
59
60
  * By the time a response exists the fact that distinguished the two cases is gone and what is left is
60
61
  * partly the caller's. `getUserInfo` is the last seam that holds the fact itself: `callback.mjs:120`
61
- * calls it, `:220` calls `handleOAuthUserInfo`, and **nothing runs in between** — so a refusal thrown
62
+ * calls it, `:172` calls `handleOAuthUserInfo`, and **nothing between them reads a user row** — so a refusal thrown
62
63
  * here means neither of those two lines is ever reached and there is no pair left to collapse.
63
64
  *
64
65
  * ## Why a wrapper, and not a `getUserInfo` supplied in the config block
@@ -134,8 +135,8 @@ type UserInfoResult = Awaited<ReturnType<OAuthProvider["getUserInfo"]>>;
134
135
  * than asserted:** `providerSignInGate.workers.test.ts` drives a refusal the dependency still emits
135
136
  * (`email_not_found`) beside one this gate emits and requires the two `Location` headers to differ in
136
137
  * nothing but the code. `ctx.redirect(url)` is itself only `new APIError("FOUND", undefined, headers)`
137
- * with `location` set (`better-call/dist/context.mjs:60`), and better-auth's router passes a `FOUND`
138
- * straight through its `onError` to `toResponse` (`api/index.mjs:192`), so this is the same object the
138
+ * with `location` set (`better-call/dist/context.mjs:62`), and better-auth's router passes a `FOUND`
139
+ * straight through its `onError` to `toResponse` (`api/index.mjs:196`), so this is the same object the
139
140
  * dependency would have thrown — built without the endpoint context `getUserInfo` is not handed.
140
141
  *
141
142
  * The value being appended to is the OAuth state's own `errorURL`, which is where `redirectOnError`
@@ -165,12 +166,13 @@ function refusalWithoutRedirect(): APIError {
165
166
  /**
166
167
  * Is this provider identity already attached to some account here? Row 1.
167
168
  *
168
- * **Keyed on `(providerId, accountId)`, which is wider than Better Auth's `(issuer, accountId)`, and
169
- * wider is the safe direction.** Deriving the issuer means copying `createOAuthAccountIssuer` —
170
- * `local:oauth:${encodeAccountIssuerProviderId(id)}` — from a package the kit does not depend on, and a
171
- * second copy of a dependency's decision is the defect class this repo has been bitten by four times
172
- * (#106, #108, #109, #113). A false match here passes the attempt through and lets Better Auth decide,
173
- * which is today's behavior; a false *miss* is what would be dangerous, and widening cannot cause one.
169
+ * **Keyed on `(providerId, accountId)`, which is Better Auth's own account key.** 1.7.0–1.7.2 keyed an
170
+ * account on `(issuer, accountId)` instead, and this gate read the wider pair rather than copy how Better
171
+ * Auth derived an issuer. 1.7.3 reverted to the 1.6 model (better-auth/better-auth#11153), and the lookup
172
+ * the callback makes is now `findAccountOwnerByKey({ providerId, accountId })` (`link-account.mjs:80`), so
173
+ * the two ask the same question of the same columns (#787). A false match here would pass the attempt
174
+ * through and let Better Auth decide, which is the safe direction; a false *miss* is what would be
175
+ * dangerous, and an identical key cannot cause one.
174
176
  *
175
177
  * It reads no address and no verified flag, which is what keeps an `allowDifferentEmails` link signing in.
176
178
  *
@@ -214,13 +216,13 @@ async function gateProviderSignIn(args: {
214
216
  }): Promise<void> {
215
217
  const { ctx, provider, token, result, deps } = args;
216
218
 
217
- // No OAuth state: `/link-social` and `/account-info` with an id token (`api/routes/account.mjs:174`,
218
- // `:609`), which never generate one, and `/sign-in/social`'s own id-token branch, which returns before
219
+ // No OAuth state: `/link-social` and `/account-info` with an id token (`api/routes/account.mjs:172`,
220
+ // `:604`), which never generate one, and `/sign-in/social`'s own id-token branch, which returns before
219
221
  // `generateState`. The first two must be untouched — linking from inside the account is a different
220
222
  // flow with both sides already proven — and the third is the uncovered path named in the reach section.
221
223
  //
222
224
  // **`getOAuthState()` throws where no request state was established**, which is every caller reaching
223
- // a provider object by hand rather than through an endpoint (`to-auth-endpoints.mjs:50` wraps them
225
+ // a provider object by hand rather than through an endpoint (`to-auth-endpoints.mjs:52` wraps them
224
226
  // all, `auth.api.*` included). Deliberately not caught: a missing store cannot be a callback today,
225
227
  // and swallowing it would turn a dependency that stopped establishing one into a silent pass-through
226
228
  // instead of a loud failure. There is no such caller in this kit.
@@ -234,7 +236,7 @@ async function gateProviderSignIn(args: {
234
236
  // Verified, load-bearing, and planted against — the gate keys on this field.
235
237
  if (state.link !== undefined && state.link !== null) return;
236
238
 
237
- // No address at all. Better Auth answers `email_not_found` from `callback.mjs:205`, which is the same
239
+ // No address at all. Better Auth answers `email_not_found` from `callback.mjs:168`, which is the same
238
240
  // string on both sides of the fork, so there is nothing here to collapse and nothing to decide. The
239
241
  // kit's own GitHub resolver fails closed to exactly this shape (`./githubUserInfo.ts`).
240
242
  const email = result.user.email;
@@ -245,7 +247,7 @@ async function gateProviderSignIn(args: {
245
247
 
246
248
  const local = await ctx.internalAdapter.findUserByEmail(email);
247
249
 
248
- // Row 2, as the two halves of `link-account.mjs:83` — read from the dependency's own resolved values
250
+ // Row 2, as the two halves of `link-account.mjs:139` — read from the dependency's own resolved values
249
251
  // rather than restated. `emailVerified` here is the **effective** flag: this is the return of the
250
252
  // provider's own `getUserInfo`, so `mapProfileToUser` has already run and Facebook's forced `true` is
251
253
  // already in it.
@@ -268,10 +270,10 @@ async function gateProviderSignIn(args: {
268
270
  // every first provider sign-up into a refusal. Three ways the refusal is certain:
269
271
  //
270
272
  // - **A local row exists.** Better Auth never creates a user when one matched, and row 2 has just
271
- // failed, so `link-account.mjs:86` is where that attempt ends.
273
+ // failed, so `link-account.mjs:142` is where that attempt ends.
272
274
  // - **Sign-up is disabled for this provider** — `provider.options.disableSignUp`, which is the kit's
273
275
  // own `signUpOption()` output (`./auth.ts`) read back off the object rather than restated.
274
- // `callback.mjs:229` also ORs in `disableImplicitSignUp && !requestSignUp`; ignoring that half is
276
+ // `callback.mjs:181` also ORs in `disableImplicitSignUp && !requestSignUp`; ignoring that half is
275
277
  // deliberate, since the kit never sets it and ignoring it can only cause a pass-through.
276
278
  // - **The address is not verified**, which the kit's own `user.create.before` hook refuses anyway.
277
279
  const certain = local !== null || provider.options?.disableSignUp === true || result.user.emailVerified !== true;
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { pithyCommand } from "@pithy-sh/core/src/cli/command";
4
5
  import { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
6
  import { z } from "zod";
6
7
  import type {
@@ -179,7 +180,7 @@ export function providerUnavailable(provider: SocialProviderId): PithyError {
179
180
  code: "auth/provider_unavailable",
180
181
  status: 503,
181
182
  message: `Signing in with ${provider} is unavailable right now. Use a magic link instead.`,
182
- action: `Provision \`auth-${provider}-credentials\` for this environment with \`pithy secrets create\`, or set \`${provider}.enabled\` to false in pithy.config.ts.`,
183
+ action: `Provision \`auth-${provider}-credentials\` for this environment with \`${pithyCommand("secrets create", { args: [`auth-${provider}-credentials`] })}\`, or set \`${provider}.enabled\` to false in pithy.config.ts.`,
183
184
  detail: `provider ${provider} is enabled and its credential could not be resolved; the instance was built without it`,
184
185
  });
185
186
  }
@@ -1,10 +1,12 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
4
5
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
5
6
  import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
6
7
  import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
7
8
  import { z } from "zod";
9
+ import type { SessionSecretVersions } from "./sessionSecrets";
8
10
 
9
11
  /**
10
12
  * The secrets `@pithy-sh/auth` reads, declared as a minimal registry. The secret name is the join key:
@@ -31,6 +33,41 @@ export const AUTH_APPLE_CREDENTIALS = "auth-apple-credentials";
31
33
  export const AUTH_FACEBOOK_CREDENTIALS = "auth-facebook-credentials";
32
34
  export const AUTH_GITHUB_CREDENTIALS = "auth-github-credentials";
33
35
 
36
+ /**
37
+ * The JWKS private keys, as `auth-session-secret`'s overlap names them (#602).
38
+ *
39
+ * Better Auth encrypts every key in `pithy_auth_jwks` under the session secret, and a key never expires —
40
+ * so retiring the version one is sealed under would leave a signing key nothing can open. The session
41
+ * secret's registry entry names this dependent, `instance/jwksReencryption.ts` moves the keys under the
42
+ * newest version and records it, and the secrets manager retires nothing until it has.
43
+ */
44
+ export const AUTH_JWKS_DEPENDENT = "auth-jwks";
45
+
46
+ /**
47
+ * The Better Auth plugins that seal rows of their own under the session secret, by id.
48
+ *
49
+ * `two-factor` seals every TOTP secret with `symmetricEncrypt({ key: ctx.context.secretConfig })`, and its
50
+ * backup codes the same way under `storeBackupCodes: "encrypted"` (`plugins/two-factor/index.mjs`,
51
+ * `backup-codes/index.mjs`). Neither expires. Nothing in the kit re-encrypts them, so an unattended rotation
52
+ * beside one is refused at `auth()` rather than allowed to retire the version they are sealed under.
53
+ */
54
+ export const SESSION_SECRET_SEALING_PLUGINS: readonly string[] = ["two-factor"];
55
+
56
+ /** Seconds in a day. */
57
+ const DAY_SECONDS = 86_400;
58
+
59
+ /**
60
+ * How many days a replaced session secret keeps verifying: the session's own lifetime, rounded up.
61
+ *
62
+ * **That is the whole of the overlap's argument.** A session in use is re-signed on its next request
63
+ * (`http/credentialResign.ts`), and its expiry slides forward on use — so a session that goes the whole
64
+ * overlap without one request has expired by the time the overlap ends. Any shorter, and a session used
65
+ * yesterday is signed out when the old version retires.
66
+ */
67
+ export function sessionSecretOverlapDays(sessionExpiresIn: number): number {
68
+ return Math.max(1, Math.ceil(sessionExpiresIn / DAY_SECONDS));
69
+ }
70
+
34
71
  /** The Google OAuth credential pair, stored as one typed JSON secret. */
35
72
  export const GoogleOAuthCredentials = z
36
73
  .object({
@@ -135,6 +172,9 @@ export const authSecretsRegistry = defineSecretRegistry({
135
172
  // a session signature, so the kit both makes it and replaces it.
136
173
  origin: { kind: "minted", recipe: { kind: "random", bytes: 32, encoding: "base64url" } },
137
174
  rotation: { kind: "local" },
175
+ // The default session lifetime's overlap, and the JWKS keys sealed under it (#602). `auth()` declares
176
+ // its own from the configured `sessionExpiresIn`; this is what a module reading the secret sees.
177
+ overlap: { days: 7, minimumDays: 7, reencrypt: [AUTH_JWKS_DEPENDENT] },
138
178
  },
139
179
  // The four below are `obtained` and rotate `manual`, and each names the page rather than the product.
140
180
  // An adopter searching Google's console for which of four credential types "client secret" means is the
@@ -177,6 +217,49 @@ export const authSecretsRegistry = defineSecretRegistry({
177
217
  },
178
218
  });
179
219
 
220
+ /**
221
+ * **The registry `auth()` contributes, from its own configuration (#602).**
222
+ *
223
+ * The session secret's overlap follows the configured session lifetime — {@link sessionSecretOverlapDays} —
224
+ * and it is both the overlap and its floor: an adopter who lengthens sessions lengthens the overlap with
225
+ * them, rather than holding a seven-day overlap against a thirty-day session. `rotateEveryDays` is
226
+ * `sessionSecretRotateEveryDays`, and only an adopter sets it: the kit turns no unattended rotation on.
227
+ *
228
+ * Checked by `defineSecretRegistry` like every registry, so a period no longer than the session lifetime is
229
+ * refused here, at `auth()`, naming the secret — rather than at a 03:00 cron that could only skip it.
230
+ *
231
+ * **A period is refused beside a plugin that seals rows under the session secret** —
232
+ * {@link SESSION_SECRET_SEALING_PLUGINS}. Only the JWKS keys are moved before a retirement; a plugin's own
233
+ * sealed rows would be left under the retired version, and nothing could open them again.
234
+ */
235
+ export function authSecretsRegistryFor(config: {
236
+ sessionExpiresIn: number;
237
+ sessionSecretRotateEveryDays?: number;
238
+ plugins?: readonly { id: string }[];
239
+ }) {
240
+ if (config.sessionSecretRotateEveryDays !== undefined) {
241
+ const sealing = (config.plugins ?? []).find((plugin) => SESSION_SECRET_SEALING_PLUGINS.includes(plugin.id));
242
+ if (sealing !== undefined) {
243
+ throw new ValidationError({
244
+ message: `${AUTH_SESSION_SECRET} cannot rotate unattended while the Better Auth "${sealing.id}" plugin is composed.`,
245
+ action: `Remove sessionSecretRotateEveryDays from auth({ ... }), or remove ${sealing.id}() from auth({ plugins: [...] }). ${sealing.id}() seals its secrets under ${AUTH_SESSION_SECRET}, and a rotation retires the version they are sealed under with nothing to move them first.`,
246
+ detail: `sessionSecretRotateEveryDays set with plugin "${sealing.id}", which seals rows under ${AUTH_SESSION_SECRET}`,
247
+ });
248
+ }
249
+ }
250
+ const days = sessionSecretOverlapDays(config.sessionExpiresIn);
251
+ return defineSecretRegistry({
252
+ ...authSecretsRegistry,
253
+ [AUTH_SESSION_SECRET]: {
254
+ ...authSecretsRegistry[AUTH_SESSION_SECRET],
255
+ overlap: { days, minimumDays: days, reencrypt: [AUTH_JWKS_DEPENDENT] },
256
+ ...(config.sessionSecretRotateEveryDays === undefined
257
+ ? {}
258
+ : { rotateEveryDays: config.sessionSecretRotateEveryDays }),
259
+ },
260
+ });
261
+ }
262
+
180
263
  /**
181
264
  * Which provider a credential belongs to — the join the CLI must never make by spelling (#541).
182
265
  *
@@ -217,12 +300,22 @@ export function inapplicableProviderSecrets(providers: AuthProviderToggles): Rec
217
300
  return declared;
218
301
  }
219
302
 
220
- /** Resolve the Better Auth session secret for this invocation. */
303
+ /** Resolve the Better Auth session secret for this invocation — the current version alone. */
221
304
  export async function resolveSessionSecret(env: SecretsStoreEnv): Promise<string> {
222
305
  const secrets = await sharedSecretsStore(env, authSecretsRegistry);
223
306
  return secrets.get(AUTH_SESSION_SECRET);
224
307
  }
225
308
 
309
+ /**
310
+ * Resolve every retained version of the session secret (#602) — what an instance needs to open values sealed
311
+ * under the previous version, and what a credential signed under it is verified against. One read through
312
+ * the same cached accessor as {@link resolveSessionSecret}.
313
+ */
314
+ export async function resolveSessionSecrets(env: SecretsStoreEnv): Promise<SessionSecretVersions> {
315
+ const secrets = await sharedSecretsStore(env, authSecretsRegistry);
316
+ return secrets.getVersions(AUTH_SESSION_SECRET);
317
+ }
318
+
226
319
  /** Resolve the Google OAuth credential pair for this invocation (only call when Google is enabled). */
227
320
  export async function resolveGoogleCredentials(env: SecretsStoreEnv): Promise<GoogleOAuthCredentials> {
228
321
  const secrets = await sharedSecretsStore(env, authSecretsRegistry);
@@ -0,0 +1,64 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * **The session secret as Better Auth needs it across a rotation (#602): every retained version.**
6
+ *
7
+ * `auth-session-secret` is `rotatable: true`, and an unattended rotation appends a version and keeps the
8
+ * previous one for the overlap. The kit used to hand Better Auth one value — the current one — which made
9
+ * the overlap decorative: the moment the version changed, the JWKS private keys were sealed under a value
10
+ * the instance no longer held. Better Auth 1.7 takes a version set instead (`secrets: [{ version, value }]`,
11
+ * newest first): it encrypts under the first and decrypts under whichever version a ciphertext names
12
+ * (`$ba$<version>$…`, `better-auth/dist/crypto/index.mjs`).
13
+ *
14
+ * **It versions encryption and not signatures.** With `secrets` set, `ctx.secret` is the first entry alone
15
+ * (`context/create-context.mjs:75`), and the session cookie is signed and verified under `ctx.secret`
16
+ * (`cookies/index.mjs:172`). So a cookie signed under the previous version still fails after a rotation;
17
+ * `http/credentialResign.ts` is what verifies it under a retained version and re-signs it.
18
+ *
19
+ * **`secret` is the oldest retained version, and that is deliberate.** With a version set, Better Auth reads
20
+ * `secret` only as the *legacy* secret — the one it tries on a bare ciphertext with no `$ba$` envelope. Every
21
+ * JWKS key written before the kit passed a version set is one of those, sealed under the value that was
22
+ * current then, which is the oldest the envelope still holds. Re-encryption moves them into the envelope;
23
+ * until it has, this is what opens them.
24
+ */
25
+
26
+ /** A secret's retained versions, as `secretsStore(…).getVersions` answers. */
27
+ export interface SessionSecretVersions {
28
+ /** The version key reads resolve to. */
29
+ currentVersion: string;
30
+ /** Every retained version: version key → value. */
31
+ versions: Readonly<Record<string, string>>;
32
+ }
33
+
34
+ /** What `betterAuth()` is handed: the version set, newest first, and the legacy secret. */
35
+ export interface BetterAuthSecretOptions {
36
+ /** Every retained version, current first, then the rest newest first. */
37
+ secrets: { version: number; value: string }[];
38
+ /** The oldest retained version — Better Auth's legacy secret, for a ciphertext sealed before versions existed. */
39
+ secret: string;
40
+ }
41
+
42
+ /** The retained versions, current first and the rest in descending numeric order. */
43
+ function ordered(versions: SessionSecretVersions): { version: number; value: string }[] {
44
+ const prior = Object.entries(versions.versions)
45
+ .filter(([version]) => version !== versions.currentVersion)
46
+ .map(([version, value]) => ({ version: Number(version), value }))
47
+ .sort((left, right) => right.version - left.version);
48
+ const current = versions.versions[versions.currentVersion];
49
+ return current === undefined ? prior : [{ version: Number(versions.currentVersion), value: current }, ...prior];
50
+ }
51
+
52
+ /** The version set and legacy secret for `betterAuth()`. */
53
+ export function betterAuthSecrets(versions: SessionSecretVersions): BetterAuthSecretOptions {
54
+ const secrets = ordered(versions);
55
+ const oldest = [...secrets].sort((left, right) => left.version - right.version)[0];
56
+ return { secrets, secret: oldest?.value ?? "" };
57
+ }
58
+
59
+ /** Every retained value but the current one, newest first — what a credential signed before a rotation is tried under. */
60
+ export function priorSessionSecrets(versions: SessionSecretVersions): string[] {
61
+ return ordered(versions)
62
+ .filter((one) => String(one.version) !== versions.currentVersion)
63
+ .map((one) => one.value);
64
+ }
@@ -82,12 +82,11 @@ export const auth_0001_init: Migration = {
82
82
  await db.schema
83
83
  .createTable("pithyAuthAccounts")
84
84
  .addColumn("id", "text", (c) => c.primaryKey())
85
- // `issuer` is 1.7's account identity, and it is `required: true` in Better Auth's own model
86
- // (#451). An account is the pair `(issuer, accountId)` now rather than `(providerId, accountId)`,
87
- // because a provider id is ours to name and an issuer is the identity provider's own — two
88
- // providers configured against one directory could otherwise mint the same `accountId` and land
89
- // on different rows. `local:credential` for a password, the discovery URL for an OIDC provider,
90
- // `local:oauth:<id>` for an OAuth provider that publishes none.
85
+ // `issuer` was Better Auth 1.7.0–1.7.2's account identity, `required: true` in its model then
86
+ // (#451), with an account the pair `(issuer, accountId)`. 1.7.3 reverted to the 1.6 model, which
87
+ // identifies an account by `(providerId, accountId)` and never writes this column
88
+ // (better-auth/better-auth#11153). This `NOT NULL` is history: `0003_account_issuer_nullable`
89
+ // relaxes it and drops the index below, and the column stays only to keep what 1.7.1 wrote (#787).
91
90
  .addColumn("issuer", "text", (c) => c.notNull())
92
91
  .addColumn("accountId", "text", (c) => c.notNull())
93
92
  .addColumn("providerId", "text", (c) => c.notNull())
@@ -168,10 +167,9 @@ export const auth_0001_init: Migration = {
168
167
  await db.schema.createIndex("pithyAuthSessionsUserIdIdx").on("pithyAuthSessions").column("userId").execute();
169
168
  await db.schema.createIndex("pithyAuthSessionsDeviceIdIdx").on("pithyAuthSessions").column("deviceId").execute();
170
169
  await db.schema.createIndex("pithyAuthAccountsUserIdIdx").on("pithyAuthAccounts").column("userId").execute();
171
- // The identity 1.7 looks an account up by, and unique because the pair *is* the identity: two rows
172
- // sharing it are two records of one account at one provider, which is the account-confusion state
173
- // Better Auth's own 1.7 upgrade guide has adopters audit for before adding this (#451). Declared
174
- // here rather than backfilled, because nothing is published and no row predates it.
170
+ // The identity 1.7.0–1.7.2 looked an account up by, unique because the pair was the identity (#451).
171
+ // 1.7.3 looks an account up by `(providerId, accountId)` again, and `0003_account_issuer_nullable`
172
+ // drops this index first, as Better Auth's 1.7 upgrade guide orders it (#787).
175
173
  await db.schema
176
174
  .createIndex("pithyAuthAccountsIssuerAccountIdIdx")
177
175
  .on("pithyAuthAccounts")