@pithy-sh/auth 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/audit/actions.d.ts +32 -28
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +32 -28
- package/dist/audit/emit.d.ts +40 -34
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +45 -32
- package/dist/capability.js +1 -1
- package/dist/http/middleware.js +1 -1
- package/dist/http/providerFreshness.d.ts +30 -31
- package/dist/http/providerFreshness.d.ts.map +1 -1
- package/dist/http/providerFreshness.js +26 -31
- package/dist/http/recentSignIn.d.ts +57 -0
- package/dist/http/recentSignIn.d.ts.map +1 -0
- package/dist/http/recentSignIn.js +88 -0
- package/dist/http/routes.js +2 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/instance/auth.js +2 -2
- package/dist/mcp/http/routes.js +2 -2
- package/dist/test-utils/dropOrder.d.ts +26 -0
- package/dist/test-utils/dropOrder.d.ts.map +1 -0
- package/dist/test-utils/dropOrder.js +120 -0
- package/dist/test-utils/scopedBackend.d.ts +10 -6
- package/dist/test-utils/scopedBackend.d.ts.map +1 -1
- package/dist/test-utils/scopedBackend.js +40 -12
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +1 -1
- package/docs/recent-sign-in.md +90 -0
- package/package.json +5 -5
- package/src/audit/actions.ts +32 -28
- package/src/audit/emit.ts +50 -34
- package/src/http/providerFreshness.ts +40 -42
- package/src/http/recentSignIn.ts +114 -0
- package/src/index.ts +4 -2
- package/src/test-utils/dropOrder.ts +139 -0
- package/src/test-utils/scopedBackend.ts +51 -13
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/** One foreign key, as `PRAGMA foreign_key_list` reports it: `table` holds a column that references `references`. */
|
|
4
|
+
export interface ForeignKey {
|
|
5
|
+
table: string;
|
|
6
|
+
references: string;
|
|
7
|
+
/** What deleting a referenced row does to `table`: `CASCADE`, `SET NULL`, `SET DEFAULT`, `RESTRICT` or `NO ACTION`. */
|
|
8
|
+
onDelete: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The order to drop `tables` in, so that no drop meets a table already gone.
|
|
12
|
+
*
|
|
13
|
+
* With foreign keys on, dropping a table deletes its rows first. A key that cascades deletes the referencing
|
|
14
|
+
* rows with them, which looks up every table the referencing table references and cascades on from there.
|
|
15
|
+
* A set null or set default key only rewrites the referencing column, which looks up the table being dropped
|
|
16
|
+
* and nothing past it. So a table is dropped before every table it references, and a self-reference is no
|
|
17
|
+
* constraint. Tables that reference each other in a cycle have no such order; they are ordered so that no
|
|
18
|
+
* cascade from a drop reaches a table that still names a dropped one, and refused when no order does.
|
|
19
|
+
*
|
|
20
|
+
* Names match as SQLite matches them, ignoring ASCII case, and the order names each table as `tables` does.
|
|
21
|
+
*
|
|
22
|
+
* The caller runs the drops in one batch under `PRAGMA defer_foreign_keys = on`, which is what lets the
|
|
23
|
+
* rows of a cycle go: each table's rows still reference the next table's until both are gone.
|
|
24
|
+
*/
|
|
25
|
+
export declare function dropOrder(tables: readonly string[], foreignKeys: readonly ForeignKey[]): string[];
|
|
26
|
+
//# sourceMappingURL=dropOrder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dropOrder.d.ts","sourceRoot":"","sources":["../../src/test-utils/dropOrder.ts"],"names":[],"mappings":"AAGA,qHAAqH;AACrH,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,uHAAuH;IACvH,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,WAAW,EAAE,SAAS,UAAU,EAAE,GAAG,MAAM,EAAE,CA2BjG"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
//#region src/test-utils/dropOrder.ts
|
|
4
|
+
/**
|
|
5
|
+
* The order to drop `tables` in, so that no drop meets a table already gone.
|
|
6
|
+
*
|
|
7
|
+
* With foreign keys on, dropping a table deletes its rows first. A key that cascades deletes the referencing
|
|
8
|
+
* rows with them, which looks up every table the referencing table references and cascades on from there.
|
|
9
|
+
* A set null or set default key only rewrites the referencing column, which looks up the table being dropped
|
|
10
|
+
* and nothing past it. So a table is dropped before every table it references, and a self-reference is no
|
|
11
|
+
* constraint. Tables that reference each other in a cycle have no such order; they are ordered so that no
|
|
12
|
+
* cascade from a drop reaches a table that still names a dropped one, and refused when no order does.
|
|
13
|
+
*
|
|
14
|
+
* Names match as SQLite matches them, ignoring ASCII case, and the order names each table as `tables` does.
|
|
15
|
+
*
|
|
16
|
+
* The caller runs the drops in one batch under `PRAGMA defer_foreign_keys = on`, which is what lets the
|
|
17
|
+
* rows of a cycle go: each table's rows still reference the next table's until both are gone.
|
|
18
|
+
*/
|
|
19
|
+
function dropOrder(tables, foreignKeys) {
|
|
20
|
+
const listed = new Map(tables.map((table) => [foldCase(table), table]));
|
|
21
|
+
const keys = foreignKeys.flatMap((key) => {
|
|
22
|
+
const table = listed.get(foldCase(key.table));
|
|
23
|
+
const references = listed.get(foldCase(key.references));
|
|
24
|
+
return table !== void 0 && references !== void 0 ? [{
|
|
25
|
+
...key,
|
|
26
|
+
table,
|
|
27
|
+
references
|
|
28
|
+
}] : [];
|
|
29
|
+
});
|
|
30
|
+
const position = new Map(tables.map((table, index) => [table, index]));
|
|
31
|
+
const listedOrder = (a, b) => (position.get(a) ?? 0) - (position.get(b) ?? 0);
|
|
32
|
+
const pending = components(tables, keys).map((component) => component.sort(listedOrder)).sort((a, b) => listedOrder(a[0] ?? "", b[0] ?? ""));
|
|
33
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
34
|
+
const order = [];
|
|
35
|
+
while (pending.length > 0) {
|
|
36
|
+
const ready = pending.findIndex((component) => keys.every((key) => !component.includes(key.references) || component.includes(key.table) || dropped.has(key.table)));
|
|
37
|
+
const [component = []] = pending.splice(ready, 1);
|
|
38
|
+
const members = component.length === 1 ? component : orderCycle(component, keys);
|
|
39
|
+
for (const table of members) dropped.add(table);
|
|
40
|
+
order.push(...members);
|
|
41
|
+
}
|
|
42
|
+
return order;
|
|
43
|
+
}
|
|
44
|
+
/** The strongly connected components of the reference graph: each cycle together, every other table alone. */
|
|
45
|
+
function components(tables, keys) {
|
|
46
|
+
const index = /* @__PURE__ */ new Map();
|
|
47
|
+
const low = /* @__PURE__ */ new Map();
|
|
48
|
+
const stack = [];
|
|
49
|
+
const onStack = /* @__PURE__ */ new Set();
|
|
50
|
+
const found = [];
|
|
51
|
+
const visit = (table) => {
|
|
52
|
+
const own = index.size;
|
|
53
|
+
index.set(table, own);
|
|
54
|
+
low.set(table, own);
|
|
55
|
+
stack.push(table);
|
|
56
|
+
onStack.add(table);
|
|
57
|
+
for (const key of keys) {
|
|
58
|
+
if (key.table !== table) continue;
|
|
59
|
+
const parent = key.references;
|
|
60
|
+
if (!index.has(parent)) visit(parent);
|
|
61
|
+
else if (!onStack.has(parent)) continue;
|
|
62
|
+
low.set(table, Math.min(low.get(table) ?? own, low.get(parent) ?? own));
|
|
63
|
+
}
|
|
64
|
+
if (low.get(table) !== own) return;
|
|
65
|
+
const component = [];
|
|
66
|
+
for (let member = stack.pop(); member !== void 0; member = stack.pop()) {
|
|
67
|
+
onStack.delete(member);
|
|
68
|
+
component.push(member);
|
|
69
|
+
if (member === table) break;
|
|
70
|
+
}
|
|
71
|
+
found.push(component);
|
|
72
|
+
};
|
|
73
|
+
for (const table of tables) if (!index.has(table)) visit(table);
|
|
74
|
+
return found;
|
|
75
|
+
}
|
|
76
|
+
/** The members of one cycle in an order no drop fails on, searched in listed order first. */
|
|
77
|
+
function orderCycle(members, allKeys) {
|
|
78
|
+
const keys = allKeys.filter((key) => members.includes(key.table) && members.includes(key.references));
|
|
79
|
+
const dead = /* @__PURE__ */ new Set();
|
|
80
|
+
const search = (left) => {
|
|
81
|
+
if (left.length === 0) return [];
|
|
82
|
+
const state = JSON.stringify(left);
|
|
83
|
+
if (dead.has(state)) return void 0;
|
|
84
|
+
for (const table of left) {
|
|
85
|
+
if (!safeToDrop(table, left, keys)) continue;
|
|
86
|
+
const rest = search(left.filter((other) => other !== table));
|
|
87
|
+
if (rest) return [table, ...rest];
|
|
88
|
+
}
|
|
89
|
+
dead.add(state);
|
|
90
|
+
};
|
|
91
|
+
const order = search(members);
|
|
92
|
+
if (order) return order;
|
|
93
|
+
const named = members.map((table) => `"${table}"`).join(", ");
|
|
94
|
+
throw new Error(`No drop order clears ${named}: every order cascades into a table that names one already dropped.`);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Whether `table` can go while `left` remain: every table a cascade from it reaches, itself included when the
|
|
98
|
+
* cascade comes back, still has every table it references.
|
|
99
|
+
*/
|
|
100
|
+
function safeToDrop(table, left, keys) {
|
|
101
|
+
const present = new Set(left);
|
|
102
|
+
const reached = /* @__PURE__ */ new Set();
|
|
103
|
+
const frontier = [table];
|
|
104
|
+
for (let current = frontier.pop(); current !== void 0; current = frontier.pop()) for (const key of keys) {
|
|
105
|
+
if (key.references !== current || !cascades(key) || !present.has(key.table) || reached.has(key.table)) continue;
|
|
106
|
+
reached.add(key.table);
|
|
107
|
+
frontier.push(key.table);
|
|
108
|
+
}
|
|
109
|
+
return [...reached].every((reachedTable) => keys.every((key) => key.table !== reachedTable || present.has(key.references)));
|
|
110
|
+
}
|
|
111
|
+
/** A key that deletes the referencing rows when a referenced row is deleted. */
|
|
112
|
+
function cascades(key) {
|
|
113
|
+
return key.onDelete.toUpperCase() === "CASCADE";
|
|
114
|
+
}
|
|
115
|
+
/** A table name as SQLite compares it: ASCII letters fold to lower case, nothing else does. */
|
|
116
|
+
function foldCase(name) {
|
|
117
|
+
return name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
export { dropOrder };
|
|
@@ -5,12 +5,12 @@ import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
|
|
|
5
5
|
import { type SecretFixture } from "@pithy-sh/secrets/src/test-utils/secretFixtures";
|
|
6
6
|
import type { Migration } from "kysely/migration";
|
|
7
7
|
/**
|
|
8
|
-
* The fixtures a workers suite needs to put a **real** `auth()` in front of a request
|
|
8
|
+
* The fixtures a workers suite needs to put a **real** `auth()` in front of a request.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* A gate tested against a stub middleware that writes `c.var.auth` itself passes whether or not anything
|
|
11
|
+
* real can open it. A suite built on this composes the actual capability through `createBackend` and signs
|
|
12
|
+
* a user in with the actual Better Auth instance, so what reaches a gate is what a deployed Worker would put
|
|
13
|
+
* there.
|
|
14
14
|
*
|
|
15
15
|
* It holds the pieces and not the composition. Which capabilities sit beside auth is the suite's own
|
|
16
16
|
* statement, and so is the probe it reads the request through.
|
|
@@ -182,6 +182,8 @@ export interface ExtraMigrations {
|
|
|
182
182
|
*
|
|
183
183
|
* Every table rather than a list of them, so a suite composing a capability beside auth does not have to
|
|
184
184
|
* restate what that capability's migrations create, and a second test never meets the first one's rows.
|
|
185
|
+
* Whatever the foreign keys between an app's own tables, children go before the tables they reference; a
|
|
186
|
+
* cycle no order can drop is refused with its tables named, before anything is dropped.
|
|
185
187
|
*/
|
|
186
188
|
export declare function prepareScopedBackend(env: SecretsStoreEnv & {
|
|
187
189
|
DB: D1Database;
|
|
@@ -192,7 +194,8 @@ export declare function prepareScopedBackend(env: SecretsStoreEnv & {
|
|
|
192
194
|
*/
|
|
193
195
|
export declare function scopedWorkerEnv(env: Record<string, unknown>, db?: unknown): Record<string, unknown>;
|
|
194
196
|
/**
|
|
195
|
-
* Sign a user in by OTP against the same database the composed backend reads, and return a bearer token
|
|
197
|
+
* Sign a user in by OTP against the same database the composed backend reads, and return a bearer token and
|
|
198
|
+
* the session cookie the same sign-in sets, as a `cookie` header value.
|
|
196
199
|
*
|
|
197
200
|
* Directly through Better Auth rather than over HTTP: the sign-in flow is not what these suites are about,
|
|
198
201
|
* and the session row it writes is exactly the one a request presenting the token resolves.
|
|
@@ -200,5 +203,6 @@ export declare function scopedWorkerEnv(env: Record<string, unknown>, db?: unkno
|
|
|
200
203
|
export declare function signInScoped(db: D1Database, address?: string): Promise<{
|
|
201
204
|
token: string;
|
|
202
205
|
userId: string;
|
|
206
|
+
cookie: string;
|
|
203
207
|
}>;
|
|
204
208
|
//# sourceMappingURL=scopedBackend.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scopedBackend.d.ts","sourceRoot":"","sources":["../../src/test-utils/scopedBackend.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAM5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,KAAK,aAAa,EAAe,MAAM,iDAAiD,CAAC;AAClG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"scopedBackend.d.ts","sourceRoot":"","sources":["../../src/test-utils/scopedBackend.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAM5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,KAAK,aAAa,EAAe,MAAM,iDAAiD,CAAC;AAClG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AASlD;;;;;;;;;;GAUG;AAEH,iGAAiG;AACjG,eAAO,MAAM,qBAAqB,4CAA4C,CAAC;AAE/E,6FAA6F;AAC7F,eAAO,MAAM,aAAa,qBAAqB,CAAC;AAEhD,+FAA+F;AAC/F,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAsD,CAAC;AAEnF,gHAAgH;AAChH,eAAO,MAAM,cAAc,EAAE,aAAa,CAAC,OAAO,eAAe,CAQhE,CAAC;AAEF,qGAAqG;AACrG,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;CACvC;AAED;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CACxC,GAAG,EAAE,eAAe,GAAG;IAAE,EAAE,EAAE,UAAU,CAAA;CAAE,EACzC,KAAK,GAAE,SAAS,eAAe,EAAO,GACrC,OAAO,CAAC,IAAI,CAAC,CAUf;AAkCD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAAE,GAAE,OAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAS3G;AAED;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,EAAE,EAAE,UAAU,EACd,OAAO,SAAoB,GAC1B,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAmC5D"}
|
|
@@ -6,6 +6,7 @@ import { NO_SOCIAL_PROVIDERS } from "../instance/providers.js";
|
|
|
6
6
|
import { makeAuth } from "../instance/auth.js";
|
|
7
7
|
import "../migrations/0001_init.js";
|
|
8
8
|
import { AUTH_MIGRATIONS } from "../migrations/set.js";
|
|
9
|
+
import { dropOrder } from "./dropOrder.js";
|
|
9
10
|
import { EMAIL_MIGRATION_ORDER } from "@pithy-sh/email/src/capability";
|
|
10
11
|
import { createMigrationRegistry } from "@pithy-sh/core/src/migrations/registry";
|
|
11
12
|
import { runMigrations } from "@pithy-sh/core/src/migrations/runner";
|
|
@@ -14,12 +15,12 @@ import { seedSecrets } from "@pithy-sh/secrets/src/test-utils/secretFixtures";
|
|
|
14
15
|
import { emailSigningRegistry } from "@pithy-sh/email/src/crypto/signingKey";
|
|
15
16
|
//#region src/test-utils/scopedBackend.ts
|
|
16
17
|
/**
|
|
17
|
-
* The fixtures a workers suite needs to put a **real** `auth()` in front of a request
|
|
18
|
+
* The fixtures a workers suite needs to put a **real** `auth()` in front of a request.
|
|
18
19
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* A gate tested against a stub middleware that writes `c.var.auth` itself passes whether or not anything
|
|
21
|
+
* real can open it. A suite built on this composes the actual capability through `createBackend` and signs
|
|
22
|
+
* a user in with the actual Better Auth instance, so what reaches a gate is what a deployed Worker would put
|
|
23
|
+
* there.
|
|
23
24
|
*
|
|
24
25
|
* It holds the pieces and not the composition. Which capabilities sit beside auth is the suite's own
|
|
25
26
|
* statement, and so is the probe it reads the request through.
|
|
@@ -64,10 +65,11 @@ const SCOPED_SECRETS = {
|
|
|
64
65
|
*
|
|
65
66
|
* Every table rather than a list of them, so a suite composing a capability beside auth does not have to
|
|
66
67
|
* restate what that capability's migrations create, and a second test never meets the first one's rows.
|
|
68
|
+
* Whatever the foreign keys between an app's own tables, children go before the tables they reference; a
|
|
69
|
+
* cycle no order can drop is refused with its tables named, before anything is dropped.
|
|
67
70
|
*/
|
|
68
71
|
async function prepareScopedBackend(env, extra = []) {
|
|
69
|
-
|
|
70
|
-
for (const { name } of tables.results) await env.DB.prepare(`drop table if exists "${name}"`).run();
|
|
72
|
+
await dropEveryTable(env.DB);
|
|
71
73
|
const provider = createMigrationRegistry([
|
|
72
74
|
{
|
|
73
75
|
database: "app",
|
|
@@ -91,6 +93,28 @@ async function prepareScopedBackend(env, extra = []) {
|
|
|
91
93
|
await seedSecrets(env, SCOPED_REGISTRY, SCOPED_SECRETS);
|
|
92
94
|
}
|
|
93
95
|
/**
|
|
96
|
+
* Drop every table but SQLite's and D1's own, in the order `dropOrder` reads off the schema's foreign keys.
|
|
97
|
+
*
|
|
98
|
+
* D1 will not turn `foreign_keys` off, so the keys stay on and the order carries the drop. One batch, so
|
|
99
|
+
* `defer_foreign_keys` holds across every drop in it. Outside a batch it lasts one statement, since each
|
|
100
|
+
* statement commits on its own.
|
|
101
|
+
*/
|
|
102
|
+
async function dropEveryTable(db) {
|
|
103
|
+
const names = (await db.prepare("select name from sqlite_master where type = 'table' and name not like 'sqlite_%' and name not like '\\_cf\\_%' escape '\\'").all()).results.map(({ name }) => name);
|
|
104
|
+
if (names.length === 0) return;
|
|
105
|
+
const keyLists = await db.batch(names.map((name) => db.prepare(`pragma foreign_key_list(${quoted(name)})`)));
|
|
106
|
+
const foreignKeys = names.flatMap((name, index) => (keyLists[index]?.results ?? []).map((key) => ({
|
|
107
|
+
table: name,
|
|
108
|
+
references: key.table,
|
|
109
|
+
onDelete: key.on_delete
|
|
110
|
+
})));
|
|
111
|
+
await db.batch([db.prepare("pragma defer_foreign_keys = on"), ...dropOrder(names, foreignKeys).map((name) => db.prepare(`drop table if exists ${quoted(name)}`))]);
|
|
112
|
+
}
|
|
113
|
+
/** A table name as an SQL identifier. */
|
|
114
|
+
function quoted(name) {
|
|
115
|
+
return `"${name.replaceAll("\"", "\"\"")}"`;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
94
118
|
* The Worker env one request runs against: the real `DB` and `SECRETS`, and stand-ins for the three
|
|
95
119
|
* bindings this composition requires and never exercises — no email is sent and the limiter always allows.
|
|
96
120
|
*/
|
|
@@ -105,7 +129,8 @@ function scopedWorkerEnv(env, db = env.DB) {
|
|
|
105
129
|
};
|
|
106
130
|
}
|
|
107
131
|
/**
|
|
108
|
-
* Sign a user in by OTP against the same database the composed backend reads, and return a bearer token
|
|
132
|
+
* Sign a user in by OTP against the same database the composed backend reads, and return a bearer token and
|
|
133
|
+
* the session cookie the same sign-in sets, as a `cookie` header value.
|
|
109
134
|
*
|
|
110
135
|
* Directly through Better Auth rather than over HTTP: the sign-in flow is not what these suites are about,
|
|
111
136
|
* and the session row it writes is exactly the one a request presenting the token resolves.
|
|
@@ -150,16 +175,19 @@ async function signInScoped(db, address = "player@test.com") {
|
|
|
150
175
|
});
|
|
151
176
|
const otp = mailbox.find((m) => m.template === "otp");
|
|
152
177
|
if (!otp?.code) throw new Error("no OTP was mailed");
|
|
153
|
-
const
|
|
178
|
+
const { headers, response } = await instance.api.signInEmailOTP({
|
|
154
179
|
body: {
|
|
155
180
|
email: address,
|
|
156
181
|
otp: otp.code
|
|
157
182
|
},
|
|
158
|
-
headers: new Headers()
|
|
183
|
+
headers: new Headers(),
|
|
184
|
+
returnHeaders: true
|
|
159
185
|
});
|
|
186
|
+
const cookie = headers.getSetCookie().map((line) => line.split(";")[0]).join("; ");
|
|
160
187
|
return {
|
|
161
|
-
token:
|
|
162
|
-
userId:
|
|
188
|
+
token: response.token,
|
|
189
|
+
userId: response.user.id,
|
|
190
|
+
cookie
|
|
163
191
|
};
|
|
164
192
|
}
|
|
165
193
|
//#endregion
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
/** This package's npm name — the join key against a release feed. */
|
|
4
4
|
export declare const PACKAGE_NAME = "@pithy-sh/auth";
|
|
5
5
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
6
|
-
export declare const PACKAGE_VERSION = "0.
|
|
6
|
+
export declare const PACKAGE_VERSION = "0.15.0";
|
|
7
7
|
//# sourceMappingURL=version.generated.d.ts.map
|
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
/** This package's npm name — the join key against a release feed. */
|
|
5
5
|
const PACKAGE_NAME = "@pithy-sh/auth";
|
|
6
6
|
/** This package's version, stamped from its own package.json at generation time. */
|
|
7
|
-
const PACKAGE_VERSION = "0.
|
|
7
|
+
const PACKAGE_VERSION = "0.15.0";
|
|
8
8
|
//#endregion
|
|
9
9
|
export { PACKAGE_NAME, PACKAGE_VERSION };
|
|
@@ -220,7 +220,7 @@ Every kit capability that holds rows about a person declares a `user` contributi
|
|
|
220
220
|
| `artifacts` | erase | Repositories the person owns, with their contents and grants, and the grants they hold. The record of every token minted for them is anonymized instead, so a token still listed reads as the kit's. |
|
|
221
221
|
| `media` | erase | Records the person holds as themselves, with their bytes and hashes. A record made for an organization is the organization's. |
|
|
222
222
|
| `storage` | erase | Files the person holds as themselves, with their bytes and share links. A file made for an organization is the organization's. |
|
|
223
|
-
| `organization` | erase | Memberships, the organization each session acted for, ownership offers made to or by them, invitations addressed to them. Invitations they sent and organizations' history keep their id; an organization they were the last owner of is left without one. |
|
|
223
|
+
| `organization` | erase | Memberships, the organization each session acted for, ownership offers made to or by them, founding records of theirs, invitations addressed to them. Invitations they sent and organizations' history keep their id; an organization they were the last owner of is left without one. |
|
|
224
224
|
| `payments` | retain | Purchases, entitlements, provider accounts, overrides, meter counters and usage reports of a user subject. *Kept for tax and accounting records, which the law requires a business to hold after an account is closed.* |
|
|
225
225
|
| `email` | retain | The address on the suppression list, and the log of mail sent to it. *Kept so your unsubscribe holds: the address stays on the list of addresses not to mail, with the record of what was sent to it.* |
|
|
226
226
|
| `audit` | retain | Every audit event where the person is the actor. *Kept as the record of who did what, which a security review or a dispute is read against.* |
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# A recent sign-in for an app route
|
|
2
|
+
|
|
3
|
+
_This copy ships in the package because `README.md` sends an adopter to it by name._
|
|
4
|
+
|
|
5
|
+
Some routes should not be reachable on a session that has been open all week. Revealing a stored account number. Changing who can see something. Exporting a person's data. `requireRecentSignIn` gates one such route on a sign-in within the window the route names, and refuses everything else with one code every client handles the same way.
|
|
6
|
+
|
|
7
|
+
## When to use it
|
|
8
|
+
|
|
9
|
+
Use it on a route where a stolen or unattended session would do lasting harm the account holder cannot undo: a secret shown once, a change of who has access, an action that sends money or data out. Leave it off ordinary reads and writes. A gate a person meets on every screen trains them to sign in without thinking, and it costs them a sign-in for nothing.
|
|
10
|
+
|
|
11
|
+
It is not a permission check. It stacks after the route's own gates and adds one question: did this caller sign in recently? Who may call the route is still `requireAuth()`, a role or a scope.
|
|
12
|
+
|
|
13
|
+
## Using it
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { requireRecentSignIn } from "@pithy-sh/auth/src/http/recentSignIn";
|
|
17
|
+
|
|
18
|
+
app.post(
|
|
19
|
+
"/things/:id/secret",
|
|
20
|
+
describeRoute({ … }),
|
|
21
|
+
requireRecentSignIn({ maxAgeSeconds: 300, purpose: "things/secret_revealed" }),
|
|
22
|
+
validate("param", ThingParams),
|
|
23
|
+
handler,
|
|
24
|
+
);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- **`maxAgeSeconds`** is the window, a whole number above zero. Five minutes suits a secret shown once; fifteen suits a settings change. It is the route's own, so two routes can hold two windows.
|
|
28
|
+
- **`purpose`** names what the route protects as `<domain>/<reason>`, in your app's own domain. It is recorded on every refusal.
|
|
29
|
+
|
|
30
|
+
Both are checked when the route is declared. A `maxAgeSeconds` of `0`, `2.5` or `"300"`, or a `purpose` that is not `<domain>/<reason>`, throws at startup rather than on a request.
|
|
31
|
+
|
|
32
|
+
## What it checks
|
|
33
|
+
|
|
34
|
+
Each session carries `authenticatedAt`, the instant its holder signed in. A sign-in stamps it, and nothing else does: `/token/rotate` carries it forward to the successor unchanged. The gate passes a session whose `authenticatedAt` is no older than `maxAgeSeconds`, boundary included.
|
|
35
|
+
|
|
36
|
+
It refuses a session whose `authenticatedAt` is older, absent, unreadable, or in the future. None of those is evidence of a recent sign-in.
|
|
37
|
+
|
|
38
|
+
A bearer session and a cookie session are judged by the same rule. There is no exemption by client kind, and none can be configured: an on-device biometric check is not proof the Worker can verify, so an exemption for phones would pass any stolen bearer token.
|
|
39
|
+
|
|
40
|
+
## The refusal
|
|
41
|
+
|
|
42
|
+
| Caller | Status | Code |
|
|
43
|
+
|---|---|---|
|
|
44
|
+
| No credential, or one that does not resolve | 401 | `auth/invalid_token`, exactly as `requireAuth()` answers |
|
|
45
|
+
| Signed in, but not within `maxAgeSeconds` | 403 | `auth/recent_sign_in_required` |
|
|
46
|
+
|
|
47
|
+
The 403 body is the kit's error envelope:
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
{ "error": { "code": "auth/recent_sign_in_required", "status": 403, "message": "Sign in again to continue. Nothing was changed." } }
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The handler never ran, so nothing was changed, and the message says so. The code is the same on every gated route in every app, so a client writes its handling once. `@pithy-sh/i18n` carries the message in Spanish, keyed by the code.
|
|
54
|
+
|
|
55
|
+
Before it throws, the gate records `auth/recent_sign_in_refused` on the audit trail, with the user, the session, and your `purpose` as `metadata.purpose`. An operator can read how often a route turned callers away, and for what.
|
|
56
|
+
|
|
57
|
+
## A web client
|
|
58
|
+
|
|
59
|
+
A browser holds a cookie session. On a 403 with `auth/recent_sign_in_required`:
|
|
60
|
+
|
|
61
|
+
1. Keep what the person was doing: the route, its body, the screen they were on.
|
|
62
|
+
2. Send them through a sign-in: a magic link, a code, or a provider button. Each one sets a new session cookie with a new `authenticatedAt`.
|
|
63
|
+
3. Retry the request once.
|
|
64
|
+
|
|
65
|
+
Do not sign the person out first. The old session still works for every ungated route, and a fresh sign-in replaces it. Do not retry without a sign-in: the answer will be the same.
|
|
66
|
+
|
|
67
|
+
## A phone client
|
|
68
|
+
|
|
69
|
+
A native app holds a bearer session through `createBearerSession`, and its credential rotates through `/token/rotate` before it expires. **A rotation never passes the gate.** The successor keeps the original `authenticatedAt`, so a phone signed in last month is still signed in last month after a thousand rotations. An app that answers the refusal by rotating, or by retrying, loops forever.
|
|
70
|
+
|
|
71
|
+
On a 403 with `auth/recent_sign_in_required`:
|
|
72
|
+
|
|
73
|
+
1. Keep what the person was doing.
|
|
74
|
+
2. Run a sign-in: an email code, or a provider through the handoff in [`apple-signin.md`](apple-signin.md) §6. It answers with a new raw session token.
|
|
75
|
+
3. Hand that token to `session.adopt(token)`. It is held and stored before `adopt` resolves, and every request after it carries the new session, with a new `authenticatedAt`.
|
|
76
|
+
4. Retry the request once.
|
|
77
|
+
|
|
78
|
+
An on-device biometric prompt may come before step 2, to decide whether to offer the sign-in at all. It never replaces it.
|
|
79
|
+
|
|
80
|
+
## The provider-change gate
|
|
81
|
+
|
|
82
|
+
Connecting and disconnecting a sign-in provider (`POST /auth/link-social`, `POST /auth/unlink-account`) holds its own gate on the same check, with a fixed fifteen-minute window. It refuses with `auth/session_not_fresh` and records the provider-change audit event, not these. A client meets that code only on those two routes and handles it the same way: sign in again, then retry.
|
|
83
|
+
|
|
84
|
+
For a check outside a route, import the same test the gates use:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { authenticationIsFresh } from "@pithy-sh/auth/src/http/providerFreshness";
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`authenticationIsFresh(authenticatedAt, now)` reads that fifteen-minute window. `authenticationIsFresh(authenticatedAt, now, seconds)` reads the window given.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithy-sh/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"better-auth": "^1.7.11"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
|
-
"@pithy-sh/core": "^0.
|
|
50
|
-
"@pithy-sh/email": "^0.10.
|
|
51
|
-
"@pithy-sh/secrets": "^0.6.
|
|
52
|
-
"@pithy-sh/turnstile": "^0.8.
|
|
49
|
+
"@pithy-sh/core": "^0.20.0",
|
|
50
|
+
"@pithy-sh/email": "^0.10.2",
|
|
51
|
+
"@pithy-sh/secrets": "^0.6.8",
|
|
52
|
+
"@pithy-sh/turnstile": "^0.8.4",
|
|
53
53
|
"hono": "^4.13.2",
|
|
54
54
|
"kysely": "^0.29.0",
|
|
55
55
|
"zod": "^4.4.0"
|
package/src/audit/actions.ts
CHANGED
|
@@ -16,8 +16,8 @@ export const AuthAuditActions = {
|
|
|
16
16
|
* A sign-out / session revocation completed — and **completed** is the load-bearing word.
|
|
17
17
|
*
|
|
18
18
|
* `/sign-out` answers `200 {"success":true}` whether or not it found a session to delete: an expired
|
|
19
|
-
* cookie, a bearer token (which it does not read) or a bare `curl` all get the same body
|
|
20
|
-
*
|
|
19
|
+
* cookie, a bearer token (which it does not read) or a bare `curl` all get the same body, so the path is
|
|
20
|
+
* no evidence that anybody was signed out. The evidence is a session row
|
|
21
21
|
* disappearing, which `../instance/auth.ts`'s `session.delete.after` observes and `../audit/evidence.ts`
|
|
22
22
|
* carries to the emitter; with no session gone there is no event, because nothing happened.
|
|
23
23
|
*/
|
|
@@ -38,14 +38,13 @@ export const AuthAuditActions = {
|
|
|
38
38
|
*/
|
|
39
39
|
magicLinkSent: "auth/magic_link_sent",
|
|
40
40
|
/**
|
|
41
|
-
* An email OTP was requested and enqueued for delivery. Same claim, same evidence
|
|
42
|
-
* endpoint that made the point (#627).
|
|
41
|
+
* An email OTP was requested and enqueued for delivery. Same claim, same evidence.
|
|
43
42
|
*
|
|
44
43
|
* It declines twice over and answers `200 {"success":true}` both times. Better Auth drops the
|
|
45
44
|
* verification row and returns success rather than confirm that an address is registered, which is the
|
|
46
45
|
* whole reason the response is shaped that way; and the kit's own `sendVerificationOTP` returns without
|
|
47
|
-
* queuing for any `type` but `sign-in`, because an OTP is a sign-in credential here.
|
|
48
|
-
*
|
|
46
|
+
* queuing for any `type` but `sign-in`, because an OTP is a sign-in credential here. The status says
|
|
47
|
+
* nothing about whether a message was made.
|
|
49
48
|
*
|
|
50
49
|
* **Two more declines sit under the send callback rather than over it, and they are not the same
|
|
51
50
|
* thing as each other.** `@pithy-sh/email` withholds a message to a suppressed address — a hard bounce,
|
|
@@ -64,17 +63,13 @@ export const AuthAuditActions = {
|
|
|
64
63
|
/**
|
|
65
64
|
* A social account row was created — from here on that provider can sign in as this user.
|
|
66
65
|
*
|
|
67
|
-
* **Emitted from the row, not from `/link-social
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
* happened, which makes "which providers can sign in as this account today" unanswerable from the
|
|
72
|
-
* trail that exists to answer it.
|
|
66
|
+
* **Emitted from the row, not from `/link-social`.** Minting the provider redirect is a request; the
|
|
67
|
+
* account row is created later at `/callback/:id` and may never be created at all — the person abandons
|
|
68
|
+
* the consent screen, the provider refuses, the linking gate rejects it. Only the row answers "which
|
|
69
|
+
* providers can sign in as this account today".
|
|
73
70
|
*
|
|
74
|
-
* **A first social sign-up writes this too, deliberately.**
|
|
75
|
-
*
|
|
76
|
-
* *path*, which cannot tell a sign-up from a link. From the row it stops mattering: this event claims a
|
|
77
|
-
* provider can now sign in as this user, and a first social sign-up is exactly when that becomes true.
|
|
71
|
+
* **A first social sign-up writes this too, deliberately.** This event claims a provider can now sign in
|
|
72
|
+
* as this user, and a first social sign-up is exactly when that becomes true.
|
|
78
73
|
* Pinned by `emit.workers.test.ts`, so the decision is asserted rather than inferred from the absence
|
|
79
74
|
* of a branch.
|
|
80
75
|
*/
|
|
@@ -82,8 +77,7 @@ export const AuthAuditActions = {
|
|
|
82
77
|
/**
|
|
83
78
|
* A social account row was removed — that provider can no longer sign in as this user.
|
|
84
79
|
*
|
|
85
|
-
* The other half of the same question
|
|
86
|
-
* detached and the trail was silent. Emitted from the row for the same reason its twin is, which also
|
|
80
|
+
* The other half of the same question. Emitted from the row for the same reason its twin is, which also
|
|
87
81
|
* means it covers every way a link ends — `/unlink-account`, and the cascade when a user is deleted —
|
|
88
82
|
* rather than the one endpoint somebody remembered to wire. Both are driven in `emit.workers.test.ts`:
|
|
89
83
|
* a sentence claiming a class is covered is not the same as a test that reddens when it stops being.
|
|
@@ -116,7 +110,7 @@ export const AuthAuditActions = {
|
|
|
116
110
|
deviceRevoked: "auth/device_revoked",
|
|
117
111
|
/**
|
|
118
112
|
* Somebody tried to sign in with a provider this deployment enables and cannot serve — its credential
|
|
119
|
-
* would not resolve, so the instance was built without it
|
|
113
|
+
* would not resolve, so the instance was built without it. Outcome `denied`, severity
|
|
120
114
|
* `warning`.
|
|
121
115
|
*
|
|
122
116
|
* **This is the operator's channel, and it is why degrading is not the same as degrading silently.**
|
|
@@ -135,9 +129,19 @@ export const AuthAuditActions = {
|
|
|
135
129
|
* account-takeover step". One is a person who left a tab open; a run of them against one user id is the
|
|
136
130
|
* incident, and without the row there is nothing to count.
|
|
137
131
|
*
|
|
138
|
-
* Mirrors the error code
|
|
132
|
+
* Mirrors the error code.
|
|
139
133
|
*/
|
|
140
134
|
sessionNotFresh: "auth/session_not_fresh",
|
|
135
|
+
/**
|
|
136
|
+
* Somebody signed in reached an app route gated by `requireRecentSignIn` without having signed in within
|
|
137
|
+
* that route's window. Outcome `denied`, severity `warning`, with the route's `purpose` in
|
|
138
|
+
* `metadata.purpose`.
|
|
139
|
+
*
|
|
140
|
+
* One action for every gated route, so one filter finds every refusal and the purpose says which route.
|
|
141
|
+
* A run of them against one user id is a stolen credential being walked toward something the app
|
|
142
|
+
* protects.
|
|
143
|
+
*/
|
|
144
|
+
recentSignInRefused: "auth/recent_sign_in_refused",
|
|
141
145
|
|
|
142
146
|
/**
|
|
143
147
|
* The admin actions, emitted only from the control-plane surface (`http/adminRoutes.ts`) and always
|
|
@@ -157,7 +161,7 @@ export const AuthAuditActions = {
|
|
|
157
161
|
adminUserRead: "auth/admin_user_read",
|
|
158
162
|
/** The device registry was walked from the management surface. */
|
|
159
163
|
adminDevicesListed: "auth/admin_devices_listed",
|
|
160
|
-
/** The verification ledger was read from the management surface
|
|
164
|
+
/** The verification ledger was read from the management surface: counts and rows over a window. */
|
|
161
165
|
adminVerificationsListed: "auth/admin_verifications_listed",
|
|
162
166
|
/** One named session was revoked from the management surface. */
|
|
163
167
|
adminSessionRevoked: "auth/admin_session_revoked",
|
|
@@ -167,7 +171,7 @@ export const AuthAuditActions = {
|
|
|
167
171
|
adminDeviceRevoked: "auth/admin_device_revoked",
|
|
168
172
|
|
|
169
173
|
/**
|
|
170
|
-
* The account lifecycle
|
|
174
|
+
* The account lifecycle. Each is written by the transition in `../lifecycle/transitions.ts`, beside
|
|
171
175
|
* the `pithy_auth_user_lifecycle` row that records the same fact — the trail answers "who, from where", the
|
|
172
176
|
* table answers "what happened to this account". The admin ones carry `actorType: "control-plane"`; the
|
|
173
177
|
* self-service deletion carries the account's own holder, and the purge `system`.
|
|
@@ -175,7 +179,7 @@ export const AuthAuditActions = {
|
|
|
175
179
|
* The dashboard's own `customer/user_suspended` and `customer/user_restored` are the client side of the
|
|
176
180
|
* same events, recorded where the operator pressed the button.
|
|
177
181
|
*
|
|
178
|
-
* **The suspend and reinstate routes record every call under the same action
|
|
182
|
+
* **The suspend and reinstate routes record every call under the same action**, the ones the
|
|
179
183
|
* transition did not write included: a refusal as `denied` with its code in `metadata.code`, and a
|
|
180
184
|
* reinstatement that found nothing to lift as a `success` with `metadata.changed: false`. A restated
|
|
181
185
|
* suspension is the transition's own event, with `metadata.updated: true`. So one filter on the action
|
|
@@ -189,7 +193,7 @@ export const AuthAuditActions = {
|
|
|
189
193
|
/** An account was deleted from the management surface, with its purge window starting now. */
|
|
190
194
|
adminUserSoftDeleted: "auth/admin_user_soft_deleted",
|
|
191
195
|
/**
|
|
192
|
-
* An account was deleted from the management surface with no window — its purge starts now
|
|
196
|
+
* An account was deleted from the management surface with no window — its purge starts now. Also
|
|
193
197
|
* written when a hard deletion brings an already-deleted account's purge forward, with
|
|
194
198
|
* `metadata.broughtForward: true`. Never written by omission: the route reaches it only for `mode: "hard"`.
|
|
195
199
|
*/
|
|
@@ -199,13 +203,13 @@ export const AuthAuditActions = {
|
|
|
199
203
|
/** A deleted account's data was erased. Recorded once, when the last purge step has run. */
|
|
200
204
|
adminUserPurged: "auth/admin_user_purged",
|
|
201
205
|
/**
|
|
202
|
-
* One purge step answered for a capability's rows: erased them, or kept them under a stated basis
|
|
206
|
+
* One purge step answered for a capability's rows: erased them, or kept them under a stated basis.
|
|
203
207
|
* `metadata.step` names the capability and `metadata.disposition` says which. The erasure attestation cites it
|
|
204
|
-
* by event id and chain position
|
|
208
|
+
* by event id and chain position.
|
|
205
209
|
*/
|
|
206
210
|
adminUserPurgeStep: "auth/admin_user_purge_step",
|
|
207
211
|
/**
|
|
208
|
-
* A purge gave up at the step `metadata.step` names, until the next daily pass starts it again
|
|
212
|
+
* A purge gave up at the step `metadata.step` names, until the next daily pass starts it again. The
|
|
209
213
|
* erasure attestation cites it, and names every failed purge in a period.
|
|
210
214
|
*/
|
|
211
215
|
adminUserPurgeFailed: "auth/admin_user_purge_failed",
|
|
@@ -213,7 +217,7 @@ export const AuthAuditActions = {
|
|
|
213
217
|
userSelfDeleted: "auth/user_self_deleted",
|
|
214
218
|
/**
|
|
215
219
|
* Everything the kit holds about one account was exported from the management surface — an access request
|
|
216
|
-
* answered
|
|
220
|
+
* answered. A **disclosure**, and the largest one on this surface: it carries every composed
|
|
217
221
|
* capability's rows about the person. Recorded with the caller, the reason they gave, and which capabilities
|
|
218
222
|
* answered; never with any of the data.
|
|
219
223
|
*/
|