@pithy-sh/auth 0.9.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 (188) hide show
  1. package/README.md +8 -2
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +40 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +41 -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 +2 -2
  9. package/dist/capability.d.ts +45 -1
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +40 -5
  12. package/dist/client/lifecycle.d.ts +19 -0
  13. package/dist/client/lifecycle.d.ts.map +1 -0
  14. package/dist/client/lifecycle.js +25 -0
  15. package/dist/client/projection.d.ts +4 -0
  16. package/dist/client/projection.d.ts.map +1 -1
  17. package/dist/data/betterAuth.d.ts +4 -0
  18. package/dist/data/betterAuth.d.ts.map +1 -1
  19. package/dist/data/betterAuth.js +6 -2
  20. package/dist/data/kitFields.d.ts +20 -25
  21. package/dist/data/kitFields.d.ts.map +1 -1
  22. package/dist/data/kitFields.js +28 -32
  23. package/dist/data/tables.d.ts +29 -2
  24. package/dist/data/tables.d.ts.map +1 -1
  25. package/dist/data/tables.js +5 -3
  26. package/dist/data/userLifecycle.d.ts +62 -0
  27. package/dist/data/userLifecycle.d.ts.map +1 -0
  28. package/dist/data/userLifecycle.js +51 -0
  29. package/dist/http/adminRoutes.d.ts.map +1 -1
  30. package/dist/http/adminRoutes.js +270 -5
  31. package/dist/http/guards.d.ts +24 -1
  32. package/dist/http/guards.d.ts.map +1 -1
  33. package/dist/http/guards.js +59 -3
  34. package/dist/http/lifecycleGate.d.ts +18 -0
  35. package/dist/http/lifecycleGate.d.ts.map +1 -0
  36. package/dist/http/lifecycleGate.js +75 -0
  37. package/dist/http/middleware.d.ts +30 -1
  38. package/dist/http/middleware.d.ts.map +1 -1
  39. package/dist/http/middleware.js +89 -7
  40. package/dist/http/providerRefusal.d.ts.map +1 -1
  41. package/dist/http/providerRefusal.js +8 -0
  42. package/dist/http/resolve.d.ts.map +1 -1
  43. package/dist/http/resolve.js +7 -4
  44. package/dist/http/responses.d.ts +180 -0
  45. package/dist/http/responses.d.ts.map +1 -1
  46. package/dist/http/responses.js +142 -1
  47. package/dist/http/routes.d.ts +1 -0
  48. package/dist/http/routes.d.ts.map +1 -1
  49. package/dist/http/routes.js +65 -4
  50. package/dist/http/schemas.d.ts +57 -0
  51. package/dist/http/schemas.d.ts.map +1 -1
  52. package/dist/http/schemas.js +51 -1
  53. package/dist/http/views.d.ts +39 -2
  54. package/dist/http/views.d.ts.map +1 -1
  55. package/dist/http/views.js +105 -1
  56. package/dist/instance/auth.d.ts +55 -3
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +53 -2
  59. package/dist/instance/microsoftEmail.d.ts +70 -0
  60. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  61. package/dist/instance/microsoftEmail.js +96 -0
  62. package/dist/instance/providerSignInGate.d.ts +7 -6
  63. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  64. package/dist/instance/providerSignInGate.js +7 -6
  65. package/dist/instance/providers.d.ts +7 -5
  66. package/dist/instance/providers.d.ts.map +1 -1
  67. package/dist/instance/providers.js +5 -3
  68. package/dist/instance/secrets.d.ts +64 -3
  69. package/dist/instance/secrets.d.ts.map +1 -1
  70. package/dist/instance/secrets.js +44 -5
  71. package/dist/lifecycle/audited.d.ts +48 -0
  72. package/dist/lifecycle/audited.d.ts.map +1 -0
  73. package/dist/lifecycle/audited.js +65 -0
  74. package/dist/lifecycle/enforce.d.ts +75 -0
  75. package/dist/lifecycle/enforce.d.ts.map +1 -0
  76. package/dist/lifecycle/enforce.js +111 -0
  77. package/dist/lifecycle/hooks.d.ts +53 -0
  78. package/dist/lifecycle/hooks.d.ts.map +1 -0
  79. package/dist/lifecycle/hooks.js +2 -0
  80. package/dist/lifecycle/reason.d.ts +11 -0
  81. package/dist/lifecycle/reason.d.ts.map +1 -0
  82. package/dist/lifecycle/reason.js +13 -0
  83. package/dist/lifecycle/request.d.ts +18 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +31 -0
  86. package/dist/lifecycle/state.d.ts +64 -0
  87. package/dist/lifecycle/state.d.ts.map +1 -0
  88. package/dist/lifecycle/state.js +90 -0
  89. package/dist/lifecycle/transitions.d.ts +272 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +623 -0
  92. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  93. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  94. package/dist/migrations/0004_user_lifecycle.js +47 -0
  95. package/dist/migrations/0005_purge_once.d.ts +22 -0
  96. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  97. package/dist/migrations/0005_purge_once.js +35 -0
  98. package/dist/migrations/pluginTables.d.ts +8 -0
  99. package/dist/migrations/pluginTables.d.ts.map +1 -1
  100. package/dist/migrations/pluginTables.js +8 -1
  101. package/dist/migrations/set.d.ts +3 -1
  102. package/dist/migrations/set.d.ts.map +1 -1
  103. package/dist/migrations/set.js +6 -2
  104. package/dist/peer.d.ts +4 -0
  105. package/dist/peer.d.ts.map +1 -1
  106. package/dist/purge/contribution.d.ts +47 -0
  107. package/dist/purge/contribution.d.ts.map +1 -0
  108. package/dist/purge/contribution.js +141 -0
  109. package/dist/purge/retryPolicy.d.ts +22 -0
  110. package/dist/purge/retryPolicy.d.ts.map +1 -0
  111. package/dist/purge/retryPolicy.js +26 -0
  112. package/dist/purge/run.d.ts +88 -0
  113. package/dist/purge/run.d.ts.map +1 -0
  114. package/dist/purge/run.js +102 -0
  115. package/dist/purge/specs.d.ts +71 -0
  116. package/dist/purge/specs.d.ts.map +1 -0
  117. package/dist/purge/specs.js +72 -0
  118. package/dist/purge/start.d.ts +42 -0
  119. package/dist/purge/start.d.ts.map +1 -0
  120. package/dist/purge/start.js +37 -0
  121. package/dist/purge/workflow.d.ts +58 -0
  122. package/dist/purge/workflow.d.ts.map +1 -0
  123. package/dist/purge/workflow.js +96 -0
  124. package/dist/test-utils/accountFootprint.d.ts +10 -0
  125. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  126. package/dist/test-utils/accountFootprint.js +44 -0
  127. package/dist/test-utils/liveApp.d.ts +21 -0
  128. package/dist/test-utils/liveApp.d.ts.map +1 -1
  129. package/dist/test-utils/liveApp.js +1 -0
  130. package/dist/test-utils/scopedBackend.d.ts +21 -0
  131. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  132. package/dist/test-utils/scopedBackend.js +7 -1
  133. package/dist/version.generated.d.ts +1 -1
  134. package/dist/version.generated.d.ts.map +1 -1
  135. package/dist/version.generated.js +1 -1
  136. package/docs/account-lifecycle.md +217 -0
  137. package/docs/apple-signin.md +7 -1
  138. package/docs/facebook-oauth.md +7 -1
  139. package/docs/github-oauth.md +7 -1
  140. package/docs/google-oauth.md +7 -1
  141. package/docs/microsoft-oauth.md +177 -0
  142. package/package.json +5 -5
  143. package/pithy.manifest.json +17 -3
  144. package/src/audit/actions.ts +42 -0
  145. package/src/audit/emit.ts +4 -2
  146. package/src/capability.ts +170 -52
  147. package/src/client/lifecycle.ts +27 -0
  148. package/src/client/projection.ts +4 -0
  149. package/src/data/betterAuth.ts +21 -1
  150. package/src/data/kitFields.ts +27 -0
  151. package/src/data/tables.ts +4 -2
  152. package/src/data/userLifecycle.ts +83 -0
  153. package/src/http/adminRoutes.ts +398 -2
  154. package/src/http/guards.ts +61 -1
  155. package/src/http/lifecycleGate.ts +78 -0
  156. package/src/http/middleware.ts +104 -2
  157. package/src/http/providerRefusal.ts +10 -0
  158. package/src/http/resolve.ts +8 -3
  159. package/src/http/responses.ts +245 -0
  160. package/src/http/routes.ts +93 -4
  161. package/src/http/schemas.ts +110 -0
  162. package/src/http/views.ts +147 -2
  163. package/src/instance/auth.ts +74 -2
  164. package/src/instance/microsoftEmail.ts +111 -0
  165. package/src/instance/providerSignInGate.ts +7 -6
  166. package/src/instance/providers.ts +8 -4
  167. package/src/instance/secrets.ts +59 -5
  168. package/src/lifecycle/audited.ts +104 -0
  169. package/src/lifecycle/enforce.ts +139 -0
  170. package/src/lifecycle/hooks.ts +54 -0
  171. package/src/lifecycle/reason.ts +11 -0
  172. package/src/lifecycle/request.ts +39 -0
  173. package/src/lifecycle/state.ts +101 -0
  174. package/src/lifecycle/transitions.ts +872 -0
  175. package/src/migrations/0004_user_lifecycle.ts +68 -0
  176. package/src/migrations/0005_purge_once.ts +42 -0
  177. package/src/migrations/pluginTables.ts +19 -1
  178. package/src/migrations/set.ts +5 -1
  179. package/src/purge/contribution.ts +191 -0
  180. package/src/purge/retryPolicy.ts +26 -0
  181. package/src/purge/run.ts +185 -0
  182. package/src/purge/specs.ts +95 -0
  183. package/src/purge/start.ts +79 -0
  184. package/src/purge/workflow.ts +144 -0
  185. package/src/test-utils/accountFootprint.ts +95 -0
  186. package/src/test-utils/liveApp.ts +2 -1
  187. package/src/test-utils/scopedBackend.ts +2 -1
  188. package/src/version.generated.ts +1 -1
