@pithy-sh/auth 0.11.0 → 0.12.1

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 (246) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/actions.d.ts +39 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +40 -1
  5. package/dist/audit/emit.d.ts +34 -0
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +47 -1
  8. package/dist/audit/evidence.d.ts +8 -2
  9. package/dist/audit/evidence.d.ts.map +1 -1
  10. package/dist/capability.d.ts +31 -11
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +38 -5
  13. package/dist/client/api.d.ts +55 -12
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +57 -18
  16. package/dist/client/bearer.d.ts +110 -0
  17. package/dist/client/bearer.d.ts.map +1 -0
  18. package/dist/client/bearer.js +265 -0
  19. package/dist/client/handoff.d.ts +77 -0
  20. package/dist/client/handoff.d.ts.map +1 -0
  21. package/dist/client/handoff.js +119 -0
  22. package/dist/client/mcp.d.ts +70 -0
  23. package/dist/client/mcp.d.ts.map +1 -0
  24. package/dist/client/mcp.js +65 -0
  25. package/dist/data/betterAuth.d.ts +3 -2
  26. package/dist/data/betterAuth.d.ts.map +1 -1
  27. package/dist/data/betterAuth.js +5 -3
  28. package/dist/data/kitFields.d.ts +5 -0
  29. package/dist/data/kitFields.d.ts.map +1 -1
  30. package/dist/data/kitFields.js +5 -0
  31. package/dist/data/tables.d.ts +25 -4
  32. package/dist/data/tables.d.ts.map +1 -1
  33. package/dist/data/tables.js +5 -3
  34. package/dist/data/userLifecycle.d.ts +9 -0
  35. package/dist/data/userLifecycle.d.ts.map +1 -1
  36. package/dist/data/userLifecycle.js +6 -2
  37. package/dist/data/verificationOutcome.d.ts +53 -0
  38. package/dist/data/verificationOutcome.d.ts.map +1 -0
  39. package/dist/data/verificationOutcome.js +50 -0
  40. package/dist/email/send.js +6 -2
  41. package/dist/http/adminRoutes.d.ts.map +1 -1
  42. package/dist/http/adminRoutes.js +56 -10
  43. package/dist/http/csrf.d.ts.map +1 -1
  44. package/dist/http/csrf.js +2 -1
  45. package/dist/http/guards.d.ts +15 -11
  46. package/dist/http/guards.d.ts.map +1 -1
  47. package/dist/http/guards.js +46 -11
  48. package/dist/http/handoff.d.ts +76 -0
  49. package/dist/http/handoff.d.ts.map +1 -0
  50. package/dist/http/handoff.js +316 -0
  51. package/dist/http/middleware.d.ts +12 -0
  52. package/dist/http/middleware.d.ts.map +1 -1
  53. package/dist/http/middleware.js +25 -4
  54. package/dist/http/resolve.d.ts.map +1 -1
  55. package/dist/http/resolve.js +9 -3
  56. package/dist/http/responses.d.ts +142 -0
  57. package/dist/http/responses.d.ts.map +1 -1
  58. package/dist/http/responses.js +66 -10
  59. package/dist/http/routes.d.ts +2 -0
  60. package/dist/http/routes.d.ts.map +1 -1
  61. package/dist/http/routes.js +35 -4
  62. package/dist/http/schemas.d.ts +57 -0
  63. package/dist/http/schemas.d.ts.map +1 -1
  64. package/dist/http/schemas.js +44 -1
  65. package/dist/http/views.d.ts +22 -2
  66. package/dist/http/views.d.ts.map +1 -1
  67. package/dist/http/views.js +40 -4
  68. package/dist/index.d.ts +2 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/instance/auth.d.ts +148 -10
  72. package/dist/instance/auth.d.ts.map +1 -1
  73. package/dist/instance/auth.js +86 -41
  74. package/dist/instance/plugins.d.ts +6 -0
  75. package/dist/instance/plugins.d.ts.map +1 -1
  76. package/dist/instance/plugins.js +14 -1
  77. package/dist/ledger/read.d.ts +53 -0
  78. package/dist/ledger/read.d.ts.map +1 -0
  79. package/dist/ledger/read.js +85 -0
  80. package/dist/ledger/record.d.ts +35 -0
  81. package/dist/ledger/record.d.ts.map +1 -0
  82. package/dist/ledger/record.js +98 -0
  83. package/dist/lifecycle/erasure.d.ts +9 -0
  84. package/dist/lifecycle/erasure.d.ts.map +1 -0
  85. package/dist/lifecycle/erasure.js +96 -0
  86. package/dist/lifecycle/inactivity.d.ts +19 -0
  87. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  88. package/dist/lifecycle/inactivity.js +28 -0
  89. package/dist/lifecycle/transitions.d.ts +22 -1
  90. package/dist/lifecycle/transitions.d.ts.map +1 -1
  91. package/dist/lifecycle/transitions.js +51 -4
  92. package/dist/mcp/argumentClass.d.ts +51 -0
  93. package/dist/mcp/argumentClass.d.ts.map +1 -0
  94. package/dist/mcp/argumentClass.js +69 -0
  95. package/dist/mcp/capability.d.ts +50 -0
  96. package/dist/mcp/capability.d.ts.map +1 -0
  97. package/dist/mcp/capability.js +140 -0
  98. package/dist/mcp/clientMetadata.d.ts +40 -0
  99. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  100. package/dist/mcp/clientMetadata.js +68 -0
  101. package/dist/mcp/consent.d.ts +49 -0
  102. package/dist/mcp/consent.d.ts.map +1 -0
  103. package/dist/mcp/consent.js +69 -0
  104. package/dist/mcp/dispatch.d.ts +35 -0
  105. package/dist/mcp/dispatch.d.ts.map +1 -0
  106. package/dist/mcp/dispatch.js +135 -0
  107. package/dist/mcp/floor.d.ts +37 -0
  108. package/dist/mcp/floor.d.ts.map +1 -0
  109. package/dist/mcp/floor.js +41 -0
  110. package/dist/mcp/host.d.ts +34 -0
  111. package/dist/mcp/host.d.ts.map +1 -0
  112. package/dist/mcp/host.js +2 -0
  113. package/dist/mcp/http/redirectList.d.ts +9 -0
  114. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  115. package/dist/mcp/http/redirectList.js +24 -0
  116. package/dist/mcp/http/responses.d.ts +143 -0
  117. package/dist/mcp/http/responses.d.ts.map +1 -0
  118. package/dist/mcp/http/responses.js +83 -0
  119. package/dist/mcp/http/routes.d.ts +28 -0
  120. package/dist/mcp/http/routes.d.ts.map +1 -0
  121. package/dist/mcp/http/routes.js +517 -0
  122. package/dist/mcp/http/schemas.d.ts +24 -0
  123. package/dist/mcp/http/schemas.d.ts.map +1 -0
  124. package/dist/mcp/http/schemas.js +18 -0
  125. package/dist/mcp/marker.d.ts +15 -0
  126. package/dist/mcp/marker.d.ts.map +1 -0
  127. package/dist/mcp/marker.js +15 -0
  128. package/dist/mcp/provider.d.ts +78 -0
  129. package/dist/mcp/provider.d.ts.map +1 -0
  130. package/dist/mcp/provider.js +108 -0
  131. package/dist/mcp/purge.d.ts +15 -0
  132. package/dist/mcp/purge.d.ts.map +1 -0
  133. package/dist/mcp/purge.js +31 -0
  134. package/dist/mcp/rpc.d.ts +79 -0
  135. package/dist/mcp/rpc.d.ts.map +1 -0
  136. package/dist/mcp/rpc.js +103 -0
  137. package/dist/mcp/toolAudit.d.ts +76 -0
  138. package/dist/mcp/toolAudit.d.ts.map +1 -0
  139. package/dist/mcp/toolAudit.js +86 -0
  140. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  141. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  142. package/dist/migrations/0006_verification_outcomes.js +35 -0
  143. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  144. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  145. package/dist/migrations/0007_erasure_record.js +36 -0
  146. package/dist/migrations/0008_last_active.d.ts +15 -0
  147. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  148. package/dist/migrations/0008_last_active.js +29 -0
  149. package/dist/migrations/set.d.ts +4 -1
  150. package/dist/migrations/set.d.ts.map +1 -1
  151. package/dist/migrations/set.js +8 -2
  152. package/dist/peer.d.ts +3 -2
  153. package/dist/peer.d.ts.map +1 -1
  154. package/dist/processing/activities.d.ts +6 -0
  155. package/dist/processing/activities.d.ts.map +1 -0
  156. package/dist/processing/activities.js +12 -0
  157. package/dist/purge/contribution.d.ts +20 -5
  158. package/dist/purge/contribution.d.ts.map +1 -1
  159. package/dist/purge/contribution.js +20 -6
  160. package/dist/purge/run.d.ts +75 -5
  161. package/dist/purge/run.d.ts.map +1 -1
  162. package/dist/purge/run.js +117 -14
  163. package/dist/purge/workflow.d.ts +15 -2
  164. package/dist/purge/workflow.d.ts.map +1 -1
  165. package/dist/purge/workflow.js +51 -7
  166. package/dist/test-utils/accountFootprint.d.ts +5 -2
  167. package/dist/test-utils/accountFootprint.d.ts.map +1 -1
  168. package/dist/test-utils/accountFootprint.js +7 -2
  169. package/dist/test-utils/liveApp.d.ts +6 -0
  170. package/dist/test-utils/liveApp.d.ts.map +1 -1
  171. package/dist/test-utils/liveApp.js +7 -2
  172. package/dist/token/handoff.d.ts +80 -0
  173. package/dist/token/handoff.d.ts.map +1 -0
  174. package/dist/token/handoff.js +136 -0
  175. package/dist/version.generated.d.ts +1 -1
  176. package/dist/version.generated.js +1 -1
  177. package/docs/account-lifecycle.md +59 -7
  178. package/docs/apple-signin.md +32 -4
  179. package/docs/facebook-oauth.md +2 -2
  180. package/docs/github-oauth.md +2 -2
  181. package/docs/google-oauth.md +9 -7
  182. package/docs/microsoft-oauth.md +2 -2
  183. package/package.json +11 -5
  184. package/pithy.manifest.json +2 -2
  185. package/pithy.mcp.manifest.json +36 -0
  186. package/src/audit/actions.ts +39 -0
  187. package/src/audit/emit.ts +63 -0
  188. package/src/audit/evidence.ts +8 -4
  189. package/src/capability.ts +80 -23
  190. package/src/client/api.ts +69 -19
  191. package/src/client/bearer.ts +388 -0
  192. package/src/client/handoff.ts +172 -0
  193. package/src/client/mcp.ts +140 -0
  194. package/src/data/betterAuth.ts +8 -4
  195. package/src/data/kitFields.ts +2 -0
  196. package/src/data/tables.ts +4 -2
  197. package/src/data/userLifecycle.ts +15 -3
  198. package/src/data/verificationOutcome.ts +86 -0
  199. package/src/email/send.ts +2 -2
  200. package/src/http/adminRoutes.ts +68 -3
  201. package/src/http/csrf.ts +4 -1
  202. package/src/http/guards.ts +48 -11
  203. package/src/http/handoff.ts +350 -0
  204. package/src/http/middleware.ts +29 -3
  205. package/src/http/resolve.ts +25 -25
  206. package/src/http/responses.ts +134 -8
  207. package/src/http/routes.ts +63 -4
  208. package/src/http/schemas.ts +85 -0
  209. package/src/http/views.ts +46 -2
  210. package/src/index.ts +2 -0
  211. package/src/instance/auth.ts +51 -1
  212. package/src/instance/plugins.ts +20 -2
  213. package/src/ledger/read.ts +133 -0
  214. package/src/ledger/record.ts +198 -0
  215. package/src/lifecycle/erasure.ts +118 -0
  216. package/src/lifecycle/inactivity.ts +56 -0
  217. package/src/lifecycle/transitions.ts +75 -5
  218. package/src/mcp/argumentClass.ts +112 -0
  219. package/src/mcp/capability.ts +194 -0
  220. package/src/mcp/clientMetadata.ts +81 -0
  221. package/src/mcp/consent.ts +95 -0
  222. package/src/mcp/dispatch.ts +154 -0
  223. package/src/mcp/floor.ts +62 -0
  224. package/src/mcp/host.ts +36 -0
  225. package/src/mcp/http/redirectList.ts +26 -0
  226. package/src/mcp/http/responses.ts +157 -0
  227. package/src/mcp/http/routes.ts +635 -0
  228. package/src/mcp/http/schemas.ts +37 -0
  229. package/src/mcp/marker.ts +18 -0
  230. package/src/mcp/provider.ts +151 -0
  231. package/src/mcp/purge.ts +39 -0
  232. package/src/mcp/rpc.ts +135 -0
  233. package/src/mcp/toolAudit.ts +132 -0
  234. package/src/migrations/0006_verification_outcomes.ts +51 -0
  235. package/src/migrations/0007_erasure_record.ts +43 -0
  236. package/src/migrations/0008_last_active.ts +30 -0
  237. package/src/migrations/set.ts +7 -1
  238. package/src/processing/activities.ts +14 -0
  239. package/src/purge/contribution.ts +37 -10
  240. package/src/purge/run.ts +179 -16
  241. package/src/purge/workflow.ts +65 -7
  242. package/src/seeds/example.ts +2 -2
  243. package/src/test-utils/accountFootprint.ts +10 -1
  244. package/src/test-utils/liveApp.ts +10 -1
  245. package/src/token/handoff.ts +180 -0
  246. package/src/version.generated.ts +1 -1
