@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,71 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
4
+ import { type LegalHolds } from "@pithy-sh/core/src/retention/holds";
5
+ import type { TerminalErrorConstructor, WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
6
+ import { type LifecycleDeps } from "../lifecycle/transitions";
7
+ import { type InactivityRun, type PurgeDueRun, type PurgeOutcome } from "./run";
8
+ /**
9
+ * The purge's two Workflow bodies (#622) — run by classes **the adopter's own Worker** exports, beside the
10
+ * `createEntrypoint` it already exports, because a purge runs every composed capability's contribution and
11
+ * those exist nowhere else:
12
+ *
13
+ * // apps/api/src/index.ts
14
+ * import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
15
+ * import { NonRetryableError } from "cloudflare:workflows";
16
+ * import { runAuthPurge, runAuthPurgeDue } from "@pithy-sh/auth/src/purge/workflow";
17
+ *
18
+ * export class AuthPurgeWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
19
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
20
+ * return runAuthPurge(this.env, event, step, NonRetryableError);
21
+ * }
22
+ * }
23
+ * export class AuthPurgeDueWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
24
+ * override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
25
+ * return runAuthPurgeDue(this.env, event, step, NonRetryableError);
26
+ * }
27
+ * }
28
+ *
29
+ * plus a `workflows` entry binding `AUTH_PURGE` and `AUTH_PURGE_DUE` to them and the daily cron —
30
+ * `docs/account-lifecycle.md` has the stanza. **The class is the adopter's, the body is the kit's**, the split
31
+ * `@pithy-sh/payments`' usage pass has, for the same reason.
32
+ *
33
+ * Each body finds the composed auth capability the way a Workflow that sends mail finds email: the class is
34
+ * exported from the entry that calls `createEntrypoint`, so the composition has happened in this isolate. The
35
+ * steps, the hooks, the config and the audit recorder are on the capability; the mail is email's own enqueue.
36
+ */
37
+ /** What a Workflow event hands a body. */
38
+ interface PurgeEvent {
39
+ readonly payload?: unknown;
40
+ readonly workflowName?: string;
41
+ readonly instanceId?: string;
42
+ }
43
+ /** Purge one account: every composed contribution, one step each, auth's last. See `./run.ts`. */
44
+ export declare function runAuthPurge(env: Record<string, unknown>, event: PurgeEvent, step: WorkflowStepLike, terminalError: TerminalErrorConstructor): Promise<PurgeOutcome>;
45
+ /**
46
+ * The daily pass: start a purge for every account past its window, then soft-delete every account inactive past the
47
+ * strictest class age it holds. See `./run.ts`.
48
+ */
49
+ export declare function runAuthPurgeDue(env: Record<string, unknown>, event: PurgeEvent, step: WorkflowStepLike, terminalError: TerminalErrorConstructor): Promise<{
50
+ started: number;
51
+ inactive: number;
52
+ }>;
53
+ /**
54
+ * The inactivity pass over this composition: the strictest class age among the classes a user's rows hold, from
55
+ * the Worker's resolved `retention` block, and the lifecycle's own soft deletion, by the system, with its notice mail.
56
+ */
57
+ export declare function inactivityRun(lifecycle: LifecycleDeps, holds: LegalHolds): InactivityRun;
58
+ /** The inactivity pass's reads and deletions over one set of lifecycle dependencies, for a class age in days. */
59
+ export declare function inactivityOps(lifecycle: LifecycleDeps, holds: LegalHolds, days: () => number | null): InactivityRun;
60
+ /**
61
+ * How the daily pass starts one account's purge: under the id the deletion names (`./start.ts`), so a purge a hard
62
+ * deletion already started today is the same instance, not a second one. No `notify`: the deletion's own row
63
+ * carries it, and the purge reads it there.
64
+ *
65
+ * **It answers whether the purge is running**, and the pass counts that. A Worker that has not bound the purge,
66
+ * and a start that failed, each log the skip rather than throwing inside a cron nobody watches — tomorrow's pass
67
+ * starts it again — and answer `false`, so the pass does not report a purge it never started.
68
+ */
69
+ export declare function purgeStarter(env: Record<string, unknown>, log: Logger, now?: () => Date): PurgeDueRun["start"];
70
+ export {};
71
+ //# sourceMappingURL=workflow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.d.ts","sourceRoot":"","sources":["../../src/purge/workflow.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAG/D,OAAO,EAAE,KAAK,UAAU,EAAc,MAAM,oCAAoC,CAAC;AAGjF,OAAO,KAAK,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CA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AAE,MAAM,IAAuB,GACjC,WAAW,CAAC,OAAO,CAAC,CAuBtB"}
@@ -0,0 +1,140 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { authDatabase } from "../data/tables.js";
4
+ import { inactiveAccounts } from "../lifecycle/inactivity.js";
5
+ import { resolveDb } from "../http/resolve.js";
6
+ import { deleteUser } from "../lifecycle/transitions.js";
7
+ import { AUTH_PURGE_BINDING, AUTH_PURGE_KEY, AuthPurgeDueParams, AuthPurgeParams } from "./specs.js";
8
+ import { startPurgeInstance } from "./start.js";
9
+ import { isAuthCapability } from "../capability.js";
10
+ import { deleteInactiveAccounts, duePurgesOf, purgeOps, purgeUser, startDuePurges } from "./run.js";
11
+ import { messageOf } from "@pithy-sh/core/src/error/pithyError";
12
+ import { bindWorkflowContext, createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
13
+ import { composedRetention, subjectClasses } from "@pithy-sh/core/src/retention/composed";
14
+ import { inactivityDays } from "@pithy-sh/core/src/retention/policy";
15
+ import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
16
+ import { composedCapabilities, composedCapability } from "@pithy-sh/core/src/capability/composition";
17
+ import { legalHolds } from "@pithy-sh/core/src/retention/holds";
18
+ import { enqueueFromEnv } from "@pithy-sh/email/src/send/fromComposition";
19
+ //#region src/purge/workflow.ts
20
+ /** The lifecycle transitions' dependencies, for a run with no request: this env, and the composition's seams. */
21
+ function lifecycleFor(auth, env, log) {
22
+ const d1 = resolveDb(env, auth.authConfig.database);
23
+ return {
24
+ db: authDatabase(d1),
25
+ d1,
26
+ emit: auth.auditFor(env),
27
+ config: auth.authConfig,
28
+ hooks: auth.lifecycleHooks,
29
+ enqueueEmail: (input) => enqueueFromEnv(env, input),
30
+ log
31
+ };
32
+ }
33
+ /** This run's logger, bound to the instance an operator reads it under. */
34
+ function runLog(env, event, name) {
35
+ return bindWorkflowContext(createWorkerLogger({ name }), {
36
+ workflow: event.workflowName ?? name,
37
+ instance: event.instanceId ?? "unknown",
38
+ env: typeof env.ENVIRONMENT === "string" ? env.ENVIRONMENT : "unknown"
39
+ });
40
+ }
41
+ /** Purge one account: every composed contribution, one step each, auth's last. See `./run.ts`. */
42
+ async function runAuthPurge(env, event, step, terminalError) {
43
+ const params = AuthPurgeParams.parse(event.payload ?? {});
44
+ const auth = composedCapability("auth", isAuthCapability);
45
+ const lifecycle = lifecycleFor(auth, env, runLog(env, event, "auth:purge"));
46
+ return purgeUser({
47
+ steps: auth.purgeSteps,
48
+ env,
49
+ ops: purgeOps(lifecycle, legalHolds(env))
50
+ }, step, terminalError, params);
51
+ }
52
+ /**
53
+ * The daily pass: start a purge for every account past its window, then soft-delete every account inactive past the
54
+ * strictest class age it holds. See `./run.ts`.
55
+ */
56
+ async function runAuthPurgeDue(env, event, step, terminalError) {
57
+ const params = AuthPurgeDueParams.parse(event.payload ?? {});
58
+ const auth = composedCapability("auth", isAuthCapability);
59
+ const log = runLog(env, event, "auth:purge-due");
60
+ const lifecycle = lifecycleFor(auth, env, log);
61
+ const holds = legalHolds(env);
62
+ const { started } = await startDuePurges({
63
+ due: duePurgesOf(lifecycle),
64
+ start: purgeStarter(env, log),
65
+ held: (userId) => holds.held("user", userId)
66
+ }, step, terminalError, params);
67
+ const { deleted } = await deleteInactiveAccounts(inactivityRun(lifecycle, holds), step, terminalError);
68
+ return {
69
+ started,
70
+ inactive: deleted
71
+ };
72
+ }
73
+ /**
74
+ * The inactivity pass over this composition: the strictest class age among the classes a user's rows hold, from
75
+ * the Worker's resolved `retention` block, and the lifecycle's own soft deletion, by the system, with its notice mail.
76
+ */
77
+ function inactivityRun(lifecycle, holds) {
78
+ return inactivityOps(lifecycle, holds, () => {
79
+ const retention = composedRetention();
80
+ return retention ? inactivityDays(retention, subjectClasses(composedCapabilities(), "user")) : null;
81
+ });
82
+ }
83
+ /** The inactivity pass's reads and deletions over one set of lifecycle dependencies, for a class age in days. */
84
+ function inactivityOps(lifecycle, holds, days) {
85
+ return {
86
+ days: async () => days(),
87
+ inactive: (cutoff, limit) => inactiveAccounts(lifecycle.db, cutoff, limit),
88
+ held: (userId) => holds.held("user", userId),
89
+ remove: async (userId, limit) => {
90
+ return (await deleteUser(lifecycle, {
91
+ userId,
92
+ actor: {
93
+ type: "system",
94
+ id: null
95
+ },
96
+ reason: `Inactive for more than ${limit} days, the retention policy's limit for the personal data it holds.`
97
+ })).outcome === "deleted";
98
+ },
99
+ now: lifecycle.now ?? (() => /* @__PURE__ */ new Date())
100
+ };
101
+ }
102
+ /**
103
+ * How the daily pass starts one account's purge: under the id the deletion names (`./start.ts`), so a purge a hard
104
+ * deletion already started today is the same instance, not a second one. No `notify`: the deletion's own row
105
+ * carries it, and the purge reads it there.
106
+ *
107
+ * **It answers whether the purge is running**, and the pass counts that. A Worker that has not bound the purge,
108
+ * and a start that failed, each log the skip rather than throwing inside a cron nobody watches — tomorrow's pass
109
+ * starts it again — and answer `false`, so the pass does not report a purge it never started.
110
+ */
111
+ function purgeStarter(env, log, now = () => /* @__PURE__ */ new Date()) {
112
+ return async (due) => {
113
+ const binding = workflowBindingFor(env, AUTH_PURGE_BINDING);
114
+ if (!binding) {
115
+ log.warn("workflow skipped", {
116
+ workflow: AUTH_PURGE_KEY,
117
+ binding: AUTH_PURGE_BINDING,
118
+ reason: "binding absent — the purge Workflow is not bound"
119
+ });
120
+ return false;
121
+ }
122
+ try {
123
+ await startPurgeInstance(binding, {
124
+ userId: due.userId,
125
+ deletedAt: due.deletedAt,
126
+ at: now()
127
+ });
128
+ return true;
129
+ } catch (error) {
130
+ log.warn("workflow skipped", {
131
+ workflow: AUTH_PURGE_KEY,
132
+ binding: AUTH_PURGE_BINDING,
133
+ reason: messageOf(error)
134
+ });
135
+ return false;
136
+ }
137
+ };
138
+ }
139
+ //#endregion
140
+ export { inactivityOps, inactivityRun, purgeStarter, runAuthPurge, runAuthPurgeDue };
@@ -0,0 +1,13 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ /** Every table a footprint writes to, with the column that names the person in it. */
5
+ export declare const FOOTPRINT_TABLES: readonly [readonly ["pithy_auth_users", "id"], readonly ["pithy_auth_sessions", "user_id"], readonly ["pithy_auth_accounts", "user_id"], readonly ["pithy_auth_devices", "user_id"], readonly ["pithy_auth_rotated_tokens", "user_id"], readonly ["pithy_auth_verification_outcomes", "user_id"]];
6
+ /**
7
+ * Write a full footprint for one account: a user, a session, a provider link, a device, a spent token, two pending
8
+ * codes, and the ledger row of a sign-in link it used.
9
+ */
10
+ export declare function seedAccountFootprint(d1: D1Database, userId: string, email?: string): Promise<void>;
11
+ /** How many rows one account still holds in each footprint table, and in the pending codes for its address. */
12
+ export declare function footprintCounts(d1: D1Database, userId: string, email?: string): Promise<Record<string, number>>;
13
+ //# sourceMappingURL=accountFootprint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountFootprint.d.ts","sourceRoot":"","sources":["../../src/test-utils/accountFootprint.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAW5D,sFAAsF;AACtF,eAAO,MAAM,gBAAgB,sBAC1B,kBAAkB,EAAE,IAAI,aACxB,qBAAqB,EAAE,SAAS,aAChC,qBAAqB,EAAE,SAAS,aAChC,oBAAoB,EAAE,SAAS,aAC/B,2BAA2B,EAAE,SAAS,aACtC,kCAAkC,EAAE,SAAS,EACtC,CAAC;AAEX;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,KAAK,SAAuB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAgDf;AAED,+GAA+G;AAC/G,wBAAsB,eAAe,CAAC,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,SAAuB,mCAoBjG"}
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/test-utils/accountFootprint.ts
4
+ /**
5
+ * One account's rows across every `pithy_auth_*` table that keys a row to a person — what a purge must erase
6
+ * and an export must read (#622). For the workers suites; the tables are the real ones, written by raw SQL in
7
+ * the shapes the kit's own writers produce, so a test reads back exactly what production would hold.
8
+ */
9
+ const AT = "2026-10-01T00:00:00.000Z";
10
+ const AT_MS = Date.parse(AT);
11
+ /** Every table a footprint writes to, with the column that names the person in it. */
12
+ const FOOTPRINT_TABLES = [
13
+ ["pithy_auth_users", "id"],
14
+ ["pithy_auth_sessions", "user_id"],
15
+ ["pithy_auth_accounts", "user_id"],
16
+ ["pithy_auth_devices", "user_id"],
17
+ ["pithy_auth_rotated_tokens", "user_id"],
18
+ ["pithy_auth_verification_outcomes", "user_id"]
19
+ ];
20
+ /**
21
+ * Write a full footprint for one account: a user, a session, a provider link, a device, a spent token, two pending
22
+ * codes, and the ledger row of a sign-in link it used.
23
+ */
24
+ async function seedAccountFootprint(d1, userId, email = `${userId}@test.com`) {
25
+ await d1.batch([
26
+ d1.prepare("insert into pithy_auth_users (id, name, email, email_verified, locale, created_at, updated_at) values (?, 'Sam', ?, 1, null, ?, ?)").bind(userId, email, AT, AT),
27
+ d1.prepare("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', ?, ?)").bind(`s-${userId}`, "2099-01-01T00:00:00.000Z", `token-${userId}`, AT, AT, userId, `d-${userId}`),
28
+ d1.prepare("insert into pithy_auth_accounts (id, account_id, provider_id, user_id, access_token, refresh_token, created_at, updated_at) values (?, ?, 'google', ?, ?, ?, ?, ?)").bind(`a-${userId}`, `g-${userId}`, userId, `access-${userId}`, `refresh-${userId}`, AT, AT),
29
+ d1.prepare("insert into pithy_auth_devices (id, user_id, platform, push_token, last_ip, last_seen_at, created_at) values (?, ?, 'ios', ?, '203.0.113.9', ?, ?)").bind(`d-${userId}`, userId, `push-${userId}`, AT_MS, AT_MS),
30
+ d1.prepare("insert into pithy_auth_rotated_tokens (token, family_id, user_id, rotated_at) values (?, ?, ?, ?)").bind(`spent-${userId}`, `f-${userId}`, userId, AT_MS),
31
+ d1.prepare("insert into pithy_auth_verification_outcomes (verification_id, type, user_id, email_job_id, issued_at, expires_at, used_at) values (?, 'magic_link', ?, ?, ?, ?, ?)").bind(`used-link-${userId}`, userId, `job-${userId}`, AT_MS, AT_MS + 3e5, AT_MS + 6e4),
32
+ d1.prepare("insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, '123456:0', ?, ?, ?)").bind(`otp-${userId}`, `sign-in-otp-${email}`, "2099-01-01T00:00:00.000Z", AT, AT),
33
+ d1.prepare("insert into pithy_auth_verifications (id, identifier, value, expires_at, created_at, updated_at) values (?, ?, ?, ?, ?, ?)").bind(`link-${userId}`, `magic-link-${userId}`, JSON.stringify({
34
+ email,
35
+ name: "",
36
+ attempt: 0
37
+ }), "2099-01-01T00:00:00.000Z", AT, AT)
38
+ ]);
39
+ }
40
+ /** How many rows one account still holds in each footprint table, and in the pending codes for its address. */
41
+ async function footprintCounts(d1, userId, email = `${userId}@test.com`) {
42
+ const counts = {};
43
+ for (const [table, column] of FOOTPRINT_TABLES) counts[table] = (await d1.prepare(`select count(*) as n from ${table} where ${column} = ?`).bind(userId).first())?.n ?? 0;
44
+ counts.pithy_auth_verifications = (await d1.prepare("select count(*) as n from pithy_auth_verifications where identifier = ? or instr(value, ?) > 0").bind(`sign-in-otp-${email}`, JSON.stringify(email)).first())?.n ?? 0;
45
+ counts.pithy_auth_user_lifecycle = (await d1.prepare("select count(*) as n from pithy_auth_user_lifecycle where user_id = ?").bind(userId).first())?.n ?? 0;
46
+ return counts;
47
+ }
48
+ //#endregion
49
+ export { FOOTPRINT_TABLES, footprintCounts, seedAccountFootprint };
@@ -1,5 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
3
4
  import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
4
5
  /**
5
6
  * A real auth Worker on a real port, for the live suites (#84).
@@ -242,6 +243,11 @@ export interface LiveApp {
242
243
  * happened rather than a code that was blank.
243
244
  */
244
245
  mailedOtp(to: string): Promise<string | null>;
246
+ /**
247
+ * The app database, for a suite that has to put a row where time would have put it — a rotation
248
+ * ledger entry aged past its grace window — or count what a route left behind.
249
+ */
250
+ db: D1Database;
245
251
  /** Stop the server and dispose the runtime. Always from a `finally` or an `afterAll`. */
246
252
  close(): Promise<void>;
247
253
  }
@@ -1 +1 @@
1
- {"version":3,"file":"liveApp.d.ts","sourceRoot":"","sources":["../../src/test-utils/liveApp.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAuB3E;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,iHAAiH;AACjH,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAA0D,CAAC;AAErF,4GAA4G;AAC5G,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC;AAyBD,4GAA4G;AAC5G,MAAM,WAAW,aAAa;IAC5B,qFAAqF;IACrF,QAAQ,EAAE,MAAM,CAAC;IACjB,6BAA6B;IAC7B,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,uGAAuG;AACvG,MAAM,WAAW,cAAc;IAC7B;;;;;;;OAOG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,mFAAmF;IACnF,MAAM,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAA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AC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CA4F5E"}
@@ -10,8 +10,8 @@ import { AUTH_MIGRATIONS } from "../migrations/set.js";
10
10
  import { AuthConfig } from "../capability.js";
11
11
  import { email } from "@pithy-sh/email/src/capability";
12
12
  import { configureSharedSecrets, resetSharedSecrets } from "@pithy-sh/secrets/src/sharedSecretsStore";
13
- import { createServer } from "node:http";
14
13
  import { pithyErrorHandler } from "@pithy-sh/core/src/error/http";
14
+ import { createServer } from "node:http";
15
15
  import { createMigrationRegistry } from "@pithy-sh/core/src/migrations/registry";
16
16
  import { runMigrations } from "@pithy-sh/core/src/migrations/runner";
17
17
  import { email_0001_init } from "@pithy-sh/email/src/migrations/0001_init";
@@ -61,6 +61,7 @@ const TABLES = [
61
61
  "pithy_auth_rate_limit",
62
62
  "pithy_auth_rotated_tokens",
63
63
  "pithy_auth_user_lifecycle",
64
+ "pithy_auth_verification_outcomes",
64
65
  "pithy_auth_sessions",
65
66
  "pithy_auth_users",
66
67
  "pithy_auth_verifications",
@@ -120,7 +121,10 @@ async function startLiveApp(options) {
120
121
  }),
121
122
  resolveGithubUserInfo: void 0,
122
123
  enqueueEmail: emailCapability.enqueue,
123
- turnstile: options.turnstile ? { mode: options.turnstile.mode } : void 0
124
+ turnstile: options.turnstile ? {
125
+ mode: options.turnstile.mode,
126
+ token: { field: "cf-turnstile-response" }
127
+ } : void 0
124
128
  }, events);
