@pithy-sh/auth 0.10.0 → 0.11.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 (116) hide show
  1. package/README.md +1 -1
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +19 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +20 -1
  6. package/dist/audit/emit.d.ts +2 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +1 -1
  9. package/dist/capability.d.ts +19 -0
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +20 -3
  12. package/dist/data/tables.d.ts +1 -0
  13. package/dist/data/tables.d.ts.map +1 -1
  14. package/dist/data/userLifecycle.d.ts +1 -0
  15. package/dist/data/userLifecycle.d.ts.map +1 -1
  16. package/dist/data/userLifecycle.js +2 -1
  17. package/dist/http/adminRoutes.d.ts.map +1 -1
  18. package/dist/http/adminRoutes.js +270 -5
  19. package/dist/http/guards.d.ts +8 -7
  20. package/dist/http/guards.d.ts.map +1 -1
  21. package/dist/http/guards.js +38 -7
  22. package/dist/http/middleware.d.ts +25 -1
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +44 -3
  25. package/dist/http/responses.d.ts +180 -0
  26. package/dist/http/responses.d.ts.map +1 -1
  27. package/dist/http/responses.js +142 -1
  28. package/dist/http/routes.d.ts +1 -0
  29. package/dist/http/routes.d.ts.map +1 -1
  30. package/dist/http/routes.js +45 -3
  31. package/dist/http/schemas.d.ts +57 -0
  32. package/dist/http/schemas.d.ts.map +1 -1
  33. package/dist/http/schemas.js +51 -1
  34. package/dist/http/views.d.ts +39 -2
  35. package/dist/http/views.d.ts.map +1 -1
  36. package/dist/http/views.js +105 -1
  37. package/dist/instance/auth.d.ts.map +1 -1
  38. package/dist/instance/auth.js +2 -2
  39. package/dist/lifecycle/audited.d.ts +48 -0
  40. package/dist/lifecycle/audited.d.ts.map +1 -0
  41. package/dist/lifecycle/audited.js +65 -0
  42. package/dist/lifecycle/enforce.d.ts +37 -2
  43. package/dist/lifecycle/enforce.d.ts.map +1 -1
  44. package/dist/lifecycle/enforce.js +46 -5
  45. package/dist/lifecycle/reason.d.ts +11 -0
  46. package/dist/lifecycle/reason.d.ts.map +1 -0
  47. package/dist/lifecycle/reason.js +13 -0
  48. package/dist/lifecycle/request.d.ts +5 -2
  49. package/dist/lifecycle/request.d.ts.map +1 -1
  50. package/dist/lifecycle/request.js +6 -2
  51. package/dist/lifecycle/transitions.d.ts +158 -18
  52. package/dist/lifecycle/transitions.d.ts.map +1 -1
  53. package/dist/lifecycle/transitions.js +344 -70
  54. package/dist/migrations/0005_purge_once.d.ts +22 -0
  55. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  56. package/dist/migrations/0005_purge_once.js +35 -0
  57. package/dist/migrations/pluginTables.d.ts +8 -0
  58. package/dist/migrations/pluginTables.d.ts.map +1 -1
  59. package/dist/migrations/pluginTables.js +8 -1
  60. package/dist/migrations/set.d.ts +2 -1
  61. package/dist/migrations/set.d.ts.map +1 -1
  62. package/dist/migrations/set.js +4 -2
  63. package/dist/purge/contribution.d.ts +47 -0
  64. package/dist/purge/contribution.d.ts.map +1 -0
  65. package/dist/purge/contribution.js +141 -0
  66. package/dist/purge/retryPolicy.d.ts +22 -0
  67. package/dist/purge/retryPolicy.d.ts.map +1 -0
  68. package/dist/purge/retryPolicy.js +26 -0
  69. package/dist/purge/run.d.ts +88 -0
  70. package/dist/purge/run.d.ts.map +1 -0
  71. package/dist/purge/run.js +102 -0
  72. package/dist/purge/specs.d.ts +71 -0
  73. package/dist/purge/specs.d.ts.map +1 -0
  74. package/dist/purge/specs.js +72 -0
  75. package/dist/purge/start.d.ts +42 -0
  76. package/dist/purge/start.d.ts.map +1 -0
  77. package/dist/purge/start.js +37 -0
  78. package/dist/purge/workflow.d.ts +58 -0
  79. package/dist/purge/workflow.d.ts.map +1 -0
  80. package/dist/purge/workflow.js +96 -0
  81. package/dist/test-utils/accountFootprint.d.ts +10 -0
  82. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  83. package/dist/test-utils/accountFootprint.js +44 -0
  84. package/dist/version.generated.d.ts +1 -1
  85. package/dist/version.generated.js +1 -1
  86. package/docs/account-lifecycle.md +123 -11
  87. package/package.json +5 -5
  88. package/pithy.manifest.json +1 -1
  89. package/src/audit/actions.ts +19 -0
  90. package/src/audit/emit.ts +3 -1
  91. package/src/capability.ts +48 -1
  92. package/src/data/userLifecycle.ts +4 -1
  93. package/src/http/adminRoutes.ts +398 -2
  94. package/src/http/guards.ts +39 -7
  95. package/src/http/middleware.ts +45 -2
  96. package/src/http/responses.ts +245 -0
  97. package/src/http/routes.ts +55 -3
  98. package/src/http/schemas.ts +110 -0
  99. package/src/http/views.ts +147 -2
  100. package/src/instance/auth.ts +7 -2
  101. package/src/lifecycle/audited.ts +104 -0
  102. package/src/lifecycle/enforce.ts +55 -5
  103. package/src/lifecycle/reason.ts +11 -0
  104. package/src/lifecycle/request.ts +10 -2
  105. package/src/lifecycle/transitions.ts +482 -93
  106. package/src/migrations/0005_purge_once.ts +42 -0
  107. package/src/migrations/pluginTables.ts +19 -1
  108. package/src/migrations/set.ts +3 -1
  109. package/src/purge/contribution.ts +191 -0
  110. package/src/purge/retryPolicy.ts +26 -0
  111. package/src/purge/run.ts +185 -0
  112. package/src/purge/specs.ts +95 -0
  113. package/src/purge/start.ts +79 -0
  114. package/src/purge/workflow.ts +144 -0
  115. package/src/test-utils/accountFootprint.ts +95 -0
  116. package/src/version.generated.ts +1 -1
