@pithy-sh/auth 0.10.0 → 0.12.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 (283) hide show
  1. package/README.md +30 -2
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +58 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +59 -1
  6. package/dist/audit/emit.d.ts +36 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +48 -2
  9. package/dist/audit/evidence.d.ts +8 -2
  10. package/dist/audit/evidence.d.ts.map +1 -1
  11. package/dist/capability.d.ts +47 -8
  12. package/dist/capability.d.ts.map +1 -1
  13. package/dist/capability.js +56 -6
  14. package/dist/client/api.d.ts +55 -12
  15. package/dist/client/api.d.ts.map +1 -1
  16. package/dist/client/api.js +57 -18
  17. package/dist/client/bearer.d.ts +110 -0
  18. package/dist/client/bearer.d.ts.map +1 -0
  19. package/dist/client/bearer.js +265 -0
  20. package/dist/client/handoff.d.ts +77 -0
  21. package/dist/client/handoff.d.ts.map +1 -0
  22. package/dist/client/handoff.js +119 -0
  23. package/dist/client/mcp.d.ts +70 -0
  24. package/dist/client/mcp.d.ts.map +1 -0
  25. package/dist/client/mcp.js +65 -0
  26. package/dist/data/betterAuth.d.ts +3 -2
  27. package/dist/data/betterAuth.d.ts.map +1 -1
  28. package/dist/data/betterAuth.js +5 -3
  29. package/dist/data/kitFields.d.ts +5 -0
  30. package/dist/data/kitFields.d.ts.map +1 -1
  31. package/dist/data/kitFields.js +5 -0
  32. package/dist/data/tables.d.ts +26 -4
  33. package/dist/data/tables.d.ts.map +1 -1
  34. package/dist/data/tables.js +5 -3
  35. package/dist/data/userLifecycle.d.ts +10 -0
  36. package/dist/data/userLifecycle.d.ts.map +1 -1
  37. package/dist/data/userLifecycle.js +8 -3
  38. package/dist/data/verificationOutcome.d.ts +53 -0
  39. package/dist/data/verificationOutcome.d.ts.map +1 -0
  40. package/dist/data/verificationOutcome.js +50 -0
  41. package/dist/email/send.js +6 -2
  42. package/dist/http/adminRoutes.d.ts.map +1 -1
  43. package/dist/http/adminRoutes.js +319 -8
  44. package/dist/http/csrf.d.ts.map +1 -1
  45. package/dist/http/csrf.js +2 -1
  46. package/dist/http/guards.d.ts +15 -10
  47. package/dist/http/guards.d.ts.map +1 -1
  48. package/dist/http/guards.js +76 -10
  49. package/dist/http/handoff.d.ts +76 -0
  50. package/dist/http/handoff.d.ts.map +1 -0
  51. package/dist/http/handoff.js +316 -0
  52. package/dist/http/middleware.d.ts +37 -1
  53. package/dist/http/middleware.d.ts.map +1 -1
  54. package/dist/http/middleware.js +68 -6
  55. package/dist/http/resolve.d.ts.map +1 -1
  56. package/dist/http/resolve.js +9 -3
  57. package/dist/http/responses.d.ts +322 -0
  58. package/dist/http/responses.d.ts.map +1 -1
  59. package/dist/http/responses.js +202 -5
  60. package/dist/http/routes.d.ts +3 -0
  61. package/dist/http/routes.d.ts.map +1 -1
  62. package/dist/http/routes.js +78 -5
  63. package/dist/http/schemas.d.ts +114 -0
  64. package/dist/http/schemas.d.ts.map +1 -1
  65. package/dist/http/schemas.js +94 -1
  66. package/dist/http/views.d.ts +60 -3
  67. package/dist/http/views.d.ts.map +1 -1
  68. package/dist/http/views.js +143 -3
  69. package/dist/index.d.ts +2 -0
  70. package/dist/index.d.ts.map +1 -1
  71. package/dist/index.js +4 -2
  72. package/dist/instance/auth.d.ts +148 -10
  73. package/dist/instance/auth.d.ts.map +1 -1
  74. package/dist/instance/auth.js +87 -42
  75. package/dist/instance/plugins.d.ts +6 -0
  76. package/dist/instance/plugins.d.ts.map +1 -1
  77. package/dist/instance/plugins.js +14 -1
  78. package/dist/ledger/read.d.ts +53 -0
  79. package/dist/ledger/read.d.ts.map +1 -0
  80. package/dist/ledger/read.js +85 -0
  81. package/dist/ledger/record.d.ts +35 -0
  82. package/dist/ledger/record.d.ts.map +1 -0
  83. package/dist/ledger/record.js +98 -0
  84. package/dist/lifecycle/audited.d.ts +48 -0
  85. package/dist/lifecycle/audited.d.ts.map +1 -0
  86. package/dist/lifecycle/audited.js +65 -0
  87. package/dist/lifecycle/enforce.d.ts +37 -2
  88. package/dist/lifecycle/enforce.d.ts.map +1 -1
  89. package/dist/lifecycle/enforce.js +46 -5
  90. package/dist/lifecycle/erasure.d.ts +9 -0
  91. package/dist/lifecycle/erasure.d.ts.map +1 -0
  92. package/dist/lifecycle/erasure.js +96 -0
  93. package/dist/lifecycle/inactivity.d.ts +19 -0
  94. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  95. package/dist/lifecycle/inactivity.js +28 -0
  96. package/dist/lifecycle/reason.d.ts +11 -0
  97. package/dist/lifecycle/reason.d.ts.map +1 -0
  98. package/dist/lifecycle/reason.js +13 -0
  99. package/dist/lifecycle/request.d.ts +5 -2
  100. package/dist/lifecycle/request.d.ts.map +1 -1
  101. package/dist/lifecycle/request.js +6 -2
  102. package/dist/lifecycle/transitions.d.ts +179 -18
  103. package/dist/lifecycle/transitions.d.ts.map +1 -1
  104. package/dist/lifecycle/transitions.js +391 -70
  105. package/dist/mcp/argumentClass.d.ts +51 -0
  106. package/dist/mcp/argumentClass.d.ts.map +1 -0
  107. package/dist/mcp/argumentClass.js +69 -0
  108. package/dist/mcp/capability.d.ts +50 -0
  109. package/dist/mcp/capability.d.ts.map +1 -0
  110. package/dist/mcp/capability.js +140 -0
  111. package/dist/mcp/clientMetadata.d.ts +40 -0
  112. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  113. package/dist/mcp/clientMetadata.js +68 -0
  114. package/dist/mcp/consent.d.ts +49 -0
  115. package/dist/mcp/consent.d.ts.map +1 -0
  116. package/dist/mcp/consent.js +69 -0
  117. package/dist/mcp/dispatch.d.ts +35 -0
  118. package/dist/mcp/dispatch.d.ts.map +1 -0
  119. package/dist/mcp/dispatch.js +135 -0
  120. package/dist/mcp/floor.d.ts +37 -0
  121. package/dist/mcp/floor.d.ts.map +1 -0
  122. package/dist/mcp/floor.js +41 -0
  123. package/dist/mcp/host.d.ts +34 -0
  124. package/dist/mcp/host.d.ts.map +1 -0
  125. package/dist/mcp/host.js +2 -0
  126. package/dist/mcp/http/redirectList.d.ts +9 -0
  127. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  128. package/dist/mcp/http/redirectList.js +24 -0
  129. package/dist/mcp/http/responses.d.ts +143 -0
  130. package/dist/mcp/http/responses.d.ts.map +1 -0
  131. package/dist/mcp/http/responses.js +83 -0
  132. package/dist/mcp/http/routes.d.ts +28 -0
  133. package/dist/mcp/http/routes.d.ts.map +1 -0
  134. package/dist/mcp/http/routes.js +517 -0
  135. package/dist/mcp/http/schemas.d.ts +24 -0
  136. package/dist/mcp/http/schemas.d.ts.map +1 -0
  137. package/dist/mcp/http/schemas.js +18 -0
  138. package/dist/mcp/marker.d.ts +15 -0
  139. package/dist/mcp/marker.d.ts.map +1 -0
  140. package/dist/mcp/marker.js +15 -0
  141. package/dist/mcp/provider.d.ts +78 -0
  142. package/dist/mcp/provider.d.ts.map +1 -0
  143. package/dist/mcp/provider.js +108 -0
  144. package/dist/mcp/purge.d.ts +15 -0
  145. package/dist/mcp/purge.d.ts.map +1 -0
  146. package/dist/mcp/purge.js +31 -0
  147. package/dist/mcp/rpc.d.ts +79 -0
  148. package/dist/mcp/rpc.d.ts.map +1 -0
  149. package/dist/mcp/rpc.js +103 -0
  150. package/dist/mcp/toolAudit.d.ts +76 -0
  151. package/dist/mcp/toolAudit.d.ts.map +1 -0
  152. package/dist/mcp/toolAudit.js +86 -0
  153. package/dist/migrations/0005_purge_once.d.ts +22 -0
  154. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  155. package/dist/migrations/0005_purge_once.js +35 -0
  156. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  157. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  158. package/dist/migrations/0006_verification_outcomes.js +35 -0
  159. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  160. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  161. package/dist/migrations/0007_erasure_record.js +36 -0
  162. package/dist/migrations/0008_last_active.d.ts +15 -0
  163. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  164. package/dist/migrations/0008_last_active.js +29 -0
  165. package/dist/migrations/pluginTables.d.ts +8 -0
  166. package/dist/migrations/pluginTables.d.ts.map +1 -1
  167. package/dist/migrations/pluginTables.js +8 -1
  168. package/dist/migrations/set.d.ts +5 -1
  169. package/dist/migrations/set.d.ts.map +1 -1
  170. package/dist/migrations/set.js +10 -2
  171. package/dist/peer.d.ts +3 -2
  172. package/dist/peer.d.ts.map +1 -1
  173. package/dist/processing/activities.d.ts +6 -0
  174. package/dist/processing/activities.d.ts.map +1 -0
  175. package/dist/processing/activities.js +12 -0
  176. package/dist/purge/contribution.d.ts +62 -0
  177. package/dist/purge/contribution.d.ts.map +1 -0
  178. package/dist/purge/contribution.js +155 -0
  179. package/dist/purge/retryPolicy.d.ts +22 -0
  180. package/dist/purge/retryPolicy.d.ts.map +1 -0
  181. package/dist/purge/retryPolicy.js +26 -0
  182. package/dist/purge/run.d.ts +158 -0
  183. package/dist/purge/run.d.ts.map +1 -0
  184. package/dist/purge/run.js +205 -0
  185. package/dist/purge/specs.d.ts +71 -0
  186. package/dist/purge/specs.d.ts.map +1 -0
  187. package/dist/purge/specs.js +72 -0
  188. package/dist/purge/start.d.ts +42 -0
  189. package/dist/purge/start.d.ts.map +1 -0
  190. package/dist/purge/start.js +37 -0
  191. package/dist/purge/workflow.d.ts +71 -0
  192. package/dist/purge/workflow.d.ts.map +1 -0
  193. package/dist/purge/workflow.js +140 -0
  194. package/dist/test-utils/accountFootprint.d.ts +13 -0
  195. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  196. package/dist/test-utils/accountFootprint.js +49 -0
  197. package/dist/test-utils/liveApp.d.ts +6 -0
  198. package/dist/test-utils/liveApp.d.ts.map +1 -1
  199. package/dist/test-utils/liveApp.js +7 -2
  200. package/dist/token/handoff.d.ts +80 -0
  201. package/dist/token/handoff.d.ts.map +1 -0
  202. package/dist/token/handoff.js +136 -0
  203. package/dist/version.generated.d.ts +1 -1
  204. package/dist/version.generated.js +1 -1
  205. package/docs/account-lifecycle.md +176 -12
  206. package/docs/apple-signin.md +32 -4
  207. package/docs/facebook-oauth.md +2 -2
  208. package/docs/github-oauth.md +2 -2
  209. package/docs/google-oauth.md +9 -7
  210. package/docs/microsoft-oauth.md +2 -2
  211. package/package.json +11 -5
  212. package/pithy.manifest.json +2 -2
  213. package/pithy.mcp.manifest.json +36 -0
  214. package/src/audit/actions.ts +58 -0
  215. package/src/audit/emit.ts +66 -1
  216. package/src/audit/evidence.ts +8 -4
  217. package/src/capability.ts +122 -18
  218. package/src/client/api.ts +69 -19
  219. package/src/client/bearer.ts +388 -0
  220. package/src/client/handoff.ts +172 -0
  221. package/src/client/mcp.ts +140 -0
  222. package/src/data/betterAuth.ts +8 -4
  223. package/src/data/kitFields.ts +2 -0
  224. package/src/data/tables.ts +4 -2
  225. package/src/data/userLifecycle.ts +19 -4
  226. package/src/data/verificationOutcome.ts +86 -0
  227. package/src/email/send.ts +2 -2
  228. package/src/http/adminRoutes.ts +465 -4
  229. package/src/http/csrf.ts +4 -1
  230. package/src/http/guards.ts +79 -10
  231. package/src/http/handoff.ts +350 -0
  232. package/src/http/middleware.ts +74 -5
  233. package/src/http/resolve.ts +25 -25
  234. package/src/http/responses.ts +374 -3
  235. package/src/http/routes.ts +116 -5
  236. package/src/http/schemas.ts +195 -0
  237. package/src/http/views.ts +192 -3
  238. package/src/index.ts +2 -0
  239. package/src/instance/auth.ts +58 -3
  240. package/src/instance/plugins.ts +20 -2
  241. package/src/ledger/read.ts +133 -0
  242. package/src/ledger/record.ts +198 -0
  243. package/src/lifecycle/audited.ts +104 -0
  244. package/src/lifecycle/enforce.ts +55 -5
  245. package/src/lifecycle/erasure.ts +118 -0
  246. package/src/lifecycle/inactivity.ts +56 -0
  247. package/src/lifecycle/reason.ts +11 -0
  248. package/src/lifecycle/request.ts +10 -2
  249. package/src/lifecycle/transitions.ts +552 -93
  250. package/src/mcp/argumentClass.ts +112 -0
  251. package/src/mcp/capability.ts +194 -0
  252. package/src/mcp/clientMetadata.ts +81 -0
  253. package/src/mcp/consent.ts +95 -0
  254. package/src/mcp/dispatch.ts +154 -0
  255. package/src/mcp/floor.ts +62 -0
  256. package/src/mcp/host.ts +36 -0
  257. package/src/mcp/http/redirectList.ts +26 -0
  258. package/src/mcp/http/responses.ts +157 -0
  259. package/src/mcp/http/routes.ts +635 -0
  260. package/src/mcp/http/schemas.ts +37 -0
  261. package/src/mcp/marker.ts +18 -0
  262. package/src/mcp/provider.ts +151 -0
  263. package/src/mcp/purge.ts +39 -0
  264. package/src/mcp/rpc.ts +135 -0
  265. package/src/mcp/toolAudit.ts +132 -0
  266. package/src/migrations/0005_purge_once.ts +42 -0
  267. package/src/migrations/0006_verification_outcomes.ts +51 -0
  268. package/src/migrations/0007_erasure_record.ts +43 -0
  269. package/src/migrations/0008_last_active.ts +30 -0
  270. package/src/migrations/pluginTables.ts +19 -1
  271. package/src/migrations/set.ts +9 -1
  272. package/src/processing/activities.ts +14 -0
  273. package/src/purge/contribution.ts +218 -0
  274. package/src/purge/retryPolicy.ts +26 -0
  275. package/src/purge/run.ts +348 -0
  276. package/src/purge/specs.ts +95 -0
  277. package/src/purge/start.ts +79 -0
  278. package/src/purge/workflow.ts +202 -0
  279. package/src/seeds/example.ts +2 -2
  280. package/src/test-utils/accountFootprint.ts +104 -0
  281. package/src/test-utils/liveApp.ts +10 -1
  282. package/src/token/handoff.ts +180 -0
  283. package/src/version.generated.ts +1 -1
@@ -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,10 @@ 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";
9
+ import { auth_0006_verification_outcomes } from "./0006_verification_outcomes";
10
+ import { auth_0007_erasure_record } from "./0007_erasure_record";
11
+ import { auth_0008_last_active } from "./0008_last_active";
8
12
 
9
13
  /**
10
14
  * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
@@ -16,7 +20,7 @@ import { auth_0004_user_lifecycle } from "./0004_user_lifecycle";
16
20
  * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
17
21
  * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
18
22
  *
19
- * `0003` and `0004` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
23
+ * `0003` through `0007` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
20
24
  * its subject is that one migration's own `up` and `down`, so it names it directly.
21
25
  */
22
26
  export const AUTH_MIGRATIONS = {
@@ -24,4 +28,8 @@ export const AUTH_MIGRATIONS = {
24
28
  "0002_session_authenticated_at": auth_0002_session_authenticated_at,
25
29
  "0003_account_issuer_nullable": auth_0003_account_issuer_nullable,
26
30
  "0004_user_lifecycle": auth_0004_user_lifecycle,
31
+ "0005_purge_once": auth_0005_purge_once,
32
+ "0006_verification_outcomes": auth_0006_verification_outcomes,
33
+ "0007_erasure_record": auth_0007_erasure_record,
34
+ "0008_last_active": auth_0008_last_active,
27
35
  } as const;
@@ -0,0 +1,14 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { ProcessingActivityInput } from "@pithy-sh/core/src/processing/activity";
5
+
6
+ /** What auth does with personal data: it keeps accounts and signs their holders in. */
7
+ export const AUTH_PROCESSING: readonly ProcessingActivityInput[] = [
8
+ {
9
+ id: "auth.account",
10
+ purpose: "Keep a person's account, sign them in, and keep the sessions that prove it.",
11
+ classes: ["pii"],
12
+ legalBasis: "contract",
13
+ },
14
+ ];
@@ -0,0 +1,218 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+ import type { ErasingPurgeContribution, PurgeContext } 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 { VerificationOutcome } from "../data/verificationOutcome";
13
+ import type { AuthUserExport } from "../http/responses";
14
+ import { authUserExportView } from "../http/views";
15
+ import { purgeAddress } from "../lifecycle/transitions";
16
+
17
+ /**
18
+ * Auth's own purge contribution (#622): what erasing one person means for the `pithy_auth_*` tables, and what
19
+ * exporting them hands back.
20
+ *
21
+ * **Every row keyed to the account goes, except its history.** The user row, its sessions, its linked
22
+ * providers, its devices, its refresh-token ledger, any sign-in code or link still pending for its address, its
23
+ * rows in the verification ledger (#829), and its rows in every table a composed Better Auth plugin created keyed by `userId` — a two-factor secret
24
+ * and its backup codes, a passkey, an API key. Those tables have no foreign key to the user row, so deleting
25
+ * 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
26
+ * erased, and it names the account by id and holds nothing else about the person (`../data/userLifecycle.ts`).
27
+ * The rate-limit and JWKS tables are keyed to no person and are not touched.
28
+ *
29
+ * **One transaction.** The deletes are one `d1.batch()`, which D1 runs as one, so a failure leaves every row
30
+ * where it was and the retried step erases the lot. **Idempotent**, as the contract requires: a second run
31
+ * finds no rows and deletes nothing, and succeeds.
32
+ *
33
+ * The purge Workflow runs this step **last**, after every other capability's and after the deletion-complete
34
+ * mail, because the address that mail is sent to lives on the user row this deletes.
35
+ */
36
+
37
+ /** The one sentence the purge records with this step. */
38
+ export const AUTH_PURGE_SUMMARY =
39
+ "Deletes the account, its sessions, linked providers, devices, refresh-token ledger, pending sign-in codes, the record of the sign-in links and codes it was sent, and its rows in the tables its Better Auth plugins created. Its lifecycle history stays.";
40
+
41
+ /**
42
+ * A plugin table's column that holds a credential — a TOTP secret, backup codes, a key or its hash, a token.
43
+ * The export leaves these out, as it leaves out a session's token and a provider's: an access request is
44
+ * answered with what is held, never with the means to sign in as the person.
45
+ */
46
+ const CREDENTIAL_COLUMN = /secret|token|key|code|hash|password|credential/i;
47
+
48
+ /** The auth Kysely without its table map — a plugin's table is named by the plan, not by `authTables`. */
49
+ export function untyped(db: AuthDatabase): Kysely<Record<string, Record<string, unknown>>> {
50
+ return db as unknown as Kysely<Record<string, Record<string, unknown>>>;
51
+ }
52
+
53
+ /** The D1 binding the auth tables live in, off a run's env — or a wiring fault naming it. */
54
+ export function bindingOf(env: Record<string, unknown>, database: string): D1Database {
55
+ const binding = env[database];
56
+ if (typeof binding !== "object" || binding === null) {
57
+ throw new InternalError({
58
+ message: "The auth database is not bound, so this purge step could not run.",
59
+ action: `Bind the ${database} D1 database to the Worker that runs the purge.`,
60
+ detail: `auth purge contribution found no ${database} binding on the env`,
61
+ });
62
+ }
63
+ return binding as D1Database;
64
+ }
65
+
66
+ /** `%` and `_` escaped, so an address is matched as itself inside a LIKE pattern and nothing wider. */
67
+ function literal(value: string): string {
68
+ return value.replace(/[\\%_]/g, (character) => `\\${character}`);
69
+ }
70
+
71
+ /** Bind a compiled statement to D1, so it can join a `batch`. */
72
+ export function prepared(d1: D1Database, compiled: CompiledQuery) {
73
+ return d1.prepare(compiled.sql).bind(...(compiled.parameters as unknown[]));
74
+ }
75
+
76
+ /**
77
+ * Erase one account's `pithy_auth_*` rows, its history excepted. Succeeds, having found nothing, when they are
78
+ * already gone.
79
+ *
80
+ * The pending sign-in codes are found by the address, which is why it is read first: an email OTP's identifier
81
+ * is `<type>-otp-<address>`, and a magic link's value is JSON carrying `"email":"<address>"`. With the user row
82
+ * already gone there is no address to look for, and none is needed — a code lives for minutes.
83
+ */
84
+ export async function eraseAuthUser(
85
+ db: AuthDatabase,
86
+ d1: D1Database,
87
+ userId: string,
88
+ pluginTables: readonly string[] = [],
89
+ ): Promise<void> {
90
+ const user = await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst();
91
+ const statements = [
92
+ db.deleteFrom("pithyAuthSessions").where("userId", "=", userId),
93
+ db.deleteFrom("pithyAuthAccounts").where("userId", "=", userId),
94
+ db.deleteFrom("pithyAuthDevices").where("userId", "=", userId),
95
+ db.deleteFrom("pithyAuthRotatedTokens").where("userId", "=", userId),
96
+ // The sign-in links and codes it was sent (#829). A sign-up nobody completed names no account and holds no
97
+ // address, so there is nothing of the person's in it to find.
98
+ db.deleteFrom("pithyAuthVerificationOutcomes").where("userId", "=", userId),
99
+ ].map((query) => prepared(d1, query.compile()));
100
+ // A plugin's rows, in the same batch: `CamelCasePlugin` snake-cases the table and `user_id` as it does for
101
+ // the plugin's own migration, so the names match what `pithy migrate` created.
102
+ for (const table of pluginTables) {
103
+ statements.push(prepared(d1, untyped(db).deleteFrom(table).where("userId", "=", userId).compile()));
104
+ }
105
+ if (user) {
106
+ const address = literal(user.email);
107
+ const otp = `%-otp-${address}`;
108
+ const changingFrom = `%-otp-${address}-%`;
109
+ const link = `%"email":${literal(JSON.stringify(user.email))}%`;
110
+ // Raw SQL for the predicate, for `users.ts`'s reason: SQLite's `ESCAPE` belongs to the `LIKE` operator, so
111
+ // there is no expression-builder form of it. Both columns are single words, so `CamelCasePlugin` has
112
+ // nothing to rewrite.
113
+ const pending = db
114
+ .deleteFrom("pithyAuthVerifications")
115
+ .where(
116
+ sql<SqlBool>`(identifier like ${otp} escape '\\' or identifier like ${changingFrom} escape '\\' or value like ${link} escape '\\')`,
117
+ );
118
+ statements.push(prepared(d1, pending.compile()));
119
+ }
120
+ statements.push(prepared(d1, db.deleteFrom("pithyAuthUsers").where("id", "=", userId).compile()));
121
+ await d1.batch(statements);
122
+ }
123
+
124
+ /**
125
+ * What auth holds about one account, for an export: the account, its sessions, providers, devices and
126
+ * history, every list whole. `null` when there is no account to export.
127
+ */
128
+ export async function exportAuthUser(
129
+ db: AuthDatabase,
130
+ userId: string,
131
+ pluginTables: readonly string[] = [],
132
+ ): Promise<AuthUserExport | null> {
133
+ const row = await db.selectFrom("pithyAuthUsers").selectAll().where("id", "=", userId).executeTakeFirst();
134
+ if (!row) return null;
135
+ const [sessions, accounts, devices, history, verifications, plugins] = await Promise.all([
136
+ db
137
+ .selectFrom("pithyAuthSessions")
138
+ .selectAll()
139
+ .where("userId", "=", userId)
140
+ .orderBy("createdAt", "desc")
141
+ .orderBy("id", "desc")
142
+ .execute(),
143
+ // Two columns, never `select *`: the account row holds the provider's tokens, and they are never loaded.
144
+ db
145
+ .selectFrom("pithyAuthAccounts")
146
+ .select(["providerId", "createdAt"])
147
+ .where("userId", "=", userId)
148
+ .orderBy("providerId", "asc")
149
+ .execute(),
150
+ db
151
+ .selectFrom("pithyAuthDevices")
152
+ .selectAll()
153
+ .where("userId", "=", userId)
154
+ .orderBy("lastSeenAt", "desc")
155
+ .orderBy("id", "desc")
156
+ .execute(),
157
+ db.selectFrom("pithyAuthUserLifecycle").selectAll().where("userId", "=", userId).orderBy("id", "asc").execute(),
158
+ db
159
+ .selectFrom("pithyAuthVerificationOutcomes")
160
+ .selectAll()
161
+ .where("userId", "=", userId)
162
+ .orderBy("issuedAt", "desc")
163
+ .orderBy("id", "desc")
164
+ .execute(),
165
+ Promise.all(pluginTables.map(async (table) => [table, await pluginRows(db, table, userId)] as const)),
166
+ ]);
167
+ return authUserExportView({
168
+ now: new Date(),
169
+ user: User.parse(row),
170
+ sessions: sessions.map((session) => Session.parse(session)),
171
+ accounts: accounts.map((account) => Account.pick({ providerId: true, createdAt: true }).parse(account)),
172
+ devices: devices.map((device) => Device.parse(device)),
173
+ history: history.map((event) => UserLifecycleEvent.parse(event)),
174
+ verifications: verifications.map((row) => VerificationOutcome.parse(row)),
175
+ plugins: Object.fromEntries(plugins),
176
+ });
177
+ }
178
+
179
+ /** One plugin table's rows about the account, every column but a credential's. */
180
+ export async function pluginRows(db: AuthDatabase, table: string, userId: string): Promise<Record<string, unknown>[]> {
181
+ const rows = await untyped(db).selectFrom(table).selectAll().where("userId", "=", userId).execute();
182
+ return rows.map((row) =>
183
+ Object.fromEntries(Object.entries(row).filter(([column]) => !CREDENTIAL_COLUMN.test(column))),
184
+ );
185
+ }
186
+
187
+ /**
188
+ * The contribution `auth()` declares, over the D1 binding its config names. The export of an account that is
189
+ * not there is an empty object, which the route never reaches: it answers 404 before it reads any capability.
190
+ */
191
+ /**
192
+ * An account's address by user id, over the env's auth database — what auth answers through core's `addressOf`
193
+ * seam, so a capability holding state by address (email's suppression list) finds it without importing auth.
194
+ * `null` for an account that has none, or no longer exists.
195
+ */
196
+ export function authAddressOf(database: string) {
197
+ return (env: Record<string, unknown>, userId: string): Promise<string | null> =>
198
+ purgeAddress(authDatabase(bindingOf(env, database)), userId);
199
+ }
200
+
201
+ export function authPurgeContribution(
202
+ database: string,
203
+ pluginTables: readonly string[] = [],
204
+ ): ErasingPurgeContribution {
205
+ const open = (context: PurgeContext) => {
206
+ const d1 = bindingOf(context.env, database);
207
+ return { d1, db: authDatabase(d1) };
208
+ };
209
+ return {
210
+ subject: "user",
211
+ summary: AUTH_PURGE_SUMMARY,
212
+ erase: async (context) => {
213
+ const { d1, db } = open(context);
214
+ await eraseAuthUser(db, d1, context.subject.id, pluginTables);
215
+ },
216
+ export: async (context) => (await exportAuthUser(open(context).db, context.subject.id, pluginTables)) ?? {},
217
+ };
218
+ }
@@ -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
+ };