@pithy-sh/auth 0.8.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 (164) hide show
  1. package/README.md +12 -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/caller/certificate.d.ts +83 -0
  7. package/dist/caller/certificate.d.ts.map +1 -0
  8. package/dist/caller/certificate.js +92 -0
  9. package/dist/caller/request.d.ts +66 -0
  10. package/dist/caller/request.d.ts.map +1 -0
  11. package/dist/caller/request.js +71 -0
  12. package/dist/caller/token.d.ts +130 -0
  13. package/dist/caller/token.d.ts.map +1 -0
  14. package/dist/caller/token.js +207 -0
  15. package/dist/capability.d.ts +70 -2
  16. package/dist/capability.d.ts.map +1 -1
  17. package/dist/capability.js +28 -7
  18. package/dist/client/lifecycle.d.ts +19 -0
  19. package/dist/client/lifecycle.d.ts.map +1 -0
  20. package/dist/client/lifecycle.js +25 -0
  21. package/dist/client/projection.d.ts +4 -0
  22. package/dist/client/projection.d.ts.map +1 -1
  23. package/dist/data/betterAuth.d.ts +5 -1
  24. package/dist/data/betterAuth.d.ts.map +1 -1
  25. package/dist/data/betterAuth.js +7 -3
  26. package/dist/data/kitFields.d.ts +20 -25
  27. package/dist/data/kitFields.d.ts.map +1 -1
  28. package/dist/data/kitFields.js +28 -32
  29. package/dist/data/tables.d.ts +29 -3
  30. package/dist/data/tables.d.ts.map +1 -1
  31. package/dist/data/tables.js +5 -3
  32. package/dist/data/userLifecycle.d.ts +61 -0
  33. package/dist/data/userLifecycle.d.ts.map +1 -0
  34. package/dist/data/userLifecycle.js +50 -0
  35. package/dist/http/credentialResign.d.ts +46 -0
  36. package/dist/http/credentialResign.d.ts.map +1 -0
  37. package/dist/http/credentialResign.js +203 -0
  38. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  39. package/dist/http/errorCallbackUrl.js +15 -9
  40. package/dist/http/guards.d.ts +23 -1
  41. package/dist/http/guards.d.ts.map +1 -1
  42. package/dist/http/guards.js +28 -3
  43. package/dist/http/lifecycleGate.d.ts +18 -0
  44. package/dist/http/lifecycleGate.d.ts.map +1 -0
  45. package/dist/http/lifecycleGate.js +75 -0
  46. package/dist/http/middleware.d.ts +5 -0
  47. package/dist/http/middleware.d.ts.map +1 -1
  48. package/dist/http/middleware.js +113 -21
  49. package/dist/http/providerRefusal.d.ts +8 -7
  50. package/dist/http/providerRefusal.d.ts.map +1 -1
  51. package/dist/http/providerRefusal.js +37 -32
  52. package/dist/http/resolve.d.ts.map +1 -1
  53. package/dist/http/resolve.js +23 -5
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +20 -1
  56. package/dist/instance/auth.d.ts +1280 -5
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +59 -4
  59. package/dist/instance/jwksReencryption.d.ts +75 -0
  60. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  61. package/dist/instance/jwksReencryption.js +160 -0
  62. package/dist/instance/microsoftEmail.d.ts +70 -0
  63. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  64. package/dist/instance/microsoftEmail.js +96 -0
  65. package/dist/instance/providerSignInGate.d.ts +14 -12
  66. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  67. package/dist/instance/providerSignInGate.js +23 -20
  68. package/dist/instance/providers.d.ts +7 -5
  69. package/dist/instance/providers.d.ts.map +1 -1
  70. package/dist/instance/providers.js +5 -3
  71. package/dist/instance/secrets.d.ts +232 -4
  72. package/dist/instance/secrets.d.ts.map +1 -1
  73. package/dist/instance/secrets.js +129 -7
  74. package/dist/instance/sessionSecrets.d.ts +45 -0
  75. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  76. package/dist/instance/sessionSecrets.js +29 -0
  77. package/dist/lifecycle/enforce.d.ts +40 -0
  78. package/dist/lifecycle/enforce.d.ts.map +1 -0
  79. package/dist/lifecycle/enforce.js +70 -0
  80. package/dist/lifecycle/hooks.d.ts +53 -0
  81. package/dist/lifecycle/hooks.d.ts.map +1 -0
  82. package/dist/lifecycle/hooks.js +2 -0
  83. package/dist/lifecycle/request.d.ts +15 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +27 -0
  86. package/dist/lifecycle/state.d.ts +64 -0
  87. package/dist/lifecycle/state.d.ts.map +1 -0
  88. package/dist/lifecycle/state.js +90 -0
  89. package/dist/lifecycle/transitions.d.ts +132 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +349 -0
  92. package/dist/migrations/0001_init.d.ts.map +1 -1
  93. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  94. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  95. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  96. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  97. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  98. package/dist/migrations/0004_user_lifecycle.js +47 -0
  99. package/dist/migrations/set.d.ts +3 -1
  100. package/dist/migrations/set.d.ts.map +1 -1
  101. package/dist/migrations/set.js +6 -2
  102. package/dist/peer.d.ts +4 -0
  103. package/dist/peer.d.ts.map +1 -1
  104. package/dist/test-utils/liveApp.d.ts +26 -0
  105. package/dist/test-utils/liveApp.d.ts.map +1 -1
  106. package/dist/test-utils/liveApp.js +1 -0
  107. package/dist/test-utils/schemaDrift.d.ts +49 -0
  108. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  109. package/dist/test-utils/schemaDrift.js +35 -0
  110. package/dist/test-utils/scopedBackend.d.ts +204 -0
  111. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  112. package/dist/test-utils/scopedBackend.js +166 -0
  113. package/dist/version.generated.d.ts +1 -1
  114. package/dist/version.generated.d.ts.map +1 -1
  115. package/dist/version.generated.js +1 -1
  116. package/docs/account-lifecycle.md +105 -0
  117. package/docs/apple-signin.md +7 -1
  118. package/docs/facebook-oauth.md +7 -1
  119. package/docs/github-oauth.md +7 -1
  120. package/docs/google-oauth.md +7 -1
  121. package/docs/microsoft-oauth.md +177 -0
  122. package/docs/server-authoritative.md +182 -0
  123. package/package.json +11 -8
  124. package/pithy.manifest.json +17 -3
  125. package/src/audit/actions.ts +23 -0
  126. package/src/audit/emit.ts +1 -1
  127. package/src/caller/certificate.ts +133 -0
  128. package/src/caller/request.ts +84 -0
  129. package/src/caller/token.ts +276 -0
  130. package/src/capability.ts +170 -38
  131. package/src/client/lifecycle.ts +27 -0
  132. package/src/client/projection.ts +4 -0
  133. package/src/data/betterAuth.ts +23 -2
  134. package/src/data/kitFields.ts +27 -0
  135. package/src/data/tables.ts +4 -2
  136. package/src/data/userLifecycle.ts +80 -0
  137. package/src/http/credentialResign.ts +268 -0
  138. package/src/http/errorCallbackUrl.ts +21 -13
  139. package/src/http/guards.ts +29 -1
  140. package/src/http/lifecycleGate.ts +78 -0
  141. package/src/http/middleware.ts +161 -37
  142. package/src/http/providerRefusal.ts +40 -32
  143. package/src/http/resolve.ts +34 -5
  144. package/src/http/routes.ts +39 -2
  145. package/src/instance/auth.ts +91 -6
  146. package/src/instance/jwksReencryption.ts +206 -0
  147. package/src/instance/microsoftEmail.ts +111 -0
  148. package/src/instance/providerSignInGate.ts +30 -27
  149. package/src/instance/providers.ts +8 -4
  150. package/src/instance/secrets.ts +153 -6
  151. package/src/instance/sessionSecrets.ts +64 -0
  152. package/src/lifecycle/enforce.ts +89 -0
  153. package/src/lifecycle/hooks.ts +54 -0
  154. package/src/lifecycle/request.ts +31 -0
  155. package/src/lifecycle/state.ts +101 -0
  156. package/src/lifecycle/transitions.ts +483 -0
  157. package/src/migrations/0001_init.ts +8 -10
  158. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  159. package/src/migrations/0004_user_lifecycle.ts +68 -0
  160. package/src/migrations/set.ts +5 -1
  161. package/src/test-utils/liveApp.ts +2 -1
  162. package/src/test-utils/schemaDrift.ts +82 -0
  163. package/src/test-utils/scopedBackend.ts +137 -0
  164. package/src/version.generated.ts +1 -1
