@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
@@ -2,20 +2,21 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { AuthAuditActions } from "../audit/actions.js";
4
4
  import { LifecycleColumns, accountStanding } from "./state.js";
5
+ import "./reason.js";
5
6
  import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
6
- import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
7
+ import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
7
8
  import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
8
9
  import { sql } from "kysely";
10
+ import { composedRetention } from "@pithy-sh/core/src/retention/composed";
11
+ import { purgeWindowDays } from "@pithy-sh/core/src/retention/policy";
9
12
  //#region src/lifecycle/transitions.ts
10
- /** The longest reason the kit stores. It is shown to the person, so it is a sentence, not a case file. */
11
- const MAX_REASON = 500;
12
13
  /** A reason, trimmed and bounded, or null when none was given. */
13
14
  function reasonOf(reason) {
14
15
  if (reason === null || reason === void 0) return null;
15
16
  const trimmed = reason.trim();
16
17
  if (trimmed === "") return null;
17
- if (trimmed.length > MAX_REASON) throw new ValidationError({
18
- message: `A reason is at most ${MAX_REASON} characters.`,
18
+ if (trimmed.length > 500) throw new ValidationError({
19
+ message: `A reason is at most 500 characters.`,
19
20
  detail: `lifecycle reason of ${trimmed.length} characters`
20
21
  });
21
22
  return trimmed;
@@ -60,6 +61,9 @@ function encoded(row) {
60
61
  reason: row.reason,
61
62
  suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
62
63
  step: row.step ?? null,
64
+ notify: row.notify === void 0 || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
65
+ mode: row.mode ?? null,
66
+ purgeAfter: row.purgeAfter ? SQLiteDate.encode(row.purgeAfter) : null,
63
67
  createdAt: SQLiteDate.encode(row.at)
64
68
  };
65
69
  }
@@ -88,6 +92,9 @@ async function move(deps, update, row) {
88
92
  "reason",
89
93
  "suspendedUntil",
90
94
  "step",
95
+ "notify",
96
+ "mode",
97
+ "purgeAfter",
91
98
  "createdAt"
92
99
  ]).expression(deps.db.selectNoFrom([
93
100
  sql.val(v.userId).as("userId"),
@@ -97,6 +104,9 @@ async function move(deps, update, row) {
97
104
  sql.val(v.reason).as("reason"),
98
105
  sql.val(v.suspendedUntil).as("suspendedUntil"),
99
106
  sql.val(v.step).as("step"),
107
+ sql.val(v.notify).as("notify"),
108
+ sql.val(v.mode).as("mode"),
109
+ sql.val(v.purgeAfter).as("purgeAfter"),
100
110
  sql.val(v.createdAt).as("createdAt")
101
111
  ]).where(sql`changes()`, ">", 0)).compile();
102
112
  const [updated] = await deps.d1.batch([prepared(deps.d1, update.compile()), prepared(deps.d1, insert)]);
@@ -104,6 +114,7 @@ async function move(deps, update, row) {
104
114
  }
105
115
  /** The audit event, swallowed on failure — an audit write never breaks what it records. */
106
116
  async function audit(deps, action, userId, actor, metadata) {
117
+ const context = deps.context;
107
118
  const event = {
108
119
  action,
109
120
  outcome: "success",
@@ -111,17 +122,23 @@ async function audit(deps, action, userId, actor, metadata) {
111
122
  actorId: actor.id,
112
123
  resourceType: "user",
113
124
  resourceId: userId,
114
- metadata
125
+ ...context?.ip ? { ip: context.ip } : {},
126
+ ...context?.userAgent ? { userAgent: context.userAgent } : {},
127
+ ...context?.requestId ? { requestId: context.requestId } : {},
128
+ metadata: {
129
+ ...context?.metadata,
130
+ ...metadata
131
+ }
115
132
  };
116
133
  try {
117
134
  await deps.emit(event);
118
135
  } catch (error) {
119
- deps.log?.warn(`lifecycle audit ${action} failed; the transition stands`, { reason: messageOf(error) });
136
+ deps.log?.warn(`lifecycle audit ${action} failed; the transition stands`, { reason: messageOf$1(error) });
120
137
  }
121
138
  }
122
- /** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. */
139
+ /** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. Says whether it was enqueued. */
123
140
  async function mail(deps, enabled, to, locale, template, payload) {
124
- if (!enabled || !deps.enqueueEmail) return;
141
+ if (!enabled || !deps.enqueueEmail) return false;
125
142
  try {
126
143
  await deps.enqueueEmail({
127
144
  to,
@@ -129,8 +146,10 @@ async function mail(deps, enabled, to, locale, template, payload) {
129
146
  payload,
130
147
  ...locale ? { locale } : {}
131
148
  });
149
+ return true;
132
150
  } catch (error) {
133
- deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, { reason: messageOf(error) });
151
+ deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, { reason: messageOf$1(error) });
152
+ return false;
134
153
  }
135
154
  }
136
155
  /** Fire one hook. Swallowed and logged: the transition is already written, and a retry would fire nothing. */
@@ -141,22 +160,68 @@ async function fire(deps, name, hook, event) {
141
160
  } catch (error) {
142
161
  deps.log?.warn(`${name} threw; the transition stands`, {
143
162
  userId: event.userId,
144
- reason: messageOf(error)
163
+ reason: messageOf$1(error)
145
164
  });
146
165
  }
147
166
  }
148
- function messageOf(error) {
167
+ function messageOf$1(error) {
149
168
  return error instanceof Error ? error.message : String(error);
150
169
  }
151
170
  /** Without a name, a greeting says "Hi," rather than greeting an empty string. */
152
171
  function named(name) {
153
172
  return name.trim() ? { name } : {};
154
173
  }
174
+ /** The conflict for a deleted account: deletion outranks a suspension, so restore it first. */
175
+ function deletedConflict(restoreRoute, then) {
176
+ return new ConflictError({
177
+ message: restoreRoute ? `This account is deleted. Restore it with ${restoreRoute} first.` : "This account is deleted. Restore it first.",
178
+ action: restoreRoute ? `Restore it with ${restoreRoute}. ${then}` : `Restore it first. ${then}`
179
+ });
180
+ }
181
+ /** The conflict for a write that found the account moved under it by another request. Retrying is safe. */
182
+ function raced(userId) {
183
+ return new ConflictError({
184
+ message: "The account changed while this request was being made. Send it again.",
185
+ detail: `lifecycle write for user ${userId} matched no row; another request moved the account first`
186
+ });
187
+ }
188
+ /**
189
+ * The instant a purge-window guard compares against, **read when the statement runs**, as ms-epoch (#622).
190
+ *
191
+ * A restore and a purge's `due` check race for one account, and each has to see the window the other saw. A
192
+ * timestamp the restore took before its statement went out is stale by the time D1 runs it: the window can
193
+ * close in between, by itself or because a hard deletion brought it forward, and a purge whose `due` check ran
194
+ * in that gap goes on to erase an account the restore reported back. So on the system clock the guard is the
195
+ * database's own time, evaluated inside the statement, and D1 runs statements one at a time: whichever lands
196
+ * first, the other sees it. An injected clock is a test's, and is read afresh here, at the statement.
197
+ */
198
+ function windowClock(deps) {
199
+ return deps.now ? sql`${deps.now().getTime()}` : sql`cast(round(unixepoch('subsec') * 1000) as integer)`;
200
+ }
201
+ /** The conflict for an account whose purge window has closed: nothing can restore it now. */
202
+ function windowClosed(userId, closes) {
203
+ return new ConflictError({
204
+ message: `This account's purge window closed on ${closes.toISOString()}. It can no longer be restored.`,
205
+ action: "The purge is due and erases its data once it runs. There is nothing to restore.",
206
+ detail: `restore for user ${userId}, whose purge was due at ${closes.toISOString()}`
207
+ });
208
+ }
155
209
  /**
156
210
  * Suspend an account, until `until` or until it is reinstated.
157
211
  *
158
212
  * A deleted account cannot be suspended — deletion already shuts it, and outranks a suspension — so that is a
159
- * conflict rather than a no-op. A suspension whose end has passed is not in force, and a new one replaces it.
213
+ * conflict rather than a no-op, and names `restoreRoute` when the caller gives one. A suspension whose end has
214
+ * passed is not in force, and a new one replaces it.
215
+ *
216
+ * **An account already suspended has its terms restated (#621).** The reason and the end are replaced, a
217
+ * `suspended` row records the new reason — the newest one is what the person is shown — and the audit event
218
+ * and the mail say so. The start is kept, and no hook fires: the account was suspended and still is, so
219
+ * nothing transitioned. A fresh suspension that loses the race to another suspension finds the account
220
+ * suspended, so it retries once as a restatement rather than failing. A write that finds the account moved
221
+ * under it any other way, by a reinstatement or a deletion that landed first, is a conflict: what the caller
222
+ * asked for no longer describes the account.
223
+ *
224
+ * `notify: false` sends no mail, whatever the config says; the config can only turn mail off, never on.
160
225
  */
161
226
  async function suspendUser(deps, input) {
162
227
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
@@ -165,39 +230,56 @@ async function suspendUser(deps, input) {
165
230
  if (until && until.getTime() <= at.getTime()) throw new ValidationError({ message: "A suspension must end in the future, or not at all." });
166
231
  const subject = await subjectOf(deps.db, input.userId);
167
232
  const standing = accountStanding(subject.columns, at);
168
- if (standing.state === "deleted") throw new ConflictError({
169
- message: "This account is deleted.",
170
- action: "Restore it first, if it should be suspended instead."
171
- });
172
- if (standing.state === "suspended") return { changed: false };
173
- if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
233
+ if (standing.state === "deleted") throw deletedConflict(input.restoreRoute, "Then suspend it, if it should be suspended instead.");
234
+ const encodedUntil = until ? SQLiteDate.encode(until) : null;
235
+ /** The same suspension, still in force: pinned by its start, so a reinstate-then-suspend in between is a different suspension and this write matches nothing. */
236
+ const restatement = (startedAt) => deps.db.updateTable("pithyAuthUsers").set({ suspendedUntil: encodedUntil }).where("id", "=", input.userId).where("deletedAt", "is", null).where("suspendedAt", "=", SQLiteDate.encode(startedAt)).where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
237
+ const fresh = deps.db.updateTable("pithyAuthUsers").set({
174
238
  suspendedAt: SQLiteDate.encode(at),
175
- suspendedUntil: until ? SQLiteDate.encode(until) : null
176
- }).where("id", "=", input.userId).where("deletedAt", "is", null).where((eb) => eb.or([eb("suspendedAt", "is", null), eb.and([eb("suspendedUntil", "is not", null), eb("suspendedUntil", "<=", SQLiteDate.encode(at))])])), {
239
+ suspendedUntil: encodedUntil
240
+ }).where("id", "=", input.userId).where("deletedAt", "is", null).where((eb) => eb.or([eb("suspendedAt", "is", null), eb.and([eb("suspendedUntil", "is not", null), eb("suspendedUntil", "<=", SQLiteDate.encode(at))])]));
241
+ const row = {
177
242
  userId: input.userId,
178
243
  action: "suspended",
179
244
  actor: input.actor,
180
245
  reason,
181
246
  at,
182
247
  suspendedUntil: until
183
- })) return { changed: false };
248
+ };
249
+ let updated = standing.state === "suspended";
250
+ let startedAt = updated && subject.columns.suspendedAt ? subject.columns.suspendedAt : at;
251
+ if (!await move(deps, updated ? restatement(startedAt) : fresh, row)) {
252
+ const now = updated ? null : await subjectOf(deps.db, input.userId);
253
+ const moved = now ? accountStanding(now.columns, at) : null;
254
+ if (!now?.columns.suspendedAt || moved?.state !== "suspended") throw raced(input.userId);
255
+ updated = true;
256
+ startedAt = now.columns.suspendedAt;
257
+ if (!await move(deps, restatement(startedAt), row)) throw raced(input.userId);
258
+ }
184
259
  await audit(deps, AuthAuditActions.adminUserSuspended, input.userId, input.actor, {
185
260
  reason,
186
- suspendedUntil: until?.toISOString() ?? null
261
+ suspendedUntil: until?.toISOString() ?? null,
262
+ updated
187
263
  });
