@pithy-sh/auth 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/README.md +8 -2
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +40 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +41 -1
  6. package/dist/audit/emit.d.ts +2 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +2 -2
  9. package/dist/capability.d.ts +45 -1
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +40 -5
  12. package/dist/client/lifecycle.d.ts +19 -0
  13. package/dist/client/lifecycle.d.ts.map +1 -0
  14. package/dist/client/lifecycle.js +25 -0
  15. package/dist/client/projection.d.ts +4 -0
  16. package/dist/client/projection.d.ts.map +1 -1
  17. package/dist/data/betterAuth.d.ts +4 -0
  18. package/dist/data/betterAuth.d.ts.map +1 -1
  19. package/dist/data/betterAuth.js +6 -2
  20. package/dist/data/kitFields.d.ts +20 -25
  21. package/dist/data/kitFields.d.ts.map +1 -1
  22. package/dist/data/kitFields.js +28 -32
  23. package/dist/data/tables.d.ts +29 -2
  24. package/dist/data/tables.d.ts.map +1 -1
  25. package/dist/data/tables.js +5 -3
  26. package/dist/data/userLifecycle.d.ts +62 -0
  27. package/dist/data/userLifecycle.d.ts.map +1 -0
  28. package/dist/data/userLifecycle.js +51 -0
  29. package/dist/http/adminRoutes.d.ts.map +1 -1
  30. package/dist/http/adminRoutes.js +270 -5
  31. package/dist/http/guards.d.ts +24 -1
  32. package/dist/http/guards.d.ts.map +1 -1
  33. package/dist/http/guards.js +59 -3
  34. package/dist/http/lifecycleGate.d.ts +18 -0
  35. package/dist/http/lifecycleGate.d.ts.map +1 -0
  36. package/dist/http/lifecycleGate.js +75 -0
  37. package/dist/http/middleware.d.ts +30 -1
  38. package/dist/http/middleware.d.ts.map +1 -1
  39. package/dist/http/middleware.js +89 -7
  40. package/dist/http/providerRefusal.d.ts.map +1 -1
  41. package/dist/http/providerRefusal.js +8 -0
  42. package/dist/http/resolve.d.ts.map +1 -1
  43. package/dist/http/resolve.js +7 -4
  44. package/dist/http/responses.d.ts +180 -0
  45. package/dist/http/responses.d.ts.map +1 -1
  46. package/dist/http/responses.js +142 -1
  47. package/dist/http/routes.d.ts +1 -0
  48. package/dist/http/routes.d.ts.map +1 -1
  49. package/dist/http/routes.js +65 -4
  50. package/dist/http/schemas.d.ts +57 -0
  51. package/dist/http/schemas.d.ts.map +1 -1
  52. package/dist/http/schemas.js +51 -1
  53. package/dist/http/views.d.ts +39 -2
  54. package/dist/http/views.d.ts.map +1 -1
  55. package/dist/http/views.js +105 -1
  56. package/dist/instance/auth.d.ts +55 -3
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +53 -2
  59. package/dist/instance/microsoftEmail.d.ts +70 -0
  60. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  61. package/dist/instance/microsoftEmail.js +96 -0
  62. package/dist/instance/providerSignInGate.d.ts +7 -6
  63. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  64. package/dist/instance/providerSignInGate.js +7 -6
  65. package/dist/instance/providers.d.ts +7 -5
  66. package/dist/instance/providers.d.ts.map +1 -1
  67. package/dist/instance/providers.js +5 -3
  68. package/dist/instance/secrets.d.ts +64 -3
  69. package/dist/instance/secrets.d.ts.map +1 -1
  70. package/dist/instance/secrets.js +44 -5
  71. package/dist/lifecycle/audited.d.ts +48 -0
  72. package/dist/lifecycle/audited.d.ts.map +1 -0
  73. package/dist/lifecycle/audited.js +65 -0
  74. package/dist/lifecycle/enforce.d.ts +75 -0
  75. package/dist/lifecycle/enforce.d.ts.map +1 -0
  76. package/dist/lifecycle/enforce.js +111 -0
  77. package/dist/lifecycle/hooks.d.ts +53 -0
  78. package/dist/lifecycle/hooks.d.ts.map +1 -0
  79. package/dist/lifecycle/hooks.js +2 -0
  80. package/dist/lifecycle/reason.d.ts +11 -0
  81. package/dist/lifecycle/reason.d.ts.map +1 -0
  82. package/dist/lifecycle/reason.js +13 -0
  83. package/dist/lifecycle/request.d.ts +18 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +31 -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 +272 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +623 -0
  92. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  93. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  94. package/dist/migrations/0004_user_lifecycle.js +47 -0
  95. package/dist/migrations/0005_purge_once.d.ts +22 -0
  96. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  97. package/dist/migrations/0005_purge_once.js +35 -0
  98. package/dist/migrations/pluginTables.d.ts +8 -0
  99. package/dist/migrations/pluginTables.d.ts.map +1 -1
  100. package/dist/migrations/pluginTables.js +8 -1
  101. package/dist/migrations/set.d.ts +3 -1
  102. package/dist/migrations/set.d.ts.map +1 -1
  103. package/dist/migrations/set.js +6 -2
  104. package/dist/peer.d.ts +4 -0
  105. package/dist/peer.d.ts.map +1 -1
  106. package/dist/purge/contribution.d.ts +47 -0
  107. package/dist/purge/contribution.d.ts.map +1 -0
  108. package/dist/purge/contribution.js +141 -0
  109. package/dist/purge/retryPolicy.d.ts +22 -0
  110. package/dist/purge/retryPolicy.d.ts.map +1 -0
  111. package/dist/purge/retryPolicy.js +26 -0
  112. package/dist/purge/run.d.ts +88 -0
  113. package/dist/purge/run.d.ts.map +1 -0
  114. package/dist/purge/run.js +102 -0
  115. package/dist/purge/specs.d.ts +71 -0
  116. package/dist/purge/specs.d.ts.map +1 -0
  117. package/dist/purge/specs.js +72 -0
  118. package/dist/purge/start.d.ts +42 -0
  119. package/dist/purge/start.d.ts.map +1 -0
  120. package/dist/purge/start.js +37 -0
  121. package/dist/purge/workflow.d.ts +58 -0
  122. package/dist/purge/workflow.d.ts.map +1 -0
  123. package/dist/purge/workflow.js +96 -0
  124. package/dist/test-utils/accountFootprint.d.ts +10 -0
  125. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  126. package/dist/test-utils/accountFootprint.js +44 -0
  127. package/dist/test-utils/liveApp.d.ts +21 -0
  128. package/dist/test-utils/liveApp.d.ts.map +1 -1
  129. package/dist/test-utils/liveApp.js +1 -0
  130. package/dist/test-utils/scopedBackend.d.ts +21 -0
  131. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  132. package/dist/test-utils/scopedBackend.js +7 -1
  133. package/dist/version.generated.d.ts +1 -1
  134. package/dist/version.generated.d.ts.map +1 -1
  135. package/dist/version.generated.js +1 -1
  136. package/docs/account-lifecycle.md +217 -0
  137. package/docs/apple-signin.md +7 -1
  138. package/docs/facebook-oauth.md +7 -1
  139. package/docs/github-oauth.md +7 -1
  140. package/docs/google-oauth.md +7 -1
  141. package/docs/microsoft-oauth.md +177 -0
  142. package/package.json +5 -5
  143. package/pithy.manifest.json +17 -3
  144. package/src/audit/actions.ts +42 -0
  145. package/src/audit/emit.ts +4 -2
  146. package/src/capability.ts +170 -52
  147. package/src/client/lifecycle.ts +27 -0
  148. package/src/client/projection.ts +4 -0
  149. package/src/data/betterAuth.ts +21 -1
  150. package/src/data/kitFields.ts +27 -0
  151. package/src/data/tables.ts +4 -2
  152. package/src/data/userLifecycle.ts +83 -0
  153. package/src/http/adminRoutes.ts +398 -2
  154. package/src/http/guards.ts +61 -1
  155. package/src/http/lifecycleGate.ts +78 -0
  156. package/src/http/middleware.ts +104 -2
  157. package/src/http/providerRefusal.ts +10 -0
  158. package/src/http/resolve.ts +8 -3
  159. package/src/http/responses.ts +245 -0
  160. package/src/http/routes.ts +93 -4
  161. package/src/http/schemas.ts +110 -0
  162. package/src/http/views.ts +147 -2
  163. package/src/instance/auth.ts +74 -2
  164. package/src/instance/microsoftEmail.ts +111 -0
  165. package/src/instance/providerSignInGate.ts +7 -6
  166. package/src/instance/providers.ts +8 -4
  167. package/src/instance/secrets.ts +59 -5
  168. package/src/lifecycle/audited.ts +104 -0
  169. package/src/lifecycle/enforce.ts +139 -0
  170. package/src/lifecycle/hooks.ts +54 -0
  171. package/src/lifecycle/reason.ts +11 -0
  172. package/src/lifecycle/request.ts +39 -0
  173. package/src/lifecycle/state.ts +101 -0
  174. package/src/lifecycle/transitions.ts +872 -0
  175. package/src/migrations/0004_user_lifecycle.ts +68 -0
  176. package/src/migrations/0005_purge_once.ts +42 -0
  177. package/src/migrations/pluginTables.ts +19 -1
  178. package/src/migrations/set.ts +5 -1
  179. package/src/purge/contribution.ts +191 -0
  180. package/src/purge/retryPolicy.ts +26 -0
  181. package/src/purge/run.ts +185 -0
  182. package/src/purge/specs.ts +95 -0
  183. package/src/purge/start.ts +79 -0
  184. package/src/purge/workflow.ts +144 -0
  185. package/src/test-utils/accountFootprint.ts +95 -0
  186. package/src/test-utils/liveApp.ts +2 -1
  187. package/src/test-utils/scopedBackend.ts +2 -1
  188. package/src/version.generated.ts +1 -1