@@ -0,0 +1,47 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/migrations/0004_user_lifecycle.ts
4
+ /** The four state columns, in the order `up` adds them and `down` takes them away in reverse. */
5
+ const STATE_COLUMNS = [
6
+ "suspendedAt",
7
+ "suspendedUntil",
8
+ "deletedAt",
9
+ "purgeAfter"
10
+ ];
11
+ /**
12
+ * The account lifecycle (#620): whether an account is suspended or deleted, and the record of how it got
13
+ * there.
14
+ *
15
+ * **Four columns on `pithy_auth_users`, so a session read already carries the state.** Better Auth loads the
16
+ * user row for every session it resolves, and returns these because `../data/kitFields.ts` declares them —
17
+ * so refusing a suspended account costs no query on the request that is refused, and none on the requests
18
+ * that are not.
19
+ *
20
+ * **One kit-owned table beside them, `pithy_auth_user_lifecycle`**, holding every transition with its
21
+ * actor, its reason and its time. The columns say what is true now; the table says what happened. No
22
+ * foreign key from it to the user: a purge erases the user row, and this table is the record that must
23
+ * outlive it (`../data/userLifecycle.ts`).
24
+ *
25
+ * **`integer`, not `text`, unlike every Better Auth date on the same table.** Better Auth writes those, as
26
+ * ISO-8601. Nothing but the kit writes these — they are `input: false` — so they take the house ms-epoch
27
+ * convention, and `type: "number"` in `kitFields.ts` keeps Better Auth from converting what it reads back.
28
+ *
29
+ * **Nullable, with no backfill.** Every account that exists when this runs is in neither state, and null is
30
+ * exactly that. SQLite would refuse `ADD COLUMN … NOT NULL` without a constant default anyway.
31
+ *
32
+ * **A `0004`, appended, never folded into `0001`.** `@pithy-sh/auth` has shipped, so its chain is history.
33
+ */
34
+ const auth_0004_user_lifecycle = {
35
+ async up(db) {
36
+ for (const column of STATE_COLUMNS) await db.schema.alterTable("pithyAuthUsers").addColumn(column, "integer").execute();
37
+ await db.schema.createTable("pithyAuthUserLifecycle").addColumn("id", "integer", (c) => c.primaryKey().autoIncrement()).addColumn("userId", "text", (c) => c.notNull()).addColumn("action", "text", (c) => c.notNull()).addColumn("actorType", "text", (c) => c.notNull()).addColumn("actorId", "text").addColumn("reason", "text").addColumn("suspendedUntil", "integer").addColumn("step", "text").addColumn("createdAt", "integer", (c) => c.notNull()).execute();
38
+ await db.schema.createIndex("pithyAuthUserLifecycleUserIdIdx").on("pithyAuthUserLifecycle").columns(["userId", "id"]).execute();
39
+ },
40
+ async down(db) {
41
+ await db.schema.dropIndex("pithyAuthUserLifecycleUserIdIdx").execute();
42
+ await db.schema.dropTable("pithyAuthUserLifecycle").execute();
43
+ for (const column of [...STATE_COLUMNS].reverse()) await db.schema.alterTable("pithyAuthUsers").dropColumn(column).execute();
44
+ }
45
+ };
46
+ //#endregion
47
+ export { auth_0004_user_lifecycle };
@@ -0,0 +1,22 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { Migration } from "kysely/migration";
4
+ /**
5
+ * The purge, once (#622): what a deletion asked of its last mail, and a constraint that a purge finishes once.
6
+ *
7
+ * **`notify` on `pithy_auth_user_lifecycle`.** A hard deletion with `notify: false` asks the purge to send no
8
+ * deletion-complete mail, and the purge that sends it is not always the one the deletion started: with no
9
+ * purge Workflow bound, or a start that failed, the daily pass starts it, and the pass has no request to read
10
+ * the choice from. So the deletion's own history row carries it, and the purge reads it there. `1` or `0` on a
11
+ * hard deletion's `deleted` row that named it; null on every other row, and on one that did not.
12
+ *
13
+ * **A unique partial index on `userId` where `action` is `purged`.** Two purges of one account can overlap —
14
+ * the daily pass and a hard deletion's own, or a purge still retrying when the next pass starts another — and
15
+ * both reach `complete`. A read-then-insert lets both write the record, and both fire `onUserPurged`. With the
16
+ * index the insert is the check: the one that lands fires, the other finds the row there and does nothing.
17
+ *
18
+ * **A `0005`, appended.** `0004` has shipped. No backfill, and no duplicate to clean up first: nothing before
19
+ * this release ran a purge, so no account has a `purged` row yet.
20
+ */
21
+ export declare const auth_0005_purge_once: Migration;
22
+ //# sourceMappingURL=0005_purge_once.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"0005_purge_once.d.ts","sourceRoot":"","sources":["../../src/migrations/0005_purge_once.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAKlD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAelC,CAAC"}
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { sql } from "kysely";
4
+ //#region src/migrations/0005_purge_once.ts
5
+ /** The one index this adds: at most one `purged` row per account. */
6
+ const PURGED_ONCE_INDEX = "pithyAuthUserLifecyclePurgedOnceIdx";
7
+ /**
8
+ * The purge, once (#622): what a deletion asked of its last mail, and a constraint that a purge finishes once.
9
+ *
10
+ * **`notify` on `pithy_auth_user_lifecycle`.** A hard deletion with `notify: false` asks the purge to send no
11
+ * deletion-complete mail, and the purge that sends it is not always the one the deletion started: with no
12
+ * purge Workflow bound, or a start that failed, the daily pass starts it, and the pass has no request to read
13
+ * the choice from. So the deletion's own history row carries it, and the purge reads it there. `1` or `0` on a
14
+ * hard deletion's `deleted` row that named it; null on every other row, and on one that did not.
15
+ *
16
+ * **A unique partial index on `userId` where `action` is `purged`.** Two purges of one account can overlap —
17
+ * the daily pass and a hard deletion's own, or a purge still retrying when the next pass starts another — and
18
+ * both reach `complete`. A read-then-insert lets both write the record, and both fire `onUserPurged`. With the
19
+ * index the insert is the check: the one that lands fires, the other finds the row there and does nothing.
20
+ *
21
+ * **A `0005`, appended.** `0004` has shipped. No backfill, and no duplicate to clean up first: nothing before
22
+ * this release ran a purge, so no account has a `purged` row yet.
23
+ */
24
+ const auth_0005_purge_once = {
25
+ async up(db) {
26
+ await db.schema.alterTable("pithyAuthUserLifecycle").addColumn("notify", "integer").execute();
27
+ await db.schema.createIndex(PURGED_ONCE_INDEX).on("pithyAuthUserLifecycle").column("userId").unique().where(sql`action = 'purged'`).execute();
28
+ },
29
+ async down(db) {
30
+ await db.schema.dropIndex(PURGED_ONCE_INDEX).execute();
31
+ await db.schema.alterTable("pithyAuthUserLifecycle").dropColumn("notify").execute();
32
+ }
33
+ };
34
+ //#endregion
35
+ export { auth_0005_purge_once };
@@ -110,6 +110,14 @@ export interface AuthPluginPlan {
110
110
  id: string;
111
111
  tables: string[];
112
112
  }[];