125
129
  server.on("request", (request, response) => {
126
130
  serve(app, env, origin, request, response);
@@ -130,6 +134,7 @@ async function startLiveApp(options) {
130
134
  basePath: options.basePath,
131
135
  callbackUrl: (provider) => `${origin}${options.basePath}/callback/${provider}`,
132
136
  events,
137
+ db,
133
138
  enqueued: async () => {
134
139
  return (await db.prepare("select template, to_address from pithy_email_jobs order by rowid").all()).results.map((row) => ({
135
140
  template: row.template,
@@ -0,0 +1,80 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ import type { AuthDatabase } from "../data/tables";
5
+ /**
6
+ * The one-time code that hands a redirect sign-in back to a native app.
7
+ *
8
+ * A social sign-in that ends on an app's deep link cannot carry the session the way a browser does: the
9
+ * cookie lands in the system browser, which the app never reads. So the callback answers the deep link with
10
+ * this code instead, and the app trades it once, over `POST {base}/handoff`, for the session token.
11
+ *
12
+ * **Sixty seconds.** The trade happens the moment the app is opened from the link, so a slow device and a
13
+ * cold start are the whole of what the window has to cover. Anything longer only lengthens the time a code
14
+ * read off a URL log, or caught by another app claiming the same scheme, is still worth something.
15
+ *
16
+ * **Only the code's SHA-256 is stored.** The code carries 256 random bits, so a lookup by its digest leaks
17
+ * nothing a timing comparison could, and a read of the table yields nothing anybody can redeem. The row
18
+ * names the session by id, never by token, so the table holds no credential at all.
19
+ *
20
+ * **The code is bound to the app that started the sign-in**, the way RFC 7636 binds an authorization code. The
21
+ * app makes a random verifier, sends its S256 challenge with the sign-in, and presents the verifier with the
22
+ * code. Another app that claims the same scheme and catches the link holds the code but not the verifier, so
23
+ * the code is worth nothing to it. A code is never issued without a challenge.
24
+ *
25
+ * The rows live in `pithy_auth_verifications`, under their own identifier prefix, as Better Auth's own
26
+ * one-time tokens do. The redemption is one `DELETE … RETURNING`, so one code yields one session however
27
+ * many requests present it at once, and a wrong verifier spends the code as surely as the right one. Each issue
28
+ * also deletes a bounded batch of lapsed codes, so codes nobody traded do not pile up.
29
+ */
30
+ export declare const HANDOFF_TTL_SECONDS = 60;
31
+ /** The most lapsed codes one issue deletes. The next issue takes the rest. */
32
+ export declare const HANDOFF_SWEEP_LIMIT = 50;
33
+ /** Whether a value has the shape RFC 7636 gives a code verifier. */
34
+ export declare function isHandoffVerifier(value: string): boolean;
35
+ /** Whether a value has the shape of an S256 challenge. */
36
+ export declare function isHandoffChallenge(value: string): boolean;
37
+ /** The S256 challenge a verifier hashes to: `BASE64URL(SHA-256(verifier))`. */
38
+ export declare function handoffChallengeOf(verifier: string): Promise<string>;
39
+ /** What a code's row holds in its `value`: the session it stands for and the challenge its verifier must meet. */
40
+ export declare const StoredHandoff: z.ZodObject<{
41
+ sessionId: z.ZodString;
42
+ challenge: z.ZodString;
43
+ }, z.core.$strip>;
44
+ export type StoredHandoff = z.output<typeof StoredHandoff>;
45
+ /** What issuing a code answers: the code itself, which is never stored, and when it lapses. */
46
+ export interface IssuedHandoff {
47
+ readonly code: string;
48
+ readonly expiresAt: Date;
49
+ }
50
+ /**
51
+ * What a redemption answers. `unknown` covers a code already spent and one never issued alike. The reasons are
52
+ * for the audit trail; the caller answers every refusal the same way.
53
+ */
54
+ export type HandoffRedemption = {
55
+ readonly ok: true;
56
+ readonly sessionId: string;
57
+ } | {
58
+ readonly ok: false;
59
+ readonly reason: HandoffRefusal;
60
+ };
61
+ /** Why a code was refused. `malformed` is a verifier outside RFC 7636's shape, which no challenge was made from. */
62
+ export type HandoffRefusal = "expired" | "unknown" | "mismatch" | "malformed";
63
+ /**
64
+ * Issue a code for a session that already exists, bound to the S256 challenge the app sent. A challenge of any
65
+ * other shape throws: an unbound code is never written.
66
+ */
67
+ export declare function issueHandoff(db: AuthDatabase, input: {
68
+ sessionId: string;
69
+ challenge: string;
70
+ now: Date;
71
+ }): Promise<IssuedHandoff>;
72
+ /**
73
+ * Spend a code against the verifier the app holds. The row goes whatever the answer, so an expired code, or one
74
+ * presented with the wrong or a malformed verifier, is spent by that attempt and a second attempt reads it as unknown.
75
+ */
76
+ export declare function redeemHandoff(db: AuthDatabase, input: {
77
+ code: string;
78
+ verifier: string;
79
+ }, now: Date): Promise<HandoffRedemption>;
80
+ //# sourceMappingURL=handoff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handoff.d.ts","sourceRoot":"","sources":["../../src/token/handoff.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;;;;;;;;;;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AE,EAAE,YAAY,EAChB,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,EACzC,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,iBAAiB,CAAC,CAiB5B"}
@@ -0,0 +1,136 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { Verification } from "../data/betterAuth.js";
4
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { z } from "zod";
6
+ import { sqliteJson } from "@pithy-sh/core/src/data/codecs";
7
+ import { sha256Base64Url, timingSafeEqual } from "@pithy-sh/core/src/controlPlane/token/digest";
8
+ //#region src/token/handoff.ts
9
+ /**
10
+ * The one-time code that hands a redirect sign-in back to a native app.
11
+ *
12
+ * A social sign-in that ends on an app's deep link cannot carry the session the way a browser does: the
13
+ * cookie lands in the system browser, which the app never reads. So the callback answers the deep link with
14
+ * this code instead, and the app trades it once, over `POST {base}/handoff`, for the session token.
15
+ *
16
+ * **Sixty seconds.** The trade happens the moment the app is opened from the link, so a slow device and a
17
+ * cold start are the whole of what the window has to cover. Anything longer only lengthens the time a code
18
+ * read off a URL log, or caught by another app claiming the same scheme, is still worth something.
19
+ *
20
+ * **Only the code's SHA-256 is stored.** The code carries 256 random bits, so a lookup by its digest leaks
21
+ * nothing a timing comparison could, and a read of the table yields nothing anybody can redeem. The row
22
+ * names the session by id, never by token, so the table holds no credential at all.
23
+ *
24
+ * **The code is bound to the app that started the sign-in**, the way RFC 7636 binds an authorization code. The
25
+ * app makes a random verifier, sends its S256 challenge with the sign-in, and presents the verifier with the
26
+ * code. Another app that claims the same scheme and catches the link holds the code but not the verifier, so
27
+ * the code is worth nothing to it. A code is never issued without a challenge.
28
+ *
29
+ * The rows live in `pithy_auth_verifications`, under their own identifier prefix, as Better Auth's own
30
+ * one-time tokens do. The redemption is one `DELETE … RETURNING`, so one code yields one session however
31
+ * many requests present it at once, and a wrong verifier spends the code as surely as the right one. Each issue
32
+ * also deletes a bounded batch of lapsed codes, so codes nobody traded do not pile up.
33
+ */
34
+ const HANDOFF_TTL_SECONDS = 60;
35
+ /** The most lapsed codes one issue deletes. The next issue takes the rest. */
36
+ const HANDOFF_SWEEP_LIMIT = 50;
37
+ /** The identifier prefix that keeps these rows apart from every other verification. */
38
+ const IDENTIFIER_PREFIX = "pithy-handoff:";
39
+ /** An S256 challenge: the base64url SHA-256 of a verifier, unpadded, which is always 43 characters. */
40
+ const CHALLENGE_SHAPE = /^[A-Za-z0-9_-]{43}$/;
41
+ /** An RFC 7636 code verifier: 43 to 128 characters, each unreserved (`A-Z a-z 0-9 - . _ ~`). */
42
+ const VERIFIER_SHAPE = /^[A-Za-z0-9\-._~]{43,128}$/;
43
+ /** Whether a value has the shape RFC 7636 gives a code verifier. */
44
+ function isHandoffVerifier(value) {
45
+ return VERIFIER_SHAPE.test(value);
46
+ }
47
+ /** Whether a value has the shape of an S256 challenge. */
48
+ function isHandoffChallenge(value) {
49
+ return CHALLENGE_SHAPE.test(value);
50
+ }
51
+ /** The S256 challenge a verifier hashes to: `BASE64URL(SHA-256(verifier))`. */
52
+ function handoffChallengeOf(verifier) {
53
+ return sha256Base64Url(new TextEncoder().encode(verifier));
54
+ }
55
+ /** What a code's row holds in its `value`: the session it stands for and the challenge its verifier must meet. */
56
+ const StoredHandoff = z.object({
57
+ sessionId: z.string().describe("The id of the session the code stands for. Never its token."),
58
+ challenge: z.string().regex(CHALLENGE_SHAPE).describe("The S256 challenge the app sent with the sign-in. The trade's verifier must hash to it.")
59
+ }).describe("A handoff code's row value: the session and the challenge that binds the code to one app.");
60
+ /** The `value` column as a handoff: JSON text in SQLite, validated both ways. */
61
+ const StoredHandoffValue = sqliteJson(StoredHandoff);
62
+ async function identifierOf(code) {
63
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(code));
64
+ const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
65
+ return `${IDENTIFIER_PREFIX}${hex}`;
66
+ }
67
+ function randomCode() {
68
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
69
+ let binary = "";
70
+ for (const byte of bytes) binary += String.fromCharCode(byte);
71
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
72
+ }
73
+ /** Delete up to {@link HANDOFF_SWEEP_LIMIT} codes that lapsed by `now`. */
74
+ async function sweepLapsed(db, now) {
75
+ await db.deleteFrom("pithyAuthVerifications").where("id", "in", (lapsed) => lapsed.selectFrom("pithyAuthVerifications").select("id").where("identifier", "like", `${IDENTIFIER_PREFIX}%`).where("expiresAt", "<=", Verification.shape.expiresAt.encode(now)).limit(50)).execute();
76
+ }
77
+ /**
78
+ * Issue a code for a session that already exists, bound to the S256 challenge the app sent. A challenge of any
79
+ * other shape throws: an unbound code is never written.
80
+ */
81
+ async function issueHandoff(db, input) {
82
+ if (!isHandoffChallenge(input.challenge)) throw new InternalError({ detail: "a handoff code was asked for without an S256 challenge to bind it to" });
83
+ await sweepLapsed(db, input.now);
84
+ const code = randomCode();
85
+ const expiresAt = new Date(input.now.getTime() + 6e4);
86
+ await db.insertInto("pithyAuthVerifications").values(Verification.encode({
87
+ id: crypto.randomUUID(),
88
+ identifier: await identifierOf(code),
89
+ value: z.string().parse(StoredHandoffValue.encode({
90
+ sessionId: input.sessionId,
91
+ challenge: input.challenge
92
+ })),
93
+ expiresAt,
94
+ createdAt: input.now,
95
+ updatedAt: input.now
96
+ })).execute();
97
+ return {
98
+ code,
99
+ expiresAt
100
+ };
101
+ }
102
+ /**
103
+ * Spend a code against the verifier the app holds. The row goes whatever the answer, so an expired code, or one
104
+ * presented with the wrong or a malformed verifier, is spent by that attempt and a second attempt reads it as unknown.
105
+ */
106
+ async function redeemHandoff(db, input, now) {
107
+ const row = await db.deleteFrom("pithyAuthVerifications").where("identifier", "=", await identifierOf(input.code)).returning(["value", "expiresAt"]).executeTakeFirst();
108
+ if (!row) return {
109
+ ok: false,
110
+ reason: "unknown"
111
+ };
112
+ const parsed = StoredHandoffValue.safeParse(row.value);
113
+ if (!parsed.success) return {
114
+ ok: false,
115
+ reason: "unknown"
116
+ };
117
+ const stored = parsed.data;
118
+ if (Verification.shape.expiresAt.parse(row.expiresAt).getTime() <= now.getTime()) return {
119
+ ok: false,
120
+ reason: "expired"
121
+ };
122
+ if (!isHandoffVerifier(input.verifier)) return {
123
+ ok: false,
124
+ reason: "malformed"
125
+ };
126
+ if (!timingSafeEqual(await handoffChallengeOf(input.verifier), stored.challenge)) return {
127
+ ok: false,
128
+ reason: "mismatch"
129
+ };
130
+ return {
131
+ ok: true,
132
+ sessionId: stored.sessionId
133
+ };
134
+ }
135
+ //#endregion
136
+ export { HANDOFF_SWEEP_LIMIT, HANDOFF_TTL_SECONDS, StoredHandoff, handoffChallengeOf, isHandoffChallenge, isHandoffVerifier, issueHandoff, redeemHandoff };
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/auth";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.10.0";
6
+ export declare const PACKAGE_VERSION = "0.12.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/auth";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.10.0";
7
+ const PACKAGE_VERSION = "0.12.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };