@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
@@ -4,7 +4,7 @@
4
4
  import type { D1Database, D1PreparedStatement } from "@cloudflare/workers-types";
5
5
  import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
6
6
  import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
7
- import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
7
+ import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
8
  import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
9
9
  import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
10
10
  import type { Logger } from "@pithy-sh/core/src/logger/logger";
@@ -15,6 +15,7 @@ import type { AuthConfig } from "../capability";
15
15
  import type { AuthDatabase } from "../data/tables";
16
16
  import type { UserLifecycleAction, UserLifecycleActorType } from "../data/userLifecycle";
17
17
  import type { UserLifecycleHookEvent, UserLifecycleHooks, UserLifecycleListener } from "./hooks";
18
+ import { MAX_REASON } from "./reason";
18
19
  import { accountStanding, LifecycleColumns } from "./state";
19
20
 
20
21
  /**
@@ -69,16 +70,45 @@ export interface LifecycleDeps {
69
70
  readonly log?: Logger | undefined;
70
71
  /** The clock. Defaults to the system's. */
71
72
  readonly now?: (() => Date) | undefined;
73
+ /**
74
+ * The request a transition was asked from, carried onto its audit event: the correlation every admin event
75
+ * carries, and metadata the caller adds — the management connection's id, for a control-plane call.
76
+ */
77
+ readonly context?: LifecycleAuditContext | undefined;
78
+ }
79
+
80
+ /** What the caller's request adds to a transition's audit event. */
81
+ export interface LifecycleAuditContext {
82
+ /** The caller's address, from `cf-connecting-ip`. */
83
+ readonly ip?: string | undefined;
84
+ /** The caller's user agent. */
85
+ readonly userAgent?: string | undefined;
86
+ /** The request's id, from `cf-ray`. */
87
+ readonly requestId?: string | undefined;
88
+ /** Extra metadata, merged under the transition's own. */
89
+ readonly metadata?: Record<string, unknown> | undefined;
72
90
  }
73
91
 
74
92
  /** What a transition did. */
75
93
  export interface LifecycleTransition {
76
94
  /** Whether the account moved. `false` when it was already where the call asked to put it. */
77
95
  readonly changed: boolean;
96
+ /** Whether a lifecycle mail was enqueued for the account. False when the config, the call or a missing email capability sent none. */
97
+ readonly mailed: boolean;
78
98
  }
79
99
 
80
- /** The longest reason the kit stores. It is shown to the person, so it is a sentence, not a case file. */
81
- const MAX_REASON = 500;
100
+ /** What a suspension did, and the suspension it left in force. */
101
+ export interface SuspendTransition extends LifecycleTransition {
102
+ /**
103
+ * True when the account was already suspended and this call restated the reason and the end instead (#621).
104
+ * That is not a transition — `changed` is false and no hook fires — but it is written, audited and mailed.
105
+ */
106
+ readonly updated: boolean;
107
+ /** When the suspension in force began. A restatement keeps the original start. */
108
+ readonly suspendedAt: Date;
109
+ /** When it ends by itself, or null for one that lasts until a reinstatement. */
110
+ readonly suspendedUntil: Date | null;
111
+ }
82
112
 
83
113
  /** A reason, trimmed and bounded, or null when none was given. */
84
114
  function reasonOf(reason: string | null | undefined): string | null {
@@ -133,6 +163,8 @@ interface HistoryRow {
133
163
  readonly at: Date;
134
164
  readonly suspendedUntil?: Date | null;
135
165
  readonly step?: string | null;
166
+ /** A hard deletion's choice for the purge's last mail; see `UserLifecycleEvent.notify`. */
167
+ readonly notify?: boolean | null;
136
168
  }
137
169
 
138
170
  /** The history row's values, as the table stores them. */
@@ -145,6 +177,7 @@ function encoded(row: HistoryRow) {
145
177
  reason: row.reason,
146
178
  suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
147
179
  step: row.step ?? null,
180
+ notify: row.notify === undefined || row.notify === null ? null : SQLiteBoolean.encode(row.notify),
148
181
  createdAt: SQLiteDate.encode(row.at),
149
182
  };
150
183
  }
@@ -170,7 +203,7 @@ async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, r
170
203
  const v = encoded(row);
171
204
  const insert = deps.db
172
205
  .insertInto("pithyAuthUserLifecycle")