package/dist/purge/run.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { completePurge, duePurges, mailPurgeComplete, purgeSubject, recordPurgeStep } from "../lifecycle/transitions.js";
3
+ import { completePurge, duePurges, mailPurgeComplete, purgeAddress, purgeSubject, recordPurgeFailure, recordPurgeStep } from "../lifecycle/transitions.js";
4
4
  import { AUTH_CAPABILITY } from "./specs.js";
5
5
  import { authWorkflowRetry } from "./retryPolicy.js";
6
+ import { isRetained } from "@pithy-sh/core/src/capability/purge";
6
7
  import { classifiedSteps } from "@pithy-sh/core/src/workflow/faults";
7
8
  //#region src/purge/run.ts
8
9
  /** The operations, over the lifecycle transitions. */
9
- function purgeOps(deps) {
10
+ function purgeOps(deps, holds) {
10
11
  return {
11
12
  due: async (userId) => (await purgeSubject(deps, userId)).state,
12
13
  recordStep: (userId, step, summary) => recordPurgeStep(deps, {
@@ -14,6 +15,13 @@ function purgeOps(deps) {
14
15
  step,
15
16
  summary
16
17
  }),
18
+ recordRetained: (userId, step, basis) => recordPurgeStep(deps, {
19
+ userId,
20
+ step,
21
+ summary: basis,
22
+ retained: true
23
+ }),
24
+ address: (userId) => purgeAddress(deps.db, userId),
17
25
  mailComplete: async (userId, notify) => {
18
26
  const subject = await purgeSubject(deps, userId);
19
27
  if (subject.state !== "due") return false;
@@ -23,7 +31,12 @@ function purgeOps(deps) {
23
31
  ...silenced ? { notify: false } : {}
24
32
  })).mailed;
25
33
  },
26
- complete: async (userId) => (await completePurge(deps, { userId })).changed
34
+ complete: async (userId) => (await completePurge(deps, { userId })).changed,
35
+ fail: (userId, step) => recordPurgeFailure(deps, {
36
+ userId,
37
+ step
38
+ }),
39
+ held: (userId) => holds.held("user", userId)
27
40
  };
28
41
  }