@@ -0,0 +1,42 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { type Kysely, type SqlBool, sql } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /** The one index this adds: at most one `purged` row per account. */
8
+ const PURGED_ONCE_INDEX = "pithyAuthUserLifecyclePurgedOnceIdx";
9
+
10
+ /**
11
+ * The purge, once (#622): what a deletion asked of its last mail, and a constraint that a purge finishes once.
12
+ *
13
+ * **`notify` on `pithy_auth_user_lifecycle`.** A hard deletion with `notify: false` asks the purge to send no
14
+ * deletion-complete mail, and the purge that sends it is not always the one the deletion started: with no
15
+ * purge Workflow bound, or a start that failed, the daily pass starts it, and the pass has no request to read
16
+ * the choice from. So the deletion's own history row carries it, and the purge reads it there. `1` or `0` on a
17
+ * hard deletion's `deleted` row that named it; null on every other row, and on one that did not.
18
+ *
19
+ * **A unique partial index on `userId` where `action` is `purged`.** Two purges of one account can overlap —
20
+ * the daily pass and a hard deletion's own, or a purge still retrying when the next pass starts another — and
21
+ * both reach `complete`. A read-then-insert lets both write the record, and both fire `onUserPurged`. With the
22
+ * index the insert is the check: the one that lands fires, the other finds the row there and does nothing.
23
+ *
24
+ * **A `0005`, appended.** `0004` has shipped. No backfill, and no duplicate to clean up first: nothing before
25
+ * this release ran a purge, so no account has a `purged` row yet.
26
+ */
27
+ export const auth_0005_purge_once: Migration = {
28
+ async up(db: Kysely<unknown>): Promise<void> {
29
+ await db.schema.alterTable("pithyAuthUserLifecycle").addColumn("notify", "integer").execute();
30
+ await db.schema
31
+ .createIndex(PURGED_ONCE_INDEX)
32
+ .on("pithyAuthUserLifecycle")
33
+ .column("userId")
34
+ .unique()
35
+ .where(sql<SqlBool>`action = 'purged'`)
36
+ .execute();
37
+ },
38
+ async down(db: Kysely<unknown>): Promise<void> {
39
+ await db.schema.dropIndex(PURGED_ONCE_INDEX).execute();
40
+ await db.schema.alterTable("pithyAuthUserLifecycle").dropColumn("notify").execute();
41
+ },
42
+ };
@@ -279,8 +279,22 @@ export interface AuthPluginPlan {
279
279
  migrations: Record<string, Migration>;
280
280
  /** One entry per plugin, whatever it declared — what `pithy doctor` reports. */
281
281
  extensions: { id: string; tables: string[] }[];
282
+ /**
283
+ * The tables a plugin created that are keyed to one account by a `userId` column — `twoFactor`, `passkey`,
284
+ * an API key's table — which the purge erases and the export reads with auth's own (#622). Every one of them
285
+ * holds rows about the person and nothing else does, because a plugin's tables have no foreign key to cascade
286
+ * from the user row. `organization`'s are not here: a membership is the organization's as much as the
287
+ * person's, and what erasing one means is #623's.
288
+ */
289
+ userTables: string[];
282
290
  }
283
291
 
