@pithy-sh/auth 0.9.0 → 0.10.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 (125) hide show
  1. package/README.md +8 -2
  2. package/dist/audit/actions.d.ts +21 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +22 -1
  5. package/dist/audit/emit.js +1 -1
  6. package/dist/capability.d.ts +26 -1
  7. package/dist/capability.d.ts.map +1 -1
  8. package/dist/capability.js +23 -5
  9. package/dist/client/lifecycle.d.ts +19 -0
  10. package/dist/client/lifecycle.d.ts.map +1 -0
  11. package/dist/client/lifecycle.js +25 -0
  12. package/dist/client/projection.d.ts +4 -0
  13. package/dist/client/projection.d.ts.map +1 -1
  14. package/dist/data/betterAuth.d.ts +4 -0
  15. package/dist/data/betterAuth.d.ts.map +1 -1
  16. package/dist/data/betterAuth.js +6 -2
  17. package/dist/data/kitFields.d.ts +20 -25
  18. package/dist/data/kitFields.d.ts.map +1 -1
  19. package/dist/data/kitFields.js +28 -32
  20. package/dist/data/tables.d.ts +28 -2
  21. package/dist/data/tables.d.ts.map +1 -1
  22. package/dist/data/tables.js +5 -3
  23. package/dist/data/userLifecycle.d.ts +61 -0
  24. package/dist/data/userLifecycle.d.ts.map +1 -0
  25. package/dist/data/userLifecycle.js +50 -0
  26. package/dist/http/guards.d.ts +23 -1
  27. package/dist/http/guards.d.ts.map +1 -1
  28. package/dist/http/guards.js +28 -3
  29. package/dist/http/lifecycleGate.d.ts +18 -0
  30. package/dist/http/lifecycleGate.d.ts.map +1 -0
  31. package/dist/http/lifecycleGate.js +75 -0
  32. package/dist/http/middleware.d.ts +5 -0
  33. package/dist/http/middleware.d.ts.map +1 -1
  34. package/dist/http/middleware.js +47 -6
  35. package/dist/http/providerRefusal.d.ts.map +1 -1
  36. package/dist/http/providerRefusal.js +8 -0
  37. package/dist/http/resolve.d.ts.map +1 -1
  38. package/dist/http/resolve.js +7 -4
  39. package/dist/http/routes.d.ts.map +1 -1
  40. package/dist/http/routes.js +20 -1
  41. package/dist/instance/auth.d.ts +55 -3
  42. package/dist/instance/auth.d.ts.map +1 -1
  43. package/dist/instance/auth.js +53 -2
  44. package/dist/instance/microsoftEmail.d.ts +70 -0
  45. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  46. package/dist/instance/microsoftEmail.js +96 -0
  47. package/dist/instance/providerSignInGate.d.ts +7 -6
  48. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  49. package/dist/instance/providerSignInGate.js +7 -6
  50. package/dist/instance/providers.d.ts +7 -5
  51. package/dist/instance/providers.d.ts.map +1 -1
  52. package/dist/instance/providers.js +5 -3
  53. package/dist/instance/secrets.d.ts +64 -3
  54. package/dist/instance/secrets.d.ts.map +1 -1
  55. package/dist/instance/secrets.js +44 -5
  56. package/dist/lifecycle/enforce.d.ts +40 -0
  57. package/dist/lifecycle/enforce.d.ts.map +1 -0
  58. package/dist/lifecycle/enforce.js +70 -0
  59. package/dist/lifecycle/hooks.d.ts +53 -0
  60. package/dist/lifecycle/hooks.d.ts.map +1 -0
  61. package/dist/lifecycle/hooks.js +2 -0
  62. package/dist/lifecycle/request.d.ts +15 -0
  63. package/dist/lifecycle/request.d.ts.map +1 -0
  64. package/dist/lifecycle/request.js +27 -0
  65. package/dist/lifecycle/state.d.ts +64 -0
  66. package/dist/lifecycle/state.d.ts.map +1 -0
  67. package/dist/lifecycle/state.js +90 -0
  68. package/dist/lifecycle/transitions.d.ts +132 -0
  69. package/dist/lifecycle/transitions.d.ts.map +1 -0
  70. package/dist/lifecycle/transitions.js +349 -0
  71. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  72. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  73. package/dist/migrations/0004_user_lifecycle.js +47 -0
  74. package/dist/migrations/set.d.ts +2 -1
  75. package/dist/migrations/set.d.ts.map +1 -1
  76. package/dist/migrations/set.js +4 -2
  77. package/dist/peer.d.ts +4 -0
  78. package/dist/peer.d.ts.map +1 -1
  79. package/dist/test-utils/liveApp.d.ts +21 -0
  80. package/dist/test-utils/liveApp.d.ts.map +1 -1
  81. package/dist/test-utils/liveApp.js +1 -0
  82. package/dist/test-utils/scopedBackend.d.ts +21 -0
  83. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  84. package/dist/test-utils/scopedBackend.js +7 -1
  85. package/dist/version.generated.d.ts +1 -1
  86. package/dist/version.generated.d.ts.map +1 -1
  87. package/dist/version.generated.js +1 -1
  88. package/docs/account-lifecycle.md +105 -0
  89. package/docs/apple-signin.md +7 -1
  90. package/docs/facebook-oauth.md +7 -1
  91. package/docs/github-oauth.md +7 -1
  92. package/docs/google-oauth.md +7 -1
  93. package/docs/microsoft-oauth.md +177 -0
  94. package/package.json +5 -5
  95. package/pithy.manifest.json +17 -3
  96. package/src/audit/actions.ts +23 -0
  97. package/src/audit/emit.ts +1 -1
  98. package/src/capability.ts +125 -54
  99. package/src/client/lifecycle.ts +27 -0
  100. package/src/client/projection.ts +4 -0
  101. package/src/data/betterAuth.ts +21 -1
  102. package/src/data/kitFields.ts +27 -0
  103. package/src/data/tables.ts +4 -2
  104. package/src/data/userLifecycle.ts +80 -0
  105. package/src/http/guards.ts +29 -1
  106. package/src/http/lifecycleGate.ts +78 -0
  107. package/src/http/middleware.ts +61 -2
  108. package/src/http/providerRefusal.ts +10 -0
  109. package/src/http/resolve.ts +8 -3
  110. package/src/http/routes.ts +38 -1
  111. package/src/instance/auth.ts +69 -2
  112. package/src/instance/microsoftEmail.ts +111 -0
  113. package/src/instance/providerSignInGate.ts +7 -6
  114. package/src/instance/providers.ts +8 -4
  115. package/src/instance/secrets.ts +59 -5
  116. package/src/lifecycle/enforce.ts +89 -0
  117. package/src/lifecycle/hooks.ts +54 -0
  118. package/src/lifecycle/request.ts +31 -0
  119. package/src/lifecycle/state.ts +101 -0
  120. package/src/lifecycle/transitions.ts +483 -0
  121. package/src/migrations/0004_user_lifecycle.ts +68 -0
  122. package/src/migrations/set.ts +3 -1
  123. package/src/test-utils/liveApp.ts +2 -1
  124. package/src/test-utils/scopedBackend.ts +2 -1
  125. package/src/version.generated.ts +1 -1