188
- await mail(deps, deps.config.lifecycleEmails.accountSuspended, subject.email, subject.locale, "accountSuspended", {
264
+ const mailed = await mail(deps, deps.config.lifecycleEmails.accountSuspended && input.notify !== false, subject.email, subject.locale, "accountSuspended", {
189
265
  ...named(subject.name),
190
266
  ...reason ? { reason } : {},
191
267
  ...until ? { until: readable(until, subject.locale) } : {}
192
268
  });
193
- await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
269
+ if (!updated) await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
194
270
  userId: input.userId,
195
271
  actor: input.actor,
196
272
  reason,
197
273
  at,
198
274
  suspendedUntil: until
199
275
  });
200
- return { changed: true };
276
+ return {
277
+ changed: !updated,
278
+ updated,
279
+ mailed,
280
+ suspendedAt: startedAt,
281
+ suspendedUntil: until
282
+ };
201
283
  }
202
284
  /**
203
285
  * Lift a suspension. An account that is not suspended — including one whose suspension ran out — is a no-op.
@@ -206,17 +288,19 @@ async function suspendUser(deps, input) {
206
288
  * past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
207
289
  * for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
208
290
  * sign in again" to somebody every sign-in still refuses. Restore it first.
291
+ *
292
+ * `notify: false` sends no mail, on the same rule as `suspendUser`.
209
293
  */
