@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,90 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { User } from "../data/betterAuth.js";
4
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
+ //#region src/lifecycle/state.ts
6
+ /**
7
+ * What an account's four lifecycle columns mean, decided once.
8
+ *
9
+ * Every enforcement point — the session middleware, sign-in, token refresh — reads the state through
10
+ * {@link accountStanding} and refuses through {@link lifecycleRefusal}. Enforcement written twice is
11
+ * enforcement that disagrees, and the first disagreement would be a suspension one door honors and another
12
+ * does not.
13
+ */
14
+ /**
15
+ * The four columns, decoded off whatever carries them: a `pithy_auth_users` row, or the user object Better
16
+ * Auth resolved for a session, which carries them because `../data/kitFields.ts` declares them. Unknown keys
17
+ * are dropped, and a key that is absent — a row read before `0004_user_lifecycle` — reads as null.
18
+ */
19
+ const LifecycleColumns = User.pick({
20
+ suspendedAt: true,
21
+ suspendedUntil: true,
22
+ deletedAt: true,
23
+ purgeAfter: true
24
+ }).describe("An account's lifecycle columns, as `pithy_auth_users` stores them.");
25
+ /**
26
+ * Where an account stands at `now`.
27
+ *
28
+ * **Deleted outranks suspended.** An account deleted while it was suspended is deleted: the suspension's end
29
+ * passing must not reopen it.
30
+ *
31
+ * **A suspension past its `suspendedUntil` is not a suspension**, and no write expires it. The end is
32
+ * exclusive — at the instant it names, the account is active again. A column nobody has cleared is a
33
+ * fact about the past, not about now, and reading it that way is what lets a timed suspension end on time
34
+ * with nothing scheduled to end it.
35
+ *
36
+ * **A deletion past its `purgeAfter` is still a deletion.** Only the purge ends that state, by erasing the
37
+ * account, and until it has run the account must stay shut.
38
+ */
39
+ function accountStanding(columns, now) {
40
+ if (columns.deletedAt) return {
41
+ state: "deleted",
42
+ purgeAfter: columns.purgeAfter ?? null
43
+ };
44
+ if (columns.suspendedAt) {
45
+ const until = columns.suspendedUntil ?? null;
46
+ if (until === null || until.getTime() > now.getTime()) return {
47
+ state: "suspended",
48
+ until
49
+ };
50
+ }
51
+ return { state: "active" };
52
+ }
53
+ /** What a suspended account is told when nobody wrote a reason. */
54
+ const UNEXPLAINED_SUSPENSION = "This account is suspended.";
55
+ /**
56
+ * The refusal for an account that may not act, or `null` for one that may.
57
+ *
58
+ * **The reason an operator gave is the public `message`**, because it is written for the person who is locked
59
+ * out and it is the one thing their screen cannot invent. `params` carries the end of a suspension, or the
60
+ * last day a deletion can be undone, as ISO-8601, for a client that renders the date in its reader's own
61
+ * words. Neither the account id nor who acted crosses: `detail` holds the id for the log, and `clientError`
62
+ * strips it with `action`.
63
+ *
64
+ * 403 for both, never 401: the credential is genuine, and signing in again cannot help.
65
+ */
66
+ function lifecycleRefusal(userId, standing, reason) {
67
+ if (standing.state === "active") return null;
68
+ if (standing.state === "suspended") return new PithyError({
69
+ code: "auth/account_suspended",
70
+ status: 403,
71
+ message: reason ?? UNEXPLAINED_SUSPENSION,
72
+ ...standing.until ? { params: { suspendedUntil: standing.until.toISOString() } } : {},
73
+ action: "An operator suspended this account. Reinstate it from the management surface, or let it run out.",
74
+ detail: `user ${userId} is suspended${standing.until ? ` until ${standing.until.toISOString()}` : ""}`
75
+ });
76
+ return new PithyError({
77
+ code: "auth/account_deleted",
78
+ status: 403,
79
+ message: "This account is deleted.",
80
+ ...standing.purgeAfter ? { params: { purgeAfter: standing.purgeAfter.toISOString() } } : {},
81
+ action: "The account is inside its purge window. Restore it from the management surface before the purge runs.",
82
+ detail: `user ${userId} is deleted${standing.purgeAfter ? `, purge after ${standing.purgeAfter.toISOString()}` : ""}`
83
+ });
84
+ }
85
+ /** Whether a caught error is one of the two lifecycle refusals. */
86
+ function isLifecycleRefusal(error) {
87
+ return error instanceof PithyError && (error.payload.code === "auth/account_suspended" || error.payload.code === "auth/account_deleted");
88
+ }
89
+ //#endregion
90
+ export { LifecycleColumns, accountStanding, isLifecycleRefusal, lifecycleRefusal };
@@ -0,0 +1,132 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
5
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
6
+ import type { EnqueueInput } from "@pithy-sh/email/src/send/enqueue";
7
+ import type { AuthConfig } from "../capability";
8
+ import type { AuthDatabase } from "../data/tables";
9
+ import type { UserLifecycleActorType } from "../data/userLifecycle";
10
+ import type { UserLifecycleHooks } from "./hooks";
11
+ /**
12
+ * The account-lifecycle transitions — the one place an account's state is ever changed (#620).
13
+ *
14
+ * The admin routes (#621, #622), the self-service deletion, and the purge Workflow call these and write
15
+ * nothing themselves, so each transition happens the same way whoever asked for it:
16
+ *
17
+ * 1. **The columns move, conditionally, and the history row is written with them.** The `update` names the
18
+ * state it expects to find, so of two concurrent suspensions exactly one changes a row, and only that one
19
+ * goes on. A request that finds the account already where it asked to put it is `changed: false` and does
20
+ * nothing else — no row, no mail, no hook — which is what "once per transition" means.
21
+ * 2. **The row in `pithy_auth_user_lifecycle`** — the actor, the reason, the time — is the second statement of
22
+ * the same `d1.batch()`, which D1 runs as one transaction, and it is written only when the first moved the
23
+ * account. Two awaits would leave a gap: a failed insert after a committed update, and a retry that finds
24
+ * the account already moved, returns `changed: false`, and loses the row, the event, the mail and the hook.
25
+ * 3. **The audit event is emitted** — the trail answers who and from where; the row answers what happened.
26
+ * 4. **The mail is enqueued**, when the config sends it, in the account's own language.
27
+ * 5. **The hook fires.**
28
+ *
29
+ * Steps 3 to 5 report something that has already happened, so none of them can undo it: each swallows its own
30
+ * failure, and a throwing hook or an email binding that is not there is logged and the transition stands.
31
+ *
32
+ * **What these do not do is end sessions.** Enforcement does not need them to — a suspended account's session
33
+ * is refused at every door the moment the column is written (`./enforce.ts`) — and revoking them is a route's
34
+ * decision, made through Better Auth so `onSessionRevoked` hears about it.
35
+ */
36
+ /** Who made a transition. */
37
+ export interface LifecycleActor {
38
+ /** The kind of principal. */
39
+ readonly type: UserLifecycleActorType;
40
+ /** Its id — the connection's for a management client, the user's own for self-service — or null. */
41
+ readonly id: string | null;
42
+ }
43
+ /** Everything a transition needs, resolved by the caller from its own context. */
44
+ export interface LifecycleDeps {
45
+ /** The auth tables. */
46
+ readonly db: AuthDatabase;
47
+ /** The same database as a binding, for the hooks — see `UserLifecycleListener`. */
48
+ readonly d1: D1Database;
49
+ /** The audit seam. A no-op when the audit capability is absent. */
50
+ readonly emit: AuditEmit;
51
+ /** The resolved config: the purge window, and which mails are sent. */
52
+ readonly config: Pick<AuthConfig, "retention" | "lifecycleEmails">;
53
+ /** The adopter's hooks. */
54
+ readonly hooks: UserLifecycleHooks;
55
+ /** The email capability's enqueue, bound to this run's env. Absent, nothing is mailed. */
56
+ readonly enqueueEmail?: ((input: EnqueueInput) => Promise<unknown>) | undefined;
57
+ /** Where a swallowed failure is reported. Absent, it is swallowed silently. */
58
+ readonly log?: Logger | undefined;
59
+ /** The clock. Defaults to the system's. */
60
+ readonly now?: (() => Date) | undefined;
61
+ }
62
+ /** What a transition did. */
63
+ export interface LifecycleTransition {
64
+ /** Whether the account moved. `false` when it was already where the call asked to put it. */
65
+ readonly changed: boolean;
66
+ }
67
+ /**
68
+ * Suspend an account, until `until` or until it is reinstated.
69
+ *
70
+ * A deleted account cannot be suspended — deletion already shuts it, and outranks a suspension — so that is a
71
+ * conflict rather than a no-op. A suspension whose end has passed is not in force, and a new one replaces it.
72
+ */
73
+ export declare function suspendUser(deps: LifecycleDeps, input: {
74
+ userId: string;
75
+ actor: LifecycleActor;
76
+ reason: string | null;
77
+ until?: Date | null;
78
+ }): Promise<LifecycleTransition>;
79
+ /**
80
+ * Lift a suspension. An account that is not suspended — including one whose suspension ran out — is a no-op.
81
+ *
82
+ * Where the account stands is read through `accountStanding`, never off the raw column, because a suspension
83
+ * past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
84
+ * for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
85
+ * sign in again" to somebody every sign-in still refuses. Restore it first.
86
+ */
87
+ export declare function reinstateUser(deps: LifecycleDeps, input: {
88
+ userId: string;
89
+ actor: LifecycleActor;
90
+ reason: string | null;
91
+ }): Promise<LifecycleTransition>;
92
+ /**
93
+ * Delete an account, softly: it is shut now, and its data is erased once `retention.purgeAfterDays` have
94
+ * passed. Restorable until then. Audited as the account's own deletion when its holder is the actor.
95
+ *
96
+ * A suspension the account was under is left in place, so restoring the account does not lift it.
97
+ */
98
+ export declare function deleteUser(deps: LifecycleDeps, input: {
99
+ userId: string;
100
+ actor: LifecycleActor;
101
+ reason: string | null;
102
+ }): Promise<LifecycleTransition>;
103
+ /**
104
+ * Restore a deleted account inside its purge window. After the purge there is no account, and that is a 404
105
+ * whose action says the data is gone.
106
+ */
107
+ export declare function restoreUser(deps: LifecycleDeps, input: {
108
+ userId: string;
109
+ actor: LifecycleActor;
110
+ reason: string | null;
111
+ }): Promise<LifecycleTransition>;
112
+ /** Record that one purge step — one capability's contribution — erased its rows. */
113
+ export declare function recordPurgeStep(deps: LifecycleDeps, input: {
114
+ userId: string;
115
+ step: string;
116
+ }): Promise<void>;
117
+ /**
118
+ * Finish a purge: the last mail, the record, the audit event, the hook.
119
+ *
120
+ * **The address is handed in, not read**, because by the time a purge finishes the user row is gone — the
121
+ * Workflow captures the recipient before its first step and passes it here. Finishing a purge that already
122
+ * finished is a no-op, so a retried Workflow step mails nobody twice.
123
+ */
124
+ export declare function completePurge(deps: LifecycleDeps, input: {
125
+ userId: string;
126
+ recipient: {
127
+ email: string;
128
+ name: string | null;
129
+ locale: string | null;
130
+ };
131
+ }): Promise<LifecycleTransition>;
132
+ //# sourceMappingURL=transitions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transitions.d.ts","sourceRoot":"","sources":["../../src/lifecycle/transitions.ts"],"names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;AACpF,wBAAsB,eAAe,CAAC,IAAI,EAAE,aAAa,EAAE,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAGjH;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CACjC,IAAI,EAAE,aAAa,EACnB,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAA;CAAE,GAClG,OAAO,CAAC,mBAAmB,CAAC,CAmB9B"}
@@ -0,0 +1,349 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { AuthAuditActions } from "../audit/actions.js";
4
+ import { LifecycleColumns, accountStanding } from "./state.js";
5
+ import { ConflictError, NotFoundError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
6
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
7
+ import { formattingLocaleOf } from "@pithy-sh/core/src/i18n/locale";
8
+ import { sql } from "kysely";
9
+ //#region src/lifecycle/transitions.ts
10
+ /** The longest reason the kit stores. It is shown to the person, so it is a sentence, not a case file. */
11
+ const MAX_REASON = 500;
12
+ /** A reason, trimmed and bounded, or null when none was given. */
13
+ function reasonOf(reason) {
14
+ if (reason === null || reason === void 0) return null;
15
+ const trimmed = reason.trim();
16
+ if (trimmed === "") return null;
17
+ if (trimmed.length > MAX_REASON) throw new ValidationError({
18
+ message: `A reason is at most ${MAX_REASON} characters.`,
19
+ detail: `lifecycle reason of ${trimmed.length} characters`
20
+ });
21
+ return trimmed;
22
+ }
23
+ async function subjectOf(db, userId) {
24
+ const row = await db.selectFrom("pithyAuthUsers").select([
25
+ "email",
26
+ "name",
27
+ "locale",
28
+ "suspendedAt",
29
+ "suspendedUntil",
30
+ "deletedAt",
31
+ "purgeAfter"
32
+ ]).where("id", "=", userId).executeTakeFirst();
33
+ if (!row) throw new NotFoundError({
34
+ message: "No such account.",
35
+ action: "If it was deleted and its purge has run, its data is gone and there is nothing to act on.",
36
+ detail: `lifecycle transition for user ${userId}, which has no row`
37
+ });
38
+ return {
39
+ email: row.email,
40
+ name: row.name,
41
+ locale: row.locale ?? null,
42
+ columns: LifecycleColumns.parse(row)
43
+ };
44
+ }
45
+ /** A date written for its reader, in their language — the shape every lifecycle mail carries its dates in. */
46
+ function readable(date, locale) {
47
+ const tag = (locale ? formattingLocaleOf(locale) : null) ?? "en";
48
+ return new Intl.DateTimeFormat(tag, {
49
+ dateStyle: "long",
50
+ timeZone: "UTC"
51
+ }).format(date);
52
+ }
53
+ /** The history row's values, as the table stores them. */
54
+ function encoded(row) {
55
+ return {
56
+ userId: row.userId,
57
+ action: row.action,
58
+ actorType: row.actor.type,
59
+ actorId: row.actor.id,
60
+ reason: row.reason,
61
+ suspendedUntil: row.suspendedUntil ? SQLiteDate.encode(row.suspendedUntil) : null,
62
+ step: row.step ?? null,
63
+ createdAt: SQLiteDate.encode(row.at)
64
+ };
65
+ }
66
+ /** A history row with no column change to pair it with: a purge step, a finished purge. Not swallowed. */
67
+ async function record(deps, row) {
68
+ await deps.db.insertInto("pithyAuthUserLifecycle").values(encoded(row)).execute();
69
+ }
70
+ /** Bind a compiled statement to D1, so it can join a `batch`. */
71
+ function prepared(d1, compiled) {
72
+ return d1.prepare(compiled.sql).bind(...compiled.parameters);
73
+ }
74
+ /**
75
+ * Move the columns and write the history row as one transaction, and say whether the account moved.
76
+ *
77
+ * The insert is guarded by `changes()`, which SQLite answers for the statement just before it — the update —
78
+ * so a conditional update that matched nothing writes no row. Not swallowed: until both are written, nothing
79
+ * after them runs.
80
+ */
81
+ async function move(deps, update, row) {
82
+ const v = encoded(row);
83
+ const insert = deps.db.insertInto("pithyAuthUserLifecycle").columns([
84
+ "userId",
85
+ "action",
86
+ "actorType",
87
+ "actorId",
88
+ "reason",
89
+ "suspendedUntil",
90
+ "step",
91
+ "createdAt"
92
+ ]).expression(deps.db.selectNoFrom([
93
+ sql.val(v.userId).as("userId"),
94
+ sql.val(v.action).as("action"),
95
+ sql.val(v.actorType).as("actorType"),
96
+ sql.val(v.actorId).as("actorId"),
97
+ sql.val(v.reason).as("reason"),
98
+ sql.val(v.suspendedUntil).as("suspendedUntil"),
99
+ sql.val(v.step).as("step"),
100
+ sql.val(v.createdAt).as("createdAt")
101
+ ]).where(sql`changes()`, ">", 0)).compile();
102
+ const [updated] = await deps.d1.batch([prepared(deps.d1, update.compile()), prepared(deps.d1, insert)]);
103
+ return (updated?.meta.changes ?? 0) > 0;
104
+ }
105
+ /** The audit event, swallowed on failure — an audit write never breaks what it records. */
106
+ async function audit(deps, action, userId, actor, metadata) {
107
+ const event = {
108
+ action,
109
+ outcome: "success",
110
+ actorType: actor.type,
111
+ actorId: actor.id,
112
+ resourceType: "user",
113
+ resourceId: userId,
114
+ metadata
115
+ };
116
+ try {
117
+ await deps.emit(event);
118
+ } catch (error) {
119
+ deps.log?.warn(`lifecycle audit ${action} failed; the transition stands`, { reason: messageOf(error) });
120
+ }
121
+ }
122
+ /** One lifecycle mail, when the config sends it. Swallowed on failure, like the audit write. */
123
+ async function mail(deps, enabled, to, locale, template, payload) {
124
+ if (!enabled || !deps.enqueueEmail) return;
125
+ try {
126
+ await deps.enqueueEmail({
127
+ to,
128
+ template,
129
+ payload,
130
+ ...locale ? { locale } : {}
131
+ });
132
+ } catch (error) {
133
+ deps.log?.warn(`lifecycle mail ${template} could not be enqueued; the transition stands`, { reason: messageOf(error) });
134
+ }
135
+ }
136
+ /** Fire one hook. Swallowed and logged: the transition is already written, and a retry would fire nothing. */
137
+ async function fire(deps, name, hook, event) {
138
+ if (!hook) return;
139
+ try {
140
+ await hook(event, deps.d1);
141
+ } catch (error) {
142
+ deps.log?.warn(`${name} threw; the transition stands`, {
143
+ userId: event.userId,
144
+ reason: messageOf(error)
145
+ });
146
+ }
147
+ }
148
+ function messageOf(error) {
149
+ return error instanceof Error ? error.message : String(error);
150
+ }
151
+ /** Without a name, a greeting says "Hi," rather than greeting an empty string. */
152
+ function named(name) {
153
+ return name.trim() ? { name } : {};
154
+ }
155
+ /**
156
+ * Suspend an account, until `until` or until it is reinstated.
157
+ *
158
+ * A deleted account cannot be suspended — deletion already shuts it, and outranks a suspension — so that is a
159
+ * conflict rather than a no-op. A suspension whose end has passed is not in force, and a new one replaces it.
160
+ */
161
+ async function suspendUser(deps, input) {
162
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
163
+ const reason = reasonOf(input.reason);
164
+ const until = input.until ?? null;
165
+ if (until && until.getTime() <= at.getTime()) throw new ValidationError({ message: "A suspension must end in the future, or not at all." });
166
+ const subject = await subjectOf(deps.db, input.userId);
167
+ const standing = accountStanding(subject.columns, at);
168
+ if (standing.state === "deleted") throw new ConflictError({
169
+ message: "This account is deleted.",
170
+ action: "Restore it first, if it should be suspended instead."
171
+ });
172
+ if (standing.state === "suspended") return { changed: false };
173
+ if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
174
+ suspendedAt: SQLiteDate.encode(at),
175
+ suspendedUntil: until ? SQLiteDate.encode(until) : null
176
+ }).where("id", "=", input.userId).where("deletedAt", "is", null).where((eb) => eb.or([eb("suspendedAt", "is", null), eb.and([eb("suspendedUntil", "is not", null), eb("suspendedUntil", "<=", SQLiteDate.encode(at))])])), {
177
+ userId: input.userId,
178
+ action: "suspended",
179
+ actor: input.actor,
180
+ reason,
181
+ at,
182
+ suspendedUntil: until
183
+ })) return { changed: false };
184
+ await audit(deps, AuthAuditActions.adminUserSuspended, input.userId, input.actor, {
185
+ reason,
186
+ suspendedUntil: until?.toISOString() ?? null
187
+ });
188
+ await mail(deps, deps.config.lifecycleEmails.accountSuspended, subject.email, subject.locale, "accountSuspended", {
189
+ ...named(subject.name),
190
+ ...reason ? { reason } : {},
191
+ ...until ? { until: readable(until, subject.locale) } : {}
192
+ });
193
+ await fire(deps, "onUserSuspended", deps.hooks.onUserSuspended, {
194
+ userId: input.userId,
195
+ actor: input.actor,
196
+ reason,
197
+ at,
198
+ suspendedUntil: until
199
+ });
200
+ return { changed: true };
201
+ }
202
+ /**
203
+ * Lift a suspension. An account that is not suspended — including one whose suspension ran out — is a no-op.
204
+ *
205
+ * Where the account stands is read through `accountStanding`, never off the raw column, because a suspension
206
+ * past its end leaves `suspendedAt` set and is not a suspension. A deleted account is a conflict, as it is
207
+ * for `suspendUser`: deletion outranks the suspension it keeps, so lifting that suspension would mail "you can
208
+ * sign in again" to somebody every sign-in still refuses. Restore it first.
209
+ */
210
+ async function reinstateUser(deps, input) {
211
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
212
+ const reason = reasonOf(input.reason);
213
+ const subject = await subjectOf(deps.db, input.userId);
214
+ const standing = accountStanding(subject.columns, at);
215
+ if (standing.state === "deleted") throw new ConflictError({
216
+ message: "This account is deleted.",
217
+ action: "Restore it first. Its suspension stays in place through a restore, and can be lifted after."
218
+ });
219
+ if (standing.state !== "suspended") return { changed: false };
220
+ if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
221
+ suspendedAt: null,
222
+ suspendedUntil: null
223
+ }).where("id", "=", input.userId).where("deletedAt", "is", null).where("suspendedAt", "is not", null).where((eb) => eb.or([eb("suspendedUntil", "is", null), eb("suspendedUntil", ">", SQLiteDate.encode(at))])), {
224
+ userId: input.userId,
225
+ action: "reinstated",
226
+ actor: input.actor,
227
+ reason,
228
+ at
229
+ })) return { changed: false };
230
+ await audit(deps, AuthAuditActions.adminUserReinstated, input.userId, input.actor, { reason });
231
+ await mail(deps, deps.config.lifecycleEmails.accountReinstated, subject.email, subject.locale, "accountReinstated", named(subject.name));
232
+ await fire(deps, "onUserReinstated", deps.hooks.onUserReinstated, {
233
+ userId: input.userId,
234
+ actor: input.actor,
235
+ reason,
236
+ at
237
+ });
238
+ return { changed: true };
239
+ }
240
+ /**
241
+ * Delete an account, softly: it is shut now, and its data is erased once `retention.purgeAfterDays` have
242
+ * passed. Restorable until then. Audited as the account's own deletion when its holder is the actor.
243
+ *
244
+ * A suspension the account was under is left in place, so restoring the account does not lift it.
245
+ */
246
+ async function deleteUser(deps, input) {
247
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
248
+ const reason = reasonOf(input.reason);
249
+ const purgeAfter = new Date(at.getTime() + deps.config.retention.purgeAfterDays * 864e5);
250
+ const subject = await subjectOf(deps.db, input.userId);
251
+ if (subject.columns.deletedAt) return { changed: false };
252
+ if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
253
+ deletedAt: SQLiteDate.encode(at),
254
+ purgeAfter: SQLiteDate.encode(purgeAfter)
255
+ }).where("id", "=", input.userId).where("deletedAt", "is", null), {
256
+ userId: input.userId,
257
+ action: "deleted",
258
+ actor: input.actor,
259
+ reason,
260
+ at
261
+ })) return { changed: false };
262
+ await audit(deps, input.actor.type === "user" && input.actor.id === input.userId ? AuthAuditActions.userSelfDeleted : AuthAuditActions.adminUserSoftDeleted, input.userId, input.actor, {
263
+ reason,
264
+ purgeAfter: purgeAfter.toISOString()
265
+ });
266
+ await mail(deps, deps.config.lifecycleEmails.deletionScheduled, subject.email, subject.locale, "deletionScheduled", {
267
+ ...named(subject.name),
268
+ purgeOn: readable(purgeAfter, subject.locale)
269
+ });
270
+ await fire(deps, "onUserDeleted", deps.hooks.onUserDeleted, {
271
+ userId: input.userId,
272
+ actor: input.actor,
273
+ reason,
274
+ at,
275
+ purgeAfter
276
+ });
277
+ return { changed: true };
278
+ }
279
+ /**
280
+ * Restore a deleted account inside its purge window. After the purge there is no account, and that is a 404
281
+ * whose action says the data is gone.
282
+ */
283
+ async function restoreUser(deps, input) {
284
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
285
+ const reason = reasonOf(input.reason);
286
+ if (!(await subjectOf(deps.db, input.userId)).columns.deletedAt) return { changed: false };
287
+ if (!await move(deps, deps.db.updateTable("pithyAuthUsers").set({
288
+ deletedAt: null,
289
+ purgeAfter: null
290
+ }).where("id", "=", input.userId).where("deletedAt", "is not", null), {
291
+ userId: input.userId,
292
+ action: "restored",
293
+ actor: input.actor,
294
+ reason,
295
+ at
296
+ })) return { changed: false };
297
+ await audit(deps, AuthAuditActions.adminUserRestored, input.userId, input.actor, { reason });
298
+ return { changed: true };
299
+ }
300
+ /** The purge's own actor: a scheduled job, with nobody calling. */
301
+ const PURGE = {
302
+ type: "system",
303
+ id: null
304
+ };
305
+ /** Record that one purge step — one capability's contribution — erased its rows. */
306
+ async function recordPurgeStep(deps, input) {
307
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
308
+ await record(deps, {
309
+ userId: input.userId,
310
+ action: "purge_step",
311
+ actor: PURGE,
312
+ reason: null,
313
+ at,
314
+ step: input.step
315
+ });
316
+ }
317
+ /**
318
+ * Finish a purge: the last mail, the record, the audit event, the hook.
319
+ *
320
+ * **The address is handed in, not read**, because by the time a purge finishes the user row is gone — the
321
+ * Workflow captures the recipient before its first step and passes it here. Finishing a purge that already
322
+ * finished is a no-op, so a retried Workflow step mails nobody twice.
323
+ */
324
+ async function completePurge(deps, input) {
325
+ const at = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
326
+ if (await deps.db.selectFrom("pithyAuthUserLifecycle").select("id").where("userId", "=", input.userId).where("action", "=", "purged").executeTakeFirst()) return { changed: false };
327
+ await record(deps, {
328
+ userId: input.userId,
329
+ action: "purged",
330
+ actor: PURGE,
331
+ reason: null,
332
+ at
333
+ });
334
+ await audit(deps, AuthAuditActions.adminUserPurged, input.userId, PURGE, {});
335
+ const { email, name, locale } = input.recipient;
336
+ await mail(deps, deps.config.lifecycleEmails.deletionComplete, email, locale, "deletionComplete", {
337
+ ...named(name ?? ""),
338
+ purgedOn: readable(at, locale)
339
+ });
340
+ await fire(deps, "onUserPurged", deps.hooks.onUserPurged, {
341
+ userId: input.userId,
342
+ actor: PURGE,
343
+ reason: null,
344
+ at
345
+ });
346
+ return { changed: true };
347
+ }
348
+ //#endregion
349
+ export { completePurge, deleteUser, recordPurgeStep, reinstateUser, restoreUser, suspendUser };
@@ -1 +1 @@
1
- {"version":3,"file":"0001_init.d.ts","sourceRoot":"","sources":["../../src/migrations/0001_init.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,eAAO,MAAM,cAAc,EAAE,SA+L5B,CAAC;AAEF,oHAAoH;AACpH,eAAO,MAAM,oBAAoB,MAAM,CAAC"}
1
+ {"version":3,"file":"0001_init.d.ts","sourceRoot":"","sources":["../../src/migrations/0001_init.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,eAAO,MAAM,cAAc,EAAE,SA6L5B,CAAC;AAEF,oHAAoH;AACpH,eAAO,MAAM,oBAAoB,MAAM,CAAC"}
@@ -0,0 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { Migration } from "kysely/migration";
4
+ export declare const auth_0003_account_issuer_nullable: Migration;
5
+ //# sourceMappingURL=0003_account_issuer_nullable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"0003_account_issuer_nullable.d.ts","sourceRoot":"","sources":["../../src/migrations/0003_account_issuer_nullable.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AA2JlD,eAAO,MAAM,iCAAiC,EAAE,SAsC/C,CAAC"}