113
+ /**
114
+ * The tables a plugin created that are keyed to one account by a `userId` column — `twoFactor`, `passkey`,
115
+ * an API key's table — which the purge erases and the export reads with auth's own (#622). Every one of them
116
+ * holds rows about the person and nothing else does, because a plugin's tables have no foreign key to cascade
117
+ * from the user row. `organization`'s are not here: a membership is the organization's as much as the
118
+ * person's, and what erasing one means is #623's.
119
+ */
120
+ userTables: string[];
113
121
  }
114
122
  /**
115
123
  * Derive everything the auth capability needs from an adopter's plugin list, in one pass.
@@ -1 +1 @@
1
- {"version":3,"file":"pluginTables.d.ts","sourceRoot":"","sources":["../../src/migrations/pluginTables.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAGvE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAKlD;;;;;;;;;;;;;;;;;;GAkBG;AAEH;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,SAAS,gBAAgB,EAAE,GAAG,iBAAiB,CA0BzF;AAED,6FAA6F;AAC7F,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,SAAS,CAAC;AAElD,iDAAiD;AACjD,MAAM,WAAW,iBAAiB;IAChC,sFAAsF;IACtF,IAAI,EAAE,MAAM,CAAC;IACb,0BAA0B;IAC1B,IAAI,EAAE,gBAAgB,CAAC;IACvB,wCAAwC;IACxC,OAAO,EAAE,OAAO,CAAC;IACjB,oDAAoD;IACpD,UAAU,EAAE,OAAO,CAAC;IACpB,wDAAwD;IACxD,MAAM,EAAE,OAAO,CAAC;IAChB,mDAAmD;IACnD,KAAK,EAAE,OAAO,CAAC;CAChB;AAED,yCAAyC;AACzC,MAAM,WAAW,WAAW;IAC1B,kEAAkE;IAClE,IAAI,EAAE,MAAM,CAAC;IACb,+BAA+B;IAC/B,OAAO,EAAE,iBAAiB,EAAE,CAAC;CAC9B;AAED,uGAAuG;AACvG,MAAM,WAAW,YAAY;IAC3B,wCAAwC;IACxC,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,0BAA0B;IAC1B,IAAI,EAAE,gBAAgB,CAAC;IACvB,sDAAsD;IACtD,OAAO,EAAE,OAAO,CAAC;IACjB,mDAAmD;IACnD,KAAK,EAAE,OAAO,CAAC;CAChB;AAED,wGAAwG;AACxG,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,WAAW,EA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ACtB;AAQD;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,SAAS,gBAAgB,EAAE,GAAG,cAAc,CA4CnF"}
@@ -181,6 +181,10 @@ function pluginMigration(delta) {
181
181
  function pluginMigrationKey(id) {
182
182
  return `0002_plugin_${id.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "")}`;
183
183
  }
184
+ /** The column a plugin's table names its account by — Better Auth's own convention for a user-keyed row. */
185
+ const USER_KEY = "userId";
186
+ /** Plugins whose user-keyed tables the purge leaves to their own issue — see {@link AuthPluginPlan.userTables}. */
187
+ const PURGE_DEFERRED_PLUGINS = ["organization"];
184
188
  /**
185
189
  * Derive everything the auth capability needs from an adopter's plugin list, in one pass.
186
190
  *
@@ -197,6 +201,7 @@ function pluginMigrationKey(id) {
197
201
  function authPluginPlan(plugins) {
198
202
  const migrations = {};
199
203
  const extensions = [];
204
+ const userTables = [];
200
205
  const claimed = /* @__PURE__ */ new Map();