@@ -2,14 +2,17 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
- import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { InternalError, type PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
6
6
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
7
7
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
8
8
  import type { Context, MiddlewareHandler } from "hono";
9
9
  import type { AuthWiring, ScopeResolver, ScopeResolverSession } from "../capability";
10
+ import { authDatabase } from "../data/tables";
10
11
  import type { AuthInstance } from "../instance/auth";
12
+ import { lifecycleRefusalFor, noteRefusal, noticedRefusal, suspendedHolder } from "../lifecycle/enforce";
13
+ import { LifecycleColumns } from "../lifecycle/state";
11
14
  import { withResignedCredentials } from "./credentialResign";
12
- import { getAuthInstance } from "./resolve";
15
+ import { getAuthInstance, resolveDb } from "./resolve";
13
16
 
14
17
  /**
15
18
  * The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
@@ -93,6 +96,16 @@ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, inst
93
96
  try {
94
97
  const session = await instance.api.getSession({ headers });
95
98
  if (session) {
99
+ // **A suspended or deleted account gets no `AuthContext` at all** (#620). Read off the user Better
100
+ // Auth just loaded, which carries the four columns, so an account in good standing costs nothing
101
+ // here. Leaving `auth` null is what makes every `requireAuth()` in the kit refuse it — the copies
102
+ // other capabilities carry included, since each one only asks whether `auth` was filled. This
103
+ // capability's own guard raises the refusal itself, with its code; see `requireAuth` below.
104
+ const refusal = await standingRefusal(c, wiring, session.user);
105
+ if (refusal) {
106
+ noteRefusal(c, refusal, { userId: session.user.id, sessionId: session.session.id });
107
+ return;
108
+ }
96
109
  // Before the context is built, so a resolver sees the request exactly as it arrived and the
97
110
  // context is published once, whole. Per request and never cached: the answer is about this
98
111
  // request's caller, and a cached one is a revocation that has not taken effect (#560).
@@ -128,13 +141,102 @@ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, inst
128
141
  }
129
142
  }
130
143
 
144
+ /**
145
+ * The refusal for the session's account, or `null` when it may act.
146
+ *
147
+ * **A check that cannot be made refuses**, rather than throwing into `resolveSession`'s catch. That catch
148
+ * leaves `auth` null and notes nothing, and `handleBetterAuth` only refuses on a noted verdict — so a failed
149
+ * read of a suspension's reason, or a column that will not decode, would let Better Auth's own `/token` mint a
150
+ * JWT for the suspended account it resolved on its own. So the failure is logged and becomes the verdict: a
151
+ * 500, since the fault is this Worker's, and every door that honors a lifecycle refusal honors this one.
152
+ */
153
+ async function standingRefusal(
154
+ c: Context<PithyHonoEnv>,
155
+ wiring: AuthWiring,
156
+ user: { id: string },
157
+ ): Promise<PithyError | null> {
158
+ try {
159
+ return await lifecycleRefusalFor(
160
+ authDatabase(resolveDb(c.env, wiring.config.database)),
161
+ user.id,
162
+ LifecycleColumns.parse(user),
163
+ new Date(),
164
+ );
165
+ } catch (cause) {
166
+ // Optional, unlike the logger elsewhere here: this branch is the refusal, and a missing logger must not
167
+ // turn it back into the throw it exists to replace.
168
+ c.var.log?.child("auth").warn("the account's standing could not be checked; the request is refused", {
169
+ userId: user.id,
170
+ reason: cause instanceof Error ? cause.message : String(cause),
171
+ });
172
+ return new InternalError(
173
+ {
174
+ message: "This account could not be checked. Try again shortly.",
175
+ action: "Check the auth database binding and that the auth migrations have run.",
176
+ detail: `lifecycle check for user ${user.id} failed`,
177
+ },
178
+ { cause },
179
+ );
180
+ }
181
+ }
182
+
131
183
  /**
132
184
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
133
185
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
186
+ *
187
+ * **A genuine credential for an account that may not act is refused with what happened to it** —
188
+ * `auth/account_suspended` or `auth/account_deleted`, 403 — rather than the 401, because signing in again
189
+ * cannot help and a client that read it as an expired token would loop. The verdict is the session
190
+ * middleware's, remembered for this request; this guard only raises it.
134
191
  */
135
192
  export function requireAuth(): MiddlewareHandler<PithyHonoEnv> {
136
193
  return async (c, next) => {
137
194
  if (!c.var.auth) {
195
+ const refusal = noticedRefusal(c);
196
+ if (refusal) throw refusal;
197
+ throw new UnauthorizedError({
198
+ message: "Authentication required.",
199
+ action: "Sign in and retry with a valid session or bearer token.",
200
+ });
201
+ }
202
+ await next();
203
+ };
204
+ }
205
+
206
+ /** Whose account a request may act on as its own holder: the signed-in account, or a suspended one's. */
207
+ export interface AccountHolder {
208
+ /** The account. */
209
+ readonly userId: string;
210
+ /** The session the request presented. */
211
+ readonly sessionId: string;
212
+ /** Whether the account is suspended — every other route refuses it. */
213
+ readonly suspended: boolean;
214
+ }
215
+
216
+ /**
217
+ * The account this request's credential opens, for a route a **suspended** account may still use — and there is
218
+ * exactly one, deleting it (#622). The App Store and Google Play require that a person can delete their account
219
+ * from inside the app, and a suspension is no reason to keep somebody who wants to leave.
220
+ *
221
+ * A deleted account is not admitted: there is nothing left to delete. Neither is a request whose standing could
222
+ * not be checked.
223
+ */
224
+ export function accountHolder(c: Context<PithyHonoEnv>): AccountHolder | null {
225
+ if (c.var.auth) return { userId: c.var.auth.userId, sessionId: c.var.auth.sessionId, suspended: false };
226
+ const held = suspendedHolder(c);
227
+ return held ? { ...held, suspended: true } : null;
228
+ }
229
+
230
+ /**
231
+ * The gate for that route: `requireAuth()`, with a suspended account's genuine credential admitted. Everything
232
+ * `requireAuth()` refuses otherwise, it refuses the same way — a deleted account with its code, anything else
233
+ * with `auth/invalid_token`.
234
+ */
235
+ export function requireAccountHolder(): MiddlewareHandler<PithyHonoEnv> {
236
+ return async (c, next) => {
237
+ if (!accountHolder(c)) {
238
+ const refusal = noticedRefusal(c);
239
+ if (refusal) throw refusal;
138
240
  throw new UnauthorizedError({
139
241
  message: "Authentication required.",
140
242
  action: "Sign in and retry with a valid session or bearer token.",
@@ -169,6 +169,16 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
169
169
  why: "Two producers, and the verdict follows the one that reads our rows. `linkOAuthAccount` (link-account.mjs:45/68) answers it on `/link-social`, where the caller is signed in as the user being changed. But `handleOAuthUserInfo` answers it too, inside `if (dbUser)` when the account write fails (:171/:184), so on the social callback it says a row matched, and `unable_to_create_user` is its other half. Collapsing costs the signed-in linker a specific code for a fault. Letting it travel would cost the oracle. Corrected in #787; the earlier verdict read only the link flow.",
170
170
  },
171
171
 
172
+ // ── The account's own standing, told to the person who just proved they hold it. ──────────────
173
+ "auth/account_suspended": {
174
+ collapse: false,
175
+ why: "The kit's own `session.create.before` hook (instance/auth.ts, #620). A session is only ever created for a user the callback has already resolved and linked — the caller has just proved control of a provider identity bound to this account — so the code is told to its holder, never to somebody probing an address. Collapsing it would leave a suspended person with a screen that says nothing happened.",
176
+ },
177
+ "auth/account_deleted": {
178
+ collapse: false,
179
+ why: "The same hook, for an account inside its purge window, and the same reasoning: it is reached only after the caller authenticated as the account, so it names the state of their own account to them.",
180
+ },
181
+
172
182
  // ── The caller's own request, or the provider's. Nothing to do with our rows. ──────────────────
173
183
  no_code: {
174
184
  collapse: false,
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
+ import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
5
6
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
6
7
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
8
  import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
@@ -19,6 +20,7 @@ import {
19
20
  resolveFacebookCredentials,
20
21
  resolveGithubCredentials,
21
22
  resolveGoogleCredentials,
23
+ resolveMicrosoftCredentials,
22
24
  resolveSessionSecrets,
23
25
  } from "../instance/secrets";
24
26
  import { baseURLResolver } from "./baseUrl";
@@ -87,7 +89,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
87
89
  });
88
90
  }
89
91
  const env = c.env as unknown as AuthEnv;
90
- // Secret resolutions hit the same per-invocation cache; run them concurrently. Five reads, and they
92
+ // Secret resolutions hit the same per-invocation cache; run them concurrently. Six reads, and they
91
93
  // are not alike — which is the whole of #381.
92
94
  //
93
95
  // `resolveSessionSecret` is what an auth instance *is*: nothing signs a session without it, so its
@@ -105,12 +107,13 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
105
107
  //
106
108
  // A held failure belongs to its own secret (#170), so an unreadable provider credential does not
107
109
  // disturb the session secret's own read, and a *disabled* provider never calls `.get()` at all.
108
- const [sessionSecrets, google, apple, facebook, github] = await Promise.all([
110
+ const [sessionSecrets, google, apple, facebook, github, microsoft] = await Promise.all([
109
111
  resolveSessionSecrets(env),
110
112
  resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
111
113
  resolveProvider(cfg.apple.enabled, () => resolveAppleCredentials(env)),
112
114
  resolveProvider(cfg.facebook.enabled, () => resolveFacebookCredentials(env)),
113
115
  resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env)),
116
+ resolveProvider(cfg.microsoft.enabled, () => resolveMicrosoftCredentials(env)),
114
117
  ]);
115
118
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
116
119
  const d1 = resolveDb(c.env, cfg.database);
@@ -161,6 +164,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
161
164
  apple,
162
165
  facebook,
163
166
  github,
167
+ microsoft,
164
168
  sendEmail: makeSendAuthEmail(
165
169
  (input) => enqueueEmail(env, input),
166
170
  expiresMinutes,
@@ -179,11 +183,12 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
179
183
  apple: cfg.apple.allowSignUp,
180
184
  facebook: cfg.facebook.allowSignUp,
181
185
  github: cfg.github.allowSignUp,
186
+ microsoft: cfg.microsoft.allowSignUp,
182
187
  },
183
188
  ...(wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {}),
184
189
  // Read the emit seam lazily so a later-composed audit capability is honored regardless of the
185
190
  // capability order (the instance may be built before audit's middleware runs).
186
- emit: (event) => c.var.emit(event),
191
+ emit: (event: AuditEventInput) => c.var.emit(event),
187
192
  // This request's own headers, for the refusal rows `../instance/providerSignInGate` writes from
188
193
  // inside `getUserInfo`, where no request is in scope to read them from.
189
194
  requestHeaders: c.req.raw.headers,
@@ -198,6 +198,234 @@ export const AdminDeviceRevokeResponse = z
198
198
  .describe("How many sessions the device revocation ended, and whether the registry row went with them.");
199
199
  export type AdminDeviceRevokeResponse = z.output<typeof AdminDeviceRevokeResponse>;
200
200
 
201
+ /**
202
+ * `POST {base}/admin/users/:userId/suspend` (#621).
203
+ *
204
+ * The suspension the account is now under, how many sessions ended with it, and whether the person was told.
205
+ * Not the reason: the caller wrote it, the trail keeps it, and echoing it back would put it in one more place
206
+ * a dashboard logs.
207
+ */
208
+ export const AdminUserSuspendResponse = z
209
+ .object({
210
+ userId: z.string().describe("The account suspended, as `pithy_auth_users.id` stores it."),
211
+ state: z.literal("suspended").describe("Where the account stands now. Every sign-in and refresh is refused."),
212
+ outcome: z
213
+ .enum(["suspended", "updated"])
214
+ .describe(
215
+ "`suspended` when this call suspended an account in good standing; `updated` when it was already suspended and this call restated the reason and the end.",
216
+ ),
217
+ suspendedAt: z.iso
218
+ .datetime()
219
+ .describe("When the suspension in force began, ISO-8601. A restatement keeps the original start."),
220
+ suspendedUntil: z.iso
221
+ .datetime()
222
+ .nullable()
223
+ .describe("When it ends by itself, ISO-8601, with nothing written to end it. Null lasts until a reinstatement."),
224
+ sessionsRevoked: RevokedCount,
225
+ mailed: z
226
+ .boolean()
227
+ .describe(
228
+ "Whether the account-suspended mail was enqueued. False for `notify: false`, when the config turns it off, or when no email capability is composed.",
229
+ ),
230
+ })
231
+ .describe("A suspended account: since when, until when, how many sessions it cost, and whether the person was told.");
232
+ export type AdminUserSuspendResponse = z.output<typeof AdminUserSuspendResponse>;
233
+
234
+ /**
235
+ * `POST {base}/admin/users/:userId/reinstate` (#621).
236
+ *
237
+ * No session count: a reinstatement restores none. The person signs in again.
238
+ */
239
+ export const AdminUserReinstateResponse = z
240
+ .object({
241
+ userId: z.string().describe("The account reinstated, as `pithy_auth_users.id` stores it."),
242
+ state: z.literal("active").describe("Where the account stands now. It can sign in again."),
243
+ outcome: z
244
+ .enum(["reinstated", "unchanged"])
245
+ .describe(
246
+ "`reinstated` when this call lifted a suspension; `unchanged` when there was none in force — never suspended, or past its end — and nothing was written.",
247
+ ),
248
+ mailed: z
249
+ .boolean()
250
+ .describe(
251
+ "Whether the account-reinstated mail was enqueued. Always false for `unchanged`, and on the same rule as a suspension's otherwise.",
252
+ ),
253
+ })
254
+ .describe("A reinstated account, and whether the person was told. Its revoked sessions stay revoked.");
255
+ export type AdminUserReinstateResponse = z.output<typeof AdminUserReinstateResponse>;
256
+
257
+ /** When the purge may erase a deleted account, ISO-8601. */
258
+ const PurgeAfter = z.iso
259
+ .datetime()
260
+ .describe(
261
+ "When the purge may erase the account, ISO-8601. It can be restored until then; a hard deletion's is the moment it was deleted.",
262
+ );
263
+
264
+ /**
265
+ * `DELETE {base}/admin/users/:userId` (#622).
266
+ *
267
+ * What the deletion left in force, how many sessions ended with it, whether the person was told, and what
268
+ * became of the purge. Not the reason: the caller wrote it and the trail keeps it.
269
+ */
270
+ export const AdminUserDeleteResponse = z
271
+ .object({
272
+ userId: z.string().describe("The account deleted, as `pithy_auth_users.id` stores it."),
273
+ state: z.literal("deleted").describe("Where the account stands now. Every sign-in and refresh is refused."),
274
+ mode: z.enum(["soft", "hard"]).describe("The mode this call ran in — `soft` unless the caller named `hard`."),
275
+ outcome: z
276
+ .enum(["deleted", "brought_forward", "unchanged"])
277
+ .describe(
278
+ "`deleted` when this call deleted an account in good standing; `brought_forward` when a hard deletion moved an already-deleted account's purge to now; `unchanged` when it was already deleted and there was nothing to move.",
279
+ ),
280
+ deletedAt: z.iso.datetime().describe("When the account was deleted, ISO-8601. Kept by a deletion brought forward."),
281
+ purgeAfter: PurgeAfter,
282
+ purge: z
283
+ .enum(["scheduled", "started", "pending"])
284
+ .describe(
285
+ "`scheduled`: the daily purge erases it once `purgeAfter` passes. `started`: the purge Workflow was started by this call. `pending`: the purge is due and this Worker binds no purge Workflow to start, so it runs once one is bound.",
286
+ ),
287
+ sessionsRevoked: RevokedCount,
288
+ mailed: z
289
+ .boolean()
290
+ .describe(
291
+ "Whether the deletion-scheduled mail was enqueued. Always false for `hard`, whose mail the purge sends, for `notify: false`, and when the config turns it off.",
292
+ ),
293
+ })
294
+ .describe("A deleted account: when, until when it can be restored, what became of the purge, and its sessions.");
295
+ export type AdminUserDeleteResponse = z.output<typeof AdminUserDeleteResponse>;
296
+
297
+ /**
298
+ * `POST {base}/admin/users/:userId/restore` (#622). No session count: a restoration restores none.
299
+ */
300
+ export const AdminUserRestoreResponse = z
301
+ .object({
302
+ userId: z.string().describe("The account restored, as `pithy_auth_users.id` stores it."),
303
+ state: z
304
+ .enum(["active", "suspended"])
305
+ .describe(
306
+ "Where the account stands now: `active`, or `suspended` when a suspension it was under before the deletion is still in force.",
307
+ ),
308
+ outcome: z
309
+ .enum(["restored", "unchanged"])
310
+ .describe("`restored` when this call restored a deleted account; `unchanged` when it was not deleted."),
311
+ })
312
+ .describe("A restored account, inside its purge window. Its revoked sessions stay revoked.");
313
+ export type AdminUserRestoreResponse = z.output<typeof AdminUserRestoreResponse>;
314
+
315
+ /** One provider link an account holds, as an export carries it — no provider token. */
316
+ const AuthExportProvider = z
317
+ .object({
318
+ providerId: z.string().describe("The sign-in provider's slug — `google`, `apple`, `github`."),
319
+ createdAt: z.iso.datetime().describe("When the provider was linked, ISO-8601."),
320
+ })
321
+ .describe("One sign-in provider linked to the account. The provider's tokens are credentials and are not here.");
322
+
323
+ /** One transition in an account's history, as an export carries it — not who made it. */
324
+ const AuthExportTransition = z
325
+ .object({
326
+ action: z
327
+ .string()
328
+ .describe("What happened: `suspended`, `reinstated`, `deleted`, `restored`, `purge_step`, `purged`."),
329
+ actorType: z.string().describe("Who made it: `control-plane`, `user` (the account's holder), or `system`."),
330
+ reason: z.string().nullable().describe("The reason given, in the words of whoever made the transition, or null."),
331
+ suspendedUntil: z.iso.datetime().nullable().describe("For a suspension, when it ends by itself, ISO-8601."),
332
+ createdAt: z.iso.datetime().describe("When it happened, ISO-8601."),
333
+ })
334
+ .describe(
335
+ "One transition in the account's history. The operator's identity is theirs, not the person's, so it is not here.",
336
+ );
337
+
338
+ /**
339
+ * What `@pithy-sh/auth` holds about one account, as its purge contribution exports it (#622) — the `data` of
340
+ * the `auth` entry in an export.
341
+ *
342
+ * The person's own data and none of their credentials: no session token, no provider token, no push token.
343
+ * Every list is whole, because an export that stopped at a bound would answer an access request with part of
344
+ * an answer.
345
+ */
346
+ export const AuthUserExport = z
347
+ .object({
348
+ user: AdminUserView.extend({
349
+ suspendedAt: z.iso.datetime().nullable().describe("When a suspension in force began, ISO-8601, or null."),
350
+ suspendedUntil: z.iso.datetime().nullable().describe("When that suspension ends by itself, ISO-8601, or null."),
351
+ deletedAt: z.iso.datetime().nullable().describe("When the account was deleted, ISO-8601, or null."),
352
+ purgeAfter: z.iso.datetime().nullable().describe("When the purge may erase it, ISO-8601, or null."),
353
+ }).describe("The account itself, with where it stands."),
354
+ sessions: z.array(AdminSessionView).describe("Every live session, newest first. Without the tokens."),
355
+ providers: z.array(AuthExportProvider).describe("Every linked sign-in provider."),
356
+ devices: z
357
+ .array(AdminDeviceView)
358
+ .describe("Every registered device, most recently seen first. Without push tokens."),
359
+ history: z.array(AuthExportTransition).describe("Every lifecycle transition, oldest first."),
360
+ plugins: z
361
+ .record(z.string(), z.array(z.record(z.string(), z.unknown())))
362
+ .describe(
363
+ "The account's rows in each table a composed Better Auth plugin created keyed by `userId` — two-factor, passkeys, API keys — keyed by table. Without a column that holds a credential. Empty when no such plugin is composed.",
364
+ ),
365
+ })
366
+ .describe("Everything `@pithy-sh/auth` holds about one account, without a credential.");
367
+ export type AuthUserExport = z.output<typeof AuthUserExport>;
368
+
369
+ /** Fields every capability's export entry carries. */
370
+ const exportEntry = {
371
+ capability: z.string().describe("The capability whose rows these are — the purge step that erases them."),
372
+ summary: z.string().describe("What that capability's purge erases or anonymizes, in its own sentence."),
373
+ };
374
+
375
+ /** One capability's part of an export. */
376
+ const AdminUserExportEntry = z
377
+ .discriminatedUnion("state", [
378
+ z
379
+ .object({
380
+ ...exportEntry,
381
+ state: z.literal("exported").describe("The capability answered."),
382
+ data: z
383
+ .record(z.string(), z.unknown())
384
+ .describe(
385
+ "What it holds about the account, in the shape that capability exports. `auth`'s is `AuthUserExport`.",
386
+ ),
387
+ })
388
+ .describe("A capability's rows about the account."),
389
+ z
390
+ .object({
391
+ ...exportEntry,
392
+ state: z
393
+ .literal("not_exported")
394
+ .describe("The capability erases rows about the account and does not say how to export them."),
395
+ })
396
+ .describe("A capability that holds rows it does not export. Ask its owner."),
397
+ z
398
+ .object({
399
+ ...exportEntry,
400
+ state: z.literal("unavailable").describe("The capability's rows could not be read on this request."),
401
+ })
402
+ .describe("Nothing was established about this capability's rows. Deliberately empty — it is not 'none'."),
403
+ ])
404
+ .describe("One capability's part of an export, behind a state, so an unread part cannot be taken for an empty one.");
405
+
406
+ /**
407
+ * `GET {base}/admin/users/:userId/export` (#622).
408
+ *
409
+ * Everything the kit holds about one account — the answer to an access request. One entry per composed
410
+ * capability that declares a purge contribution, in the order the purge runs them, each read on its own so
411
+ * one that will not read costs its own entry and not the document.
412
+ */
413
+ export const AdminUserExportResponse = z
414
+ .object({
415
+ subject: z
416
+ .object({
417
+ type: z.literal("user").describe("The kind of subject: one person's account."),
418
+ id: z.string().describe("The account's id, as `pithy_auth_users.id` stores it."),
419
+ })
420
+ .describe("Who this export is about."),
421
+ exportedAt: z.iso.datetime().describe("When the export was read, ISO-8601."),
422
+ capabilities: z
423
+ .array(AdminUserExportEntry)
424
+ .describe("Every composed capability's part, in the order the purge erases them."),
425
+ })
426
+ .describe("Everything the kit holds about one account, from every composed capability, as one document.");
427
+ export type AdminUserExportResponse = z.output<typeof AdminUserExportResponse>;
428
+
201
429
  /*
202
430
  * The routes a signed-in person calls on their own account. These are not read across the management
203
431
  * version boundary the admin schemas above are, but a client generated from the contract reads Workers on
@@ -251,3 +479,20 @@ export const MyDeviceRevokeResponse = z
251
479
  .object({ revoked: RevokedCount })
252
480
  .describe("How many of the device's sessions the revocation signed out. The device's row goes with them.");
253
481
  export type MyDeviceRevokeResponse = z.output<typeof MyDeviceRevokeResponse>;
482
+
483
+ /**
484
+ * `DELETE {base}/account` (#622) — the signed-in person deleted their own account. Always soft, on the
485
+ * configured window. Their sessions end with it, this one included.
486
+ */
487
+ export const AccountDeleteResponse = z
488
+ .object({
489
+ state: z.literal("deleted").describe("The account is deleted. This session and every other one has ended."),
490
+ purgeAfter: PurgeAfter,
491
+ mailed: z
492
+ .boolean()
493
+ .describe(
494
+ "Whether the deletion-scheduled mail, with the purge date and how to ask for the account back, was sent.",
495
+ ),
496
+ })
497
+ .describe("The caller's own account, deleted: when its data will be erased, and whether they were mailed.");
498
+ export type AccountDeleteResponse = z.output<typeof AccountDeleteResponse>;
@@ -10,10 +10,15 @@ import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image
10
10
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
11
11
  import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
12
12
  import type { Context, Hono } from "hono";
13
+ import { userSessionTokens } from "../admin/users";
13
14
  import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit";
14
15
  import type { AuthWiring } from "../capability";
15
16
  import { authDatabase } from "../data/tables";
16
17
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry";
18
+ import { noticedRefusal } from "../lifecycle/enforce";
19
+ import { lifecycleDeps } from "../lifecycle/request";
20
+ import { isLifecycleRefusal } from "../lifecycle/state";
21
+ import { deleteUser } from "../lifecycle/transitions";
17
22
  import { PROFILE_IMAGE_PATH } from "../profile/profile";
18
23
  import {
19
24
  consumeSession,
@@ -25,12 +30,14 @@ import {
25
30
  import { registerAuthAdminRoutes } from "./adminRoutes";
26
31
  import { guardErrorCallbackURL } from "./errorCallbackUrl";
27
32
  import { apiErrorToPithy } from "./errors";
28
- import { requireAuth } from "./middleware";
33
+ import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate";
34
+ import { accountHolder, requireAccountHolder, requireAuth } from "./middleware";
29
35
  import { requireFreshAuthentication } from "./providerFreshness";
30
36
  import { collapseProviderRefusal } from "./providerRefusal";
31
37
  import { getAuthInstance, resolveDb } from "./resolve";
32
- import { MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses";
33
- import { RevokeDeviceBody } from "./schemas";
38
+ import { AccountDeleteResponse, MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses";
39
+ import { DeleteAccountBody, RevokeDeviceBody } from "./schemas";
40
+ import { accountDeletionView } from "./views";
34
41
 
35
42
  type Ctx = Context<PithyHonoEnv>;
36
43
 
@@ -64,6 +71,7 @@ function db(c: Ctx, wiring: AuthWiring) {
64
71
  * | `POST /token/rotate` | bearer/session | none — the credential only |
65
72
  * | `GET /devices` | bearer/session | none |
66
73
  * | `POST /devices/revoke` | bearer/session | json `RevokeDeviceBody` |
74
+ * | `DELETE /account` | bearer/session | json `DeleteAccountBody` |
67
75
  * | `* /admin/*` | control-plane | see `./adminRoutes` |
68
76
  *
69
77
  * The catch-all takes NO validator, deliberately: `handleBetterAuth` hands Better Auth `c.req.raw`,
@@ -132,6 +140,25 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
132
140
  (c) => revokeMyDevice(c, wiring, c.req.valid("json")),
133
141
  );
134
142
 
143
+ // The signed-in person deletes their own account (#622) — always soft, on the configured window. The one
144
+ // route a suspended account still reaches: the app stores require that somebody can always leave, and a
145
+ // suspension is no reason to keep them. CSRF-guarded as a mutating route; the subject is the session's own,
146
+ // and nothing in the body can name another.
147
+ app.delete(
148
+ `${base}/account`,
149
+ describeRoute({
150
+ summary: "Delete the caller's own account. Always soft: restorable until the purge window closes.",
151
+ description:
152
+ "What the App Store and Google Play require of an app with accounts. A suspended account may still delete itself, with the session a sign-in carrying `x-pithy-intent: delete-account` gets it; a deleted one is refused with `auth/account_deleted`. Every session ends, this one included. The body must carry `confirm: true`.",
153
+ verification: ["bearer", "session"],
154
+ responses: { 200: AccountDeleteResponse },
155
+ }),
156
+ requireAccountHolder(),
157
+ csrf,
158
+ validate("json", DeleteAccountBody),
159
+ (c) => deleteMyAccount(c, wiring),
160
+ );
161
+
135
162
  // **Changing which providers can sign you in requires a recent authentication — both directions.**
136
163
  // Mounted explicitly ahead of the catch-all, or neither gate runs. `http/providerFreshness.ts`
137
164
  // carries the argument: Better Auth guards the two unevenly, and its guard on the unlink side reads
@@ -279,6 +306,15 @@ async function auditRefusal(c: Ctx, response: Response): Promise<void> {
279
306
  async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
280
307
  const instance = await getAuthInstance(c, wiring);
281
308
 
309
+ // **A suspended or deleted account does not reach Better Auth as itself (#620).** The session middleware
310
+ // has already refused it an `AuthContext`, but Better Auth resolves its own session on these endpoints and
311
+ // would happily mint a `/token` for it. So its verdict is applied here too, on every endpoint that acts as
312
+ // the credential's holder — and not on the ones that end a session or start a new one. `./lifecycleGate`
313
+ // says which, and why a stale cookie must not stop somebody else signing in.
314
+ const pathname = new URL(c.req.raw.url).pathname;
315
+ const refusal = noticedRefusal(c);
316
+ if (refusal && !admitsRefusedAccount(pathname.slice(wiring.config.basePath.length))) throw refusal;
317
+
282
318
  // **The first of the two guards on the refusal redirect (#625).** `errorCallbackURL` is the caller's
283
319
  // string and `redirectOnError` builds the redirect on it, so the shape handed *in* decides
284
320
  // whether the collapse below is reading a query at all. `./errorCallbackUrl` normalizes it to something
@@ -290,7 +326,26 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
290
326
  try {
291
327
  response = await instance.handler(request);
292
328
  } catch (error) {
293
- throw apiErrorToPithy(error);
329
+ const pithy = apiErrorToPithy(error);
330
+ // A sign-in refused because the account is suspended or deleted: the session hook threw it, so it
331
+ // arrives here rather than as a Better Auth response, and is recorded here for the same reason.
332
+ if (isLifecycleRefusal(pithy)) {
333
+ if (isSignInAttempt(pathname)) {
334
+ await emitDenied(c.var.emit, { ...correlation(c.req.raw.headers), detail: pithy.payload.code });
335
+ }
336
+ // A magic link is a browser navigation, so the refusal goes back to the screen the link named rather
337
+ // than stranding the reader on this origin's 403. OTP and every JSON caller get the envelope.
338
+ if (c.req.method === "GET" && pathname === `${wiring.config.basePath}/magic-link/verify`) {
339
+ const redirect = lifecycleRedirect(
340
+ new URL(request.url),
341
+ wiring.config.baseURL,
342
+ wiring.config.trustedOrigins,
343
+ pithy,
344
+ );
345
+ if (redirect) return redirect;
346
+ }
347
+ }
348
+ throw pithy;
294
349
  }
295
350
 
296
351
  // **The enumeration oracle on the social callback, closed here because here is the only place both
@@ -390,6 +445,12 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
390
445
  });
391
446
  }
392
447
 
448
+ // An account that may not act gets no successor (#620). `session.create.before` would refuse the mint below
449
+ // anyway; refusing here, from the middleware's verdict, is what keeps the presented token unspent and the
450
+ // successor never written, so a reinstated account's device still holds a credential that works.
451
+ const refusal = noticedRefusal(c);
452
+ if (refusal) throw refusal;
453
+
393
454
  const ip = headers.get("cf-connecting-ip") ?? undefined;
394
455
  const userAgent = headers.get("user-agent") ?? undefined;
395
456
  const session = current.session as {
@@ -465,6 +526,34 @@ async function listMyDevices(c: Ctx, wiring: AuthWiring): Promise<Response> {
465
526
  return c.json({ devices: await listDevices(db(c, wiring), userId) });
466
527
  }
467
528
 
529
+ /**
530
+ * Delete the caller's own account (#622): soft, on the configured window, audited as `auth/user_self_deleted`
531
+ * with them as the actor, and every session they hold ended after the columns are written — through Better
532
+ * Auth's adapter, so `onSessionRevoked` hears each. No reason: a person leaving owes nobody one.
533
+ */
534
+ async function deleteMyAccount(c: Ctx, wiring: AuthWiring): Promise<Response> {
535
+ const holder = accountHolder(c);
536
+ if (!holder) throw new UnauthorizedError({ message: "Authentication required." });
537
+ const { ip, userAgent } = correlation(c.req.raw.headers);
538
+ const deps = lifecycleDeps(c, wiring, {
539
+ ip,
540
+ userAgent,
541
+ requestId: c.req.header("cf-ray"),
542
+ metadata: { sessionId: holder.sessionId, suspended: holder.suspended },
543
+ });
544
+ const result = await deleteUser(deps, {
545
+ userId: holder.userId,
546
+ actor: { type: "user", id: holder.userId },
547
+ reason: null,
548
+ });
549
+ const tokens = await userSessionTokens(db(c, wiring), holder.userId);
550
+ const ctx = await (await getAuthInstance(c, wiring)).$context;
551
+ for (const token of tokens) {
552
+ await ctx.internalAdapter.deleteSession(token);
553
+ }
554
+ return c.json(accountDeletionView(result) satisfies AccountDeleteResponse);
555
+ }
556
+
468
557
  /** Revoke one of the authenticated user's devices: sign out its sessions, then drop the device row. */
469
558
  async function revokeMyDevice(c: Ctx, wiring: AuthWiring, body: RevokeDeviceBody): Promise<Response> {
470
559
  const userId = c.var.auth?.userId;