@@ -0,0 +1,483 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { D1Database, D1PreparedStatement } from "@cloudflare/workers-types";
5
+ import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
6
+ import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
7
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
8
+ import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
9
+ import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
10
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
11
+ import type { EnqueueInput } from "@pithy-sh/email/src/send/enqueue";
12
+ import { type CompiledQuery, sql } from "kysely";
13
+ import { type AuthAuditAction, AuthAuditActions } from "../audit/actions";
14
+ import type { AuthConfig } from "../capability";
15
+ import type { AuthDatabase } from "../data/tables";
16
+ import type { UserLifecycleAction, UserLifecycleActorType } from "../data/userLifecycle";
17
+ import type { UserLifecycleHookEvent, UserLifecycleHooks, UserLifecycleListener } from "./hooks";
18
+ import { accountStanding, LifecycleColumns } from "./state";
19
+
20
+ /**
21
+ * The account-lifecycle transitions — the one place an account's state is ever changed (#620).
22
+ *
23
+ * The admin routes (#621, #622), the self-service deletion, and the purge Workflow call these and write
24
+ * nothing themselves, so each transition happens the same way whoever asked for it:
25
+ *
26
+ * 1. **The columns move, conditionally, and the history row is written with them.** The `update` names the
27
+ * state it expects to find, so of two concurrent suspensions exactly one changes a row, and only that one
28
+ * goes on. A request that finds the account already where it asked to put it is `changed: false` and does
29
+ * nothing else — no row, no mail, no hook — which is what "once per transition" means.
30
+ * 2. **The row in `pithy_auth_user_lifecycle`** — the actor, the reason, the time — is the second statement of
31
+ * the same `d1.batch()`, which D1 runs as one transaction, and it is written only when the first moved the
32
+ * account. Two awaits would leave a gap: a failed insert after a committed update, and a retry that finds
33
+ * the account already moved, returns `changed: false`, and loses the row, the event, the mail and the hook.
34
+ * 3. **The audit event is emitted** — the trail answers who and from where; the row answers what happened.
35
+ * 4. **The mail is enqueued**, when the config sends it, in the account's own language.
36
+ * 5. **The hook fires.**
37
+ *
38
+ * Steps 3 to 5 report something that has already happened, so none of them can undo it: each swallows its own
39
+ * failure, and a throwing hook or an email binding that is not there is logged and the transition stands.
40
+ *
41
+ * **What these do not do is end sessions.** Enforcement does not need them to — a suspended account's session
42
+ * is refused at every door the moment the column is written (`./enforce.ts`) — and revoking them is a route's
43
+ * decision, made through Better Auth so `onSessionRevoked` hears about it.
44
+ */
45
+
46
+ /** Who made a transition. */
47
+ export interface LifecycleActor {
48
+ /** The kind of principal. */
49
+ readonly type: UserLifecycleActorType;
50
+ /** Its id — the connection's for a management client, the user's own for self-service — or null. */
51
+ readonly id: string | null;
52
+ }
53
+
54
+ /** Everything a transition needs, resolved by the caller from its own context. */
55
+ export interface LifecycleDeps {
56
+ /** The auth tables. */
57
+ readonly db: AuthDatabase;
58
+ /** The same database as a binding, for the hooks — see `UserLifecycleListener`. */
59
+ readonly d1: D1Database;
60
+ /** The audit seam. A no-op when the audit capability is absent. */
61
+ readonly emit: AuditEmit;
62
+ /** The resolved config: the purge window, and which mails are sent. */
63
+ readonly config: Pick<AuthConfig, "retention" | "lifecycleEmails">;
64
+ /** The adopter's hooks. */
65
+ readonly hooks: UserLifecycleHooks;
66
+ /** The email capability's enqueue, bound to this run's env. Absent, nothing is mailed. */
67
+ readonly enqueueEmail?: ((input: EnqueueInput) => Promise<unknown>) | undefined;
68
+ /** Where a swallowed failure is reported. Absent, it is swallowed silently. */
69
+ readonly log?: Logger | undefined;
70
+ /** The clock. Defaults to the system's. */
71
+ readonly now?: (() => Date) | undefined;
72
+ }
73
+
74
+ /** What a transition did. */
75
+ export interface LifecycleTransition {
76
+ /** Whether the account moved. `false` when it was already where the call asked to put it. */
77
+ readonly changed: boolean;
78
+ }
79
+
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;
82
+
83
+ /** A reason, trimmed and bounded, or null when none was given. */
84
+ function reasonOf(reason: string | null | undefined): string | null {
85
+ if (reason === null || reason === undefined) return null;
86
+ const trimmed = reason.trim();
87
+ if (trimmed === "") return null;
88
+ if (trimmed.length > MAX_REASON) {
89
+ throw new ValidationError({
90
+ message: `A reason is at most ${MAX_REASON} characters.`,
91
+ detail: `lifecycle reason of ${trimmed.length} characters`,
92
+ });
93
+ }
94
+ return trimmed;
95
+ }
96
+
97
+ /** The account a transition acts on: who to write to, and where it stands. */
98
+ interface Subject {
99
+ readonly email: string;
100
+ readonly name: string;
101
+ readonly locale: string | null;
102
+ readonly columns: LifecycleColumns;
103
+ }
104
+
105
+ async function subjectOf(db: AuthDatabase, userId: string): Promise<Subject> {
106
+ const row = await db
107
+ .selectFrom("pithyAuthUsers")
108
+ .select(["email", "name", "locale", "suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"])
109
+ .where("id", "=", userId)
110
+ .executeTakeFirst();
111
+ if (!row) {
112
+ throw new NotFoundError({
113
+ message: "No such account.",
114
+ action: "If it was deleted and its purge has run, its data is gone and there is nothing to act on.",
115
+ detail: `lifecycle transition for user ${userId}, which has no row`,
116
+ });
117
+ }
118
+ return { email: row.email, name: row.name, locale: row.locale ?? null, columns: LifecycleColumns.parse(row) };
119
+ }
120
+
121
+ /** A date written for its reader, in their language — the shape every lifecycle mail carries its dates in. */
122
+ function readable(date: Date, locale: string | null): string {
123
+ const tag = (locale ? formattingLocaleOf(locale) : null) ?? "en";
124
+ return new Intl.DateTimeFormat(tag, { dateStyle: "long", timeZone: "UTC" }).format(date);
125
+ }
126
+
127
+ /** One row of an account's history. */
128
+ interface HistoryRow {
129
+ readonly userId: string;
130
+ readonly action: UserLifecycleAction;
131
+ readonly actor: LifecycleActor;
132
+ readonly reason: string | null;
133
+ readonly at: Date;
134
+ readonly suspendedUntil?: Date | null;
135
+ readonly step?: string | null;
136
+ }
137
+
138
+ /** The history row's values, as the table stores them. */
139
+ function encoded(row: HistoryRow) {
140
+ return {
141
+ userId: row.userId,
142
+ action: row.action,
143
+ actorType: row.actor.type,
144
+ actorId: row.actor.id,
145
+ reason: row.reason,
146
+ suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
147
+ step: row.step ?? null,
148
+ createdAt: SQLiteDate.encode(row.at),
149
+ };
150
+ }
151
+
152
+ /** A history row with no column change to pair it with: a purge step, a finished purge. Not swallowed. */
153
+ async function record(deps: LifecycleDeps, row: HistoryRow): Promise<void> {
154
+ await deps.db.insertInto("pithyAuthUserLifecycle").values(encoded(row)).execute();
155
+ }
156
+
157
+ /** Bind a compiled statement to D1, so it can join a `batch`. */
158
+ function prepared(d1: D1Database, compiled: CompiledQuery): D1PreparedStatement {
159
+ return d1.prepare(compiled.sql).bind(...(compiled.parameters as unknown[]));
160
+ }
161
+
162
+ /**
163
+ * Move the columns and write the history row as one transaction, and say whether the account moved.
164
+ *
165
+ * The insert is guarded by `changes()`, which SQLite answers for the statement just before it — the update —
166
+ * so a conditional update that matched nothing writes no row. Not swallowed: until both are written, nothing
167
+ * after them runs.
168
+ */
169
+ async function move(deps: LifecycleDeps, update: { compile(): CompiledQuery }, row: HistoryRow): Promise<boolean> {
170
+ const v = encoded(row);
171
+ const insert = deps.db
172
+ .insertInto("pithyAuthUserLifecycle")
173
+ .columns(["userId", "action", "actorType", "actorId", "reason", "suspendedUntil", "step", "createdAt"])
174
+ .expression(
175
+ deps.db
176
+ .selectNoFrom([
177
+ sql.val(v.userId).as("userId"),
178
+ sql.val(v.action).as("action"),
179
+ sql.val(v.actorType).as("actorType"),
180
+ sql.val(v.actorId).as("actorId"),
181
+ sql.val(v.reason).as("reason"),
182
+ sql.val(v.suspendedUntil).as("suspendedUntil"),
183
+ sql.val(v.step).as("step"),
184
+ sql.val(v.createdAt).as("createdAt"),
185
+ ])
186
+ .where(sql<number>`changes()`, ">", 0),
187
+ )
188
+ .compile();
189
+ const [updated] = await deps.d1.batch([prepared(deps.d1, update.compile()), prepared(deps.d1, insert)]);
190
+ return (updated?.meta.changes ?? 0) > 0;
191
+ }
192
+
193
+ /** The audit event, swallowed on failure — an audit write never breaks what it records. */
194
+ async function audit(
195
+ deps: LifecycleDeps,
196
+ action: AuthAuditAction,
197
+ userId: string,
198
+ actor: LifecycleActor,
199
+ metadata: Record<string, unknown>,
200
+ ): Promise<void> {
201
+ const event: AuditEventInput = {
202
+ action,
203
+ outcome: "success",
204
+ actorType: actor.type,
205
+ actorId: actor.id,
206
+ resourceType: "user",
207
+ resourceId: userId,
208
+ metadata,
209
+ };
210
+ try {
211
+ await deps.emit(event);
212
+ } catch (error) {
213
+ deps.log?.warn(`lifecycle audit ${action} failed; the transition stands`, { reason: messageOf(error) });
214
+ }
215
+ }
216
+
217
+ /** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. */
218
+ async function mail(
219
+ deps: LifecycleDeps,
220
+ enabled: boolean,
221
+ to: string,
222
+ locale: string | null,
223
+ template: "accountSuspended" | "accountReinstated" | "deletionScheduled" | "deletionComplete",
224
+ payload: Record<string, unknown>,
225
+ ): Promise<void> {
226
+ if (!enabled || !deps.enqueueEmail) return;
227
+ try {
228
+ await deps.enqueueEmail({ to, template, payload, ...(locale ? { locale } : {}) });
229
+ } catch (error) {
230
+ deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, {
231
+ reason: messageOf(error),
232
+ });
233
+ }
234
+ }
235
+
236
+ /** Fire one hook. Swallowed and logged: the transition is already written, and a retry would fire nothing. */
237
+ async function fire(
238
+ deps: LifecycleDeps,
239
+ name: keyof UserLifecycleHooks,
240
+ hook: UserLifecycleListener | undefined,
241
+ event: UserLifecycleHookEvent,
242
+ ): Promise<void> {
243
+ if (!hook) return;
244
+ try {
245
+ await hook(event, deps.d1);
246
+ } catch (error) {
247
+ deps.log?.warn(`${name} threw; the transition stands`, { userId: event.userId, reason: messageOf(error) });
248
+ }
249
+ }
250
+
251
+ function messageOf(error: unknown): string {
252
+ return error instanceof Error ? error.message : String(error);
253
+ }
254
+
255
+ /** Without a name, a greeting says "Hi," rather than greeting an empty string. */
256
+ function named(name: string): { name?: string } {
257
+ return name.trim() ? { name } : {};
258
+ }
259
+
260
+ /**
261
+ * Suspend an account, until `until` or until it is reinstated.
262
+ *
263
+ * 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.
265
+ */
266
+ export async function suspendUser(
267
+ deps: LifecycleDeps,
268
+ input: { userId: string; actor: LifecycleActor; reason: string | null; until?: Date | null },
269
+ ): Promise<LifecycleTransition> {
270
+ const at = (deps.now ?? (() => new Date()))();
271
+ const reason = reasonOf(input.reason);
272
+ const until = input.until ?? null;
273
+ if (until && until.getTime() <= at.getTime()) {
274
+ throw new ValidationError({ message: "A suspension must end in the future, or not at all." });
275
+ }
276
+ const subject = await subjectOf(deps.db, input.userId);
277
+ const standing = accountStanding(subject.columns, at);
278
+ 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
+ });
283
+ }
284
+ if (standing.state === "suspended") return { changed: false };
285
+ const update = deps.db
286
+ .updateTable("pithyAuthUsers")
287
+ .set({ suspendedAt: SQLiteDate.encode(at), suspendedUntil: until ? SQLiteDate.encode(until) : null })
288
+ .where("id", "=", input.userId)
289
+ .where("deletedAt", "is", null)
290
+ .where((eb) =>
291
+ eb.or([
292
+ eb("suspendedAt", "is", null),
293
+ eb.and([eb("suspendedUntil", "is not", null), eb("suspendedUntil", "<=", SQLiteDate.encode(at))]),
294
+ ]),
295
+ );
296
+ const row: HistoryRow = {
297
+ userId: input.userId,
298
+ action: "suspended",
299
+ actor: input.actor,
300
+ reason,
301
+ at,
302
+ suspendedUntil: until,
303
+ };
304
+ if (!(await move(deps, update, row))) return { changed: false };
305
+
306
+ await audit(deps, AuthAuditActions.adminUserSuspended, input.userId, input.actor, {
307
+ reason,
308
+ suspendedUntil: until?.toISOString() ?? null,
309
+ });
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 };
323
+ }
324
+
325
+ /**
326
+ * Lift a suspension. An account that is not suspended — including one whose suspension ran out — is a no-op.
327
+ *
328
+ * Where the account stands is read through `accountStanding`, never off the raw column, because a suspension
329
+ * past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
330
+ * for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
331
+ * sign in again" to somebody every sign-in still refuses. Restore it first.
332
+ */
333
+ export async function reinstateUser(
334
+ deps: LifecycleDeps,
335
+ input: { userId: string; actor: LifecycleActor; reason: string | null },
336
+ ): Promise<LifecycleTransition> {
337
+ const at = (deps.now ?? (() => new Date()))();
338
+ const reason = reasonOf(input.reason);
339
+ const subject = await subjectOf(deps.db, input.userId);
340
+ const standing = accountStanding(subject.columns, at);
341
+ 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
+ });
346
+ }
347
+ if (standing.state !== "suspended") return { changed: false };
348
+ const update = deps.db
349
+ .updateTable("pithyAuthUsers")
350
+ .set({ suspendedAt: null, suspendedUntil: null })
351
+ .where("id", "=", input.userId)
352
+ .where("deletedAt", "is", null)
353
+ .where("suspendedAt", "is not", null)
354
+ .where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))]));
355
+ const row: HistoryRow = { userId: input.userId, action: "reinstated", actor: input.actor, reason, at };
356
+ if (!(await move(deps, update, row))) return { changed: false };
357
+
358
+ await audit(deps, AuthAuditActions.adminUserReinstated, input.userId, input.actor, { reason });
359
+ await mail(
360
+ deps,
361
+ deps.config.lifecycleEmails.accountReinstated,
362
+ subject.email,
363
+ subject.locale,
364
+ "accountReinstated",
365
+ named(subject.name),
366
+ );
367
+ await fire(deps, "onUserReinstated", deps.hooks.onUserReinstated, {
368
+ userId: input.userId,
369
+ actor: input.actor,
370
+ reason,
371
+ at,
372
+ });
373
+ return { changed: true };
374
+ }
375
+
376
+ /**
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.
379
+ *
380
+ * A suspension the account was under is left in place, so restoring the account does not lift it.
381
+ */
382
+ export async function deleteUser(
383
+ deps: LifecycleDeps,
384
+ input: { userId: string; actor: LifecycleActor; reason: string | null },
385
+ ): Promise<LifecycleTransition> {
386
+ const at = (deps.now ?? (() => new Date()))();
387
+ const reason = reasonOf(input.reason);
388
+ const purgeAfter = new Date(at.getTime() + deps.config.retention.purgeAfterDays * 86_400_000);
389
+ const subject = await subjectOf(deps.db, input.userId);
390
+ if (subject.columns.deletedAt) return { changed: false };
391
+ const update = deps.db
392
+ .updateTable("pithyAuthUsers")
393
+ .set({ deletedAt: SQLiteDate.encode(at), purgeAfter: SQLiteDate.encode(purgeAfter) })
394
+ .where("id", "=", input.userId)
395
+ .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 };
398
+
399
+ 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
+ });
411
+ await fire(deps, "onUserDeleted", deps.hooks.onUserDeleted, {
412
+ userId: input.userId,
413
+ actor: input.actor,
414
+ reason,
415
+ at,
416
+ purgeAfter,
417
+ });
418
+ return { changed: true };
419
+ }
420
+
421
+ /**
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.
424
+ */
425
+ export async function restoreUser(
426
+ deps: LifecycleDeps,
427
+ input: { userId: string; actor: LifecycleActor; reason: string | null },
428
+ ): Promise<LifecycleTransition> {
429
+ const at = (deps.now ?? (() => new Date()))();
430
+ const reason = reasonOf(input.reason);
431
+ const subject = await subjectOf(deps.db, input.userId);
432
+ if (!subject.columns.deletedAt) return { changed: false };
433
+ const update = deps.db
434
+ .updateTable("pithyAuthUsers")
435
+ .set({ deletedAt: null, purgeAfter: null })
436
+ .where("id", "=", input.userId)
437
+ .where("deletedAt", "is not", null);
438
+ const row: HistoryRow = { userId: input.userId, action: "restored", actor: input.actor, reason, at };
439
+ if (!(await move(deps, update, row))) return { changed: false };
440
+
441
+ await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
442
+ return { changed: true };
443
+ }
444
+
445
+ /** The purge's own actor: a scheduled job, with nobody calling. */
446
+ const PURGE: LifecycleActor = { type: "system", id: null };
447
+
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 });
452
+ }
453
+
454
+ /**
455
+ * Finish a purge: the last mail, the record, the audit event, the hook.
456
+ *
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.
460
+ */
461
+ export async function completePurge(
462
+ deps: LifecycleDeps,
463
+ input: { userId: string; recipient: { email: string; name: string | null; locale: string | null } },
464
+ ): Promise<LifecycleTransition> {
465
+ 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")
471
+ .executeTakeFirst();
472
+ if (already) return { changed: false };
473
+
474
+ await record(deps, { userId: input.userId, action: "purged", actor: PURGE, reason: null, at });
475
+ 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
+ await fire(deps, "onUserPurged", deps.hooks.onUserPurged, { userId: input.userId, actor: PURGE, reason: null, at });
482
+ return { changed: true };
483
+ }
@@ -0,0 +1,68 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Kysely } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /** The four state columns, in the order `up` adds them and `down` takes them away in reverse. */
8
+ const STATE_COLUMNS = ["suspendedAt", "suspendedUntil", "deletedAt", "purgeAfter"] as const;
9
+
10
+ /**
11
+ * The account lifecycle (#620): whether an account is suspended or deleted, and the record of how it got
12
+ * there.
13
+ *
14
+ * **Four columns on `pithy_auth_users`, so a session read already carries the state.** Better Auth loads the
15
+ * user row for every session it resolves, and returns these because `../data/kitFields.ts` declares them —
16
+ * so refusing a suspended account costs no query on the request that is refused, and none on the requests
17
+ * that are not.
18
+ *
19
+ * **One kit-owned table beside them, `pithy_auth_user_lifecycle`**, holding every transition with its
20
+ * actor, its reason and its time. The columns say what is true now; the table says what happened. No
21
+ * foreign key from it to the user: a purge erases the user row, and this table is the record that must
22
+ * outlive it (`../data/userLifecycle.ts`).
23
+ *
24
+ * **`integer`, not `text`, unlike every Better Auth date on the same table.** Better Auth writes those, as
25
+ * ISO-8601. Nothing but the kit writes these — they are `input: false` — so they take the house ms-epoch
26
+ * convention, and `type: "number"` in `kitFields.ts` keeps Better Auth from converting what it reads back.
27
+ *
28
+ * **Nullable, with no backfill.** Every account that exists when this runs is in neither state, and null is
29
+ * exactly that. SQLite would refuse `ADD COLUMN … NOT NULL` without a constant default anyway.
30
+ *
31
+ * **A `0004`, appended, never folded into `0001`.** `@pithy-sh/auth` has shipped, so its chain is history.
32
+ */
33
+ export const auth_0004_user_lifecycle: Migration = {
34
+ async up(db: Kysely<unknown>): Promise<void> {
35
+ for (const column of STATE_COLUMNS) {
36
+ await db.schema.alterTable("pithyAuthUsers").addColumn(column, "integer").execute();
37
+ }
38
+ await db.schema
39
+ .createTable("pithyAuthUserLifecycle")
40
+ .addColumn("id", "integer", (c) => c.primaryKey().autoIncrement())
41
+ .addColumn("userId", "text", (c) => c.notNull())
42
+ .addColumn("action", "text", (c) => c.notNull())
43
+ .addColumn("actorType", "text", (c) => c.notNull())
44
+ .addColumn("actorId", "text")
45
+ .addColumn("reason", "text")
46
+ .addColumn("suspendedUntil", "integer")
47
+ .addColumn("step", "text")
48
+ .addColumn("createdAt", "integer", (c) => c.notNull())
49
+ .execute();
50
+ // A user's history, newest first, is the one read this table serves — the refusal that shows a
51
+ // suspended person the reason, and an operator's view of what happened to one account. The trailing
52
+ // id orders two transitions written in the same millisecond the way they were written.
53
+ await db.schema
54
+ .createIndex("pithyAuthUserLifecycleUserIdIdx")
55
+ .on("pithyAuthUserLifecycle")
56
+ .columns(["userId", "id"])
57
+ .execute();
58
+ },
59
+ async down(db: Kysely<unknown>): Promise<void> {
60
+ // The exact inverse. Nothing else references this table or these columns, and SQLite has supported
61
+ // `DROP COLUMN` since 3.35, which D1 is well past.
62
+ await db.schema.dropIndex("pithyAuthUserLifecycleUserIdIdx").execute();
63
+ await db.schema.dropTable("pithyAuthUserLifecycle").execute();
64
+ for (const column of [...STATE_COLUMNS].reverse()) {
65
+ await db.schema.alterTable("pithyAuthUsers").dropColumn(column).execute();
66
+ }
67
+ },
68
+ };
@@ -4,6 +4,7 @@
4
4
  import { auth_0001_init } from "./0001_init";