292
+ /** The column a plugin's table names its account by — Better Auth's own convention for a user-keyed row. */
293
+ const USER_KEY = "userId";
294
+
295
+ /** Plugins whose user-keyed tables the purge leaves to their own issue — see {@link AuthPluginPlan.userTables}. */
296
+ const PURGE_DEFERRED_PLUGINS: readonly string[] = ["organization"];
297
+
284
298
  /**
285
299
  * Derive everything the auth capability needs from an adopter's plugin list, in one pass.
286
300
  *
@@ -297,6 +311,7 @@ export interface AuthPluginPlan {
297
311
  export function authPluginPlan(plugins: readonly BetterAuthPlugin[]): AuthPluginPlan {
298
312
  const migrations: Record<string, Migration> = {};
299
313
  const extensions: { id: string; tables: string[] }[] = [];
314
+ const userTables: string[] = [];
300
315
  const claimed = new Map<string, string>();
301
316
 
302
317
  for (const plugin of plugins) {
@@ -319,6 +334,9 @@ export function authPluginPlan(plugins: readonly BetterAuthPlugin[]): AuthPlugin
319
334
  });
320
335
  }
321
336
  claimed.set(table.name, plugin.id);
337
+ if (!PURGE_DEFERRED_PLUGINS.includes(plugin.id) && table.columns.some((column) => column.name === USER_KEY)) {
338
+ userTables.push(table.name);
339
+ }
322
340
  }
323
341
 
324
342
  if (delta.tables.length === 0 && delta.columns.length === 0) continue;
@@ -333,5 +351,5 @@ export function authPluginPlan(plugins: readonly BetterAuthPlugin[]): AuthPlugin
333
351
  migrations[key] = pluginMigration(delta);
334
352
  }
335
353
 
336
- return { migrations, extensions };
354
+ return { migrations, extensions, userTables };
337
355
  }
@@ -5,6 +5,7 @@ import { auth_0001_init } from "./0001_init";
5
5
  import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at";
6
6
  import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullable";
7
7
  import { auth_0004_user_lifecycle } from "./0004_user_lifecycle";
8
+ import { auth_0005_purge_once } from "./0005_purge_once";
8
9
 
9
10
  /**
10
11
  * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
@@ -16,7 +17,7 @@ import { auth_0004_user_lifecycle } from "./0004_user_lifecycle";
16
17
  * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
17
18
  * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
18
19
  *
19
- * `0003` and `0004` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
20
+ * `0003`, `0004` and `0005` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
20
21
  * its subject is that one migration's own `up` and `down`, so it names it directly.
21
22
  */