201
206
  for (const plugin of plugins) {
202
207
  const delta = pluginSchemaDelta(plugin);
@@ -217,6 +222,7 @@ function authPluginPlan(plugins) {
217
222
  detail: `plugins "${owner}" and "${plugin.id}" both claim table "${table.name}"`
218
223
  });
219
224
  claimed.set(table.name, plugin.id);
225
+ if (!PURGE_DEFERRED_PLUGINS.includes(plugin.id) && table.columns.some((column) => column.name === USER_KEY)) userTables.push(table.name);
220
226
  }
221
227
  if (delta.tables.length === 0 && delta.columns.length === 0) continue;
222
228
  const key = pluginMigrationKey(plugin.id);
@@ -229,7 +235,8 @@ function authPluginPlan(plugins) {
229
235
  }
230
236
  return {
231
237
  migrations,
232
- extensions
238
+ extensions,
239
+ userTables
233
240
  };
234
241
  }
235
242
  //#endregion
@@ -10,12 +10,14 @@
10
10
  * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
11
11
  * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
12
12
  *
13
- * `0003` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
13
+ * `0003`, `0004` and `0005` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
14
14
  * its subject is that one migration's own `up` and `down`, so it names it directly.
15
15
  */
16
16
  export declare const AUTH_MIGRATIONS: {
17
17
  readonly "0001_init": import("kysely/migration").Migration;
18
18
  readonly "0002_session_authenticated_at": import("kysely/migration").Migration;
19
19
  readonly "0003_account_issuer_nullable": import("kysely/migration").Migration;
20
+ readonly "0004_user_lifecycle": import("kysely/migration").Migration;
21
+ readonly "0005_purge_once": import("kysely/migration").Migration;
20
22
  };
21
23
  //# sourceMappingURL=set.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"set.d.ts","sourceRoot":"","sources":["../../src/migrations/set.ts"],"names":[],"mappings":"AAOA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,eAAe;aAC1B,WAAW;aACX,+BAA+B;aAC/B,8BAA8B;CACtB,CAAC"}