29
42
  /** Run one account's purge, one step per contribution, auth's last. See the file header for the order. */
@@ -35,28 +48,76 @@ async function purgeUser(run, step, terminalError, params) {
35
48
  userId,
36
49
  state,
37
50
  erased: [],
51
+ retained: [],
38
52
  mailed: false
39
53
  };
54
+ const stopped = (next) => own.do(`hold ${next}`, () => run.ops.held(userId));
40
55
  const context = {
41
56
  subject: {
42
57
  type: "user",
43
58
  id: userId
44
59
  },
45
- env: run.env
60
+ env: run.env,
61
+ address: () => run.ops.address(userId)
46
62
  };
47
63
  const auth = run.steps.filter((each) => each.step === AUTH_CAPABILITY);
48
64
  const others = run.steps.filter((each) => each.step !== AUTH_CAPABILITY);
49
65
  const erased = [];
50
- for (const each of others) erased.push(await eraseStep(step, run.ops, each, context));
51
- const mailed = await own.do("mail", () => run.ops.mailComplete(userId, params.notify));
52
- for (const each of auth) erased.push(await eraseStep(step, run.ops, each, context));
53
- await own.do("complete", () => run.ops.complete(userId));
54
- return {
66
+ const retained = [];
67
+ let current = "due";
68
+ const held = {
55
69
  userId,
56
- state: "purged",
70
+ state: "held",
57
71
  erased,
58
- mailed
72
+ retained,
73
+ mailed: false
74
+ };
75
+ const runStep = async (each) => {
76
+ const { contribution } = each;
77
+ current = each.step;
78
+ if (isRetained(contribution)) retained.push(await retainStep(step, run.ops, each.step, contribution.retain.basis, userId));
79
+ else erased.push(await eraseStep(step, run.ops, each, context));
59
80
  };
81
+ try {
82
+ for (const each of others) {
83
+ if (await stopped(each.step)) return held;
84
+ await runStep(each);
85
+ }
86
+ current = "mail";
87
+ if (await stopped("mail")) return held;
88
+ const mailed = await own.do("mail", () => run.ops.mailComplete(userId, params.notify));
89
+ for (const each of auth) {
90
+ if (await stopped(each.step)) return {
91
+ ...held,
92
+ mailed
93
+ };
94
+ await runStep(each);
95
+ }
96
+ current = "complete";
97
+ await own.do("complete", () => run.ops.complete(userId));
98
+ return {
99
+ userId,
100
+ state: "purged",
101
+ erased,
102
+ retained,
103
+ mailed
104
+ };
105
+ } catch (error) {
106
+ await recordFailure(step, run.ops, userId, current);
107
+ throw error;
108
+ }
109
+ }
110
+ /**
111
+ * Record where a purge gave up, in its own step, and never mask the failure that stopped it: a `fail` step that
112
+ * cannot write is swallowed. See the file header.
113
+ */
114
+ async function recordFailure(step, ops, userId, at) {
115
+ try {
116
+ await step.do("fail", async () => {
117
+ await ops.fail(userId, at);
118
+ return at;
119
+ });
120
+ } catch {}
60
121
  }