210
294
  async function reinstateUser(deps, input) {
211
295
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
212
296
  const reason = reasonOf(input.reason);
213
297
  const subject = await subjectOf(deps.db, input.userId);
214
298
  const standing = accountStanding(subject.columns, at);
215
- if (standing.state === "deleted") throw new ConflictError({
216
- message: "This account is deleted.",
217
- action: "Restore it first. Its suspension stays in place through a restore, and can be lifted after."
218
- });
219
- if (standing.state !== "suspended") return { changed: false };
299
+ if (standing.state === "deleted") throw deletedConflict(input.restoreRoute, "Its suspension stays in place through a restore, and can be lifted after.");
300
+ if (standing.state !== "suspended") return {
301
+ changed: false,
302
+ mailed: false
303
+ };
220
304
  if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
221
305
  suspendedAt: null,
222
306
  suspendedUntil: null
@@ -226,46 +310,112 @@ async function reinstateUser(deps, input) {
226
310
  actor: input.actor,
227
311
  reason,
228
312
  at
229
- })) return { changed: false };
313
+ })) return {
314
+ changed: false,
315
+ mailed: false
316
+ };
230
317
  await audit(deps, AuthAuditActions.adminUserReinstated, input.userId, input.actor, { reason });
231
- await mail(deps, deps.config.lifecycleEmails.accountReinstated, subject.email, subject.locale, "accountReinstated", named(subject.name));
318
+ const mailed = await mail(deps, deps.config.lifecycleEmails.accountReinstated && input.notify !== false, subject.email, subject.locale, "accountReinstated", named(subject.name));
232
319
  await fire(deps, "onUserReinstated", deps.hooks.onUserReinstated, {
233
320
  userId: input.userId,
234
321
  actor: input.actor,
235
322
  reason,
236
323
  at
237
324
  });
238
- return { changed: true };
325
+ return {
326
+ changed: true,
327
+ mailed
328
+ };
329
+ }
330
+ /**
331
+ * How many days a soft deletion stays restorable: the Worker's `retention.purgeWindows.user` when its block
332
+ * names one, else `retention.purgeAfterDays` from this capability's own config.
333
+ */
334
+ function userPurgeWindowDays(config) {
335
+ const retention = composedRetention();
336
+ return (retention && purgeWindowDays(retention, "user")) ?? config.retention.purgeAfterDays;
239
337
  }
240
338
  /**
241
- * Delete an account, softly: it is shut now, and its data is erased once `retention.purgeAfterDays` have
242
- * passed. Restorable until then. Audited as the account's own deletion when its holder is the actor.
339
+ * Delete an account. Audited as the account's own deletion when its holder is the actor.
340
+ *
341
+ * **Soft, the default**: it is shut now, and its data is erased once `retention.purgeAfterDays` have passed.
342
+ * Restorable until then. The deletion-scheduled mail carries the purge date and, when the config names one,
343
+ * the restore path. A deleted account deleted softly again is no transition.
344
+ *
345
+ * **Hard** (#622): `purgeAfter` is now, so the window is already closed — nothing can restore it — and the
346
+ * caller starts the purge. No deletion-scheduled mail, because nothing is scheduled; the purge sends the
347
+ * deletion-complete one. An account already deleted softly has its purge brought forward to now, which is
348
+ * written and audited but fires no hook: the account was deleted and still is. One already due is unchanged.
243
349
  *
244
350
  * A suspension the account was under is left in place, so restoring the account does not lift it.
351
+ * `notify: false` sends no mail, whatever the config says.
245
352
  */