173
- .columns(["userId", "action", "actorType", "actorId", "reason", "suspendedUntil", "step", "createdAt"])
206
+ .columns(["userId", "action", "actorType", "actorId", "reason", "suspendedUntil", "step", "notify", "createdAt"])
174
207
  .expression(
175
208
  deps.db
176
209
  .selectNoFrom([
@@ -181,6 +214,7 @@ async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, r
181
214
  sql.val(v.reason).as("reason"),
182
215
  sql.val(v.suspendedUntil).as("suspendedUntil"),
183
216
  sql.val(v.step).as("step"),
217
+ sql.val(v.notify).as("notify"),
184
218
  sql.val(v.createdAt).as("createdAt"),
185
219
  ])
186
220
  .where(sql<number>`changes()`, ">", 0),
@@ -198,6 +232,7 @@ async function audit(
198
232
  actor: LifecycleActor,
199
233
  metadata: Record<string, unknown>,
200
234
  ): Promise<void> {
235
+ const context = deps.context;
201
236
  const event: AuditEventInput = {
202
237
  action,
203
238
  outcome: "success",
@@ -205,7 +240,10 @@ async function audit(
205
240
  actorId: actor.id,
206
241
  resourceType: "user",
207
242
  resourceId: userId,
208
- metadata,
243
+ ...(context?.ip ? { ip: context.ip } : {}),
244
+ ...(context?.userAgent ? { userAgent: context.userAgent } : {}),
245
+ ...(context?.requestId ? { requestId: context.requestId } : {}),
246
+ metadata: { ...context?.metadata, ...metadata },
209
247
  };
210
248
  try {
211
249
  await deps.emit(event);
@@ -214,7 +252,7 @@ async function audit(
214
252
  }
215
253
  }
216
254
 
217
- /** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. */
255
+ /** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. Says whether it was enqueued. */
218
256
  async function mail(
219
257
  deps: LifecycleDeps,
220
258
  enabled: boolean,
@@ -222,14 +260,16 @@ async function mail(
222
260
  locale: string | null,
223
261
  template: "accountSuspended" | "accountReinstated" | "deletionScheduled" | "deletionComplete",
224
262
  payload: Record<string, unknown>,
225
- ): Promise<void> {
226
- if (!enabled || !deps.enqueueEmail) return;
263
+ ): Promise<boolean> {
264
+ if (!enabled || !deps.enqueueEmail) return false;
227
265
  try {
228
266
  await deps.enqueueEmail({ to, template, payload, ...(locale ? { locale } : {}) });
267
+ return true;
229
268
  } catch (error) {
230
269
  deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, {
231
270
  reason: messageOf(error),
232
271
  });
272
+ return false;
233
273
  }
234
274
  }
235
275
 
@@ -257,16 +297,77 @@ function named(name: string): { name?: string } {
257
297
  return name.trim() ? { name } : {};
258
298
  }
259
299
 
300
+ /** The conflict for a deleted account: deletion outranks a suspension, so restore it first. */
301
+ function deletedConflict(restoreRoute: string | undefined, then: string): ConflictError {
302
+ return new ConflictError({
303
+ message: restoreRoute
304
+ ? `This account is deleted. Restore it with ${restoreRoute} first.`
305
+ : "This account is deleted. Restore it first.",
306
+ action: restoreRoute ? `Restore it with ${restoreRoute}. ${then}` : `Restore it first. ${then}`,
307
+ });
308
+ }
309
+
310
+ /** The conflict for a write that found the account moved under it by another request. Retrying is safe. */
311
+ function raced(userId: string): ConflictError {
312
+ return new ConflictError({
313
+ message: "The account changed while this request was being made. Send it again.",
314
+ detail: `lifecycle write for user ${userId} matched no row; another request moved the account first`,
315
+ });
316
+ }
317
+
318
+ /**
319
+ * The instant a purge-window guard compares against, **read when the statement runs**, as ms-epoch (#622).
320
+ *
321
+ * A restore and a purge's `due` check race for one account, and each has to see the window the other saw. A
322
+ * timestamp the restore took before its statement went out is stale by the time D1 runs it: the window can
323
+ * close in between, by itself or because a hard deletion brought it forward, and a purge whose `due` check ran
324
+ * in that gap goes on to erase an account the restore reported back. So on the system clock the guard is the
325
+ * database's own time, evaluated inside the statement, and D1 runs statements one at a time: whichever lands
326
+ * first, the other sees it. An injected clock is a test's, and is read afresh here, at the statement.
327
+ */
328
+ function windowClock(deps: LifecycleDeps) {
329
+ return deps.now
330
+ ? sql<number>`${deps.now().getTime()}`
331
+ : sql<number>`cast(round(unixepoch('subsec') * 1000) as integer)`;
332
+ }
333
+
334
+ /** The conflict for an account whose purge window has closed: nothing can restore it now. */
335
+ function windowClosed(userId: string, closes: Date): ConflictError {
336
+ return new ConflictError({
337
+ message: `This account's purge window closed on ${closes.toISOString()}. It can no longer be restored.`,
338
+ action: "The purge is due and erases its data once it runs. There is nothing to restore.",
339
+ detail: `restore for user ${userId}, whose purge was due at ${closes.toISOString()}`,
340
+ });
341
+ }
342
+
260
343
  /**
261
344
  * Suspend an account, until `until` or until it is reinstated.
262
345
  *
263
346
  * A deleted account cannot be suspended — deletion already shuts it, and outranks a suspension — so that is a
264
- * conflict rather than a no-op. A suspension whose end has passed is not in force, and a new one replaces it.
347
+ * conflict rather than a no-op, and names `restoreRoute` when the caller gives one. A suspension whose end has
348
+ * passed is not in force, and a new one replaces it.
349
+ *
350
+ * **An account already suspended has its terms restated (#621).** The reason and the end are replaced, a
351
+ * `suspended` row records the new reason — the newest one is what the person is shown — and the audit event
352
+ * and the mail say so. The start is kept, and no hook fires: the account was suspended and still is, so
353
+ * nothing transitioned. A fresh suspension that loses the race to another suspension finds the account
354
+ * suspended, so it retries once as a restatement rather than failing. A write that finds the account moved
355
+ * under it any other way, by a reinstatement or a deletion that landed first, is a conflict: what the caller
356
+ * asked for no longer describes the account.
357
+ *
358
+ * `notify: false` sends no mail, whatever the config says; the config can only turn mail off, never on.
265
359
  */
266
360
  export async function suspendUser(
267
361
  deps: LifecycleDeps,
268
- input: { userId: string; actor: LifecycleActor; reason: string | null; until?: Date | null },
269
- ): Promise<LifecycleTransition> {
362
+ input: {
363
+ userId: string;
364
+ actor: LifecycleActor;
365
+ reason: string | null;
366
+ until?: Date | null;
367
+ notify?: boolean;
368
+ restoreRoute?: string;
369
+ },
370
+ ): Promise<SuspendTransition> {
270
371
  const at = (deps.now ?? (() => new Date()))();
271
372
  const reason = reasonOf(input.reason);
272
373
  const until = input.until ?? null;
@@ -276,15 +377,21 @@ export async function suspendUser(
276
377
  const subject = await subjectOf(deps.db, input.userId);
277
378
  const standing = accountStanding(subject.columns, at);
278
379
  if (standing.state === "deleted") {
279
- throw new ConflictError({
280
- message: "This account is deleted.",
281
- action: "Restore it first, if it should be suspended instead.",
282
- });
380
+ throw deletedConflict(input.restoreRoute, "Then suspend it, if it should be suspended instead.");
283
381
  }
284
- if (standing.state === "suspended") return { changed: false };
285
- const update = deps.db
382
+ const encodedUntil = until ? SQLiteDate.encode(until) : null;
383
+ /** 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. */
384
+ const restatement = (startedAt: Date) =>
385
+ deps.db
386
+ .updateTable("pithyAuthUsers")
387
+ .set({ suspendedUntil: encodedUntil })
388
+ .where("id", "=", input.userId)
389
+ .where("deletedAt", "is", null)
390
+ .where("suspendedAt", "=", SQLiteDate.encode(startedAt))
391
+ .where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
392
+ const fresh = deps.db
286
393
  .updateTable("pithyAuthUsers")
287
- .set({ suspendedAt: SQLiteDate.encode(at), suspendedUntil: until ? SQLiteDate.encode(until) : null })
394
+ .set({ suspendedAt: SQLiteDate.encode(at), suspendedUntil: encodedUntil })
288
395
  .where("id", "=", input.userId)
289
396
  .where("deletedAt", "is", null)
290
397
  .where((eb) =>
@@ -301,25 +408,47 @@ export async function suspendUser(
301
408
  at,
302
409
  suspendedUntil: until,
303
410
  };
304
- if (!(await move(deps, update, row))) return { changed: false };
411
+ let updated = standing.state === "suspended";
412
+ let startedAt = updated && subject.columns.suspendedAt ? subject.columns.suspendedAt : at;
413
+ if (!(await move(deps, updated ? restatement(startedAt) : fresh, row))) {
414
+ // A fresh suspension that lost to another suspension landing first finds the account suspended, which
415
+ // is the case a restatement answers: retry once as one. Anything else — a deletion, or a restatement
416
+ // that lost to a reinstatement — means what the caller asked for no longer describes the account.
417
+ const now = updated ? null : await subjectOf(deps.db, input.userId);
418
+ const moved = now ? accountStanding(now.columns, at) : null;
419
+ if (!now?.columns.suspendedAt || moved?.state !== "suspended") throw raced(input.userId);
420
+ updated = true;
421
+ startedAt = now.columns.suspendedAt;
422
+ if (!(await move(deps, restatement(startedAt), row))) throw raced(input.userId);
423
+ }
305
424
 
306
425
  await audit(deps, AuthAuditActions.adminUserSuspended, input.userId, input.actor, {
307
426
  reason,
308
427
  suspendedUntil: until?.toISOString() ?? null,
428
+ updated,
309
429
  });
310
- await mail(deps, deps.config.lifecycleEmails.accountSuspended, subject.email, subject.locale, "accountSuspended", {
311
- ...named(subject.name),
312
- ...(reason ? { reason } : {}),
313
- ...(until ? { until: readable(until, subject.locale) } : {}),
314
- });
315
- await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
316
- userId: input.userId,
317
- actor: input.actor,
318
- reason,
319
- at,
320
- suspendedUntil: until,
321
- });
322
- return { changed: true };
430
+ const mailed = await mail(
431
+ deps,
432
+ deps.config.lifecycleEmails.accountSuspended && input.notify !== false,
433
+ subject.email,
434
+ subject.locale,
435
+ "accountSuspended",
436
+ {
437
+ ...named(subject.name),
438
+ ...(reason ? { reason } : {}),
439
+ ...(until ? { until: readable(until, subject.locale) } : {}),
440
+ },
441
+ );
442
+ if (!updated) {
443
+ await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
444
+ userId: input.userId,
445
+ actor: input.actor,
446
+ reason,
447
+ at,
448
+ suspendedUntil: until,
449
+ });
450
+ }
451
+ return { changed: !updated, updated, mailed, suspendedAt: startedAt, suspendedUntil: until };
323
452
  }
324
453
 
325
454
  /**
@@ -329,22 +458,24 @@ export async function suspendUser(
329
458
  * past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
330
459
  * for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
331
460
  * sign in again" to somebody every sign-in still refuses. Restore it first.
461
+ *
462
+ * `notify: false` sends no mail, on the same rule as `suspendUser`.
332
463
  */
333
464
  export async function reinstateUser(
334
465
  deps: LifecycleDeps,
335
- input: { userId: string; actor: LifecycleActor; reason: string | null },
466
+ input: { userId: string; actor: LifecycleActor; reason: string | null; notify?: boolean; restoreRoute?: string },
336
467
  ): Promise<LifecycleTransition> {
337
468
  const at = (deps.now ?? (() => new Date()))();
338
469
  const reason = reasonOf(input.reason);
339
470
  const subject = await subjectOf(deps.db, input.userId);
340
471
  const standing = accountStanding(subject.columns, at);
341
472
  if (standing.state === "deleted") {
342
- throw new ConflictError({
343
- message: "This account is deleted.",
344
- action: "Restore it first. Its suspension stays in place through a restore, and can be lifted after.",
345
- });
473
+ throw deletedConflict(
474
+ input.restoreRoute,
475
+ "Its suspension stays in place through a restore, and can be lifted after.",
476
+ );
346
477
  }
347
- if (standing.state !== "suspended") return { changed: false };
478
+ if (standing.state !== "suspended") return { changed: false, mailed: false };
348
479
  const update = deps.db
349
480
  .updateTable("pithyAuthUsers")
350
481
  .set({ suspendedAt: null, suspendedUntil: null })
@@ -353,12 +484,12 @@ export async function reinstateUser(
353
484
  .where("suspendedAt", "is not", null)
354
485
  .where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
355
486
  const row: HistoryRow = { userId: input.userId, action: "reinstated", actor: input.actor, reason, at };
356
- if (!(await move(deps, update, row))) return { changed: false };
487
+ if (!(await move(deps, update, row))) return { changed: false, mailed: false };
357
488
 
358
489
  await audit(deps, AuthAuditActions.adminUserReinstated, input.userId, input.actor, { reason });
359
- await mail(
490
+ const mailed = await mail(
360
491
  deps,
361
- deps.config.lifecycleEmails.accountReinstated,
492
+ deps.config.lifecycleEmails.accountReinstated && input.notify !== false,
362
493
  subject.email,
363
494
  subject.locale,
364
495
  "accountReinstated",
@@ -370,44 +501,123 @@ export async function reinstateUser(
370
501
  reason,
371
502
  at,
372
503
  });
373
- return { changed: true };
504
+ return { changed: true, mailed };
505
+ }
506
+
507
+ /** How a deletion runs: shut now and purged once the window closes, or purged now. */
508
+ export type DeletionMode = "soft" | "hard";
509
+
510
+ /** What a deletion did, and the deletion it left in force. */
511
+ export interface DeleteTransition extends LifecycleTransition {
512
+ /**
513
+ * `deleted` when this call deleted an account in good standing; `brought_forward` when the account was
514
+ * already deleted and a hard deletion moved its purge to now; `unchanged` when it was already deleted and
515
+ * this call had nothing to move.
516
+ */
517
+ readonly outcome: "deleted" | "brought_forward" | "unchanged";
518
+ /** When the account was deleted. A deletion brought forward keeps its original start. */
519
+ readonly deletedAt: Date;
520
+ /** When the purge may erase it — now, for a hard deletion. Restorable until then. */
521
+ readonly purgeAfter: Date;
374
522
  }
375
523
 
376
524
  /**
377
- * Delete an account, softly: it is shut now, and its data is erased once `retention.purgeAfterDays` have
378
- * passed. Restorable until then. Audited as the account's own deletion when its holder is the actor.
525
+ * Delete an account. Audited as the account's own deletion when its holder is the actor.
526
+ *
527
+ * **Soft, the default**: it is shut now, and its data is erased once `retention.purgeAfterDays` have passed.
528
+ * Restorable until then. The deletion-scheduled mail carries the purge date and, when the config names one,
529
+ * the restore path. A deleted account deleted softly again is no transition.
530
+ *
531
+ * **Hard** (#622): `purgeAfter` is now, so the window is already closed — nothing can restore it — and the
532
+ * caller starts the purge. No deletion-scheduled mail, because nothing is scheduled; the purge sends the
533
+ * deletion-complete one. An account already deleted softly has its purge brought forward to now, which is
534
+ * written and audited but fires no hook: the account was deleted and still is. One already due is unchanged.
379
535
  *
380
536
  * A suspension the account was under is left in place, so restoring the account does not lift it.
537
+ * `notify: false` sends no mail, whatever the config says.
381
538
  */
382
539
  export async function deleteUser(
383
540
  deps: LifecycleDeps,
384
- input: { userId: string; actor: LifecycleActor; reason: string | null },
385
- ): Promise<LifecycleTransition> {
541
+ input: { userId: string; actor: LifecycleActor; reason: string | null; mode?: DeletionMode; notify?: boolean },
542
+ ): Promise<DeleteTransition> {
386
543
  const at = (deps.now ?? (() => new Date()))();
387
544
  const reason = reasonOf(input.reason);
388
- const purgeAfter = new Date(at.getTime() + deps.config.retention.purgeAfterDays * 86_400_000);
545
+ const hard = input.mode === "hard";
546
+ const purgeAfter = hard ? at : new Date(at.getTime() + deps.config.retention.purgeAfterDays * 86_400_000);
389
547
  const subject = await subjectOf(deps.db, input.userId);
390
- if (subject.columns.deletedAt) return { changed: false };
548
+ // A hard deletion's `notify` is the purge's to read, so it is written on the row: the purge that sends the last
549
+ // mail may be one the daily pass started, with no request to carry it (#622).
550
+ const row: HistoryRow = {
551
+ userId: input.userId,
552
+ action: "deleted",
553
+ actor: input.actor,
554
+ reason,
555
+ at,
556
+ ...(hard && input.notify !== undefined ? { notify: input.notify } : {}),
557
+ };
558
+ const existing = subject.columns.deletedAt;
559
+ if (existing) {
560
+ const due = subject.columns.purgeAfter ?? existing;
561
+ const unchanged = {
562
+ changed: false,
563
+ mailed: false,
564
+ outcome: "unchanged",
565
+ deletedAt: existing,
566
+ purgeAfter: due,
567
+ } as const;
568
+ if (!hard || due.getTime() <= at.getTime()) return unchanged;
569
+ // Brought forward: the same deletion, with its window closed now. Pinned by its start, so a restore and a
570
+ // fresh deletion in between is a different deletion and this write matches nothing.
571
+ const forward = deps.db
572
+ .updateTable("pithyAuthUsers")
573
+ .set({ purgeAfter: SQLiteDate.encode(at) })
574
+ .where("id", "=", input.userId)
575
+ .where("deletedAt", "=", SQLiteDate.encode(existing))
576
+ .where("purgeAfter", ">", SQLiteDate.encode(at));
577
+ if (!(await move(deps, forward, row))) return unchanged;
578
+ await audit(deps, AuthAuditActions.adminUserHardDeleted, input.userId, input.actor, {
579
+ reason,
580
+ purgeAfter: at.toISOString(),
581
+ broughtForward: true,
582
+ });
583
+ return { changed: false, mailed: false, outcome: "brought_forward", deletedAt: existing, purgeAfter: at };
584
+ }
391
585
  const update = deps.db
392
586
  .updateTable("pithyAuthUsers")
393
587
  .set({ deletedAt: SQLiteDate.encode(at), purgeAfter: SQLiteDate.encode(purgeAfter) })
394
588
  .where("id", "=", input.userId)
395
589
  .where("deletedAt", "is", null);
396
- const row: HistoryRow = { userId: input.userId, action: "deleted", actor: input.actor, reason, at };
397
- if (!(await move(deps, update, row))) return { changed: false };
590
+ if (!(await move(deps, update, row))) {
591
+ // Another deletion landed first. The account is where this call asked to put it, so it is no transition;
592
+ // anything else moved it is a conflict, and a retry reads it afresh.
593
+ const now = await subjectOf(deps.db, input.userId);
594
+ if (!now.columns.deletedAt) throw raced(input.userId);
595
+ const due = now.columns.purgeAfter ?? now.columns.deletedAt;
596
+ return { changed: false, mailed: false, outcome: "unchanged", deletedAt: now.columns.deletedAt, purgeAfter: due };
597
+ }
398
598
 
399
599
  const self = input.actor.type === "user" && input.actor.id === input.userId;
400
- await audit(
401
- deps,
402
- self ? AuthAuditActions.userSelfDeleted : AuthAuditActions.adminUserSoftDeleted,
403
- input.userId,
404
- input.actor,
405
- { reason, purgeAfter: purgeAfter.toISOString() },
406
- );
407
- await mail(deps, deps.config.lifecycleEmails.deletionScheduled, subject.email, subject.locale, "deletionScheduled", {
408
- ...named(subject.name),
409
- purgeOn: readable(purgeAfter, subject.locale),
410
- });
600
+ const action = hard
601
+ ? AuthAuditActions.adminUserHardDeleted
602
+ : self
603
+ ? AuthAuditActions.userSelfDeleted
604
+ : AuthAuditActions.adminUserSoftDeleted;
605
+ await audit(deps, action, input.userId, input.actor, { reason, purgeAfter: purgeAfter.toISOString() });
606
+ const restoreUrl = deps.config.retention.restoreUrl;
607
+ const mailed = hard
608
+ ? false
609
+ : await mail(
610
+ deps,
611
+ deps.config.lifecycleEmails.deletionScheduled && input.notify !== false,
612
+ subject.email,
613
+ subject.locale,
614
+ "deletionScheduled",
615
+ {
616
+ ...named(subject.name),
617
+ purgeOn: readable(purgeAfter, subject.locale),
618
+ ...(restoreUrl ? { restoreUrl } : {}),
619
+ },
620
+ );
411
621
  await fire(deps, "onUserDeleted", deps.hooks.onUserDeleted, {
412
622
  userId: input.userId,
413
623
  actor: input.actor,
@@ -415,69 +625,248 @@ export async function deleteUser(
415
625
  at,
416
626
  purgeAfter,
417
627
  });
418
- return { changed: true };
628
+ return { changed: true, mailed, outcome: "deleted", deletedAt: at, purgeAfter };
629
+ }
630
+
631
+ /** What a restoration did, and where it left the account. */
632
+ export interface RestoreTransition extends LifecycleTransition {
633
+ /** Where the account stands now: `active`, or `suspended` when a suspension it was under is still in force. */
634
+ readonly state: "active" | "suspended";
419
635
  }
420
636
 
421
637
  /**
422
- * Restore a deleted account inside its purge window. After the purge there is no account, and that is a 404
423
- * whose action says the data is gone.
638
+ * Restore a deleted account inside its purge window.
639
+ *
640
+ * **Only inside it.** Once `purgeAfter` has passed the purge is due, may already be running, and erases each
641
+ * capability's rows in turn, so restoring then would hand back an account with some of its data gone. That
642
+ * is a conflict naming the date the window closed. After the purge there is no account at all, and that is a
643
+ * 404 whose action says the data is gone — read off the history row the purge leaves behind, so it is told
644
+ * apart from an id that never existed.
645
+ *
646
+ * An account that is not deleted is no transition. A suspension it was under is still in force after.
424
647
  */
425
648
  export async function restoreUser(
426
649
  deps: LifecycleDeps,
427
650
  input: { userId: string; actor: LifecycleActor; reason: string | null },
428
- ): Promise<LifecycleTransition> {
651
+ ): Promise<RestoreTransition> {
429
652
  const at = (deps.now ?? (() => new Date()))();
430
653
  const reason = reasonOf(input.reason);
431
- const subject = await subjectOf(deps.db, input.userId);
432
- if (!subject.columns.deletedAt) return { changed: false };
654
+ const subject = await subjectOf(deps.db, input.userId).catch(async (error: unknown) => {
655
+ throw (await purgedRefusal(deps.db, input.userId)) ?? error;
656
+ });
657
+ const suspended = (columns: LifecycleColumns) =>
658
+ accountStanding({ ...columns, deletedAt: null, purgeAfter: null }, at).state === "suspended";
659
+ const state = suspended(subject.columns) ? "suspended" : "active";
660
+ if (!subject.columns.deletedAt) return { changed: false, mailed: false, state };
661
+ // Early, and only ever early: `at` was read before the account was, so a window it finds closed is closed. One
662
+ // it finds open may not be by the time the update runs, which is why the update guards on its own clock.
663
+ const closes = subject.columns.purgeAfter;
664
+ if (closes && closes.getTime() <= at.getTime()) throw windowClosed(input.userId, closes);
433
665
  const update = deps.db
434
666
  .updateTable("pithyAuthUsers")
435
667
  .set({ deletedAt: null, purgeAfter: null })
436
668
  .where("id", "=", input.userId)
437
- .where("deletedAt", "is not", null);
669
+ .where("deletedAt", "is not", null)
670
+ .where("purgeAfter", ">", windowClock(deps));
438
671
  const row: HistoryRow = { userId: input.userId, action: "restored", actor: input.actor, reason, at };
439
- if (!(await move(deps, update, row))) return { changed: false };
672
+ if (!(await move(deps, update, row))) {
673
+ // Another restoration landed first: no transition. A window that closed while this one was in flight — by
674
+ // itself, or brought forward by a hard deletion — is the conflict above. Anything else a retry reads afresh.
675
+ const now = await subjectOf(deps.db, input.userId).catch(async (error: unknown) => {
676
+ throw (await purgedRefusal(deps.db, input.userId)) ?? error;
677
+ });
678
+ if (!now.columns.deletedAt) {
679
+ return { changed: false, mailed: false, state: suspended(now.columns) ? "suspended" : "active" };
680
+ }
681
+ // Read afresh: a window still open now means something else moved the account — a restore and a new
682
+ // deletion both landed in between — and that is the retry's to read.
683
+ const closed = now.columns.purgeAfter;
684
+ if (closed && closed.getTime() <= (deps.now ?? (() => new Date()))().getTime()) {
685
+ throw windowClosed(input.userId, closed);
686
+ }
687
+ throw raced(input.userId);
688
+ }
440
689
 
441
690
  await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
442
- return { changed: true };
691
+ return { changed: true, mailed: false, state };
692
+ }
693
+
694
+ /**
695
+ * The refusal for an account the purge has erased, or `null` when none was. A 404, because there is no
696
+ * account, with the date in the action so an operator answering a restore request knows it is final.
697
+ */
698
+ async function purgedRefusal(db: AuthDatabase, userId: string): Promise<NotFoundError | null> {
699
+ const purged = await db
700
+ .selectFrom("pithyAuthUserLifecycle")
701
+ .select("createdAt")
702
+ .where("userId", "=", userId)
703
+ .where("action", "=", "purged")
704
+ .orderBy("id", "desc")
705
+ .executeTakeFirst();
706
+ if (!purged) return null;
707
+ const on = SQLiteDate.parse(purged.createdAt).toISOString();
708
+ return new NotFoundError({
709
+ message: "No such account.",
710
+ action: `This account was purged on ${on}. Its data is gone, and there is nothing to restore or export.`,
711
+ detail: `user ${userId} was purged at ${on}`,
712
+ });
713
+ }
714
+
715
+ /**
716
+ * The account's row, or the refusal for one that is not there — the 404 that says the data is gone when the
717
+ * purge erased it, and the plain one otherwise. For a route that reads an account outside a transition: the
718
+ * export.
719
+ */
720
+ export async function requirePresent(db: AuthDatabase, userId: string): Promise<void> {
721
+ const row = await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", userId).executeTakeFirst();
722
+ if (row) return;
723
+ throw (
724
+ (await purgedRefusal(db, userId)) ??
725
+ new NotFoundError({ message: "No such user.", detail: `no pithy_auth_users row for ${userId}` })
726
+ );
443
727
  }
444
728
 
445
729
  /** The purge's own actor: a scheduled job, with nobody calling. */
446
730
  const PURGE: LifecycleActor = { type: "system", id: null };
447
731
 
448
- /** Record that one purge step — one capability's contribution — erased its rows. */
449
- export async function recordPurgeStep(deps: LifecycleDeps, input: { userId: string; step: string }): Promise<void> {
450
- const at = (deps.now ?? (() => new Date()))();
451
- await record(deps, { userId: input.userId, action: "purge_step", actor: PURGE, reason: null, at, step: input.step });
732
+ /** Who the purge's last mail goes to, captured before any step erases the address. */
733
+ export interface PurgeRecipient {
734
+ readonly email: string;
735
+ readonly name: string | null;
736
+ readonly locale: string | null;
452
737
  }
453
738
 
454
739
  /**
455
- * Finish a purge: the last mail, the record, the audit event, the hook.
740
+ * Whether one account is due for its purge, who its last mail goes to, and whether it goes (#622).
741
+ *
742
+ * `due` only for an account that is deleted and whose `purgeAfter` has passed — the cron and a hard deletion
743
+ * both start a purge, and this is the one check either passes through, so an account restored in between is
744
+ * `not_due` and nothing is erased. `gone` when there is no row: the purge already erased it, or the id never
745
+ * existed, and either way there is nothing to do. The recipient is read here, before the first step, because
746
+ * the last step erases it.
456
747
  *
457
- * **The address is handed in, not read**, because by the time a purge finishes the user row is gone — the
458
- * Workflow captures the recipient before its first step and passes it here. Finishing a purge that already
459
- * finished is a no-op, so a retried Workflow step mails nobody twice.
748
+ * `notify` is what the deletion in force asked of the last mail — its newest `deleted` row's — so a hard
749
+ * deletion's `notify: false` holds for a purge the daily pass started, which was handed no such parameter.
460
750
  */
461
- export async function completePurge(
751
+ export async function purgeSubject(
462
752
  deps: LifecycleDeps,
463
- input: { userId: string; recipient: { email: string; name: string | null; locale: string | null } },
753
+ userId: string,
754
+ ): Promise<
755
+ { state: "due"; recipient: PurgeRecipient; notify: boolean | null } | { state: "not_due" } | { state: "gone" }
756
+ > {
757
+ // The instant is the database's, read in the same statement as the row — the clock `restoreUser` guards on, so
758
+ // a restore and this check agree on whether the window has closed, whichever runs first (#622).
759
+ const row = await deps.db
760
+ .selectFrom("pithyAuthUsers")
761
+ .select(["email", "name", "locale", "suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"])
762
+ .select(windowClock(deps).as("checkedAt"))
763
+ .where("id", "=", userId)
764
+ .executeTakeFirst();
765
+ if (!row) return { state: "gone" };
766
+ const columns = LifecycleColumns.parse(row);
767
+ if (!columns.deletedAt || !columns.purgeAfter || columns.purgeAfter.getTime() > Number(row.checkedAt)) {
768
+ return { state: "not_due" };
769
+ }
770
+ const deletion = await deps.db
771
+ .selectFrom("pithyAuthUserLifecycle")
772
+ .select("notify")
773
+ .where("userId", "=", userId)
774
+ .where("action", "=", "deleted")
775
+ .orderBy("id", "desc")
776
+ .limit(1)
777
+ .executeTakeFirst();
778
+ const saved = deletion?.notify;
779
+ const notify = saved === undefined || saved === null ? null : SQLiteBoolean.decode(saved);
780
+ return { state: "due", recipient: { email: row.email, name: row.name, locale: row.locale ?? null }, notify };
781
+ }
782
+
783
+ /** One account whose purge is due: which, and the deletion it is due under — ms-epoch, so a Workflow journal holds it. */
784
+ export interface DuePurge {
785
+ readonly userId: string;
786
+ readonly deletedAt: number;
787
+ }
788
+
789
+ /**
790
+ * The accounts whose purge is due — deleted, with `purgeAfter` passed — oldest first, at most `limit` (#622).
791
+ * What the daily cron starts a purge for. An account still inside its window is not here, and neither is one
792
+ * that was restored. Each carries its deletion's start, which names the purge's instance (`../purge/start.ts`).
793
+ */
794
+ export async function duePurges(deps: LifecycleDeps, limit: number): Promise<DuePurge[]> {
795
+ const at = (deps.now ?? (() => new Date()))();
796
+ const rows = await deps.db
797
+ .selectFrom("pithyAuthUsers")
798
+ .select(["id", "deletedAt"])
799
+ .where("deletedAt", "is not", null)
800
+ .where("purgeAfter", "is not", null)
801
+ .where("purgeAfter", "<=", SQLiteDate.encode(at))
802
+ .orderBy("purgeAfter", "asc")
803
+ .orderBy("id", "asc")
804
+ .limit(limit)
805
+ .execute();
806
+ return rows.map((row) => ({ userId: row.id, deletedAt: Number(row.deletedAt) }));
807
+ }
808
+
809
+ /**
810
+ * Record that one purge step — one capability's contribution — erased its rows. The contribution's summary is
811
+ * the row's reason, so the history says what the step erased and not only that it ran.
812
+ */
813
+ export async function recordPurgeStep(
814
+ deps: LifecycleDeps,
815
+ input: { userId: string; step: string; summary?: string | null },
816
+ ): Promise<void> {
817
+ const at = (deps.now ?? (() => new Date()))();
818
+ await record(deps, {
819
+ userId: input.userId,
820
+ action: "purge_step",
821
+ actor: PURGE,
822
+ reason: input.summary?.trim() ? input.summary.trim().slice(0, MAX_REASON) : null,
823
+ at,
824
+ step: input.step,
825
+ });
826
+ }
827
+
828
+ /**
829
+ * The deletion-complete mail, sent **before the address is erased** (#622). The purge calls this after every
830
+ * other capability's rows are gone and before auth's own, which holds the address, so the last mail is
831
+ * enqueued while there is still an account to have sent it to. The address is handed in, captured before the
832
+ * first step. `notify: false` sends nothing, whatever the config says.
833
+ */
834
+ export async function mailPurgeComplete(
835
+ deps: LifecycleDeps,
836
+ input: { recipient: PurgeRecipient; notify?: boolean },
464
837
  ): Promise<LifecycleTransition> {
465
838
  const at = (deps.now ?? (() => new Date()))();
466
- const already = await deps.db
467
- .selectFrom("pithyAuthUserLifecycle")
468
- .select("id")
469
- .where("userId", "=", input.userId)
470
- .where("action", "=", "purged")
839
+ const { email, name, locale } = input.recipient;
840
+ const mailed = await mail(
841
+ deps,
842
+ deps.config.lifecycleEmails.deletionComplete && input.notify !== false,
843
+ email,
844
+ locale,
845
+ "deletionComplete",
846
+ { ...named(name ?? ""), purgedOn: readable(at, locale) },
847
+ );
848
+ return { changed: false, mailed };
849
+ }
850
+
851
+ /**
852
+ * Finish a purge: the record, the audit event, the hook. The last thing that happens to the account.
853
+ *
854
+ * By the time a purge finishes the user row is gone, so this reads nothing about the account. Finishing a
855
+ * purge that already finished is a no-op, so a retried Workflow step records and fires once — and so do two
856
+ * purges of one account that overlapped. **The insert is the check**: `0005_purge_once` allows one `purged` row
857
+ * per account, the insert ignores a second, and only the call whose row landed audits and fires. A read
858
+ * before the insert would let two concurrent calls both find nothing and both write.
859
+ */
860
+ export async function completePurge(deps: LifecycleDeps, input: { userId: string }): Promise<LifecycleTransition> {
861
+ const at = (deps.now ?? (() => new Date()))();
862
+ const inserted = await deps.db
863
+ .insertInto("pithyAuthUserLifecycle")
864
+ .values(encoded({ userId: input.userId, action: "purged", actor: PURGE, reason: null, at }))
865
+ .onConflict((conflict) => conflict.doNothing())
471
866
  .executeTakeFirst();
472
- if (already) return { changed: false };
867
+ if (Number(inserted.numInsertedOrUpdatedRows ?? 0n) === 0) return { changed: false, mailed: false };
473
868
 
474
- await record(deps, { userId: input.userId, action: "purged", actor: PURGE, reason: null, at });
475
869
  await audit(deps, AuthAuditActions.adminUserPurged, input.userId, PURGE, {});
476
- const { email, name, locale } = input.recipient;
477
- await mail(deps, deps.config.lifecycleEmails.deletionComplete, email, locale, "deletionComplete", {
478
- ...named(name ?? ""),
479
- purgedOn: readable(at, locale),
480
- });
481
870
  await fire(deps, "onUserPurged", deps.hooks.onUserPurged, { userId: input.userId, actor: PURGE, reason: null, at });
482
- return { changed: true };
871
+ return { changed: true, mailed: false };
483
872
  }