@@ -0,0 +1,31 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
+ import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
6
+ import type { Context } from "hono";
7
+ import type { AuthWiring } from "../capability";
8
+ import { authDatabase } from "../data/tables";
9
+ import { resolveDb } from "../http/resolve";
10
+ import type { LifecycleDeps } from "./transitions";
11
+
12
+ /**
13
+ * The transitions' dependencies, resolved from one request — what a lifecycle route hands `./transitions.ts`.
14
+ *
15
+ * One function so every route resolves them the same way: this request's database, its audit seam and logger,
16
+ * the composed email capability's enqueue bound to this request's env, and the adopter's hooks as `auth()` was
17
+ * handed them. A route that assembled its own would be the second place a hook could be forgotten.
18
+ */
19
+ export function lifecycleDeps(c: Context<PithyHonoEnv>, wiring: AuthWiring): LifecycleDeps {
20
+ const d1 = resolveDb(c.env, wiring.config.database);
21
+ const enqueue = wiring.enqueueEmail;
22
+ return {
23
+ db: authDatabase(d1),
24
+ d1,
25
+ emit: c.var.emit,
26
+ config: wiring.config,
27
+ hooks: wiring.lifecycleHooks ?? {},
28
+ enqueueEmail: enqueue ? (input) => enqueue(c.env as unknown as EmailEnqueueEnv, input) : undefined,
29
+ log: c.var.log?.child("auth"),
30
+ };
31
+ }
@@ -0,0 +1,101 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
+ import type { z } from "zod";
6
+ import { User } from "../data/betterAuth";
7
+
8
+ /**
9
+ * What an account's four lifecycle columns mean, decided once.
10
+ *
11
+ * Every enforcement point — the session middleware, sign-in, token refresh — reads the state through
12
+ * {@link accountStanding} and refuses through {@link lifecycleRefusal}. Enforcement written twice is
13
+ * enforcement that disagrees, and the first disagreement would be a suspension one door honors and another
14
+ * does not.
15
+ */
16
+
17
+ /**
18
+ * The four columns, decoded off whatever carries them: a `pithy_auth_users` row, or the user object Better
19
+ * Auth resolved for a session, which carries them because `../data/kitFields.ts` declares them. Unknown keys
20
+ * are dropped, and a key that is absent — a row read before `0004_user_lifecycle` — reads as null.
21
+ */
22
+ export const LifecycleColumns = User.pick({
23
+ suspendedAt: true,
24
+ suspendedUntil: true,
25
+ deletedAt: true,
26
+ purgeAfter: true,
27
+ }).describe("An account's lifecycle columns, as `pithy_auth_users` stores them.");
28
+ export type LifecycleColumns = z.output<typeof LifecycleColumns>;
29
+
30
+ /** Where an account stands, at one instant. */
31
+ export type AccountStanding =
32
+ | { readonly state: "active" }
33
+ | { readonly state: "suspended"; readonly until: Date | null }
34
+ | { readonly state: "deleted"; readonly purgeAfter: Date | null };
35
+
36
+ /**
37
+ * Where an account stands at `now`.
38
+ *
39
+ * **Deleted outranks suspended.** An account deleted while it was suspended is deleted: the suspension's end
40
+ * passing must not reopen it.
41
+ *
42
+ * **A suspension past its `suspendedUntil` is not a suspension**, and no write expires it. The end is
43
+ * exclusive — at the instant it names, the account is active again. A column nobody has cleared is a
44
+ * fact about the past, not about now, and reading it that way is what lets a timed suspension end on time
45
+ * with nothing scheduled to end it.
46
+ *
47
+ * **A deletion past its `purgeAfter` is still a deletion.** Only the purge ends that state, by erasing the
48
+ * account, and until it has run the account must stay shut.
49
+ */
50
+ export function accountStanding(columns: Partial<LifecycleColumns>, now: Date): AccountStanding {
51
+ if (columns.deletedAt) return { state: "deleted", purgeAfter: columns.purgeAfter ?? null };
52
+ if (columns.suspendedAt) {
53
+ const until = columns.suspendedUntil ?? null;
54
+ if (until === null || until.getTime() > now.getTime()) return { state: "suspended", until };
55
+ }
56
+ return { state: "active" };
57
+ }
58
+
59
+ /** What a suspended account is told when nobody wrote a reason. */
60
+ const UNEXPLAINED_SUSPENSION = "This account is suspended.";
61
+
62
+ /**
63
+ * The refusal for an account that may not act, or `null` for one that may.
64
+ *
65
+ * **The reason an operator gave is the public `message`**, because it is written for the person who is locked
66
+ * out and it is the one thing their screen cannot invent. `params` carries the end of a suspension, or the
67
+ * last day a deletion can be undone, as ISO-8601, for a client that renders the date in its reader's own
68
+ * words. Neither the account id nor who acted crosses: `detail` holds the id for the log, and `clientError`
69
+ * strips it with `action`.
70
+ *
71
+ * 403 for both, never 401: the credential is genuine, and signing in again cannot help.
72
+ */
73
+ export function lifecycleRefusal(userId: string, standing: AccountStanding, reason: string | null): PithyError | null {
74
+ if (standing.state === "active") return null;
75
+ if (standing.state === "suspended") {
76
+ return new PithyError({
77
+ code: "auth/account_suspended",
78
+ status: 403,
79
+ message: reason ?? UNEXPLAINED_SUSPENSION,
80
+ ...(standing.until ? { params: { suspendedUntil: standing.until.toISOString() } } : {}),
81
+ action: "An operator suspended this account. Reinstate it from the management surface, or let it run out.",
82
+ detail: `user ${userId} is suspended${standing.until ? ` until ${standing.until.toISOString()}` : ""}`,
83
+ });
84
+ }
85
+ return new PithyError({
86
+ code: "auth/account_deleted",
87
+ status: 403,
88
+ message: "This account is deleted.",
89
+ ...(standing.purgeAfter ? { params: { purgeAfter: standing.purgeAfter.toISOString() } } : {}),
90
+ action: "The account is inside its purge window. Restore it from the management surface before the purge runs.",
91
+ detail: `user ${userId} is deleted${standing.purgeAfter ? `, purge after ${standing.purgeAfter.toISOString()}` : ""}`,
92
+ });
93
+ }
94
+
95
+ /** Whether a caught error is one of the two lifecycle refusals. */
96
+ export function isLifecycleRefusal(error: unknown): error is PithyError {
97
+ return (
98
+ error instanceof PithyError &&
99
+ (error.payload.code === "auth/account_suspended" || error.payload.code === "auth/account_deleted")
100
+ );
101
+ }
@@ -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
+ }
@@ -82,12 +82,11 @@ export const auth_0001_init: Migration = {
82
82
  await db.schema
83
83
  .createTable("pithyAuthAccounts")
84
84
  .addColumn("id", "text", (c) => c.primaryKey())
85
- // `issuer` is 1.7's account identity, and it is `required: true` in Better Auth's own model
86
- // (#451). An account is the pair `(issuer, accountId)` now rather than `(providerId, accountId)`,
87
- // because a provider id is ours to name and an issuer is the identity provider's own — two
88
- // providers configured against one directory could otherwise mint the same `accountId` and land
89
- // on different rows. `local:credential` for a password, the discovery URL for an OIDC provider,
90
- // `local:oauth:<id>` for an OAuth provider that publishes none.
85
+ // `issuer` was Better Auth 1.7.0–1.7.2's account identity, `required: true` in its model then
86
+ // (#451), with an account the pair `(issuer, accountId)`. 1.7.3 reverted to the 1.6 model, which
87
+ // identifies an account by `(providerId, accountId)` and never writes this column
88
+ // (better-auth/better-auth#11153). This `NOT NULL` is history: `0003_account_issuer_nullable`
89
+ // relaxes it and drops the index below, and the column stays only to keep what 1.7.1 wrote (#787).
91
90
  .addColumn("issuer", "text", (c) => c.notNull())
92
91
  .addColumn("accountId", "text", (c) => c.notNull())
93
92
  .addColumn("providerId", "text", (c) => c.notNull())
@@ -168,10 +167,9 @@ export const auth_0001_init: Migration = {
168
167
  await db.schema.createIndex("pithyAuthSessionsUserIdIdx").on("pithyAuthSessions").column("userId").execute();
169
168
  await db.schema.createIndex("pithyAuthSessionsDeviceIdIdx").on("pithyAuthSessions").column("deviceId").execute();
170
169
  await db.schema.createIndex("pithyAuthAccountsUserIdIdx").on("pithyAuthAccounts").column("userId").execute();
171
- // The identity 1.7 looks an account up by, and unique because the pair *is* the identity: two rows
172
- // sharing it are two records of one account at one provider, which is the account-confusion state
173
- // Better Auth's own 1.7 upgrade guide has adopters audit for before adding this (#451). Declared
174
- // here rather than backfilled, because nothing is published and no row predates it.
170
+ // The identity 1.7.0–1.7.2 looked an account up by, unique because the pair was the identity (#451).
171
+ // 1.7.3 looks an account up by `(providerId, accountId)` again, and `0003_account_issuer_nullable`
172
+ // drops this index first, as Better Auth's 1.7 upgrade guide orders it (#787).
175
173
  await db.schema
176
174
  .createIndex("pithyAuthAccountsIssuerAccountIdIdx")
177
175
  .on("pithyAuthAccounts")