246
353
  async function deleteUser(deps, input) {
247
354
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
248
355
  const reason = reasonOf(input.reason);
249
- const purgeAfter = new Date(at.getTime() + deps.config.retention.purgeAfterDays * 864e5);
356
+ const hard = input.mode === "hard";
357
+ const purgeAfter = hard ? at : new Date(at.getTime() + userPurgeWindowDays(deps.config) * 864e5);
250
358
  const subject = await subjectOf(deps.db, input.userId);
251
- if (subject.columns.deletedAt) return { changed: false };
252
- if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
253
- deletedAt: SQLiteDate.encode(at),
254
- purgeAfter: SQLiteDate.encode(purgeAfter)
255
- }).where("id", "=", input.userId).where("deletedAt", "is", null), {
359
+ const row = {
256
360
  userId: input.userId,
257
361
  action: "deleted",
258
362
  actor: input.actor,
259
363
  reason,
260
- at
261
- })) return { changed: false };
262
- await audit(deps, input.actor.type === "user" && input.actor.id === input.userId ? AuthAuditActions.userSelfDeleted : AuthAuditActions.adminUserSoftDeleted, input.userId, input.actor, {
364
+ at,
365
+ mode: hard ? "hard" : "soft",
366
+ purgeAfter,
367
+ ...hard && input.notify !== void 0 ? { notify: input.notify } : {}
368
+ };
369
+ const existing = subject.columns.deletedAt;
370
+ if (existing) {
371
+ const due = subject.columns.purgeAfter ?? existing;
372
+ const unchanged = {
373
+ changed: false,
374
+ mailed: false,
375
+ outcome: "unchanged",
376
+ deletedAt: existing,
377
+ purgeAfter: due
378
+ };
379
+ if (!hard || due.getTime() <= at.getTime()) return unchanged;
380
+ if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({ purgeAfter: SQLiteDate.encode(at) }).where("id", "=", input.userId).where("deletedAt", "=", SQLiteDate.encode(existing)).where("purgeAfter", ">", SQLiteDate.encode(at)), row)) return unchanged;
381
+ await audit(deps, AuthAuditActions.adminUserHardDeleted, input.userId, input.actor, {
382
+ reason,
383
+ purgeAfter: at.toISOString(),
384
+ broughtForward: true
385
+ });
386
+ return {
387
+ changed: false,
388
+ mailed: false,
389
+ outcome: "brought_forward",
390
+ deletedAt: existing,
391
+ purgeAfter: at
392
+ };
393
+ }
394
+ if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
395
+ deletedAt: SQLiteDate.encode(at),
396
+ purgeAfter: SQLiteDate.encode(purgeAfter)
397
+ }).where("id", "=", input.userId).where("deletedAt", "is", null), row)) {
398
+ const now = await subjectOf(deps.db, input.userId);
399
+ if (!now.columns.deletedAt) throw raced(input.userId);
400
+ const due = now.columns.purgeAfter ?? now.columns.deletedAt;
401
+ return {
402
+ changed: false,
403
+ mailed: false,
404
+ outcome: "unchanged",
405
+ deletedAt: now.columns.deletedAt,
406
+ purgeAfter: due
407
+ };
408
+ }
409
+ const self = input.actor.type === "user" && input.actor.id === input.userId;
410
+ await audit(deps, hard ? AuthAuditActions.adminUserHardDeleted : self ? AuthAuditActions.userSelfDeleted : AuthAuditActions.adminUserSoftDeleted, input.userId, input.actor, {
263
411
  reason,
264
412
  purgeAfter: purgeAfter.toISOString()
265
413
  });
