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