5
5
  import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at";
6
6
  import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullable";
7
+ import { auth_0004_user_lifecycle } from "./0004_user_lifecycle";
7
8
 
8
9
  /**
9
10
  * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
@@ -15,11 +16,12 @@ import { auth_0003_account_issuer_nullable } from "./0003_account_issuer_nullabl
15
16
  * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
16
17
  * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
17
18
  *
18
- * `0003` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
19
+ * `0003` and `0004` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
19
20
  * its subject is that one migration's own `up` and `down`, so it names it directly.
20
21
  */
21
22
  export const AUTH_MIGRATIONS = {
22
23
  "0001_init": auth_0001_init,
23
24
  "0002_session_authenticated_at": auth_0002_session_authenticated_at,
24
25
  "0003_account_issuer_nullable": auth_0003_account_issuer_nullable,
26
+ "0004_user_lifecycle": auth_0004_user_lifecycle,
25
27
  } as const;
@@ -66,6 +66,7 @@ const TABLES = [
66
66
  "pithy_auth_jwks",
67
67
  "pithy_auth_rate_limit",
68
68
  "pithy_auth_rotated_tokens",
69
+ "pithy_auth_user_lifecycle",
69
70
  "pithy_auth_sessions",
70
71
  "pithy_auth_users",
71
72
  "pithy_auth_verifications",
@@ -266,7 +267,7 @@ function buildApp(wiring: AuthWiring, events: AuditEventInput[]): Hono<PithyHono
266
267
  app.onError(pithyErrorHandler);
267
268
  app.use("*", async (c, next) => {
268
269
  if (c.get("emit") === undefined) {
269
- c.set("emit", async (event) => {
270
+ c.set("emit", async (event: AuditEventInput) => {
270
271
  events.push(event);
271
272
  });
272
273
  }
@@ -45,6 +45,7 @@ export const SCOPED_SECRETS: SecretFixture<typeof SCOPED_REGISTRY> = {
45
45
  "auth-apple-credentials": { clientId: "a", clientSecret: "a" },
46
46
  "auth-facebook-credentials": { clientId: "f", clientSecret: "f" },
47
47
  "auth-github-credentials": { clientId: "h", clientSecret: "h" },
48
+ "auth-microsoft-credentials": { clientId: "m", clientSecret: "m", tenantId: "common" },
48
49
  "email-link-signing-key": "dev-link-signing-key",
49
50
  };
50
51
 
@@ -121,7 +122,7 @@ export async function signInScoped(
121
122
  verificationExpiresIn: 300,
122
123
  otpLength: 6,
123
124
  disableSignUp: false,
124
- providerSignUp: { google: true, apple: true, facebook: true, github: true },
125
+ providerSignUp: { google: true, apple: true, facebook: true, github: true, microsoft: true },
125
126
  emit: async () => {},
126
127
  plugins: [],
127
128
  });
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/auth";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.9.0";
16
+ export const PACKAGE_VERSION = "0.10.0";