266
- await mail(deps, deps.config.lifecycleEmails.deletionScheduled, subject.email, subject.locale, "deletionScheduled", {
414
+ const restoreUrl = deps.config.retention.restoreUrl;
415
+ const mailed = hard ? false : await mail(deps, deps.config.lifecycleEmails.deletionScheduled && input.notify !== false, subject.email, subject.locale, "deletionScheduled", {
267
416
  ...named(subject.name),
268
- purgeOn: readable(purgeAfter, subject.locale)
417
+ purgeOn: readable(purgeAfter, subject.locale),
418
+ ...restoreUrl ? { restoreUrl } : {}
269
419
  });
270
420
  await fire(deps, "onUserDeleted", deps.hooks.onUserDeleted, {
271
421
  userId: input.userId,
@@ -274,76 +424,247 @@ async function deleteUser(deps, input) {
274
424
  at,
275
425
  purgeAfter
276
426
  });
277
- return { changed: true };
427
+ return {
428
+ changed: true,
429
+ mailed,
430
+ outcome: "deleted",
431
+ deletedAt: at,
432
+ purgeAfter
433
+ };
278
434
  }
279
435
  /**
280
- * Restore a deleted account inside its purge window. After the purge there is no account, and that is a 404
281
- * whose action says the data is gone.
436
+ * Restore a deleted account inside its purge window.
437
+ *
438
+ * **Only inside it.** Once `purgeAfter` has passed the purge is due, may already be running, and erases each
439
+ * capability's rows in turn, so restoring then would hand back an account with some of its data gone. That
440
+ * is a conflict naming the date the window closed. After the purge there is no account at all, and that is a
441
+ * 404 whose action says the data is gone — read off the history row the purge leaves behind, so it is told
442
+ * apart from an id that never existed.
443
+ *
444
+ * An account that is not deleted is no transition. A suspension it was under is still in force after.
282
445
  */
283
446
  async function restoreUser(deps, input) {
284
447
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
285
448
  const reason = reasonOf(input.reason);
286
- if (!(await subjectOf(deps.db, input.userId)).columns.deletedAt) return { changed: false };
449
+ const subject = await subjectOf(deps.db, input.userId).catch(async (error) => {
450
+ throw await purgedRefusal(deps.db, input.userId) ?? error;
451
+ });
452
+ const suspended = (columns) => accountStanding({
453
+ ...columns,
454
+ deletedAt: null,
455
+ purgeAfter: null
456
+ }, at).state === "suspended";
457
+ const state = suspended(subject.columns) ? "suspended" : "active";
458
+ if (!subject.columns.deletedAt) return {
459
+ changed: false,
460
+ mailed: false,
461
+ state
462
+ };
463
+ const closes = subject.columns.purgeAfter;
464
+ if (closes && closes.getTime() <= at.getTime()) throw windowClosed(input.userId, closes);
287
465
  if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
288
466
  deletedAt: null,
289
467
  purgeAfter: null
290
- }).where("id", "=", input.userId).where("deletedAt", "is not", null), {
468
+ }).where("id", "=", input.userId).where("deletedAt", "is not", null).where("purgeAfter", ">", windowClock(deps)), {
291
469
  userId: input.userId,
292
470
  action: "restored",
293
471
  actor: input.actor,
294
472
  reason,
295
473
  at
296
- })) return { changed: false };
474
+ })) {
475
+ const now = await subjectOf(deps.db, input.userId).catch(async (error) => {
476
+ throw await purgedRefusal(deps.db, input.userId) ?? error;
477
+ });
478
+ if (!now.columns.deletedAt) return {
479
+ changed: false,
480
+ mailed: false,
481
+ state: suspended(now.columns) ? "suspended" : "active"
482
+ };
483
+ const closed = now.columns.purgeAfter;
484
+ if (closed && closed.getTime() <= (deps.now ?? (() => /* @__PURE__ */ new Date()))().getTime()) throw windowClosed(input.userId, closed);
485
+ throw raced(input.userId);
486
+ }
297
487
  await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