1
+ {"version":3,"file":"set.d.ts","sourceRoot":"","sources":["../../src/migrations/set.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,eAAe;aAC1B,WAAW;aACX,+BAA+B;aAC/B,8BAA8B;aAC9B,qBAAqB;aACrB,iBAAiB;CACT,CAAC"}
@@ -3,6 +3,8 @@
3
3
  import { auth_0001_init } from "./0001_init.js";
4
4
  import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at.js";
5
5
  import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullable.js";
6
+ import { auth_0004_user_lifecycle } from "./0004_user_lifecycle.js";
7
+ import { auth_0005_purge_once } from "./0005_purge_once.js";
6
8
  //#region src/migrations/set.ts
7
9
  /**
8
10
  * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
@@ -14,13 +16,15 @@ import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullabl
14
16
  * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
15
17
  * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
16
18
  *
17
- * `0003` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
19
+ * `0003`, `0004` and `0005` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
18
20
  * its subject is that one migration's own `up` and `down`, so it names it directly.
19
21
  */
20
22
  const AUTH_MIGRATIONS = {
21
23
  "0001_init": auth_0001_init,
22
24
  "0002_session_authenticated_at": auth_0002_session_authenticated_at,
23
- "0003_account_issuer_nullable": auth_0003_account_issuer_nullable
25
+ "0003_account_issuer_nullable": auth_0003_account_issuer_nullable,
26
+ "0004_user_lifecycle": auth_0004_user_lifecycle,
27
+ "0005_purge_once": auth_0005_purge_once
24
28
  };
25
29
  //#endregion
26
30
  export { AUTH_MIGRATIONS };
package/dist/peer.d.ts CHANGED
@@ -30,6 +30,10 @@ export declare const authPeer: {
30
30
  locale: import("zod").ZodNullable<import("zod").ZodString>;
31
31
  createdAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
32
32
  updatedAt: import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodString, import("zod").ZodNumber, import("zod").ZodDate]>, import("zod").ZodDate>;
33
+ suspendedAt: import("zod").ZodOptional<import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>>>;
34
+ suspendedUntil: import("zod").ZodOptional<import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>>>;
35
+ deletedAt: import("zod").ZodOptional<import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>>>;
36
+ purgeAfter: import("zod").ZodOptional<import("zod").ZodNullable<import("zod").ZodCodec<import("zod").ZodUnion<readonly [import("zod").ZodNumber, import("zod").ZodString, import("zod").ZodDate]>, import("zod").ZodDate>>>;
33
37
  }, import("zod/v4/core").$strip>;
