@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
@@ -0,0 +1,202 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { composedCapabilities, composedCapability } from "@pithy-sh/core/src/capability/composition";
5
+ import { messageOf } from "@pithy-sh/core/src/error/pithyError";
6
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
7
+ import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
8
+ import { composedRetention, subjectClasses } from "@pithy-sh/core/src/retention/composed";
9
+ import { type LegalHolds, legalHolds } from "@pithy-sh/core/src/retention/holds";
10
+ import { inactivityDays } from "@pithy-sh/core/src/retention/policy";
11
+ import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
12
+ import type { TerminalErrorConstructor, WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
13
+ import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
14
+ import { enqueueFromEnv } from "@pithy-sh/email/src/send/fromComposition";
15
+ import { type AuthCapability, isAuthCapability } from "../capability";
16
+ import { authDatabase } from "../data/tables";
17
+ import { resolveDb } from "../http/resolve";
18
+ import { inactiveAccounts } from "../lifecycle/inactivity";
19
+ import { deleteUser, type LifecycleDeps } from "../lifecycle/transitions";
20
+ import {
21
+ deleteInactiveAccounts,
22
+ duePurgesOf,
23
+ type InactivityRun,
24
+ type PurgeDueRun,
25
+ type PurgeOutcome,
26
+ purgeOps,
27
+ purgeUser,
28
+ startDuePurges,
29
+ } from "./run";
30
+ import { AUTH_PURGE_BINDING, AUTH_PURGE_KEY, AuthPurgeDueParams, AuthPurgeParams } from "./specs";
31
+ import { startPurgeInstance } from "./start";
32
+
33
+ /**
34
+ * The purge's two Workflow bodies (#622) — run by classes **the adopter's own Worker** exports, beside the
35
+ * `createEntrypoint` it already exports, because a purge runs every composed capability's contribution and
36
+ * those exist nowhere else:
37
+ *
38
+ * // apps/api/src/index.ts
39
+ * import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
40
+ * import { NonRetryableError } from "cloudflare:workflows";
41
+ * import { runAuthPurge, runAuthPurgeDue } from "@pithy-sh/auth/src/purge/workflow";
42
+ *
43
+ * export class AuthPurgeWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
44
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
45
+ * return runAuthPurge(this.env, event, step, NonRetryableError);
46
+ * }
47
+ * }
48
+ * export class AuthPurgeDueWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
49
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
50
+ * return runAuthPurgeDue(this.env, event, step, NonRetryableError);
51
+ * }
52
+ * }
53
+ *
54
+ * plus a `workflows` entry binding `AUTH_PURGE` and `AUTH_PURGE_DUE` to them and the daily cron —
55
+ * `docs/account-lifecycle.md` has the stanza. **The class is the adopter's, the body is the kit's**, the split
56
+ * `@pithy-sh/payments`' usage pass has, for the same reason.
57
+ *
58
+ * Each body finds the composed auth capability the way a Workflow that sends mail finds email: the class is
59
+ * exported from the entry that calls `createEntrypoint`, so the composition has happened in this isolate. The
60
+ * steps, the hooks, the config and the audit recorder are on the capability; the mail is email's own enqueue.
61
+ */
62
+
63
+ /** What a Workflow event hands a body. */
64
+ interface PurgeEvent {
65
+ readonly payload?: unknown;
66
+ readonly workflowName?: string;
67
+ readonly instanceId?: string;
68
+ }
69
+
70
+ /** The lifecycle transitions' dependencies, for a run with no request: this env, and the composition's seams. */
71
+ function lifecycleFor(auth: AuthCapability, env: Record<string, unknown>, log: Logger): LifecycleDeps {
72
+ const d1 = resolveDb(env, auth.authConfig.database);
73
+ return {
74
+ db: authDatabase(d1),
75
+ d1,
76
+ emit: auth.auditFor(env),
77
+ config: auth.authConfig,
78
+ hooks: auth.lifecycleHooks,
79
+ enqueueEmail: (input) => enqueueFromEnv(env as unknown as EmailEnqueueEnv, input),
80
+ log,
81
+ };
82
+ }
83
+
84
+ /** This run's logger, bound to the instance an operator reads it under. */
85
+ function runLog(env: Record<string, unknown>, event: PurgeEvent, name: string): Logger {
86
+ return bindWorkflowContext(createWorkerLogger({ name }), {
87
+ workflow: event.workflowName ?? name,
88
+ instance: event.instanceId ?? "unknown",
89
+ env: typeof env.ENVIRONMENT === "string" ? env.ENVIRONMENT : "unknown",
90
+ });
91
+ }
92
+
93
+ /** Purge one account: every composed contribution, one step each, auth's last. See `./run.ts`. */
94
+ export async function runAuthPurge(
95
+ env: Record<string, unknown>,
96
+ event: PurgeEvent,
97
+ step: WorkflowStepLike,
98
+ terminalError: TerminalErrorConstructor,
99
+ ): Promise<PurgeOutcome> {
100
+ // Parsed rather than trusted: an instance can be started by the daily pass, by a hard deletion, or by hand.
101
+ const params = AuthPurgeParams.parse(event.payload ?? {});
102
+ const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
103
+ const lifecycle = lifecycleFor(auth, env, runLog(env, event, "auth:purge"));
104
+ return purgeUser(
105
+ { steps: auth.purgeSteps, env, ops: purgeOps(lifecycle, legalHolds(env)) },
106
+ step,
107
+ terminalError,
108
+ params,
109
+ );
110
+ }
111
+
112
+ /**
113
+ * The daily pass: start a purge for every account past its window, then soft-delete every account inactive past the
114
+ * strictest class age it holds. See `./run.ts`.
115
+ */
116
+ export async function runAuthPurgeDue(
117
+ env: Record<string, unknown>,
118
+ event: PurgeEvent,
119
+ step: WorkflowStepLike,
120
+ terminalError: TerminalErrorConstructor,
121
+ ): Promise<{ started: number; inactive: number }> {
122
+ const params = AuthPurgeDueParams.parse(event.payload ?? {});
123
+ const auth = composedCapability<AuthCapability>("auth", isAuthCapability);
124
+ const log = runLog(env, event, "auth:purge-due");
125
+ const lifecycle = lifecycleFor(auth, env, log);
126
+ const holds = legalHolds(env);
127
+ const { started } = await startDuePurges(
128
+ { due: duePurgesOf(lifecycle), start: purgeStarter(env, log), held: (userId) => holds.held("user", userId) },
129
+ step,
130
+ terminalError,
131
+ params,
132
+ );
133
+ const { deleted } = await deleteInactiveAccounts(inactivityRun(lifecycle, holds), step, terminalError);
134
+ return { started, inactive: deleted };
135
+ }
136
+
137
+ /**
138
+ * The inactivity pass over this composition: the strictest class age among the classes a user's rows hold, from
139
+ * the Worker's resolved `retention` block, and the lifecycle's own soft deletion, by the system, with its notice mail.
140
+ */
141
+ export function inactivityRun(lifecycle: LifecycleDeps, holds: LegalHolds): InactivityRun {
142
+ return inactivityOps(lifecycle, holds, () => {
143
+ const retention = composedRetention();
144
+ return retention ? inactivityDays(retention, subjectClasses(composedCapabilities(), "user")) : null;
145
+ });
146
+ }
147
+
148
+ /** The inactivity pass's reads and deletions over one set of lifecycle dependencies, for a class age in days. */
149
+ export function inactivityOps(lifecycle: LifecycleDeps, holds: LegalHolds, days: () => number | null): InactivityRun {
150
+ return {
151
+ days: async () => days(),
152
+ inactive: (cutoff, limit) => inactiveAccounts(lifecycle.db, cutoff, limit),
153
+ held: (userId) => holds.held("user", userId),
154
+ remove: async (userId, limit) => {
155
+ const deletion = await deleteUser(lifecycle, {
156
+ userId,
157
+ actor: { type: "system", id: null },
158
+ reason: `Inactive for more than ${limit} days, the retention policy's limit for the personal data it holds.`,
159
+ });
160
+ return deletion.outcome === "deleted";
161
+ },
162
+ now: lifecycle.now ?? (() => new Date()),
163
+ };
164
+ }
165
+
166
+ /**
167
+ * How the daily pass starts one account's purge: under the id the deletion names (`./start.ts`), so a purge a hard
168
+ * deletion already started today is the same instance, not a second one. No `notify`: the deletion's own row
169
+ * carries it, and the purge reads it there.
170
+ *
171
+ * **It answers whether the purge is running**, and the pass counts that. A Worker that has not bound the purge,
172
+ * and a start that failed, each log the skip rather than throwing inside a cron nobody watches — tomorrow's pass
173
+ * starts it again — and answer `false`, so the pass does not report a purge it never started.
174
+ */
175
+ export function purgeStarter(
176
+ env: Record<string, unknown>,
177
+ log: Logger,
178
+ now: () => Date = () => new Date(),
179
+ ): PurgeDueRun["start"] {
180
+ return async (due) => {
181
+ const binding = workflowBindingFor(env, AUTH_PURGE_BINDING);
182
+ if (!binding) {
183
+ log.warn("workflow skipped", {
184
+ workflow: AUTH_PURGE_KEY,
185
+ binding: AUTH_PURGE_BINDING,
186
+ reason: "binding absent — the purge Workflow is not bound",
187
+ });
188
+ return false;
189
+ }
190
+ try {
191
+ await startPurgeInstance(binding, { userId: due.userId, deletedAt: due.deletedAt, at: now() });
192
+ return true;
193
+ } catch (error) {
194
+ log.warn("workflow skipped", {
195
+ workflow: AUTH_PURGE_KEY,
196
+ binding: AUTH_PURGE_BINDING,
197
+ reason: messageOf(error),
198
+ });
199
+ return false;
200
+ }
201
+ };
202
+ }
@@ -33,8 +33,8 @@ export const authExampleSeed: SeedSet = defineSeed({
33
33
  User,
34
34
  EXAMPLE_IDENTITIES.map((identity) => ({
35
35
  id: identity.id,
36
- name: identity.name,
37
- email: identity.email,
36
+ name: identity.name as User["name"],
37
+ email: identity.email as User["email"],
38
38
  emailVerified: true,
39
39
  image: null,
40
40
  // The example cast has never picked a language, which is the state most real users are in:
@@ -0,0 +1,104 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database } from "@cloudflare/workers-types";
5
+
6
+ /**
7
+ * One account's rows across every `pithy_auth_*` table that keys a row to a person — what a purge must erase
8
+ * and an export must read (#622). For the workers suites; the tables are the real ones, written by raw SQL in
9
+ * the shapes the kit's own writers produce, so a test reads back exactly what production would hold.
10
+ */
11
+
12
+ const AT = "2026-10-01T00:00:00.000Z";
13
+ const AT_MS = Date.parse(AT);
14
+
15
+ /** Every table a footprint writes to, with the column that names the person in it. */
16
+ export const FOOTPRINT_TABLES = [
17
+ ["pithy_auth_users", "id"],
18
+ ["pithy_auth_sessions", "user_id"],
19
+ ["pithy_auth_accounts", "user_id"],
20
+ ["pithy_auth_devices", "user_id"],
21
+ ["pithy_auth_rotated_tokens", "user_id"],
22
+ ["pithy_auth_verification_outcomes", "user_id"],
23
+ ] as const;
24
+
25
+ /**
26
+ * Write a full footprint for one account: a user, a session, a provider link, a device, a spent token, two pending
27
+ * codes, and the ledger row of a sign-in link it used.
28
+ */
29
+ export async function seedAccountFootprint(
30
+ d1: D1Database,
31
+ userId: string,
32
+ email = `${userId}@test.com`,
33
+ ): Promise<void> {
34
+ await d1.batch([
35
+ d1
36
+ .prepare(
37
+ "insert into pithy_auth_users (id, name, email, email_verified, locale, created_at, updated_at) values (?, 'Sam', ?, 1, null, ?, ?)",
38
+ )
39
+ .bind(userId, email, AT, AT),
40
+ d1
41
+ .prepare(
42
+ "insert into pithy_auth_sessions (id, expires_at, token, created_at, updated_at, ip_address, user_agent, user_id, device_id) values (?, ?, ?, ?, ?, '203.0.113.9', 'Pithy/1.0', ?, ?)",
43
+ )
44
+ .bind(`s-${userId}`, "2099-01-01T00:00:00.000Z", `token-${userId}`, AT, AT, userId, `d-${userId}`),
45
+ d1
46
+ .prepare(
47
+ "insert into pithy_auth_accounts (id, account_id, provider_id, user_id, access_token, refresh_token, created_at, updated_at) values (?, ?, 'google', ?, ?, ?, ?, ?)",
48
+ )
49
+ .bind(`a-${userId}`, `g-${userId}`, userId, `access-${userId}`, `refresh-${userId}`, AT, AT),
50
+ d1
51
+ .prepare(
52
+ "insert into pithy_auth_devices (id, user_id, platform, push_token, last_ip, last_seen_at, created_at) values (?, ?, 'ios', ?, '203.0.113.9', ?, ?)",
53
+ )
54
+ .bind(`d-${userId}`, userId, `push-${userId}`, AT_MS, AT_MS),
55
+ d1
56
+ .prepare("insert into pithy_auth_rotated_tokens (token, family_id, user_id, rotated_at) values (?, ?, ?, ?)")
57
+ .bind(`spent-${userId}`, `f-${userId}`, userId, AT_MS),
58
+ d1
59
+ .prepare(
60
+ "insert into pithy_auth_verification_outcomes (verification_id, type, user_id, email_job_id, issued_at, expires_at, used_at) values (?, 'magic_link', ?, ?, ?, ?, ?)",
61
+ )
62
+ .bind(`used-link-${userId}`, userId, `job-${userId}`, AT_MS, AT_MS + 300_000, AT_MS + 60_000),
63
+ d1
64
+ .prepare(
65
+ "insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, '123456:0', ?, ?, ?)",
66
+ )
67
+ .bind(`otp-${userId}`, `sign-in-otp-${email}`, "2099-01-01T00:00:00.000Z", AT, AT),
68
+ d1
69
+ .prepare(
70
+ "insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, ?, ?, ?, ?)",
71
+ )
72
+ .bind(
73
+ `link-${userId}`,
74
+ `magic-link-${userId}`,
75
+ JSON.stringify({ email, name: "", attempt: 0 }),
76
+ "2099-01-01T00:00:00.000Z",
77
+ AT,
78
+ AT,
79
+ ),
80
+ ]);
81
+ }
82
+
83
+ /** How many rows one account still holds in each footprint table, and in the pending codes for its address. */
84
+ export async function footprintCounts(d1: D1Database, userId: string, email = `${userId}@test.com`) {
85
+ const counts: Record<string, number> = {};
86
+ for (const [table, column] of FOOTPRINT_TABLES) {
87
+ const row = await d1
88
+ .prepare(`select count(*) as n from ${table} where ${column} = ?`)
89
+ .bind(userId)
90
+ .first<{ n: number }>();
91
+ counts[table] = row?.n ?? 0;
92
+ }
93
+ const codes = await d1
94
+ .prepare("select count(*) as n from pithy_auth_verifications where identifier = ? or instr(value, ?) > 0")
95
+ .bind(`sign-in-otp-${email}`, JSON.stringify(email))
96
+ .first<{ n: number }>();
97
+ counts.pithy_auth_verifications = codes?.n ?? 0;
98
+ const history = await d1
99
+ .prepare("select count(*) as n from pithy_auth_user_lifecycle where user_id = ?")
100
+ .bind(userId)
101
+ .first<{ n: number }>();
102
+ counts.pithy_auth_user_lifecycle = history?.n ?? 0;
103
+ return counts;
104
+ }
@@ -67,6 +67,7 @@ const TABLES = [
67
67
  "pithy_auth_rate_limit",
68
68
  "pithy_auth_rotated_tokens",
69
69
  "pithy_auth_user_lifecycle",
70
+ "pithy_auth_verification_outcomes",
70
71
  "pithy_auth_sessions",
71
72
  "pithy_auth_users",
72
73
  "pithy_auth_verifications",
@@ -140,6 +141,11 @@ export interface LiveApp {
140
141
  * happened rather than a code that was blank.
141
142
  */
142
143
  mailedOtp(to: string): Promise<string | null>;
144
+ /**
145
+ * The app database, for a suite that has to put a row where time would have put it — a rotation
146
+ * ledger entry aged past its grace window — or count what a route left behind.
147
+ */
148
+ db: D1Database;
143
149
  /** Stop the server and dispose the runtime. Always from a `finally` or an `afterAll`. */
144
150
  close(): Promise<void>;
145
151
  }
@@ -196,7 +202,9 @@ export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
196
202
  }),
197
203
  resolveGithubUserInfo: undefined,
198
204
  enqueueEmail: emailCapability.enqueue,
199
- turnstile: options.turnstile ? { mode: options.turnstile.mode } : undefined,
205
+ turnstile: options.turnstile
206
+ ? { mode: options.turnstile.mode, token: { field: "cf-turnstile-response" } }
207
+ : undefined,
200
208
  };
201
209
 
202
210
  const app = buildApp(wiring, events);
@@ -209,6 +217,7 @@ export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
209
217
  basePath: options.basePath,
210
218
  callbackUrl: (provider) => `${origin}${options.basePath}/callback/${provider}`,
211
219
  events,
220
+ db,
212
221
  enqueued: async () => {
213
222
  const rows = await db.prepare("select template, to_address from pithy_email_jobs order by rowid").all();
214
223
  return (rows.results as { template: string; to_address: string }[]).map((row) => ({
@@ -0,0 +1,180 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { sha256Base64Url, timingSafeEqual } from "@pithy-sh/core/src/controlPlane/token/digest";
5
+ import { sqliteJson } from "@pithy-sh/core/src/data/codecs";
6
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
+ import { z } from "zod";
8
+ import { Verification } from "../data/betterAuth";
9
+ import type { AuthDatabase } from "../data/tables";
10
+
11
+ /**
12
+ * The one-time code that hands a redirect sign-in back to a native app.
13
+ *
14
+ * A social sign-in that ends on an app's deep link cannot carry the session the way a browser does: the
15
+ * cookie lands in the system browser, which the app never reads. So the callback answers the deep link with
16
+ * this code instead, and the app trades it once, over `POST {base}/handoff`, for the session token.
17
+ *
18
+ * **Sixty seconds.** The trade happens the moment the app is opened from the link, so a slow device and a
19
+ * cold start are the whole of what the window has to cover. Anything longer only lengthens the time a code
20
+ * read off a URL log, or caught by another app claiming the same scheme, is still worth something.
21
+ *
22
+ * **Only the code's SHA-256 is stored.** The code carries 256 random bits, so a lookup by its digest leaks
23
+ * nothing a timing comparison could, and a read of the table yields nothing anybody can redeem. The row
24
+ * names the session by id, never by token, so the table holds no credential at all.
25
+ *
26
+ * **The code is bound to the app that started the sign-in**, the way RFC 7636 binds an authorization code. The
27
+ * app makes a random verifier, sends its S256 challenge with the sign-in, and presents the verifier with the
28
+ * code. Another app that claims the same scheme and catches the link holds the code but not the verifier, so
29
+ * the code is worth nothing to it. A code is never issued without a challenge.
30
+ *
31
+ * The rows live in `pithy_auth_verifications`, under their own identifier prefix, as Better Auth's own
32
+ * one-time tokens do. The redemption is one `DELETE … RETURNING`, so one code yields one session however
33
+ * many requests present it at once, and a wrong verifier spends the code as surely as the right one. Each issue
34
+ * also deletes a bounded batch of lapsed codes, so codes nobody traded do not pile up.
35
+ */
36
+ export const HANDOFF_TTL_SECONDS = 60;
37
+
38
+ /** The most lapsed codes one issue deletes. The next issue takes the rest. */
39
+ export const HANDOFF_SWEEP_LIMIT = 50;
40
+
41
+ /** The identifier prefix that keeps these rows apart from every other verification. */
42
+ const IDENTIFIER_PREFIX = "pithy-handoff:";
43
+
44
+ /** An S256 challenge: the base64url SHA-256 of a verifier, unpadded, which is always 43 characters. */
45
+ const CHALLENGE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
46
+
47
+ /** An RFC 7636 code verifier: 43 to 128 characters, each unreserved (`A-Z a-z 0-9 - . _ ~`). */
48
+ const VERIFIER_SHAPE = /^[A-Za-z0-9\-._~]{43,128}$/;
49
+
50
+ /** Whether a value has the shape RFC 7636 gives a code verifier. */
51
+ export function isHandoffVerifier(value: string): boolean {
52
+ return VERIFIER_SHAPE.test(value);
53
+ }
54
+
55
+ /** Whether a value has the shape of an S256 challenge. */
56
+ export function isHandoffChallenge(value: string): boolean {
57
+ return CHALLENGE_SHAPE.test(value);
58
+ }
59
+
60
+ /** The S256 challenge a verifier hashes to: `BASE64URL(SHA-256(verifier))`. */
61
+ export function handoffChallengeOf(verifier: string): Promise<string> {
62
+ return sha256Base64Url(new TextEncoder().encode(verifier));
63
+ }
64
+
65
+ /** What a code's row holds in its `value`: the session it stands for and the challenge its verifier must meet. */
66
+ export const StoredHandoff = z
67
+ .object({
68
+ sessionId: z.string().describe("The id of the session the code stands for. Never its token."),
69
+ challenge: z
70
+ .string()
71
+ .regex(CHALLENGE_SHAPE)
72
+ .describe("The S256 challenge the app sent with the sign-in. The trade's verifier must hash to it."),
73
+ })
74
+ .describe("A handoff code's row value: the session and the challenge that binds the code to one app.");
75
+ export type StoredHandoff = z.output<typeof StoredHandoff>;
76
+
77
+ /** The `value` column as a handoff: JSON text in SQLite, validated both ways. */
78
+ const StoredHandoffValue = sqliteJson(StoredHandoff);
79
+
80
+ /** What issuing a code answers: the code itself, which is never stored, and when it lapses. */
81
+ export interface IssuedHandoff {
82
+ readonly code: string;
83
+ readonly expiresAt: Date;
84
+ }
85
+
86
+ /**
87
+ * What a redemption answers. `unknown` covers a code already spent and one never issued alike. The reasons are
88
+ * for the audit trail; the caller answers every refusal the same way.
89
+ */
90
+ export type HandoffRedemption =
91
+ | { readonly ok: true; readonly sessionId: string }
92
+ | { readonly ok: false; readonly reason: HandoffRefusal };
93
+
94
+ /** Why a code was refused. `malformed` is a verifier outside RFC 7636's shape, which no challenge was made from. */
95
+ export type HandoffRefusal = "expired" | "unknown" | "mismatch" | "malformed";
96
+
97
+ async function identifierOf(code: string): Promise<string> {
98
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(code));
99
+ const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
100
+ return `${IDENTIFIER_PREFIX}${hex}`;
101
+ }
102
+
103
+ function randomCode(): string {
104
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
105
+ let binary = "";
106
+ for (const byte of bytes) binary += String.fromCharCode(byte);
107
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
108
+ }
109
+
110
+ /** Delete up to {@link HANDOFF_SWEEP_LIMIT} codes that lapsed by `now`. */
111
+ async function sweepLapsed(db: AuthDatabase, now: Date): Promise<void> {
112
+ await db
113
+ .deleteFrom("pithyAuthVerifications")
114
+ .where("id", "in", (lapsed) =>
115
+ lapsed
116
+ .selectFrom("pithyAuthVerifications")
117
+ .select("id")
118
+ .where("identifier", "like", `${IDENTIFIER_PREFIX}%`)
119
+ .where("expiresAt", "<=", Verification.shape.expiresAt.encode(now))
120
+ .limit(HANDOFF_SWEEP_LIMIT),
121
+ )
122
+ .execute();
123
+ }
124
+
125
+ /**
126
+ * Issue a code for a session that already exists, bound to the S256 challenge the app sent. A challenge of any
127
+ * other shape throws: an unbound code is never written.
128
+ */
129
+ export async function issueHandoff(
130
+ db: AuthDatabase,
131
+ input: { sessionId: string; challenge: string; now: Date },
132
+ ): Promise<IssuedHandoff> {
133
+ if (!isHandoffChallenge(input.challenge)) {
134
+ throw new InternalError({ detail: "a handoff code was asked for without an S256 challenge to bind it to" });
135
+ }
136
+ await sweepLapsed(db, input.now);
137
+ const code = randomCode();
138
+ const expiresAt = new Date(input.now.getTime() + HANDOFF_TTL_SECONDS * 1000);
139
+ await db
140
+ .insertInto("pithyAuthVerifications")
141
+ .values(
142
+ Verification.encode({
143
+ id: crypto.randomUUID(),
144
+ identifier: await identifierOf(code),
145
+ value: z.string().parse(StoredHandoffValue.encode({ sessionId: input.sessionId, challenge: input.challenge })),
146
+ expiresAt,
147
+ createdAt: input.now,
148
+ updatedAt: input.now,
149
+ }),
150
+ )
151
+ .execute();
152
+ return { code, expiresAt };
153
+ }
154
+
155
+ /**
156
+ * Spend a code against the verifier the app holds. The row goes whatever the answer, so an expired code, or one
157
+ * presented with the wrong or a malformed verifier, is spent by that attempt and a second attempt reads it as unknown.
158
+ */
159
+ export async function redeemHandoff(
160
+ db: AuthDatabase,
161
+ input: { code: string; verifier: string },
162
+ now: Date,
163
+ ): Promise<HandoffRedemption> {
164
+ const row = await db
165
+ .deleteFrom("pithyAuthVerifications")
166
+ .where("identifier", "=", await identifierOf(input.code))
167
+ .returning(["value", "expiresAt"])
168
+ .executeTakeFirst();
169
+ if (!row) return { ok: false, reason: "unknown" };
170
+ const parsed = StoredHandoffValue.safeParse(row.value);
171
+ if (!parsed.success) return { ok: false, reason: "unknown" };
172
+ const stored = parsed.data;
173
+ const expiresAt = Verification.shape.expiresAt.parse(row.expiresAt);
174
+ if (expiresAt.getTime() <= now.getTime()) return { ok: false, reason: "expired" };
175
+ if (!isHandoffVerifier(input.verifier)) return { ok: false, reason: "malformed" };
176
+ if (!timingSafeEqual(await handoffChallengeOf(input.verifier), stored.challenge)) {
177
+ return { ok: false, reason: "mismatch" };
178
+ }
179
+ return { ok: true, sessionId: stored.sessionId };
180
+ }
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/auth";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.10.0";
16
+ export const PACKAGE_VERSION = "0.12.0";