@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
@@ -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")
@@ -0,0 +1,199 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { ConflictError, InternalError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { type CompiledQuery, type Kysely, sql } from "kysely";
6
+ import type { Migration } from "kysely/migration";
7
+
8
+ /**
9
+ * Relax `pithy_auth_accounts.issuer` to nullable and drop the `(issuer, accountId)` unique index (#787).
10
+ *
11
+ * **Better Auth reverted `issuer` in a patch release.** 1.7.0 made an account the pair `(issuer, accountId)`,
12
+ * required `issuer`, and `0001_init` followed it (#451). 1.7.3 restored the 1.6 model, which identifies an
13
+ * account by `(providerId, accountId)` again (better-auth/better-auth#11153), and stopped writing `issuer`
14
+ * at all. So on 1.7.3 and later every insert into this table failed on the `NOT NULL`, and every email OTP
15
+ * sign-in answered 500. 1.7.3 also validates the schema at initialization, which is where the logged
16
+ * `Database schema mismatch` came from.
17
+ *
18
+ * **This is Better Auth's own cleanup, from its 1.7 upgrade guide.** Drop the unique index first, then
19
+ * relax the constraint. No backfill. The column stays, with every value in it: a Worker migrated under
20
+ * 1.7.1 loses nothing, and the step can be reversed. Dropping the column is a separate decision.
21
+ *
22
+ * **A `0003`, never an edit to `0001_init`.** `0001` has shipped and has run against real rows, so it is
23
+ * history. A fresh install runs `0001` then this, and ends in the same schema as an upgraded one.
24
+ *
25
+ * **SQLite has no `ALTER COLUMN`, so relaxing a constraint is a table rebuild.** A new table, every row
26
+ * copied across, the old one dropped, the new one renamed into its place, its indexes recreated. Nothing
27
+ * references this table by foreign key, so dropping it cascades into nothing.
28
+ *
29
+ * **The rebuild reads the table it replaces rather than a column list written here.** An adopter's Better
30
+ * Auth plugin can add columns and indexes to this table through its own `0002_plugin_<id>` migration, which
31
+ * sorts before this one, and a rebuild from a fixed list would drop them and their data without a word. So
32
+ * the columns come from `pragma_table_info` and the indexes from `sqlite_master`, and only `issuer`'s
33
+ * constraint and the one index are changed.
34
+ *
35
+ * **The swap is one round trip.** The migration runner queues schema statements and sends a run of them as
36
+ * one `d1.batch()`, which D1 applies as one transaction. A raw `sql` template is never queued: it flushes
37
+ * the queue and runs alone. So the index drops, the table drop, the rename and every index recreate are
38
+ * built as schema statements, back to back, and either all of them apply or none does. Separate, a run that
39
+ * died after the drop would leave auth with no accounts table, and one that died after the rename would
40
+ * leave it with no indexes and a retry that records Success over the loss.
41
+ *
42
+ * `down` is the tested inverse: the same rebuild with `NOT NULL` back, then the unique index, in the same
43
+ * batch. It refuses before it touches anything when a row has no `issuer`, since the constraint cannot hold
44
+ * over that row, or when two rows share an `(issuer, accountId)`, since the index cannot.
45
+ */
46
+
47
+ const ACCOUNTS = "pithy_auth_accounts";
48
+ const ACCOUNTS_NEXT = "pithy_auth_accounts_next";
49
+
50
+ /** One column of a table, as SQLite's `pragma_table_info` reports it. */
51
+ interface TableColumn {
52
+ name: string;
53
+ type: string;
54
+ notnull: number;
55
+ /** `dflt_value`, renamed in the query: the `CamelCasePlugin` would rename a snake_case result key. */
56
+ initial: string | null;
57
+ pk: number;
58
+ }
59
+
60
+ /**
61
+ * Every column of the accounts table, in declaration order.
62
+ *
63
+ * The names come back snake_case, as the database stores them, and go back into the rebuild the same
64
+ * way: `CamelCasePlugin` leaves a name with no capital in it as it is.
65
+ */
66
+ async function accountColumns(db: Kysely<unknown>): Promise<TableColumn[]> {
67
+ const { rows } =
68
+ await sql<TableColumn>`select name, type, "notnull", dflt_value as initial, pk from pragma_table_info(${ACCOUNTS}) order by cid`.execute(
69
+ db,
70
+ );
71
+ return rows;
72
+ }
73
+
74
+ /** The DDL of every index on the accounts table that SQLite did not create for itself. */
75
+ async function accountIndexes(db: Kysely<unknown>): Promise<{ name: string; sql: string }[]> {
76
+ const { rows } = await sql<{
77
+ name: string;
78
+ sql: string;
79
+ }>`select name, sql from sqlite_master where type = 'index' and tbl_name = ${ACCOUNTS} and sql is not null order by name`.execute(
80
+ db,
81
+ );
82
+ return rows;
83
+ }
84
+
85
+ /** One column's definition, as `create table` takes it. */
86
+ function columnDefinition(column: TableColumn, issuerNotNull: boolean): ReturnType<typeof sql> {
87
+ const parts = [sql.id(column.name), sql.raw(column.type)];
88
+ if (column.pk === 1) parts.push(sql`primary key`);
89
+ const notNull = column.name === "issuer" ? issuerNotNull : column.notnull === 1;
90
+ if (notNull && column.pk !== 1) parts.push(sql`not null`);
91
+ if (column.initial !== null) parts.push(sql`default ${sql.raw(column.initial)}`);
92
+ return sql.join(parts, sql` `);
93
+ }
94
+
95
+ /**
96
+ * Rebuild the accounts table with `issuer` nullable or not, keeping every other column, row and index.
97
+ * The unique `(issuer, accountId)` index is dropped before the rebuild and is not carried across.
98
+ */
99
+ async function rebuild(db: Kysely<unknown>, issuerNotNull: boolean): Promise<void> {
100
+ const columns = await accountColumns(db);
101
+ if (!columns.some((column) => column.name === "issuer")) {
102
+ throw new InternalError({
103
+ message: `${ACCOUNTS} has no issuer column, so there is no constraint to change.`,
104
+ action: "Compare the table with auth's 0001_init. Something outside the migration chain has reshaped it.",
105
+ });
106
+ }
107
+ if (columns.filter((column) => column.pk > 0).length !== 1) {
108
+ throw new InternalError({
109
+ message: `${ACCOUNTS} does not have the single-column primary key 0001_init gave it.`,
110
+ action: "Compare the table with auth's 0001_init. Something outside the migration chain has reshaped it.",
111
+ });
112
+ }
113
+
114
+ // A rebuild an earlier run left half-done. The create and the copy below are raw `sql` and each its own
115
+ // round trip, so a run that died after either leaves this behind beside an intact table, indexes
116
+ // included, and the retry would fail on it. The checks above have just read the real table whole, so
117
+ // nothing here is the only copy of anything.
118
+ await sql`drop table if exists ${sql.id(ACCOUNTS_NEXT)}`.execute(db);
119
+
120
+ // First, as Better Auth's upgrade guide orders it. `ifExists`, because `down` runs this rebuild too and
121
+ // the index is already gone by then.
122
+ await db.schema.dropIndex("pithyAuthAccountsIssuerAccountIdIdx").ifExists().execute();
123
+ const indexes = await accountIndexes(db);
124
+
125
+ await sql`create table ${sql.id(ACCOUNTS_NEXT)} (${sql.join(columns.map((column) => columnDefinition(column, issuerNotNull)))})`.execute(
126
+ db,
127
+ );
128
+ const names = sql.join(columns.map((column) => sql.id(column.name)));
129
+ await sql`insert into ${sql.id(ACCOUNTS_NEXT)} (${names}) select ${names} from ${sql.id(ACCOUNTS)}`.execute(db);
130
+
131
+ // From here to the end of the migration body, every statement is a schema statement, so the runner sends
132
+ // them as one batch: each index drop, the table drop, the rename, each index recreate, and in `down` the
133
+ // unique index after them. A failure anywhere in it rolls all of it back, and the retry finds the
134
+ // original table whole, its indexes on it. Nothing in this stretch may be a raw `sql` template, which
135
+ // would split the batch.
136
+ //
137
+ // Each index is dropped by name before the table, as every `down` in the kit drops what it created, and
138
+ // recreated after the rename. Inside the one batch that costs nothing: the original keeps every index
139
+ // unless the whole batch applies. The index names are SQLite's own, so they skip the `CamelCasePlugin`.
140
+ // The table names go through it, so they are written camelCase, as `0001_init` writes them.
141
+ for (const index of indexes) await db.withoutPlugins().schema.dropIndex(index.name).execute();
142
+ await db.schema.dropTable("pithyAuthAccounts").execute();
143
+ await db.schema.alterTable("pithyAuthAccountsNext").renameTo("pithyAuthAccounts").execute();
144
+ for (const index of indexes) await db.executeQuery(recreateIndex(db, index));
145
+ }
146
+
147
+ /**
148
+ * One index's recreate, as a schema statement carrying the DDL SQLite kept for it, verbatim.
149
+ *
150
+ * Verbatim, because a plugin's index can be partial, on an expression, or collated, and rebuilding it from
151
+ * a builder would mean parsing that back out of its DDL. The DDL names the table by the name the rebuilt
152
+ * one has once renamed. The statement is a `create index` node with that text as its SQL, which is exactly
153
+ * what it is, and the node is what lets the runner queue it into the batch the drop and rename are in. The
154
+ * runner reads only the node's kind, so the builder's column is a placeholder that never reaches SQLite.
155
+ */
156
+ function recreateIndex(db: Kysely<unknown>, index: { name: string; sql: string }): CompiledQuery {
157
+ const node = db.withoutPlugins().schema.createIndex(index.name).on(ACCOUNTS).column("id").compile();
158
+ return { ...node, sql: index.sql };
159
+ }
160
+
161
+ export const auth_0003_account_issuer_nullable: Migration = {
162
+ async up(db: Kysely<unknown>): Promise<void> {
163
+ await rebuild(db, false);
164
+ },
165
+
166
+ async down(db: Kysely<unknown>): Promise<void> {
167
+ const { rows: unissued } = await sql<{
168
+ count: number;
169
+ }>`select count(*) as count from ${sql.id(ACCOUNTS)} where issuer is null`.execute(db);
170
+ const missing = Number(unissued[0]?.count ?? 0);
171
+ if (missing > 0) {
172
+ throw new ConflictError({
173
+ message: `Cannot restore NOT NULL on ${ACCOUNTS}.issuer. ${missing} account row(s) have no issuer. Nothing was changed.`,
174
+ action:
175
+ "Better Auth 1.7.3 and later never write an issuer. Fill the column for those rows, or stay on this migration.",
176
+ });
177
+ }
178
+ const { rows: shared } = await sql<{
179
+ count: number;
180
+ }>`select count(*) as count from (select 1 from ${sql.id(ACCOUNTS)} group by issuer, account_id having count(*) > 1)`.execute(
181
+ db,
182
+ );
183
+ const duplicated = Number(shared[0]?.count ?? 0);
184
+ if (duplicated > 0) {
185
+ throw new ConflictError({
186
+ message: `Cannot restore the unique (issuer, account_id) index on ${ACCOUNTS}. ${duplicated} pair(s) are held by more than one row. Nothing was changed.`,
187
+ action: "Resolve the duplicate accounts first. Each pair is one account at one identity provider.",
188
+ });
189
+ }
190
+
191
+ await rebuild(db, true);
192
+ await db.schema
193
+ .createIndex("pithyAuthAccountsIssuerAccountIdIdx")
194
+ .on("pithyAuthAccounts")
195
+ .columns(["issuer", "accountId"])
196
+ .unique()
197
+ .execute();
198
+ },
199
+ };
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { auth_0001_init } from "./0001_init";
5
5
  import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at";
6
+ import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullable";
6
7
 
7
8
  /**
8
9
  * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
@@ -14,10 +15,11 @@ import { auth_0002_session_authenticated_at } from "./0002_session_authenticated
14
15
  * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
15
16
  * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
16
17
  *
17
- * A `0003` appends here and reaches every reader. `0001_init.workers.test.ts` is deliberately not a reader:
18
+ * `0003` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
18
19
  * its subject is that one migration's own `up` and `down`, so it names it directly.
19
20
  */
20
21
  export const AUTH_MIGRATIONS = {
21
22
  "0001_init": auth_0001_init,
22
23
  "0002_session_authenticated_at": auth_0002_session_authenticated_at,
24
+ "0003_account_issuer_nullable": auth_0003_account_issuer_nullable,
23
25
  } as const;
@@ -0,0 +1,82 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * What Better Auth writes against what the kit's tables hold, in both directions (#451, #787).
6
+ *
7
+ * **The first direction is #451's.** A column Better Auth writes and the table lacks fails every insert
8
+ * that names it: 1.7's `jwt` plugin added `alg` and `crv`, `0001_init` had neither, and every sign-in that
9
+ * minted a signing key died on `table pithy_auth_jwks has no column named alg`.
10
+ *
11
+ * **The second direction is #787's, and its absence let the first one's mirror image ship.** A `NOT NULL`
12
+ * column with no default that Better Auth does not write fails every insert into its table, because
13
+ * nothing supplies it. 1.7.3 stopped writing `pithy_auth_accounts.issuer`, `0001_init` still required it,
14
+ * and every email OTP sign-in answered 500. The first direction could not see it: every column Better Auth
15
+ * declared was there. This is the same comparison Better Auth's own initialization check makes
16
+ * (`@better-auth/core`'s `diffSchema`), held here so CI makes it at whatever version is installed.
17
+ *
18
+ * Both halves compare in the database's vocabulary: Better Auth's camelCase names are snake-cased the way
19
+ * the `CamelCasePlugin` does it, and `pragma_table_info` reports the rest.
20
+ */
21
+
22
+ /** A field of a Better Auth model, as `getSchema` reports it. Only the column name matters here. */
23
+ export interface DeclaredField {
24
+ /** The column name, when it differs from the field's key. */
25
+ fieldName?: string;
26
+ }
27
+
28
+ /** A Better Auth model, as `getSchema` reports it. */
29
+ export interface DeclaredModel {
30
+ /** Every field the model writes, keyed by field name. */
31
+ fields: Record<string, DeclaredField>;
32
+ }
33
+
34
+ /** One column of a table, as `pragma_table_info` describes it. */
35
+ export interface ActualColumn {
36
+ /** The column name, snake_case. */
37
+ name: string;
38
+ /** Whether the column is `NOT NULL`. */
39
+ notNull: boolean;
40
+ /** Whether the column carries a default. */
41
+ hasDefault: boolean;
42
+ }
43
+
44
+ /** camelCase → snake_case, the one transformation `CamelCasePlugin` applies to an identifier. */
45
+ export function snake(name: string): string {
46
+ return name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
47
+ }
48
+
49
+ /**
50
+ * Every disagreement between what Better Auth writes and what the tables hold, one line each.
51
+ *
52
+ * `actual` maps a snake_case table name to its columns, and a table it does not name is a table that does
53
+ * not exist. A model with no table is reported once, as such, rather than as every column it lacks. The
54
+ * `id` primary key counts as written: Better Auth generates one for every row.
55
+ */
56
+ export function schemaDrift(
57
+ declared: Record<string, DeclaredModel>,
58
+ actual: Record<string, readonly ActualColumn[]>,
59
+ ): string[] {
60
+ const findings: string[] = [];
61
+ for (const [model, spec] of Object.entries(declared)) {
62
+ const table = snake(model);
63
+ const columns = actual[table];
64
+ if (columns === undefined || columns.length === 0) {
65
+ findings.push(`${table}: no such table`);
66
+ continue;
67
+ }
68
+ const written = new Set([
69
+ "id",
70
+ ...Object.entries(spec.fields).map(([field, definition]) => snake(definition.fieldName ?? field)),
71
+ ]);
72
+ const present = new Set(columns.map((column) => column.name));
73
+ for (const column of written) {
74
+ if (!present.has(column)) findings.push(`${table}.${column}: missing`);
75
+ }
76
+ for (const column of columns) {
77
+ if (written.has(column.name) || !column.notNull || column.hasDefault) continue;
78
+ findings.push(`${table}.${column.name}: required, and Better Auth never writes it`);
79
+ }
80
+ }
81
+ return findings;
82
+ }