22
23
  export const AUTH_MIGRATIONS = {
@@ -24,4 +25,5 @@ export const AUTH_MIGRATIONS = {
24
25
  "0002_session_authenticated_at": auth_0002_session_authenticated_at,
25
26
  "0003_account_issuer_nullable": auth_0003_account_issuer_nullable,
26
27
  "0004_user_lifecycle": auth_0004_user_lifecycle,
28
+ "0005_purge_once": auth_0005_purge_once,
27
29
  } as const;
@@ -0,0 +1,191 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import type { PurgeContext, PurgeContribution } from "@pithy-sh/core/src/capability/purge";
6
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
+ import { type CompiledQuery, type Kysely, type SqlBool, sql } from "kysely";
8
+ import { Account, Session, User } from "../data/betterAuth";
9
+ import { Device } from "../data/device";
10
+ import { type AuthDatabase, authDatabase } from "../data/tables";
11
+ import { UserLifecycleEvent } from "../data/userLifecycle";
12
+ import type { AuthUserExport } from "../http/responses";
13
+ import { authUserExportView } from "../http/views";
14
+
15
+ /**
16
+ * Auth's own purge contribution (#622): what erasing one person means for the `pithy_auth_*` tables, and what
17
+ * exporting them hands back.
18
+ *
19
+ * **Every row keyed to the account goes, except its history.** The user row, its sessions, its linked
20
+ * providers, its devices, its refresh-token ledger, any sign-in code or link still pending for its address,
21
+ * and its rows in every table a composed Better Auth plugin created keyed by `userId` — a two-factor secret
22
+ * and its backup codes, a passkey, an API key. Those tables have no foreign key to the user row, so deleting
23
+ * it removes nothing from them; they are named by the plugin plan (`../migrations/pluginTables.ts`). `pithy_auth_user_lifecycle` stays: it is the record that the account existed, was deleted and was
24
+ * erased, and it names the account by id and holds nothing else about the person (`../data/userLifecycle.ts`).
25
+ * The rate-limit and JWKS tables are keyed to no person and are not touched.
26
+ *
27
+ * **One transaction.** The deletes are one `d1.batch()`, which D1 runs as one, so a failure leaves every row
28
+ * where it was and the retried step erases the lot. **Idempotent**, as the contract requires: a second run
29
+ * finds no rows and deletes nothing, and succeeds.
30
+ *
31
+ * The purge Workflow runs this step **last**, after every other capability's and after the deletion-complete
32
+ * mail, because the address that mail is sent to lives on the user row this deletes.
33
+ */
34
+
35
+ /** The one sentence the purge records with this step. */
36
+ export const AUTH_PURGE_SUMMARY =
37
+ "Deletes the account, its sessions, linked providers, devices, refresh-token ledger, pending sign-in codes and its rows in the tables its Better Auth plugins created. Its lifecycle history stays.";
38
+
39
+ /**
40
+ * A plugin table's column that holds a credential — a TOTP secret, backup codes, a key or its hash, a token.
41
+ * The export leaves these out, as it leaves out a session's token and a provider's: an access request is
42
+ * answered with what is held, never with the means to sign in as the person.
43
+ */
44
+ const CREDENTIAL_COLUMN = /secret|token|key|code|hash|password|credential/i;
45
+
46
+ /** The auth Kysely without its table map — a plugin's table is named by the plan, not by `authTables`. */
47
+ function untyped(db: AuthDatabase): Kysely<Record<string, Record<string, unknown>>> {
48
+ return db as unknown as Kysely<Record<string, Record<string, unknown>>>;
49
+ }
50
+
51
+ /** The D1 binding the auth tables live in, off a run's env — or a wiring fault naming it. */
52
+ function bindingOf(env: Record<string, unknown>, database: string): D1Database {
53
+ const binding = env[database];
54
+ if (typeof binding !== "object" || binding === null) {
55
+ throw new InternalError({
56
+ message: "The auth database is not bound, so this purge step could not run.",
57
+ action: `Bind the ${database} D1 database to the Worker that runs the purge.`,
58
+ detail: `auth purge contribution found no ${database} binding on the env`,
59
+ });
60
+ }
61
+ return binding as D1Database;
62
+ }
63
+
64
+ /** `%` and `_` escaped, so an address is matched as itself inside a LIKE pattern and nothing wider. */
65
+ function literal(value: string): string {
66
+ return value.replace(/[\\%_]/g, (character) => `\\${character}`);
67
+ }
68
+
69
+ /** Bind a compiled statement to D1, so it can join a `batch`. */
70
+ function prepared(d1: D1Database, compiled: CompiledQuery) {
71
+ return d1.prepare(compiled.sql).bind(...(compiled.parameters as unknown[]));
72
+ }
73
+
74
+ /**
75
+ * Erase one account's `pithy_auth_*` rows, its history excepted. Succeeds, having found nothing, when they are
76
+ * already gone.
77
+ *
78
+ * The pending sign-in codes are found by the address, which is why it is read first: an email OTP's identifier
79
+ * is `<type>-otp-<address>`, and a magic link's value is JSON carrying `"email":"<address>"`. With the user row
80
+ * already gone there is no address to look for, and none is needed — a code lives for minutes.
81
+ */
82
+ export async function eraseAuthUser(
83
+ db: AuthDatabase,
84
+ d1: D1Database,
85
+ userId: string,
86
+ pluginTables: readonly string[] = [],
87
+ ): Promise<void> {
88
+ const user = await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst();
89
+ const statements = [
90
+ db.deleteFrom("pithyAuthSessions").where("userId", "=", userId),
91
+ db.deleteFrom("pithyAuthAccounts").where("userId", "=", userId),
92
+ db.deleteFrom("pithyAuthDevices").where("userId", "=", userId),
93
+ db.deleteFrom("pithyAuthRotatedTokens").where("userId", "=", userId),
94
+ ].map((query) => prepared(d1, query.compile()));
95
+ // A plugin's rows, in the same batch: `CamelCasePlugin` snake-cases the table and `user_id` as it does for
96
+ // the plugin's own migration, so the names match what `pithy migrate` created.
97
+ for (const table of pluginTables) {
98
+ statements.push(prepared(d1, untyped(db).deleteFrom(table).where("userId", "=", userId).compile()));
99
+ }
100
+ if (user) {
101
+ const address = literal(user.email);
102
+ const otp = `%-otp-${address}`;
103
+ const changingFrom = `%-otp-${address}-%`;
104
+ const link = `%"email":${literal(JSON.stringify(user.email))}%`;
105
+ // Raw SQL for the predicate, for `users.ts`'s reason: SQLite's `ESCAPE` belongs to the `LIKE` operator, so
106
+ // there is no expression-builder form of it. Both columns are single words, so `CamelCasePlugin` has
107
+ // nothing to rewrite.
108
+ const pending = db
109
+ .deleteFrom("pithyAuthVerifications")
110
+ .where(
111
+ sql<SqlBool>`(identifier like ${otp} escape '\\' or identifier like ${changingFrom} escape '\\' or value like ${link} escape '\\')`,
112
+ );
113
+ statements.push(prepared(d1, pending.compile()));
114
+ }
115
+ statements.push(prepared(d1, db.deleteFrom("pithyAuthUsers").where("id", "=", userId).compile()));
116
+ await d1.batch(statements);
117
+ }
118
+
119
+ /**
120
+ * What auth holds about one account, for an export: the account, its sessions, providers, devices and
121
+ * history, every list whole. `null` when there is no account to export.
122
+ */
123
+ export async function exportAuthUser(
124
+ db: AuthDatabase,
125
+ userId: string,
126
+ pluginTables: readonly string[] = [],
127
+ ): Promise<AuthUserExport | null> {
128
+ const row = await db.selectFrom("pithyAuthUsers").selectAll().where("id", "=", userId).executeTakeFirst();
129
+ if (!row) return null;
130
+ const [sessions, accounts, devices, history, plugins] = await Promise.all([
131
+ db
132
+ .selectFrom("pithyAuthSessions")
133
+ .selectAll()
134
+ .where("userId", "=", userId)
135
+ .orderBy("createdAt", "desc")
136
+ .orderBy("id", "desc")
137
+ .execute(),
138
+ // Two columns, never `select *`: the account row holds the provider's tokens, and they are never loaded.
139
+ db
140
+ .selectFrom("pithyAuthAccounts")
141
+ .select(["providerId", "createdAt"])
142
+ .where("userId", "=", userId)
143
+ .orderBy("providerId", "asc")
144
+ .execute(),
145
+ db
146
+ .selectFrom("pithyAuthDevices")
147
+ .selectAll()
148
+ .where("userId", "=", userId)
149
+ .orderBy("lastSeenAt", "desc")
150
+ .orderBy("id", "desc")
151
+ .execute(),
152
+ db.selectFrom("pithyAuthUserLifecycle").selectAll().where("userId", "=", userId).orderBy("id", "asc").execute(),
153
+ Promise.all(pluginTables.map(async (table) => [table, await pluginRows(db, table, userId)] as const)),
154
+ ]);
155
+ return authUserExportView({
156
+ user: User.parse(row),
157
+ sessions: sessions.map((session) => Session.parse(session)),
158
+ accounts: accounts.map((account) => Account.pick({ providerId: true, createdAt: true }).parse(account)),
159
+ devices: devices.map((device) => Device.parse(device)),
160
+ history: history.map((event) => UserLifecycleEvent.parse(event)),
161
+ plugins: Object.fromEntries(plugins),
162
+ });
163
+ }
164
+
165
+ /** One plugin table's rows about the account, every column but a credential's. */
166
+ async function pluginRows(db: AuthDatabase, table: string, userId: string): Promise<Record<string, unknown>[]> {
167
+ const rows = await untyped(db).selectFrom(table).selectAll().where("userId", "=", userId).execute();
168
+ return rows.map((row) =>
169
+ Object.fromEntries(Object.entries(row).filter(([column]) => !CREDENTIAL_COLUMN.test(column))),
170
+ );
171
+ }
172
+
173
+ /**
174
+ * The contribution `auth()` declares, over the D1 binding its config names. The export of an account that is
175
+ * not there is an empty object, which the route never reaches: it answers 404 before it reads any capability.
176
+ */
177
+ export function authPurgeContribution(database: string, pluginTables: readonly string[] = []): PurgeContribution {
178
+ const open = (context: PurgeContext) => {
179
+ const d1 = bindingOf(context.env, database);
180
+ return { d1, db: authDatabase(d1) };
181
+ };
182
+ return {
183
+ subject: "user",
184
+ summary: AUTH_PURGE_SUMMARY,
185
+ erase: async (context) => {
186
+ const { d1, db } = open(context);
187
+ await eraseAuthUser(db, d1, context.subject.id, pluginTables);
188
+ },
189
+ export: async (context) => (await exportAuthUser(open(context).db, context.subject.id, pluginTables)) ?? {},
190
+ };
191
+ }
@@ -0,0 +1,26 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { WorkflowRetryPolicy } from "@pithy-sh/core/src/workflow/faults";
5
+
6
+ /**
7
+ * **What the purge's own steps retry, and what they refuse to** (#622).
8
+ *
9
+ * The purge's own steps — reading whether the account is due, the last mail, the final record — and the daily
10
+ * pass's are D1, and core answers for D1's transient vocabulary through `withD1Retry`. There is no `auth/*`
11
+ * code a second attempt can answer differently, so the record is empty, and that is a statement: an account
12
+ * that is not due, or a binding that is not there, is the same answer next time.
13
+ *
14
+ * **A capability's erase step is not classified here, deliberately.** It runs the contribution's own code —
15
+ * another capability's, or the adopter's — whose fault vocabulary the kit cannot know, and the contract makes
16
+ * every `erase` idempotent precisely so that any fault in it can be retried. So the purge hands those steps to
17
+ * the platform's own retry, with its backoff: a failing contribution retries alone, and the steps that finished
18
+ * are served from the journal. That is the classification, stated at its one site, `./run.ts`.
19
+ *
20
+ * **The cron is the outer retry.** A pass whose `start` step fails is run again the next day, and a purge whose
21
+ * instance failed is started again for the account still past its window.
22
+ */
23
+ export const authWorkflowRetry: WorkflowRetryPolicy = {
24
+ capability: "auth",
25
+ retryable: {},
26
+ };
@@ -0,0 +1,185 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { PurgeContext, PurgeStep } from "@pithy-sh/core/src/capability/purge";
5
+ import {
6
+ classifiedSteps,
7
+ type TerminalErrorConstructor,
8
+ type WorkflowStepLike,
9
+ } from "@pithy-sh/core/src/workflow/faults";
10
+ import {
11
+ completePurge,
12
+ type DuePurge,
13
+ duePurges,
14
+ type LifecycleDeps,
15
+ mailPurgeComplete,
16
+ purgeSubject,
17
+ recordPurgeStep,
18
+ } from "../lifecycle/transitions";
19
+ import { authWorkflowRetry } from "./retryPolicy";
20
+ import { AUTH_CAPABILITY, type AuthPurgeDueParams, type AuthPurgeParams } from "./specs";
21
+
22
+ /**
23
+ * The purge, as steps (#622) — the bodies `./workflow.ts` hands a Workflow's step runner to.
24
+ *
25
+ * ## One step per contribution, and the order they run in
26
+ *
27
+ * 1. **`due`** — is the account deleted, and has its window closed? A restored account, one inside its window,
28
+ * and one already erased all end the run here, having erased nothing. This is the one check a cron-started
29
+ * purge and a hard deletion's both pass through, so re-running a purge for the same subject exits cleanly.
30
+ * 2. **`erase <capability>`** — one step per composed contribution, in composition order, each recording that it
31
+ * ran in `pithy_auth_user_lifecycle`. Handed to the platform's retry unclassified: an `erase` is idempotent by
32
+ * contract and runs code the kit did not write, so any fault in it is worth another attempt (`./retryPolicy.ts`).
33
+ * A failing contribution retries alone, and the ones that finished are served from the journal.
34
+ * 3. **`mail`** — the deletion-complete mail, **before the address is erased**: every other capability's rows are
35
+ * gone, and auth's, which hold the address, are not yet. The address is read in the step, never carried out of
36
+ * one, so it is in no Workflow's journal.
37
+ * 4. **`erase auth`** — auth's own contribution, last for that reason.
38
+ * 5. **`complete`** — the `purged` record, the audit event, `onUserPurged`. Once.
39
+ */
40
+
41
+ /** What a purge does with the account's own records — the transitions, over one set of dependencies. */
42
+ export interface PurgeOps {
43
+ /** Whether the account is due: deleted, with its window closed. `gone` when there is no account. */
44
+ due(userId: string): Promise<"due" | "not_due" | "gone">;
45
+ /** Record that one capability's step erased its rows. */
46
+ recordStep(userId: string, step: string, summary: string): Promise<void>;
47
+ /**
48
+ * Send the deletion-complete mail to the account's address, if it is still there to read, unless this purge's
49
+ * `notify` or the deletion's own saved choice is false. Says whether.
50
+ */
51
+ mailComplete(userId: string, notify: boolean | undefined): Promise<boolean>;
52
+ /** Write the `purged` record, the audit event and the hook. Says whether this call wrote them. */
53
+ complete(userId: string): Promise<boolean>;
54
+ }
55
+
56
+ /** The operations, over the lifecycle transitions. */
57
+ export function purgeOps(deps: LifecycleDeps): PurgeOps {
58
+ return {
59
+ due: async (userId) => (await purgeSubject(deps, userId)).state,
60
+ recordStep: (userId, step, summary) => recordPurgeStep(deps, { userId, step, summary }),
61
+ mailComplete: async (userId, notify) => {
62
+ const subject = await purgeSubject(deps, userId);
63
+ if (subject.state !== "due") return false;
64
+ // Either can silence it: the parameter a hard deletion started this purge with, or the choice that deletion
65
+ // wrote on its history row — the one a purge the daily pass started still has (#622).
66
+ const silenced = notify === false || subject.notify === false;
67
+ return (await mailPurgeComplete(deps, { recipient: subject.recipient, ...(silenced ? { notify: false } : {}) }))
68
+ .mailed;
69
+ },
70
+ complete: async (userId) => (await completePurge(deps, { userId })).changed,
71
+ };
72
+ }
73
+
74
+ /** What one purge did: the account, how it ended, and the capabilities whose rows it erased. */
75
+ export interface PurgeOutcome {
76
+ /** The account. */
77
+ readonly userId: string;
78
+ /** `purged`, or why nothing was erased: `not_due` (restored, or inside its window) and `gone` (no account). */
79
+ readonly state: "purged" | "not_due" | "gone";
80
+ /** Every step that erased its rows, in the order it ran. Empty when nothing was erased. */
81
+ readonly erased: readonly string[];
82
+ /** Whether the deletion-complete mail was enqueued. */
83
+ readonly mailed: boolean;
84
+ }
85
+
86
+ /** What one purge reads its plan from: the composed contributions, this run's env, and its operations. */
87
+ export interface PurgeRun {
88
+ /** Every composed purge step for `user`, auth's own among them. */
89
+ readonly steps: readonly PurgeStep[];
90
+ /** This run's bindings, handed to each contribution. */
91
+ readonly env: Record<string, unknown>;
92
+ /** The account's own records. */
93
+ readonly ops: PurgeOps;
94
+ }
95
+
96
+ /** Run one account's purge, one step per contribution, auth's last. See the file header for the order. */
97
+ export async function purgeUser(
98
+ run: PurgeRun,
99
+ step: WorkflowStepLike,
100
+ terminalError: TerminalErrorConstructor,
101
+ params: AuthPurgeParams,
102
+ ): Promise<PurgeOutcome> {
103
+ const own = classifiedSteps(step, authWorkflowRetry, terminalError);
104
+ const userId = params.userId;
105
+ const state = await own.do("due", () => run.ops.due(userId));
106
+ if (state !== "due") return { userId, state, erased: [], mailed: false };
107
+
108
+ const context: PurgeContext = { subject: { type: "user", id: userId }, env: run.env };
109
+ const auth = run.steps.filter((each) => each.step === AUTH_CAPABILITY);
110
+ const others = run.steps.filter((each) => each.step !== AUTH_CAPABILITY);
111
+ const erased: string[] = [];
112
+ for (const each of others) {
113
+ erased.push(await eraseStep(step, run.ops, each, context));
114
+ }
115
+ const mailed = await own.do("mail", () => run.ops.mailComplete(userId, params.notify));
116
+ for (const each of auth) {
117
+ erased.push(await eraseStep(step, run.ops, each, context));
118
+ }
119
+ await own.do("complete", () => run.ops.complete(userId));
120
+ return { userId, state: "purged", erased, mailed };
121
+ }
122
+
123
+ /**
124
+ * One capability's step: erase, then record that it ran. On the platform's own retry, unclassified — see the
125
+ * file header. Recorded inside the same step, so a step that erased and failed to record is retried whole, and
126
+ * the second erase finds nothing.
127
+ */
128
+ function eraseStep(step: WorkflowStepLike, ops: PurgeOps, each: PurgeStep, context: PurgeContext): Promise<string> {
129
+ return step.do(`erase ${each.step}`, async () => {
130
+ await each.contribution.erase(context);
131
+ await ops.recordStep(context.subject.id, each.step, each.contribution.summary);
132
+ return each.step;
133
+ });
134
+ }
135
+
136
+ /** How many purges one `start` step dispatches — a page, so one pass over a backlog is a bounded number of steps. */
137
+ export const PURGE_START_PAGE = 50;
138
+
139
+ /** The default size of one daily pass. */
140
+ export const PURGE_DUE_DEFAULT_LIMIT = 500;
141
+
142
+ /** What the daily pass reads and starts through. */
143
+ export interface PurgeDueRun {
144
+ /** Every account whose purge is due, oldest first, at most `limit`, with the deletion it is due under. */
145
+ due(limit: number): Promise<DuePurge[]>;
146
+ /**
147
+ * Start one account's purge — under the instance id its deletion names, so a start repeated is the same one.
148
+ * Says whether the purge is running: started now, or found already started. `false` when it could not be
149
+ * started, and the pass does not count it.
150
+ */
151
+ start(due: DuePurge): Promise<boolean>;
152
+ }
153
+
154
+ /**
155
+ * The daily pass (#622): list every account past its window, and start a purge for each — in pages, one step
156
+ * each, so a pass that dies part-way resumes after the page it finished rather than starting every purge
157
+ * again. An account still inside its window is not listed, so it is not started.
158
+ */
159
+ export async function startDuePurges(
160
+ run: PurgeDueRun,
161
+ step: WorkflowStepLike,
162
+ terminalError: TerminalErrorConstructor,
163
+ params: AuthPurgeDueParams,
164
+ ): Promise<{ started: number }> {
165
+ const own = classifiedSteps(step, authWorkflowRetry, terminalError);
166
+ const limit = params.limit ?? PURGE_DUE_DEFAULT_LIMIT;
167
+ const due = await own.do("due", () => run.due(limit));
168
+ let started = 0;
169
+ for (let page = 0; page * PURGE_START_PAGE < due.length; page += 1) {
170
+ const ids = due.slice(page * PURGE_START_PAGE, (page + 1) * PURGE_START_PAGE);
171
+ started += await own.do(`start ${page + 1}`, async () => {
172
+ // Counted from what each start answered, never from the page's length: a purge the binding could not start
173
+ // is not running, and `{ started }` is what an operator reads to learn whether they are.
174
+ let running = 0;
175
+ for (const each of ids) if (await run.start(each)) running += 1;
176
+ return running;
177
+ });
178
+ }
179
+ return { started };
180
+ }
181
+
182
+ /** The daily pass's reads, over the lifecycle transitions. */
183
+ export function duePurgesOf(deps: LifecycleDeps): PurgeDueRun["due"] {
184
+ return (limit) => duePurges(deps, limit);
185
+ }
@@ -0,0 +1,95 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { workflowKey } from "@pithy-sh/core/src/workflow/naming";
5
+ import type { WorkflowRegistry, WorkflowSpecMap } from "@pithy-sh/core/src/workflow/spec";
6
+ import { z } from "zod";
7
+
8
+ /** This capability's name, and the first segment of its workflow dispatch keys. */
9
+ export const AUTH_CAPABILITY = "auth";
10
+
11
+ /** The binding the purge of one account is started on. */
12
+ export const AUTH_PURGE_BINDING = "AUTH_PURGE";
13
+
14
+ /** The binding the daily pass that starts every due purge runs on. */
15
+ export const AUTH_PURGE_DUE_BINDING = "AUTH_PURGE_DUE";
16
+
17
+ /** The dispatch key of the purge of one account. */
18
+ export const AUTH_PURGE_KEY = workflowKey(AUTH_CAPABILITY, "purge");
19
+
20
+ /** One account's purge: which, and whether its last mail is sent. */
21
+ export const AuthPurgeParams = z
22
+ .object({
23
+ userId: z.string().min(1).max(255).describe("The account to erase, as `pithy_auth_users.id` stores it."),
24
+ notify: z
25
+ .boolean()
26
+ .optional()
27
+ .describe(
28
+ "Whether the deletion-complete mail is sent. Absent is true; the config can still turn it off. A hard deletion with `notify: false` passes false.",
29
+ ),
30
+ })
31
+ .describe("One account's purge. It erases nothing unless the account is deleted and its window has closed.");
32
+ export type AuthPurgeParams = z.infer<typeof AuthPurgeParams>;
33
+
34
+ /**
35
+ * The daily pass's parameters. Every field optional, because a cron passes none — `createEntrypoint` starts a
36
+ * scheduled job with `{}`.
37
+ */
38
+ export const AuthPurgeDueParams = z
39
+ .object({
40
+ limit: z
41
+ .number()
42
+ .int()
43
+ .min(1)
44
+ .max(1000)
45
+ .optional()
46
+ .describe("How many due accounts to start a purge for in this pass, oldest first. Defaults to 500."),
47
+ })
48
+ .describe("One pass that starts a purge for every account past its window. A cron passes no field.");
49
+ export type AuthPurgeDueParams = z.infer<typeof AuthPurgeDueParams>;
50
+
51
+ /**
52
+ * The two durable jobs auth owns (#622) — **both hosted by the adopter's own Worker**, the one that composes
53
+ * auth, never a prebuilt host.
54
+ *
55
+ * **Why not a host.** A purge runs every composed capability's contribution, the adopter's own `app` among
56
+ * them, and those exist only in the Worker whose `pithy.config.ts` composed them. A prebuilt host composes
57
+ * nothing. So each class is five lines in the adopter's entry, calling `runAuthPurge` and `runAuthPurgeDue` in
58
+ * `./workflow.ts`, exactly as `@pithy-sh/payments`' usage pass is: Cloudflare resolves a `class_name` in the
59
+ * script that binds it, and the body finds the composition the way a Workflow that sends mail finds email.
60
+ * No `className` here, deliberately: the class is the adopter's, and so is its `workflows` entry. The docs
61
+ * give both (`docs/account-lifecycle.md`).
62
+ *
63
+ * **`purge-due` is daily at 02:00 UTC**, ahead of storage's and the secrets rotation at 03:00, payments' 04:00
64
+ * and testers' 05:00. Daily because the window is counted in days: an hourly pass would start the same purge
65
+ * twenty-four times and erase nothing sooner. Both stay dispatchable on demand — a hard deletion starts
66
+ * `purge` directly.
67
+ *
68
+ * `optional: true` for both, so a Worker composing auth still boots before the adopter has bound them. A
69
+ * deletion then reports its purge as `pending`, and nothing is erased until they are.
70
+ */
71
+ export const authWorkflows = {
72
+ purge: {
73
+ binding: AUTH_PURGE_BINDING,
74
+ params: AuthPurgeParams,
75
+ optional: true,
76
+ },
77
+ "purge-due": {
78
+ binding: AUTH_PURGE_DUE_BINDING,
79
+ params: AuthPurgeDueParams,
80
+ schedule: "0 2 * * *",
81
+ optional: true,
82
+ },
83
+ } as const satisfies WorkflowSpecMap;
84
+
85
+ /**
86
+ * The jobs as a dispatch registry, keyed `auth/<job>`, built here for the reason testers builds its own: the key
87
+ * format is core's either way. The daily pass starts each purge on the binding directly, not through this, because
88
+ * it names the instance (`./start.ts`) and dispatch does not.
89
+ */
90
+ export const authWorkflowRegistry: WorkflowRegistry = Object.fromEntries(
91
+ Object.entries(authWorkflows).map(([job, spec]) => {
92
+ const key = workflowKey(AUTH_CAPABILITY, job);
93
+ return [key, { key, capability: AUTH_CAPABILITY, job, spec }];
94
+ }),
95
+ );