61
122
  /**
62
123
  * One capability's step: erase, then record that it ran. On the platform's own retry, unclassified — see the
@@ -65,11 +126,21 @@ async function purgeUser(run, step, terminalError, params) {
65
126
  */
66
127
  function eraseStep(step, ops, each, context) {
67
128
  return step.do(`erase ${each.step}`, async () => {
68
- await each.contribution.erase(context);
129
+ await each.contribution.erase?.(context);
69
130
  await ops.recordStep(context.subject.id, each.step, each.contribution.summary);
70
131
  return each.step;
71
132
  });
72
133
  }
134
+ /**
135
+ * One capability's retained step (#814): nothing is erased, and the record says the rows were kept and why. Its own
136
+ * step, so the trail names it in the order it would have run, and a replay serves it from the journal.
137
+ */
138
+ function retainStep(step, ops, name, basis, userId) {
139
+ return step.do(`retain ${name}`, async () => {
140
+ await ops.recordRetained(userId, name, basis);
141
+ return name;
142
+ });
143
+ }
73
144
  /** How many purges one `start` step dispatches — a page, so one pass over a backlog is a bounded number of steps. */
74
145
  const PURGE_START_PAGE = 50;
75
146
  /** The default size of one daily pass. */
@@ -88,7 +159,10 @@ async function startDuePurges(run, step, terminalError, params) {
88
159
  const ids = due.slice(page * 50, (page + 1) * 50);
89
160
  started += await own.do(`start ${page + 1}`, async () => {
90
161
  let running = 0;
91
- for (const each of ids) if (await run.start(each)) running += 1;
162
+ for (const each of ids) {
163
+ if (run.held && await run.held(each.userId)) continue;
164
+ if (await run.start(each)) running += 1;
165
+ }
92
166
  return running;
93
167
  });
94
168
  }