298
- return { changed: true };
488
+ return {
489
+ changed: true,
490
+ mailed: false,
491
+ state
492
+ };
493
+ }
494
+ /**
495
+ * The refusal for an account the purge has erased, or `null` when none was. A 404, because there is no
496
+ * account, with the date in the action so an operator answering a restore request knows it is final.
497
+ */
498
+ async function purgedRefusal(db, userId) {
499
+ const purged = await db.selectFrom("pithyAuthUserLifecycle").select("createdAt").where("userId", "=", userId).where("action", "=", "purged").orderBy("id", "desc").executeTakeFirst();
500
+ if (!purged) return null;
501
+ const on = SQLiteDate.parse(purged.createdAt).toISOString();
502
+ return new NotFoundError({
503
+ message: "No such account.",
504
+ action: `This account was purged on ${on}. Its data is gone, and there is nothing to restore or export.`,
505
+ detail: `user ${userId} was purged at ${on}`
506
+ });
507
+ }
508
+ /**
509
+ * The account's row, or the refusal for one that is not there — the 404 that says the data is gone when the
510
+ * purge erased it, and the plain one otherwise. For a route that reads an account outside a transition: the
511
+ * export.
512
+ */
513
+ async function requirePresent(db, userId) {
514
+ if (await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", userId).executeTakeFirst()) return;
515
+ throw await purgedRefusal(db, userId) ?? new NotFoundError({
516
+ message: "No such user.",
517
+ detail: `no pithy_auth_users row for ${userId}`
518
+ });
299
519
  }
300
520
  /** The purge's own actor: a scheduled job, with nobody calling. */
301
521
  const PURGE = {
302
522
  type: "system",
303
523
  id: null
304
524
  };
305
- /** Record that one purge step — one capability's contribution — erased its rows. */
525
+ /**
526
+ * Whether one account is due for its purge, who its last mail goes to, and whether it goes (#622).
527
+ *
528
+ * `due` only for an account that is deleted and whose `purgeAfter` has passed — the cron and a hard deletion
529
+ * both start a purge, and this is the one check either passes through, so an account restored in between is
530
+ * `not_due` and nothing is erased. `gone` when there is no row: the purge already erased it, or the id never
531
+ * existed, and either way there is nothing to do. The recipient is read here, before the first step, because
532
+ * the last step erases it.
533
+ *
534
+ * `notify` is what the deletion in force asked of the last mail — its newest `deleted` row's — so a hard
535
+ * deletion's `notify: false` holds for a purge the daily pass started, which was handed no such parameter.
536
+ */
537
+ async function purgeSubject(deps, userId) {
538
+ const row = await deps.db.selectFrom("pithyAuthUsers").select([
539
+ "email",
540
+ "name",
541
+ "locale",
542
+ "suspendedAt",
543
+ "suspendedUntil",
544
+ "deletedAt",
545
+ "purgeAfter"
546
+ ]).select(windowClock(deps).as("checkedAt")).where("id", "=", userId).executeTakeFirst();
547
+ if (!row) return { state: "gone" };
548
+ const columns = LifecycleColumns.parse(row);
549
+ if (!columns.deletedAt || !columns.purgeAfter || columns.purgeAfter.getTime() > Number(row.checkedAt)) return { state: "not_due" };
550
+ const saved = (await deps.db.selectFrom("pithyAuthUserLifecycle").select("notify").where("userId", "=", userId).where("action", "=", "deleted").orderBy("id", "desc").limit(1).executeTakeFirst())?.notify;
551
+ const notify = saved === void 0 || saved === null ? null : SQLiteBoolean.decode(saved);
552
+ return {
553
+ state: "due",
554
+ recipient: {
555
+ email: row.email,
556
+ name: row.name,
557
+ locale: row.locale ?? null
558
+ },
559
+ notify
560
+ };
561
+ }
562
+ /**
563
+ * The account's address, as a purge step reads it (#814) — `null` when there is no account, or no address. Read
564
+ * inside the step that asks, so it is never carried in a Workflow's journal.
565
+ */
566
+ async function purgeAddress(db, userId) {
567
+ return (await db.selectFrom("pithyAuthUsers").select("email").where("id", "=", userId).executeTakeFirst())?.email ?? null;
568
+ }
569
+ /**
570
+ * The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit` (#622).
571
+ * What the daily cron starts a purge for. An account still inside its window is not here, and neither is one
572
+ * that was restored. Each carries its deletion's start, which names the purge's instance (`../purge/start.ts`).
573
+ */
574
+ async function duePurges(deps, limit) {
575
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
576
+ return (await deps.db.selectFrom("pithyAuthUsers").select(["id", "deletedAt"]).where("deletedAt", "is not", null).where("purgeAfter", "is not", null).where("purgeAfter", "<=", SQLiteDate.encode(at)).orderBy("purgeAfter", "asc").orderBy("id", "asc").limit(limit).execute()).map((row) => ({
577
+ userId: row.id,
578
+ deletedAt: Number(row.deletedAt)
579
+ }));
580
+ }
581
+ /**
582
+ * Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
583
+ * the row's reason, so the history says what the step erased and not only that it ran. With `retained`, the step
584
+ * kept its rows instead (#814): the row is `purge_retained`, and its reason is the basis the capability gave.
585
+ */
306
586
  async function recordPurgeStep(deps, input) {
307
587
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
308
588
  await record(deps, {
309
589
  userId: input.userId,
310
- action: "purge_step",
590
+ action: input.retained ? "purge_retained" : "purge_step",
591
+ actor: PURGE,
592
+ reason: input.summary?.trim() ? input.summary.trim().slice(0, 500) : null,
593
+ at,
594
+ step: input.step
595
+ });
596
+ await audit(deps, AuthAuditActions.adminUserPurgeStep, input.userId, PURGE, {
597
+ step: input.step,
598
+ disposition: input.retained ? "retained" : "erased"
599
+ });
600
+ }
601
+ /**
602
+ * Record that a purge gave up (#823): the step it stopped at, in the history and in the trail. The daily pass starts
603
+ * the purge again tomorrow, so this is where it stands until then, not an end. The failure's message is never
604
+ * written: it is code the kit did not write, and it may name the person.
605
+ */
606
+ async function recordPurgeFailure(deps, input) {
607
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
608
+ await record(deps, {
609
+ userId: input.userId,
610
+ action: "purge_failed",
311
611
  actor: PURGE,
312
612
  reason: null,
313
613
  at,
314
614
  step: input.step
315
615
  });
616
+ await audit(deps, AuthAuditActions.adminUserPurgeFailed, input.userId, PURGE, { step: input.step });
316
617
  }
317
618
  /**
318
- * Finish a purge: the last mail, the record, the audit event, the hook.
619
+ * The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
620
+ * other capability's rows are gone and before auth's own, which holds the address, so the last mail is
621
+ * enqueued while there is still an account to have sent it to. The address is handed in, captured before the
622
+ * first step. `notify: false` sends nothing, whatever the config says.
623
+ */
624
+ async function mailPurgeComplete(deps, input) {
625
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
626
+ const { email, name, locale } = input.recipient;
627
+ return {
628
+ changed: false,
629
+ mailed: await mail(deps, deps.config.lifecycleEmails.deletionComplete && input.notify !== false, email, locale, "deletionComplete", {
630
+ ...named(name ?? ""),
631
+ purgedOn: readable(at, locale)
632
+ })
633
+ };
634
+ }
635
+ /**
636
+ * Finish a purge: the record, the audit event, the hook. The last thing that happens to the account.
319
637
  *
320
- * **The address is handed in, not read**, because by the time a purge finishes the user row is gone — the
321
- * Workflow captures the recipient before its first step and passes it here. Finishing a purge that already
322
- * finished is a no-op, so a retried Workflow step mails nobody twice.
638
+ * By the time a purge finishes the user row is gone, so this reads nothing about the account. Finishing a
639
+ * purge that already finished is a no-op, so a retried Workflow step records and fires once — and so do two
640
+ * purges of one account that overlapped. **The insert is the check**: `0005_purge_once` allows one `purged` row
641
+ * per account, the insert ignores a second, and only the call whose row landed audits and fires. A read
642
+ * before the insert would let two concurrent calls both find nothing and both write.
323
643
  */
324
644
  async function completePurge(deps, input) {
325
645
  const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
326
- if (await deps.db.selectFrom("pithyAuthUserLifecycle").select("id").where("userId", "=", input.userId).where("action", "=", "purged").executeTakeFirst()) return { changed: false };
327
- await record(deps, {
646
+ const inserted = await deps.db.insertInto("pithyAuthUserLifecycle").values(encoded({
328
647
  userId: input.userId,
329
648
  action: "purged",
330
649
  actor: PURGE,
331
650
  reason: null,
332
651
  at
333
- });
652
+ })).onConflict((conflict) => conflict.doNothing()).executeTakeFirst();
653
+ if (Number(inserted.numInsertedOrUpdatedRows ?? 0n) === 0) return {
654
+ changed: false,
655
+ mailed: false
656
+ };
334
657
  await audit(deps, AuthAuditActions.adminUserPurged, input.userId, PURGE, {});
335
- const { email, name, locale } = input.recipient;
336
- await mail(deps, deps.config.lifecycleEmails.deletionComplete, email, locale, "deletionComplete", {
337
- ...named(name ?? ""),
338
- purgedOn: readable(at, locale)
339
- });
340
658
  await fire(deps, "onUserPurged", deps.hooks.onUserPurged, {
341
659
  userId: input.userId,
342
660
  actor: PURGE,
343
661
  reason: null,
344
662
  at
345
663
  });
346
- return { changed: true };
664
+ return {
665
+ changed: true,
666
+ mailed: false
667
+ };
347
668
  }
348
669
  //#endregion
349
- export { completePurge, deleteUser, recordPurgeStep, reinstateUser, restoreUser, suspendUser };
670
+ export { completePurge, deleteUser, duePurges, mailPurgeComplete, purgeAddress, purgeSubject, recordPurgeFailure, recordPurgeStep, reinstateUser, requirePresent, restoreUser, suspendUser, userPurgeWindowDays };