34
38
  readonly Device: import("zod").ZodObject<{
35
39
  id: import("zod").ZodString;
@@ -1 +1 @@
1
- {"version":3,"file":"peer.d.ts","sourceRoot":"","sources":["../src/peer.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAA0C,CAAC;AAEhE,4DAA4D;AAC5D,MAAM,MAAM,QAAQ,GAAG,OAAO,QAAQ,CAAC"}
1
+ {"version":3,"file":"peer.d.ts","sourceRoot":"","sources":["../src/peer.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAA0C,CAAC;AAEhE,4DAA4D;AAC5D,MAAM,MAAM,QAAQ,GAAG,OAAO,QAAQ,CAAC"}
@@ -0,0 +1,47 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import type { PurgeContribution } from "@pithy-sh/core/src/capability/purge";
5
+ import { type AuthDatabase } from "../data/tables";
6
+ import type { AuthUserExport } from "../http/responses";
7
+ /**
8
+ * Auth's own purge contribution (#622): what erasing one person means for the `pithy_auth_*` tables, and what
9
+ * exporting them hands back.
10
+ *
11
+ * **Every row keyed to the account goes, except its history.** The user row, its sessions, its linked
12
+ * providers, its devices, its refresh-token ledger, any sign-in code or link still pending for its address,
13
+ * and its rows in every table a composed Better Auth plugin created keyed by `userId` — a two-factor secret
14
+ * and its backup codes, a passkey, an API key. Those tables have no foreign key to the user row, so deleting
15
+ * 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
16
+ * erased, and it names the account by id and holds nothing else about the person (`../data/userLifecycle.ts`).
17
+ * The rate-limit and JWKS tables are keyed to no person and are not touched.
18
+ *
19
+ * **One transaction.** The deletes are one `d1.batch()`, which D1 runs as one, so a failure leaves every row
20
+ * where it was and the retried step erases the lot. **Idempotent**, as the contract requires: a second run
21
+ * finds no rows and deletes nothing, and succeeds.
22
+ *
23
+ * The purge Workflow runs this step **last**, after every other capability's and after the deletion-complete
24
+ * mail, because the address that mail is sent to lives on the user row this deletes.
25
+ */
26
+ /** The one sentence the purge records with this step. */
27
+ export declare const AUTH_PURGE_SUMMARY = "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.";
28
+ /**
29
+ * Erase one account's `pithy_auth_*` rows, its history excepted. Succeeds, having found nothing, when they are
30
+ * already gone.
31
+ *
32
+ * The pending sign-in codes are found by the address, which is why it is read first: an email OTP's identifier
33
+ * is `<type>-otp-<address>`, and a magic link's value is JSON carrying `"email":"<address>"`. With the user row
34
+ * already gone there is no address to look for, and none is needed — a code lives for minutes.
35
+ */
36
+ export declare function eraseAuthUser(db: AuthDatabase, d1: D1Database, userId: string, pluginTables?: readonly string[]): Promise<void>;
37
+ /**
38
+ * What auth holds about one account, for an export: the account, its sessions, providers, devices and
39
+ * history, every list whole. `null` when there is no account to export.
40
+ */
41
+ export declare function exportAuthUser(db: AuthDatabase, userId: string, pluginTables?: readonly string[]): Promise<AuthUserExport | null>;
42
+ /**
43
+ * The contribution `auth()` declares, over the D1 binding its config names. The export of an account that is
44
+ * not there is an empty object, which the route never reaches: it answers 404 before it reads any capability.
45
+ */
46
+ export declare function authPurgeContribution(database: string, pluginTables?: readonly string[]): PurgeContribution;
47
+ //# sourceMappingURL=contribution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contribution.d.ts","sourceRoot":"","sources":["../../src/purge/contribution.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAgB,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAK3F,OAAO,EAAE,KAAK,YAAY,EAAgB,MAAM,gBAAgB,CAAC;AAEjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGxD;;;;;;;;;;;;;;;;;;GAkBG;AAEH,yDAAyD;AACzD,eAAO,MAAM,kBAAkB,uMACuK,CAAC;AAqCvM;;;;;;;GAOG;AACH,wBAAsB,aAAa,CACjC,EAAE,EAAE,YAAY,EAChB,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,YAAY,GAAE,SAAS,MAAM,EAAO,GACnC,OAAO,CAAC,IAAI,CAAC,CA8Bf;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,EAAE,EAAE,YAAY,EAChB,MAAM,EAAE,MAAM,EACd,YAAY,GAAE,SAAS,MAAM,EAAO,GACnC,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAoChC;AAUD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,YAAY,GAAE,SAAS,MAAM,EAAO,GAAG,iBAAiB,CAc/G"}
@@ -0,0 +1,141 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { Account, Session, User } from "../data/betterAuth.js";
4
+ import { Device } from "../data/device.js";
5
+ import { UserLifecycleEvent } from "../data/userLifecycle.js";
6
+ import { authDatabase } from "../data/tables.js";
7
+ import { authUserExportView } from "../http/views.js";
8
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
9
+ import { sql } from "kysely";
10
+ //#region src/purge/contribution.ts
11
+ /**
12
+ * Auth's own purge contribution (#622): what erasing one person means for the `pithy_auth_*` tables, and what
13
+ * exporting them hands back.
14
+ *
15
+ * **Every row keyed to the account goes, except its history.** The user row, its sessions, its linked
16
+ * providers, its devices, its refresh-token ledger, any sign-in code or link still pending for its address,
17
+ * and its rows in every table a composed Better Auth plugin created keyed by `userId` — a two-factor secret
18
+ * and its backup codes, a passkey, an API key. Those tables have no foreign key to the user row, so deleting
19
+ * 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
20
+ * erased, and it names the account by id and holds nothing else about the person (`../data/userLifecycle.ts`).
21
+ * The rate-limit and JWKS tables are keyed to no person and are not touched.
22
+ *
23
+ * **One transaction.** The deletes are one `d1.batch()`, which D1 runs as one, so a failure leaves every row
24
+ * where it was and the retried step erases the lot. **Idempotent**, as the contract requires: a second run
25
+ * finds no rows and deletes nothing, and succeeds.
26
+ *
27
+ * The purge Workflow runs this step **last**, after every other capability's and after the deletion-complete
28
+ * mail, because the address that mail is sent to lives on the user row this deletes.
29
+ */
30
+ /** The one sentence the purge records with this step. */
31
+ const AUTH_PURGE_SUMMARY = "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.";
32
+ /**
33
+ * A plugin table's column that holds a credential — a TOTP secret, backup codes, a key or its hash, a token.
34
+ * The export leaves these out, as it leaves out a session's token and a provider's: an access request is
35
+ * answered with what is held, never with the means to sign in as the person.
36
+ */
37
+ const CREDENTIAL_COLUMN = /secret|token|key|code|hash|password|credential/i;
38
+ /** The auth Kysely without its table map — a plugin's table is named by the plan, not by `authTables`. */
39
+ function untyped(db) {
40
+ return db;
41
+ }
42
+ /** The D1 binding the auth tables live in, off a run's env — or a wiring fault naming it. */
43
+ function bindingOf(env, database) {
44
+ const binding = env[database];
45
+ if (typeof binding !== "object" || binding === null) throw new InternalError({
46
+ message: "The auth database is not bound, so this purge step could not run.",
47
+ action: `Bind the ${database} D1 database to the Worker that runs the purge.`,
48
+ detail: `auth purge contribution found no ${database} binding on the env`
49
+ });
50
+ return binding;
51
+ }
52
+ /** `%` and `_` escaped, so an address is matched as itself inside a LIKE pattern and nothing wider. */
53
+ function literal(value) {
54
+ return value.replace(/[\\%_]/g, (character) => `\\${character}`);
55
+ }
56
+ /** Bind a compiled statement to D1, so it can join a `batch`. */
57
+ function prepared(d1, compiled) {
58
+ return d1.prepare(compiled.sql).bind(...compiled.parameters);
59
+ }
60
+ /**
61
+ * Erase one account's `pithy_auth_*` rows, its history excepted. Succeeds, having found nothing, when they are
62
+ * already gone.
63
+ *
64
+ * The pending sign-in codes are found by the address, which is why it is read first: an email OTP's identifier
65
+ * is `<type>-otp-<address>`, and a magic link's value is JSON carrying `"email":"<address>"`. With the user row
66
+ * already gone there is no address to look for, and none is needed — a code lives for minutes.
67
+ */
68
+ async function eraseAuthUser(db, d1, userId, pluginTables = []) {
69
+ const user = await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst();
70
+ const statements = [
71
+ db.deleteFrom("pithyAuthSessions").where("userId", "=", userId),
72
+ db.deleteFrom("pithyAuthAccounts").where("userId", "=", userId),
73
+ db.deleteFrom("pithyAuthDevices").where("userId", "=", userId),
74
+ db.deleteFrom("pithyAuthRotatedTokens").where("userId", "=", userId)
75
+ ].map((query) => prepared(d1, query.compile()));
76
+ for (const table of pluginTables) statements.push(prepared(d1, untyped(db).deleteFrom(table).where("userId", "=", userId).compile()));
77
+ if (user) {
78
+ const address = literal(user.email);
79
+ const otp = `%-otp-${address}`;
80
+ const changingFrom = `%-otp-${address}-%`;
81
+ const link = `%"email":${literal(JSON.stringify(user.email))}%`;
82
+ const pending = db.deleteFrom("pithyAuthVerifications").where(sql`(identifier like ${otp} escape '\\' or identifier like ${changingFrom} escape '\\' or value like ${link} escape '\\')`);
83
+ statements.push(prepared(d1, pending.compile()));
84
+ }
85
+ statements.push(prepared(d1, db.deleteFrom("pithyAuthUsers").where("id", "=", userId).compile()));
86
+ await d1.batch(statements);
87
+ }
88
+ /**
89
+ * What auth holds about one account, for an export: the account, its sessions, providers, devices and
90
+ * history, every list whole. `null` when there is no account to export.
91
+ */
92
+ async function exportAuthUser(db, userId, pluginTables = []) {
93
+ const row = await db.selectFrom("pithyAuthUsers").selectAll().where("id", "=", userId).executeTakeFirst();
94
+ if (!row) return null;
95
+ const [sessions, accounts, devices, history, plugins] = await Promise.all([
96
+ db.selectFrom("pithyAuthSessions").selectAll().where("userId", "=", userId).orderBy("createdAt", "desc").orderBy("id", "desc").execute(),
97
+ db.selectFrom("pithyAuthAccounts").select(["providerId", "createdAt"]).where("userId", "=", userId).orderBy("providerId", "asc").execute(),
98
+ db.selectFrom("pithyAuthDevices").selectAll().where("userId", "=", userId).orderBy("lastSeenAt", "desc").orderBy("id", "desc").execute(),
99
+ db.selectFrom("pithyAuthUserLifecycle").selectAll().where("userId", "=", userId).orderBy("id", "asc").execute(),
100
+ Promise.all(pluginTables.map(async (table) => [table, await pluginRows(db, table, userId)]))
101
+ ]);
102
+ return authUserExportView({
103
+ user: User.parse(row),
104
+ sessions: sessions.map((session) => Session.parse(session)),
105
+ accounts: accounts.map((account) => Account.pick({
106
+ providerId: true,
107
+ createdAt: true
108
+ }).parse(account)),
109
+ devices: devices.map((device) => Device.parse(device)),
110
+ history: history.map((event) => UserLifecycleEvent.parse(event)),
111
+ plugins: Object.fromEntries(plugins)
112
+ });
113
+ }
114
+ /** One plugin table's rows about the account, every column but a credential's. */
115
+ async function pluginRows(db, table, userId) {
116
+ return (await untyped(db).selectFrom(table).selectAll().where("userId", "=", userId).execute()).map((row) => Object.fromEntries(Object.entries(row).filter(([column]) => !CREDENTIAL_COLUMN.test(column))));
117
+ }
118
+ /**
119
+ * The contribution `auth()` declares, over the D1 binding its config names. The export of an account that is
120
+ * not there is an empty object, which the route never reaches: it answers 404 before it reads any capability.
121
+ */
122
+ function authPurgeContribution(database, pluginTables = []) {
123
+ const open = (context) => {
124
+ const d1 = bindingOf(context.env, database);
125
+ return {
126
+ d1,
127
+ db: authDatabase(d1)
128
+ };
129
+ };
130
+ return {
131
+ subject: "user",
132
+ summary: AUTH_PURGE_SUMMARY,
133
+ erase: async (context) => {
134
+ const { d1, db } = open(context);
135
+ await eraseAuthUser(db, d1, context.subject.id, pluginTables);
136
+ },
137
+ export: async (context) => await exportAuthUser(open(context).db, context.subject.id, pluginTables) ?? {}
138
+ };
139
+ }
140
+ //#endregion
141
+ export { AUTH_PURGE_SUMMARY, authPurgeContribution, eraseAuthUser, exportAuthUser };
@@ -0,0 +1,22 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { WorkflowRetryPolicy } from "@pithy-sh/core/src/workflow/faults";
4
+ /**
5
+ * **What the purge's own steps retry, and what they refuse to** (#622).
6
+ *
7
+ * The purge's own steps — reading whether the account is due, the last mail, the final record — and the daily
8
+ * pass's are D1, and core answers for D1's transient vocabulary through `withD1Retry`. There is no `auth/*`
9
+ * code a second attempt can answer differently, so the record is empty, and that is a statement: an account
10
+ * that is not due, or a binding that is not there, is the same answer next time.
11
+ *
12
+ * **A capability's erase step is not classified here, deliberately.** It runs the contribution's own code —
13
+ * another capability's, or the adopter's — whose fault vocabulary the kit cannot know, and the contract makes
14
+ * every `erase` idempotent precisely so that any fault in it can be retried. So the purge hands those steps to
15
+ * the platform's own retry, with its backoff: a failing contribution retries alone, and the steps that finished
16
+ * are served from the journal. That is the classification, stated at its one site, `./run.ts`.
17
+ *
18
+ * **The cron is the outer retry.** A pass whose `start` step fails is run again the next day, and a purge whose
19
+ * instance failed is started again for the account still past its window.
20
+ */
21
+ export declare const authWorkflowRetry: WorkflowRetryPolicy;
22
+ //# sourceMappingURL=retryPolicy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retryPolicy.d.ts","sourceRoot":"","sources":["../../src/purge/retryPolicy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAE9E;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,iBAAiB,EAAE,mBAG/B,CAAC"}
@@ -0,0 +1,26 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/purge/retryPolicy.ts
4
+ /**
5
+ * **What the purge's own steps retry, and what they refuse to** (#622).
6
+ *
7
+ * The purge's own steps — reading whether the account is due, the last mail, the final record — and the daily
8
+ * pass's are D1, and core answers for D1's transient vocabulary through `withD1Retry`. There is no `auth/*`
9
+ * code a second attempt can answer differently, so the record is empty, and that is a statement: an account
10
+ * that is not due, or a binding that is not there, is the same answer next time.
11
+ *
12
+ * **A capability's erase step is not classified here, deliberately.** It runs the contribution's own code —
13
+ * another capability's, or the adopter's — whose fault vocabulary the kit cannot know, and the contract makes
14
+ * every `erase` idempotent precisely so that any fault in it can be retried. So the purge hands those steps to
15
+ * the platform's own retry, with its backoff: a failing contribution retries alone, and the steps that finished
16
+ * are served from the journal. That is the classification, stated at its one site, `./run.ts`.
17
+ *
18
+ * **The cron is the outer retry.** A pass whose `start` step fails is run again the next day, and a purge whose
19
+ * instance failed is started again for the account still past its window.
20
+ */
21
+ const authWorkflowRetry = {
22
+ capability: "auth",
23
+ retryable: {}
24
+ };
25
+ //#endregion
26
+ export { authWorkflowRetry };
@@ -0,0 +1,88 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PurgeStep } from "@pithy-sh/core/src/capability/purge";
4
+ import { type TerminalErrorConstructor, type WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
5
+ import { type DuePurge, type LifecycleDeps } from "../lifecycle/transitions";
6
+ import { type AuthPurgeDueParams, type AuthPurgeParams } from "./specs";
7
+ /**
8
+ * The purge, as steps (#622) — the bodies `./workflow.ts` hands a Workflow's step runner to.
9
+ *
10
+ * ## One step per contribution, and the order they run in
11
+ *
12
+ * 1. **`due`** — is the account deleted, and has its window closed? A restored account, one inside its window,
13
+ * and one already erased all end the run here, having erased nothing. This is the one check a cron-started
14
+ * purge and a hard deletion's both pass through, so re-running a purge for the same subject exits cleanly.
15
+ * 2. **`erase <capability>`** — one step per composed contribution, in composition order, each recording that it
16
+ * ran in `pithy_auth_user_lifecycle`. Handed to the platform's retry unclassified: an `erase` is idempotent by
17
+ * contract and runs code the kit did not write, so any fault in it is worth another attempt (`./retryPolicy.ts`).
18
+ * A failing contribution retries alone, and the ones that finished are served from the journal.
19
+ * 3. **`mail`** — the deletion-complete mail, **before the address is erased**: every other capability's rows are
20
+ * gone, and auth's, which hold the address, are not yet. The address is read in the step, never carried out of
21
+ * one, so it is in no Workflow's journal.
22
+ * 4. **`erase auth`** — auth's own contribution, last for that reason.
23
+ * 5. **`complete`** — the `purged` record, the audit event, `onUserPurged`. Once.
24
+ */
25
+ /** What a purge does with the account's own records — the transitions, over one set of dependencies. */
26
+ export interface PurgeOps {
27
+ /** Whether the account is due: deleted, with its window closed. `gone` when there is no account. */
28
+ due(userId: string): Promise<"due" | "not_due" | "gone">;
29
+ /** Record that one capability's step erased its rows. */
30
+ recordStep(userId: string, step: string, summary: string): Promise<void>;
31
+ /**
32
+ * Send the deletion-complete mail to the account's address, if it is still there to read, unless this purge's
33
+ * `notify` or the deletion's own saved choice is false. Says whether.
34
+ */
35
+ mailComplete(userId: string, notify: boolean | undefined): Promise<boolean>;
36
+ /** Write the `purged` record, the audit event and the hook. Says whether this call wrote them. */
37
+ complete(userId: string): Promise<boolean>;
38
+ }
39
+ /** The operations, over the lifecycle transitions. */
40
+ export declare function purgeOps(deps: LifecycleDeps): PurgeOps;
41
+ /** What one purge did: the account, how it ended, and the capabilities whose rows it erased. */
42
+ export interface PurgeOutcome {
43
+ /** The account. */
44
+ readonly userId: string;
45
+ /** `purged`, or why nothing was erased: `not_due` (restored, or inside its window) and `gone` (no account). */
46
+ readonly state: "purged" | "not_due" | "gone";
47
+ /** Every step that erased its rows, in the order it ran. Empty when nothing was erased. */
48
+ readonly erased: readonly string[];
49
+ /** Whether the deletion-complete mail was enqueued. */
50
+ readonly mailed: boolean;
51
+ }
52
+ /** What one purge reads its plan from: the composed contributions, this run's env, and its operations. */
53
+ export interface PurgeRun {
54
+ /** Every composed purge step for `user`, auth's own among them. */
55
+ readonly steps: readonly PurgeStep[];
56
+ /** This run's bindings, handed to each contribution. */
57
+ readonly env: Record<string, unknown>;
58
+ /** The account's own records. */
59
+ readonly ops: PurgeOps;
60
+ }
61
+ /** Run one account's purge, one step per contribution, auth's last. See the file header for the order. */
62
+ export declare function purgeUser(run: PurgeRun, step: WorkflowStepLike, terminalError: TerminalErrorConstructor, params: AuthPurgeParams): Promise<PurgeOutcome>;
63
+ /** How many purges one `start` step dispatches — a page, so one pass over a backlog is a bounded number of steps. */
64
+ export declare const PURGE_START_PAGE = 50;
65
+ /** The default size of one daily pass. */
66
+ export declare const PURGE_DUE_DEFAULT_LIMIT = 500;
67
+ /** What the daily pass reads and starts through. */
68
+ export interface PurgeDueRun {
69
+ /** Every account whose purge is due, oldest first, at most `limit`, with the deletion it is due under. */
70
+ due(limit: number): Promise<DuePurge[]>;
71
+ /**
72
+ * Start one account's purge — under the instance id its deletion names, so a start repeated is the same one.
73
+ * Says whether the purge is running: started now, or found already started. `false` when it could not be
74
+ * started, and the pass does not count it.
75
+ */
76
+ start(due: DuePurge): Promise<boolean>;
77
+ }
78
+ /**
79
+ * The daily pass (#622): list every account past its window, and start a purge for each — in pages, one step
80
+ * each, so a pass that dies part-way resumes after the page it finished rather than starting every purge
81
+ * again. An account still inside its window is not listed, so it is not started.
82
+ */
83
+ export declare function startDuePurges(run: PurgeDueRun, step: WorkflowStepLike, terminalError: TerminalErrorConstructor, params: AuthPurgeDueParams): Promise<{
84
+ started: number;
85
+ }>;
86
+ /** The daily pass's reads, over the lifecycle transitions. */
87
+ export declare function duePurgesOf(deps: LifecycleDeps): PurgeDueRun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