@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.
- package/README.md +4 -0
- package/dist/caller/certificate.d.ts +83 -0
- package/dist/caller/certificate.d.ts.map +1 -0
- package/dist/caller/certificate.js +92 -0
- package/dist/caller/request.d.ts +66 -0
- package/dist/caller/request.d.ts.map +1 -0
- package/dist/caller/request.js +71 -0
- package/dist/caller/token.d.ts +130 -0
- package/dist/caller/token.d.ts.map +1 -0
- package/dist/caller/token.js +207 -0
- package/dist/capability.d.ts +44 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +7 -4
- package/dist/data/betterAuth.d.ts +1 -1
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +1 -1
- package/dist/data/tables.d.ts +1 -1
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +39 -8
- package/dist/http/credentialResign.d.ts +46 -0
- package/dist/http/credentialResign.d.ts.map +1 -0
- package/dist/http/credentialResign.js +203 -0
- package/dist/http/devLoginRoute.d.ts.map +1 -1
- package/dist/http/devLoginRoute.js +12 -5
- package/dist/http/errorCallbackUrl.d.ts.map +1 -1
- package/dist/http/errorCallbackUrl.js +15 -9
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +66 -15
- package/dist/http/providerRefusal.d.ts +8 -7
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +29 -32
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +18 -3
- package/dist/http/responses.d.ts +52 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +25 -1
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +60 -9
- package/dist/http/schemas.d.ts +1 -1
- package/dist/http/schemas.js +1 -1
- package/dist/instance/auth.d.ts +1225 -2
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +6 -2
- package/dist/instance/jwksReencryption.d.ts +75 -0
- package/dist/instance/jwksReencryption.d.ts.map +1 -0
- package/dist/instance/jwksReencryption.js +160 -0
- package/dist/instance/providerSignInGate.d.ts +7 -6
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +16 -14
- package/dist/instance/providers.d.ts.map +1 -1
- package/dist/instance/providers.js +2 -1
- package/dist/instance/secrets.d.ts +168 -1
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +86 -3
- package/dist/instance/sessionSecrets.d.ts +45 -0
- package/dist/instance/sessionSecrets.d.ts.map +1 -0
- package/dist/instance/sessionSecrets.js +29 -0
- package/dist/migrations/0001_init.d.ts.map +1 -1
- package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
- package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
- package/dist/migrations/0003_account_issuer_nullable.js +131 -0
- package/dist/migrations/set.d.ts +2 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +4 -2
- package/dist/seeds/devSession.d.ts.map +1 -1
- package/dist/seeds/devSession.js +2 -1
- package/dist/test-utils/liveApp.d.ts +5 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +3 -3
- package/dist/test-utils/schemaDrift.d.ts +49 -0
- package/dist/test-utils/schemaDrift.d.ts.map +1 -0
- package/dist/test-utils/schemaDrift.js +35 -0
- package/dist/test-utils/scopedBackend.d.ts +183 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -0
- package/dist/test-utils/scopedBackend.js +160 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/server-authoritative.md +182 -0
- package/package.json +14 -11
- package/src/caller/certificate.ts +133 -0
- package/src/caller/request.ts +84 -0
- package/src/caller/token.ts +276 -0
- package/src/capability.ts +65 -4
- package/src/data/betterAuth.ts +2 -1
- package/src/http/adminRoutes.ts +46 -10
- package/src/http/credentialResign.ts +268 -0
- package/src/http/devLoginRoute.ts +19 -6
- package/src/http/errorCallbackUrl.ts +21 -13
- package/src/http/middleware.ts +100 -35
- package/src/http/providerRefusal.ts +30 -32
- package/src/http/resolve.ts +27 -3
- package/src/http/responses.ts +54 -0
- package/src/http/routes.ts +97 -11
- package/src/http/schemas.ts +1 -1
- package/src/instance/auth.ts +22 -4
- package/src/instance/jwksReencryption.ts +206 -0
- package/src/instance/providerSignInGate.ts +23 -21
- package/src/instance/providers.ts +2 -1
- package/src/instance/secrets.ts +94 -1
- package/src/instance/sessionSecrets.ts +64 -0
- package/src/migrations/0001_init.ts +8 -10
- package/src/migrations/0003_account_issuer_nullable.ts +199 -0
- package/src/migrations/set.ts +3 -1
- package/src/seeds/devSession.ts +2 -1
- package/src/test-utils/liveApp.ts +8 -6
- package/src/test-utils/schemaDrift.ts +82 -0
- package/src/test-utils/scopedBackend.ts +136 -0
- package/src/version.generated.ts +1 -1
|
@@ -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
|
+
};
|
package/src/migrations/set.ts
CHANGED
|
@@ -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
|
-
*
|
|
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;
|
package/src/seeds/devSession.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import { normalizeAddress } from "@pithy-sh/core/src/address/address";
|
|
5
|
+
import { commandName } from "@pithy-sh/core/src/cli/command";
|
|
5
6
|
import { fromZodError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
6
7
|
import { MAX_SEED_ORDER } from "@pithy-sh/core/src/seed/compose";
|
|
7
8
|
import { DEV_LOGIN_FILE, DEV_LOGIN_PATH, type DevLogin, DevLogins } from "@pithy-sh/core/src/seed/devLogin";
|
|
@@ -376,7 +377,7 @@ export const authDevSessionSeed: SeedSet = defineSeed({
|
|
|
376
377
|
// fail again with the same sentence. The path is deliberately unnamed rather than guessed: this
|
|
377
378
|
// set runs inside a Worker with no filesystem and no config directory to resolve, and `pithy
|
|
378
379
|
// doctor` prints the resolved path on every run precisely so a message like this does not have to.
|
|
379
|
-
action: `Add ${AUTH_SESSION_SECRET} to this project's dev secrets file —
|
|
380
|
+
action: `Add ${AUTH_SESSION_SECRET} to this project's dev secrets file — ${commandName("doctor")} prints its path — then seed again.`,
|
|
380
381
|
});
|
|
381
382
|
}
|
|
382
383
|
|
|
@@ -17,7 +17,7 @@ import { devEncryptionKeys } from "@pithy-sh/secrets/src/test-utils/devEncryptio
|
|
|
17
17
|
import { type SecretFixture, seedSecrets } from "@pithy-sh/secrets/src/test-utils/secretFixtures";
|
|
18
18
|
import { turnstileSecretsRegistry } from "@pithy-sh/turnstile/src/secret/registry";
|
|
19
19
|
import { Hono } from "hono";
|
|
20
|
-
import { Miniflare } from "miniflare";
|
|
20
|
+
import { convertV4MiniflareOptions, Miniflare } from "miniflare";
|
|
21
21
|
import { AuthConfig, type AuthWiring } from "../capability";
|
|
22
22
|
import { publishSameOrigin } from "../http/csrf";
|
|
23
23
|
import { createSessionMiddleware } from "../http/middleware";
|
|
@@ -150,11 +150,13 @@ export interface LiveApp {
|
|
|
150
150
|
* forgets leaves a workerd process behind.
|
|
151
151
|
*/
|
|
152
152
|
export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
|
|
153
|
-
const miniflare = new Miniflare(
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
153
|
+
const miniflare = new Miniflare(
|
|
154
|
+
convertV4MiniflareOptions({
|
|
155
|
+
modules: true,
|
|
156
|
+
script: "export default {};",
|
|
157
|
+
d1Databases: { DB: "DB", SECRETS: "SECRETS" },
|
|
158
|
+
}),
|
|
159
|
+
);
|
|
158
160
|
const db = (await miniflare.getD1Database("DB")) as unknown as D1Database;
|
|
159
161
|
const secretsDb = (await miniflare.getD1Database("SECRETS")) as unknown as D1Database;
|
|
160
162
|
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
import { createMigrationRegistry } from "@pithy-sh/core/src/migrations/registry";
|
|
6
|
+
import { runMigrations } from "@pithy-sh/core/src/migrations/runner";
|
|
7
|
+
import { EMAIL_MIGRATION_ORDER } from "@pithy-sh/email/src/capability";
|
|
8
|
+
import { emailSigningRegistry } from "@pithy-sh/email/src/crypto/signingKey";
|
|
9
|
+
import { email_0001_init } from "@pithy-sh/email/src/migrations/0001_init";
|
|
10
|
+
import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
|
|
11
|
+
import { type SecretFixture, seedSecrets } from "@pithy-sh/secrets/src/test-utils/secretFixtures";
|
|
12
|
+
import type { Migration } from "kysely/migration";
|
|
13
|
+
import { authDatabase } from "../data/tables";
|
|
14
|
+
import { makeAuth } from "../instance/auth";
|
|
15
|
+
import { NO_SOCIAL_PROVIDERS } from "../instance/providers";
|
|
16
|
+
import { authSecretsRegistry } from "../instance/secrets";
|
|
17
|
+
import { AUTH_MIGRATION_ORDER } from "../migrations/0001_init";
|
|
18
|
+
import { AUTH_MIGRATIONS } from "../migrations/set";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The fixtures a workers suite needs to put a **real** `auth()` in front of a request (#560).
|
|
22
|
+
*
|
|
23
|
+
* The scope gates in `leaderboard`, `rating` and `ledger` were each tested against a stub middleware that
|
|
24
|
+
* wrote `c.var.auth` itself, so every one of them passed while nothing real could ever open it. A suite
|
|
25
|
+
* built on this composes the actual capability through `createBackend` and signs a user in with the actual
|
|
26
|
+
* Better Auth instance, so what reaches a gate is what a deployed Worker would put there.
|
|
27
|
+
*
|
|
28
|
+
* It holds the pieces and not the composition. Which capabilities sit beside auth is the suite's own
|
|
29
|
+
* statement, and so is the probe it reads the request through.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** The session secret these suites sign with. A throwaway: it authenticates nothing anywhere. */
|
|
33
|
+
export const SCOPED_SESSION_SECRET = "scoped-backend-secret-please-rotate-000";
|
|
34
|
+
|
|
35
|
+
/** The origin the composed auth serves on, and the audience a caller token is minted for. */
|
|
36
|
+
export const SCOPED_ORIGIN = "http://localhost";
|
|
37
|
+
|
|
38
|
+
/** Auth's registry and the email link key, which every composition with `email()` resolves. */
|
|
39
|
+
export const SCOPED_REGISTRY = { ...authSecretsRegistry, ...emailSigningRegistry };
|
|
40
|
+
|
|
41
|
+
/** Every secret the composed backend resolves, since the shared accessor resolves the registry in one batch. */
|
|
42
|
+
export const SCOPED_SECRETS: SecretFixture<typeof SCOPED_REGISTRY> = {
|
|
43
|
+
"auth-session-secret": SCOPED_SESSION_SECRET,
|
|
44
|
+
"auth-google-credentials": { clientId: "g", clientSecret: "g" },
|
|
45
|
+
"auth-apple-credentials": { clientId: "a", clientSecret: "a" },
|
|
46
|
+
"auth-facebook-credentials": { clientId: "f", clientSecret: "f" },
|
|
47
|
+
"auth-github-credentials": { clientId: "h", clientSecret: "h" },
|
|
48
|
+
"email-link-signing-key": "dev-link-signing-key",
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** One capability's migrations, as the registry takes them, for a suite composing more than auth. */
|
|
52
|
+
export interface ExtraMigrations {
|
|
53
|
+
namespace: string;
|
|
54
|
+
order: number;
|
|
55
|
+
migrations: Record<string, Migration>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Drop every table, re-run every migration the composition needs, then seed the secrets it resolves.
|
|
60
|
+
*
|
|
61
|
+
* Every table rather than a list of them, so a suite composing a capability beside auth does not have to
|
|
62
|
+
* restate what that capability's migrations create, and a second test never meets the first one's rows.
|
|
63
|
+
*/
|
|
64
|
+
export async function prepareScopedBackend(
|
|
65
|
+
env: SecretsStoreEnv & { DB: D1Database },
|
|
66
|
+
extra: readonly ExtraMigrations[] = [],
|
|
67
|
+
): Promise<void> {
|
|
68
|
+
const tables = await env.DB.prepare(
|
|
69
|
+
"select name from sqlite_master where type = 'table' and name not like 'sqlite_%' and name not like '\\_cf\\_%' escape '\\'",
|
|
70
|
+
).all<{ name: string }>();
|
|
71
|
+
for (const { name } of tables.results) await env.DB.prepare(`drop table if exists "${name}"`).run();
|
|
72
|
+
const provider = createMigrationRegistry([
|
|
73
|
+
{ database: "app", namespace: "auth", order: AUTH_MIGRATION_ORDER, migrations: AUTH_MIGRATIONS },
|
|
74
|
+
{ database: "app", namespace: "email", order: EMAIL_MIGRATION_ORDER, migrations: { "0001_init": email_0001_init } },
|
|
75
|
+
...extra.map((entry) => ({ database: "app", ...entry })),
|
|
76
|
+
]).app;
|
|
77
|
+
if (!provider) throw new Error('expected a migration provider for database "app"');
|
|
78
|
+
await runMigrations(env.DB, provider);
|
|
79
|
+
await seedSecrets(env, SCOPED_REGISTRY, SCOPED_SECRETS);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The Worker env one request runs against: the real `DB` and `SECRETS`, and stand-ins for the three
|
|
84
|
+
* bindings this composition requires and never exercises — no email is sent and the limiter always allows.
|
|
85
|
+
*/
|
|
86
|
+
export function scopedWorkerEnv(env: Record<string, unknown>, db: unknown = env.DB): Record<string, unknown> {
|
|
87
|
+
return {
|
|
88
|
+
...env,
|
|
89
|
+
DB: db,
|
|
90
|
+
ENVIRONMENT: "dev",
|
|
91
|
+
EMAIL_SUPPRESSIONS: env.DB,
|
|
92
|
+
EMAIL_SENDER: {},
|
|
93
|
+
AUTH_RATE_LIMITER: { limit: async () => ({ success: true }) },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Sign a user in by OTP against the same database the composed backend reads, and return a bearer token.
|
|
99
|
+
*
|
|
100
|
+
* Directly through Better Auth rather than over HTTP: the sign-in flow is not what these suites are about,
|
|
101
|
+
* and the session row it writes is exactly the one a request presenting the token resolves.
|
|
102
|
+
*/
|
|
103
|
+
export async function signInScoped(
|
|
104
|
+
db: D1Database,
|
|
105
|
+
address = "player@test.com",
|
|
106
|
+
): Promise<{ token: string; userId: string }> {
|
|
107
|
+
const mailbox: { template: string; code?: string }[] = [];
|
|
108
|
+
const instance = makeAuth({
|
|
109
|
+
db: authDatabase(db),
|
|
110
|
+
secret: SCOPED_SESSION_SECRET,
|
|
111
|
+
baseURL: SCOPED_ORIGIN,
|
|
112
|
+
basePath: "/auth",
|
|
113
|
+
trustedOrigins: [SCOPED_ORIGIN],
|
|
114
|
+
...NO_SOCIAL_PROVIDERS,
|
|
115
|
+
sendEmail: async (m) => {
|
|
116
|
+
mailbox.push(m.template === "otp" ? { template: "otp", code: m.code } : { template: m.template });
|
|
117
|
+
return { delivery: "queued" };
|
|
118
|
+
},
|
|
119
|
+
sessionExpiresIn: 604800,
|
|
120
|
+
sessionUpdateAge: 86400,
|
|
121
|
+
verificationExpiresIn: 300,
|
|
122
|
+
otpLength: 6,
|
|
123
|
+
disableSignUp: false,
|
|
124
|
+
providerSignUp: { google: true, apple: true, facebook: true, github: true },
|
|
125
|
+
emit: async () => {},
|
|
126
|
+
plugins: [],
|
|
127
|
+
});
|
|
128
|
+
await instance.api.sendVerificationOTP({ body: { email: address, type: "sign-in" }, headers: new Headers() });
|
|
129
|
+
const otp = mailbox.find((m) => m.template === "otp");
|
|
130
|
+
if (!otp?.code) throw new Error("no OTP was mailed");
|
|
131
|
+
const signedIn = await instance.api.signInEmailOTP({
|
|
132
|
+
body: { email: address, otp: otp.code },
|
|
133
|
+
headers: new Headers(),
|
|
134
|
+
});
|
|
135
|
+
return { token: signedIn.token, userId: signedIn.user.id };
|
|
136
|
+
}
|
package/src/version.generated.ts
CHANGED