@@ -98,5 +172,34 @@ async function startDuePurges(run, step, terminalError, params) {
98
172
  function duePurgesOf(deps) {
99
173
  return (limit) => duePurges(deps, limit);
100
174
  }
175
+ /** How many inactive accounts one pass soft-deletes, at most: a backlog drains over nights, never in one. */
176
+ const INACTIVE_DEFAULT_LIMIT = 200;
177
+ /**
178
+ * The inactivity pass: every account untouched for longer than the strictest class age it holds is
179
+ * soft-deleted through the lifecycle — its deletion-scheduled mail, its window, then the purge the daily pass starts
180
+ * once that window closes. A held account is skipped. With no class age that applies, the pass does nothing.
181
+ *
182
+ * Listed in one step, deleted in pages of steps, so a pass that dies part-way resumes after the page it finished.
183
+ * A deletion is no transition on an account already deleted, so a repeated page deletes nobody twice.
184
+ */
185
+ async function deleteInactiveAccounts(run, step, terminalError, limit = 200) {
186
+ const own = classifiedSteps(step, authWorkflowRetry, terminalError);
187
+ const days = await own.do("class age", () => run.days());
188
+ if (days === null) return { deleted: 0 };
189
+ const ids = await own.do("inactive", () => run.inactive(/* @__PURE__ */ new Date(run.now().getTime() - days * 864e5), limit));
190
+ let deleted = 0;
191
+ for (let page = 0; page * 50 < ids.length; page += 1) {
192
+ const slice = ids.slice(page * 50, (page + 1) * 50);
193
+ deleted += await own.do(`inactive ${page + 1}`, async () => {
194
+ let count = 0;
195
+ for (const userId of slice) {
196
+ if (await run.held(userId)) continue;
197
+ if (await run.remove(userId, days)) count += 1;
198
+ }
199
+ return count;
200
+ });
201
+ }
202
+ return { deleted };
203
+ }
101
204
  //#endregion
102
- export { PURGE_DUE_DEFAULT_LIMIT, PURGE_START_PAGE, duePurgesOf, purgeOps, purgeUser, startDuePurges };
205
+ export { INACTIVE_DEFAULT_LIMIT, PURGE_DUE_DEFAULT_LIMIT, PURGE_START_PAGE, deleteInactiveAccounts, duePurgesOf, purgeOps, purgeUser, startDuePurges };
@@ -1,8 +1,10 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import type { Logger } from "@pithy-sh/core/src/logger/logger";
4
+ import { type LegalHolds } from "@pithy-sh/core/src/retention/holds";
4
5
  import type { TerminalErrorConstructor, WorkflowStepLike } from "@pithy-sh/core/src/workflow/faults";
5
- import { type PurgeDueRun, type PurgeOutcome } from "./run";
6
+ import { type LifecycleDeps } from "../lifecycle/transitions";
7
+ import { type InactivityRun, type PurgeDueRun, type PurgeOutcome } from "./run";
6
8
  /**
7
9
  * The purge's two Workflow bodies (#622) — run by classes **the adopter's own Worker** exports, beside the
8
10
  * `createEntrypoint` it already exports, because a purge runs every composed capability's contribution and
@@ -40,10 +42,21 @@ interface PurgeEvent {
40
42
  }
41
43
  /** Purge one account: every composed contribution, one step each, auth's last. See `./run.ts`. */
42
44
  export declare function runAuthPurge(env: Record<string, unknown>, event: PurgeEvent, step: WorkflowStepLike, terminalError: TerminalErrorConstructor): Promise<PurgeOutcome>;
43
- /** The daily pass: start a purge for every account past its window. See `./run.ts`. */
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
+ */
44
49
  export declare function runAuthPurgeDue(env: Record<string, unknown>, event: PurgeEvent, step: WorkflowStepLike, terminalError: TerminalErrorConstructor): Promise<{
45
50
  started: number;
51
+ inactive: number;
46
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;
47
60
  /**
48
61
  * How the daily pass starts one account's purge: under the id the deletion names (`./start.ts`), so a purge a hard
49
62
  * deletion already started today is the same instance, not a second one. No `notify`: the deletion's own row
@@ -1 +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,KAAK,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAOrG,OAAO,EAAe,KAAK,WAAW,EAAE,KAAK,YAAY,EAAuC,MAAM,OAAO,CAAC;AAI9G;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,0CAA0C;AAC1C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 import { inactiveAccounts } from "../lifecycle/inactivity.js";
4
5
  import { resolveDb } from "../http/resolve.js";
6
+ import { deleteUser } from "../lifecycle/transitions.js";
5
7
  import { AUTH_PURGE_BINDING, AUTH_PURGE_KEY, AuthPurgeDueParams, AuthPurgeParams } from "./specs.js";
6
8
  import { startPurgeInstance } from "./start.js";
7
9
  import { isAuthCapability } from "../capability.js";
8
- import { duePurgesOf, purgeOps, purgeUser, startDuePurges } from "./run.js";
10
+ import { deleteInactiveAccounts, duePurgesOf, purgeOps, purgeUser, startDuePurges } from "./run.js";
9
11
  import { messageOf } from "@pithy-sh/core/src/error/pithyError";
10
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";
11
15
  import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
12
- import { composedCapability } from "@pithy-sh/core/src/capability/composition";
16
+ import { composedCapabilities, composedCapability } from "@pithy-sh/core/src/capability/composition";
17
+ import { legalHolds } from "@pithy-sh/core/src/retention/holds";
13
18
  import { enqueueFromEnv } from "@pithy-sh/email/src/send/fromComposition";
14
19
  //#region src/purge/workflow.ts
15
20
  /** The lifecycle transitions' dependencies, for a run with no request: this env, and the composition's seams. */
@@ -41,19 +46,58 @@ async function runAuthPurge(env, event, step, terminalError) {
41
46
  return purgeUser({
42
47
  steps: auth.purgeSteps,
43
48
  env,
44
- ops: purgeOps(lifecycle)
49
+ ops: purgeOps(lifecycle, legalHolds(env))
45
50
  }, step, terminalError, params);
46
51
  }
47
- /** The daily pass: start a purge for every account past its window. See `./run.ts`. */
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
+ */
48
56
  async function runAuthPurgeDue(env, event, step, terminalError) {
49
57
  const params = AuthPurgeDueParams.parse(event.payload ?? {});
50
58
  const auth = composedCapability("auth", isAuthCapability);
51
59
  const log = runLog(env, event, "auth:purge-due");
52
60
  const lifecycle = lifecycleFor(auth, env, log);
53
- return startDuePurges({
61
+ const holds = legalHolds(env);
62
+ const { started } = await startDuePurges({
54
63
  due: duePurgesOf(lifecycle),
55
- start: purgeStarter(env, log)
64
+ start: purgeStarter(env, log),
65
+ held: (userId) => holds.held("user", userId)
56
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
+ };
57
101
  }
58
102
  /**
59
103
  * How the daily pass starts one account's purge: under the id the deletion names (`./start.ts`), so a purge a hard
@@ -93,4 +137,4 @@ function purgeStarter(env, log, now = () => /* @__PURE__ */ new Date()) {
93
137
  };
94
138
  }
95
139
  //#endregion
96
- export { purgeStarter, runAuthPurge, runAuthPurgeDue };
140
+ export { inactivityOps, inactivityRun, purgeStarter, runAuthPurge, runAuthPurgeDue };
@@ -2,8 +2,11 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import type { D1Database } from "@cloudflare/workers-types";
4
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"]];
6
- /** Write a full footprint for one account: a user, a session, a provider link, a device, a spent token, two pending codes. */
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
+ */
7
10
  export declare function seedAccountFootprint(d1: D1Database, userId: string, email?: string): Promise<void>;
8
11
  /** How many rows one account still holds in each footprint table, and in the pending codes for its address. */
9
12
  export declare function footprintCounts(d1: D1Database, userId: string, email?: string): Promise<Record<string, number>>;
@@ -1 +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,EAC/B,CAAC;AAEX,8HAA8H;AAC9H,wBAAsB,oBAAoB,CACxC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,MAAM,EACd,KAAK,SAAuB,GAC3B,OAAO,CAAC,IAAI,CAAC,CA2Cf;AAED,+GAA+G;AAC/G,wBAAsB,eAAe,CAAC,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,SAAuB,mCAoBjG"}
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"}
@@ -14,9 +14,13 @@ const FOOTPRINT_TABLES = [
14
14
  ["pithy_auth_sessions", "user_id"],
15
15
  ["pithy_auth_accounts", "user_id"],
16
16
  ["pithy_auth_devices", "user_id"],
17
- ["pithy_auth_rotated_tokens", "user_id"]
17
+ ["pithy_auth_rotated_tokens", "user_id"],
18
+ ["pithy_auth_verification_outcomes", "user_id"]
18
19
  ];
19
- /** Write a full footprint for one account: a user, a session, a provider link, a device, a spent token, two pending codes. */
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
+ */
20
24
  async function seedAccountFootprint(d1, userId, email = `${userId}@test.com`) {
21
25
  await d1.batch([
22
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),
@@ -24,6 +28,7 @@ async function seedAccountFootprint(d1, userId, email = `${userId}@test.com`) {
24
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),
25
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),
26
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),
27
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),
28
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({
29
34
  email,
@@ -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,CAAA;KAAE,GAAG,SAAS,CAAC;IAChE,yGAAyG;IACzG,SAAS,CAAC,EAAE;QAAE,IAAI,EAAE,SAAS,GAAG,WAAW,CAAC;QAAC,SAAS,EAAE,MA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Config } 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;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAEtC,8EAA8E;AAC9E,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAWtC,oEAAoE;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