@pithy-sh/auth 0.10.0 → 0.12.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 (283) hide show
  1. package/README.md +30 -2
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +58 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +59 -1
  6. package/dist/audit/emit.d.ts +36 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +48 -2
  9. package/dist/audit/evidence.d.ts +8 -2
  10. package/dist/audit/evidence.d.ts.map +1 -1
  11. package/dist/capability.d.ts +47 -8
  12. package/dist/capability.d.ts.map +1 -1
  13. package/dist/capability.js +56 -6
  14. package/dist/client/api.d.ts +55 -12
  15. package/dist/client/api.d.ts.map +1 -1
  16. package/dist/client/api.js +57 -18
  17. package/dist/client/bearer.d.ts +110 -0
  18. package/dist/client/bearer.d.ts.map +1 -0
  19. package/dist/client/bearer.js +265 -0
  20. package/dist/client/handoff.d.ts +77 -0
  21. package/dist/client/handoff.d.ts.map +1 -0
  22. package/dist/client/handoff.js +119 -0
  23. package/dist/client/mcp.d.ts +70 -0
  24. package/dist/client/mcp.d.ts.map +1 -0
  25. package/dist/client/mcp.js +65 -0
  26. package/dist/data/betterAuth.d.ts +3 -2
  27. package/dist/data/betterAuth.d.ts.map +1 -1
  28. package/dist/data/betterAuth.js +5 -3
  29. package/dist/data/kitFields.d.ts +5 -0
  30. package/dist/data/kitFields.d.ts.map +1 -1
  31. package/dist/data/kitFields.js +5 -0
  32. package/dist/data/tables.d.ts +26 -4
  33. package/dist/data/tables.d.ts.map +1 -1
  34. package/dist/data/tables.js +5 -3
  35. package/dist/data/userLifecycle.d.ts +10 -0
  36. package/dist/data/userLifecycle.d.ts.map +1 -1
  37. package/dist/data/userLifecycle.js +8 -3
  38. package/dist/data/verificationOutcome.d.ts +53 -0
  39. package/dist/data/verificationOutcome.d.ts.map +1 -0
  40. package/dist/data/verificationOutcome.js +50 -0
  41. package/dist/email/send.js +6 -2
  42. package/dist/http/adminRoutes.d.ts.map +1 -1
  43. package/dist/http/adminRoutes.js +319 -8
  44. package/dist/http/csrf.d.ts.map +1 -1
  45. package/dist/http/csrf.js +2 -1
  46. package/dist/http/guards.d.ts +15 -10
  47. package/dist/http/guards.d.ts.map +1 -1
  48. package/dist/http/guards.js +76 -10
  49. package/dist/http/handoff.d.ts +76 -0
  50. package/dist/http/handoff.d.ts.map +1 -0
  51. package/dist/http/handoff.js +316 -0
  52. package/dist/http/middleware.d.ts +37 -1
  53. package/dist/http/middleware.d.ts.map +1 -1
  54. package/dist/http/middleware.js +68 -6
  55. package/dist/http/resolve.d.ts.map +1 -1
  56. package/dist/http/resolve.js +9 -3
  57. package/dist/http/responses.d.ts +322 -0
  58. package/dist/http/responses.d.ts.map +1 -1
  59. package/dist/http/responses.js +202 -5
  60. package/dist/http/routes.d.ts +3 -0
  61. package/dist/http/routes.d.ts.map +1 -1
  62. package/dist/http/routes.js +78 -5
  63. package/dist/http/schemas.d.ts +114 -0
  64. package/dist/http/schemas.d.ts.map +1 -1
  65. package/dist/http/schemas.js +94 -1
  66. package/dist/http/views.d.ts +60 -3
  67. package/dist/http/views.d.ts.map +1 -1
  68. package/dist/http/views.js +143 -3
  69. package/dist/index.d.ts +2 -0
  70. package/dist/index.d.ts.map +1 -1
  71. package/dist/index.js +4 -2
  72. package/dist/instance/auth.d.ts +148 -10
  73. package/dist/instance/auth.d.ts.map +1 -1
  74. package/dist/instance/auth.js +87 -42
  75. package/dist/instance/plugins.d.ts +6 -0
  76. package/dist/instance/plugins.d.ts.map +1 -1
  77. package/dist/instance/plugins.js +14 -1
  78. package/dist/ledger/read.d.ts +53 -0
  79. package/dist/ledger/read.d.ts.map +1 -0
  80. package/dist/ledger/read.js +85 -0
  81. package/dist/ledger/record.d.ts +35 -0
  82. package/dist/ledger/record.d.ts.map +1 -0
  83. package/dist/ledger/record.js +98 -0
  84. package/dist/lifecycle/audited.d.ts +48 -0
  85. package/dist/lifecycle/audited.d.ts.map +1 -0
  86. package/dist/lifecycle/audited.js +65 -0
  87. package/dist/lifecycle/enforce.d.ts +37 -2
  88. package/dist/lifecycle/enforce.d.ts.map +1 -1
  89. package/dist/lifecycle/enforce.js +46 -5
  90. package/dist/lifecycle/erasure.d.ts +9 -0
  91. package/dist/lifecycle/erasure.d.ts.map +1 -0
  92. package/dist/lifecycle/erasure.js +96 -0
  93. package/dist/lifecycle/inactivity.d.ts +19 -0
  94. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  95. package/dist/lifecycle/inactivity.js +28 -0
  96. package/dist/lifecycle/reason.d.ts +11 -0
  97. package/dist/lifecycle/reason.d.ts.map +1 -0
  98. package/dist/lifecycle/reason.js +13 -0
  99. package/dist/lifecycle/request.d.ts +5 -2
  100. package/dist/lifecycle/request.d.ts.map +1 -1
  101. package/dist/lifecycle/request.js +6 -2
  102. package/dist/lifecycle/transitions.d.ts +179 -18
  103. package/dist/lifecycle/transitions.d.ts.map +1 -1
  104. package/dist/lifecycle/transitions.js +391 -70
  105. package/dist/mcp/argumentClass.d.ts +51 -0
  106. package/dist/mcp/argumentClass.d.ts.map +1 -0
  107. package/dist/mcp/argumentClass.js +69 -0
  108. package/dist/mcp/capability.d.ts +50 -0
  109. package/dist/mcp/capability.d.ts.map +1 -0
  110. package/dist/mcp/capability.js +140 -0
  111. package/dist/mcp/clientMetadata.d.ts +40 -0
  112. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  113. package/dist/mcp/clientMetadata.js +68 -0
  114. package/dist/mcp/consent.d.ts +49 -0
  115. package/dist/mcp/consent.d.ts.map +1 -0
  116. package/dist/mcp/consent.js +69 -0
  117. package/dist/mcp/dispatch.d.ts +35 -0
  118. package/dist/mcp/dispatch.d.ts.map +1 -0
  119. package/dist/mcp/dispatch.js +135 -0
  120. package/dist/mcp/floor.d.ts +37 -0
  121. package/dist/mcp/floor.d.ts.map +1 -0
  122. package/dist/mcp/floor.js +41 -0
  123. package/dist/mcp/host.d.ts +34 -0
  124. package/dist/mcp/host.d.ts.map +1 -0
  125. package/dist/mcp/host.js +2 -0
  126. package/dist/mcp/http/redirectList.d.ts +9 -0
  127. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  128. package/dist/mcp/http/redirectList.js +24 -0
  129. package/dist/mcp/http/responses.d.ts +143 -0
  130. package/dist/mcp/http/responses.d.ts.map +1 -0
  131. package/dist/mcp/http/responses.js +83 -0
  132. package/dist/mcp/http/routes.d.ts +28 -0
  133. package/dist/mcp/http/routes.d.ts.map +1 -0
  134. package/dist/mcp/http/routes.js +517 -0
  135. package/dist/mcp/http/schemas.d.ts +24 -0
  136. package/dist/mcp/http/schemas.d.ts.map +1 -0
  137. package/dist/mcp/http/schemas.js +18 -0
  138. package/dist/mcp/marker.d.ts +15 -0
  139. package/dist/mcp/marker.d.ts.map +1 -0
  140. package/dist/mcp/marker.js +15 -0
  141. package/dist/mcp/provider.d.ts +78 -0
  142. package/dist/mcp/provider.d.ts.map +1 -0
  143. package/dist/mcp/provider.js +108 -0
  144. package/dist/mcp/purge.d.ts +15 -0
  145. package/dist/mcp/purge.d.ts.map +1 -0
  146. package/dist/mcp/purge.js +31 -0
  147. package/dist/mcp/rpc.d.ts +79 -0
  148. package/dist/mcp/rpc.d.ts.map +1 -0
  149. package/dist/mcp/rpc.js +103 -0
  150. package/dist/mcp/toolAudit.d.ts +76 -0
  151. package/dist/mcp/toolAudit.d.ts.map +1 -0
  152. package/dist/mcp/toolAudit.js +86 -0
  153. package/dist/migrations/0005_purge_once.d.ts +22 -0
  154. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  155. package/dist/migrations/0005_purge_once.js +35 -0
  156. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  157. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  158. package/dist/migrations/0006_verification_outcomes.js +35 -0
  159. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  160. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  161. package/dist/migrations/0007_erasure_record.js +36 -0
  162. package/dist/migrations/0008_last_active.d.ts +15 -0
  163. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  164. package/dist/migrations/0008_last_active.js +29 -0
  165. package/dist/migrations/pluginTables.d.ts +8 -0
  166. package/dist/migrations/pluginTables.d.ts.map +1 -1
  167. package/dist/migrations/pluginTables.js +8 -1
  168. package/dist/migrations/set.d.ts +5 -1
  169. package/dist/migrations/set.d.ts.map +1 -1
  170. package/dist/migrations/set.js +10 -2
  171. package/dist/peer.d.ts +3 -2
  172. package/dist/peer.d.ts.map +1 -1
  173. package/dist/processing/activities.d.ts +6 -0
  174. package/dist/processing/activities.d.ts.map +1 -0
  175. package/dist/processing/activities.js +12 -0
  176. package/dist/purge/contribution.d.ts +62 -0
  177. package/dist/purge/contribution.d.ts.map +1 -0
  178. package/dist/purge/contribution.js +155 -0
  179. package/dist/purge/retryPolicy.d.ts +22 -0
  180. package/dist/purge/retryPolicy.d.ts.map +1 -0
  181. package/dist/purge/retryPolicy.js +26 -0
  182. package/dist/purge/run.d.ts +158 -0
  183. package/dist/purge/run.d.ts.map +1 -0
  184. package/dist/purge/run.js +205 -0
  185. package/dist/purge/specs.d.ts +71 -0
  186. package/dist/purge/specs.d.ts.map +1 -0
  187. package/dist/purge/specs.js +72 -0
  188. package/dist/purge/start.d.ts +42 -0
  189. package/dist/purge/start.d.ts.map +1 -0
  190. package/dist/purge/start.js +37 -0
  191. package/dist/purge/workflow.d.ts +71 -0
  192. package/dist/purge/workflow.d.ts.map +1 -0
  193. package/dist/purge/workflow.js +140 -0
  194. package/dist/test-utils/accountFootprint.d.ts +13 -0
  195. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  196. package/dist/test-utils/accountFootprint.js +49 -0
  197. package/dist/test-utils/liveApp.d.ts +6 -0
  198. package/dist/test-utils/liveApp.d.ts.map +1 -1
  199. package/dist/test-utils/liveApp.js +7 -2
  200. package/dist/token/handoff.d.ts +80 -0
  201. package/dist/token/handoff.d.ts.map +1 -0
  202. package/dist/token/handoff.js +136 -0
  203. package/dist/version.generated.d.ts +1 -1
  204. package/dist/version.generated.js +1 -1
  205. package/docs/account-lifecycle.md +176 -12
  206. package/docs/apple-signin.md +32 -4
  207. package/docs/facebook-oauth.md +2 -2
  208. package/docs/github-oauth.md +2 -2
  209. package/docs/google-oauth.md +9 -7
  210. package/docs/microsoft-oauth.md +2 -2
  211. package/package.json +11 -5
  212. package/pithy.manifest.json +2 -2
  213. package/pithy.mcp.manifest.json +36 -0
  214. package/src/audit/actions.ts +58 -0
  215. package/src/audit/emit.ts +66 -1
  216. package/src/audit/evidence.ts +8 -4
  217. package/src/capability.ts +122 -18
  218. package/src/client/api.ts +69 -19
  219. package/src/client/bearer.ts +388 -0
  220. package/src/client/handoff.ts +172 -0
  221. package/src/client/mcp.ts +140 -0
  222. package/src/data/betterAuth.ts +8 -4
  223. package/src/data/kitFields.ts +2 -0
  224. package/src/data/tables.ts +4 -2
  225. package/src/data/userLifecycle.ts +19 -4
  226. package/src/data/verificationOutcome.ts +86 -0
  227. package/src/email/send.ts +2 -2
  228. package/src/http/adminRoutes.ts +465 -4
  229. package/src/http/csrf.ts +4 -1
  230. package/src/http/guards.ts +79 -10
  231. package/src/http/handoff.ts +350 -0
  232. package/src/http/middleware.ts +74 -5
  233. package/src/http/resolve.ts +25 -25
  234. package/src/http/responses.ts +374 -3
  235. package/src/http/routes.ts +116 -5
  236. package/src/http/schemas.ts +195 -0
  237. package/src/http/views.ts +192 -3
  238. package/src/index.ts +2 -0
  239. package/src/instance/auth.ts +58 -3
  240. package/src/instance/plugins.ts +20 -2
  241. package/src/ledger/read.ts +133 -0
  242. package/src/ledger/record.ts +198 -0
  243. package/src/lifecycle/audited.ts +104 -0
  244. package/src/lifecycle/enforce.ts +55 -5
  245. package/src/lifecycle/erasure.ts +118 -0
  246. package/src/lifecycle/inactivity.ts +56 -0
  247. package/src/lifecycle/reason.ts +11 -0
  248. package/src/lifecycle/request.ts +10 -2
  249. package/src/lifecycle/transitions.ts +552 -93
  250. package/src/mcp/argumentClass.ts +112 -0
  251. package/src/mcp/capability.ts +194 -0
  252. package/src/mcp/clientMetadata.ts +81 -0
  253. package/src/mcp/consent.ts +95 -0
  254. package/src/mcp/dispatch.ts +154 -0
  255. package/src/mcp/floor.ts +62 -0
  256. package/src/mcp/host.ts +36 -0
  257. package/src/mcp/http/redirectList.ts +26 -0
  258. package/src/mcp/http/responses.ts +157 -0
  259. package/src/mcp/http/routes.ts +635 -0
  260. package/src/mcp/http/schemas.ts +37 -0
  261. package/src/mcp/marker.ts +18 -0
  262. package/src/mcp/provider.ts +151 -0
  263. package/src/mcp/purge.ts +39 -0
  264. package/src/mcp/rpc.ts +135 -0
  265. package/src/mcp/toolAudit.ts +132 -0
  266. package/src/migrations/0005_purge_once.ts +42 -0
  267. package/src/migrations/0006_verification_outcomes.ts +51 -0
  268. package/src/migrations/0007_erasure_record.ts +43 -0
  269. package/src/migrations/0008_last_active.ts +30 -0
  270. package/src/migrations/pluginTables.ts +19 -1
  271. package/src/migrations/set.ts +9 -1
  272. package/src/processing/activities.ts +14 -0
  273. package/src/purge/contribution.ts +218 -0
  274. package/src/purge/retryPolicy.ts +26 -0
  275. package/src/purge/run.ts +348 -0
  276. package/src/purge/specs.ts +95 -0
  277. package/src/purge/start.ts +79 -0
  278. package/src/purge/workflow.ts +202 -0
  279. package/src/seeds/example.ts +2 -2
  280. package/src/test-utils/accountFootprint.ts +104 -0
  281. package/src/test-utils/liveApp.ts +10 -1
  282. package/src/token/handoff.ts +180 -0
  283. package/src/version.generated.ts +1 -1
@@ -17,7 +17,9 @@ import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
17
17
  import type { AuthDatabase } from "../data/tables";
18
18
  import { parseDeviceMeta, registerDevice } from "../device/registry";
19
19
  import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
20
- import { lifecycleRefusalFor } from "../lifecycle/enforce";
20
+ import { verificationLedger } from "../ledger/record";
21
+ import { admitsDeletionSignIn, lifecycleRefusalFor } from "../lifecycle/enforce";
22
+ import { recordActivity } from "../lifecycle/inactivity";
21
23
  import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile";
22
24
  import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
23
25
  import { microsoftProfileToUser } from "./microsoftEmail";
@@ -378,6 +380,9 @@ export type AuthInstance<Plugins extends readonly BetterAuthPlugin[] = readonly
378
380
  * UUIDs; rate limiting is durable (D1-backed) since memory limiting is per-isolate on Workers.
379
381
  */
380
382
  export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps: AuthInstanceDeps<Plugins>) {
383
+ // The verification ledger (#829): written from three database hooks below and from the send callback the kit's
384
+ // own plugins close over, so one instance of it pairs what each of them saw in a request. See `../ledger/record.ts`.
385
+ const ledger = verificationLedger(deps.db);
381
386
  return betterAuth({
382
387
  appName: "Pithy",
383
388
  baseURL: deps.baseURL,
@@ -412,6 +417,27 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
412
417
  // outcome is by throwing, which is what this is.
413
418
  onAPIError: { throw: true },
414
419
  databaseHooks: {
420
+ /**
421
+ * The verification ledger's two hooks on Better Auth's own verification rows (#829).
422
+ *
423
+ * **`create.after` remembers the row** — a sign-in link or code about to be sent, OAuth state, or a wrong
424
+ * code re-created with one more attempt counted; `../ledger/record.ts` tells them apart by what follows.
425
+ * **`delete.before` remembers the row about to be consumed**, and changes nothing: it returns nothing, so it
426
+ * never vetoes, and it is not a `delete.after` because claiming a verification removal the way
427
+ * `claimedDelete` does would delete the row before the consume could read it.
428
+ */
429
+ verification: {
430
+ create: {
431
+ after: async (verification, ctx) => {
432
+ await ledger.created(verification, (ctx as { context?: unknown } | null | undefined)?.context);
433
+ },
434
+ },
435
+ delete: {
436
+ before: async (verification, ctx) => {
437
+ ledger.consuming(verification, (ctx as { context?: unknown } | null | undefined)?.context);
438
+ },
439
+ },
440
+ },
415
441
  user: {
416
442
  create: {
417
443
  // Seeding guard: refuse to create a user whose email a provider has not verified. Every
@@ -522,8 +548,13 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
522
548
  // so this one check is what makes a suspension hold at every door, and the reason it is not
523
549
  // written once per endpoint. The row is read rather than trusted from the caller: nothing
524
550
  // that arrives with a sign-in may say whether its own account is suspended.
551
+ //
552
+ // **One exception: a suspended account that signs in to delete itself (#622).** The app stores
553
+ // require that a person can always leave, and a suspension has already revoked every session the
554
+ // account held. The session this admits is still a suspended account's, so every request it makes
555
+ // is refused except `DELETE /auth/account` — see `admitsDeletionSignIn`.
525
556
  const refusal = await lifecycleRefusalFor(deps.db, session.userId, null, new Date());
526
- if (refusal) refuseSession(refusal, ctx);
557
+ if (refusal && !admitsDeletionSignIn(refusal, ctx?.headers)) refuseSession(refusal, ctx);
527
558
  // **`undefined` and `null` are different answers here, and collapsing them is a hole.**
528
559
  // Absent means nobody supplied one, which is a sign-in: stamp it. Present-and-null is a
529
560
  // rotation of a session written before the column existed, and it must stay null so the gate
@@ -540,6 +571,30 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
540
571
  });
541
572
  return { data: { ...session, deviceId: meta.id, authenticatedAt } };
542
573
  },
574
+ /**
575
+ * Stamp the sign-in link or code this session was made from as used (#829), and name the account a
576
+ * sign-up just created. Only a row consumed earlier in this same request is stamped, so a token
577
+ * refresh, an OAuth callback and every other session stamp nothing — see `../ledger/record.ts`.
578
+ * After, because the session exists by now: a sign-in the `before` above refused stamps nothing.
579
+ */
580
+ after: async (session, ctx) => {
581
+ await ledger.signedIn((ctx as { context?: unknown } | null | undefined)?.context, session.userId);
582
+ // The account's activity clock, which the retention policy's class ages count from. After, so a
583
+ // refused sign-in stamps nothing; swallowed, because the session it records already exists.
584
+ await recordActivity(deps.db, session.userId, new Date()).catch(() => undefined);
585
+ },
586
+ },
587
+ update: {
588
+ /**
589
+ * The activity clock again, for a session that stays open. Better Auth slides a session forward in place
590
+ * once `updateAge` has passed, and that refresh is an update, never a create, so the hook above never
591
+ * sees it. Without this, signing out after weeks of use on one session would read as weeks idle.
592
+ */
593
+ after: async (session) => {
594
+ const userId = (session as { userId?: unknown } | null)?.userId;
595
+ if (typeof userId !== "string") return;
596
+ await recordActivity(deps.db, userId, new Date()).catch(() => undefined);
597
+ },
543
598
  },
544
599
  /**
545
600
  * Tell whoever keyed state on this session that it has gone, and record that it did.
@@ -725,6 +780,6 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
725
780
  // endpoints by id and a later registration wins, so composing the adopter's list first would let
726
781
  // it quietly redefine the sign-in this product promises. `assertAdditivePlugins` has already
727
782
  // refused a list that names one of the four; this order is what makes that refusal the only way in.
728
- plugins: [...kitPlugins(deps), ...deps.plugins],
783
+ plugins: [...kitPlugins({ ...deps, ledger }), ...deps.plugins],
729
784
  });
730
785
  }
@@ -10,8 +10,9 @@ import { emailOTP } from "better-auth/plugins/email-otp";
10
10
  import { jwt } from "better-auth/plugins/jwt";
11
11
  import { magicLink } from "better-auth/plugins/magic-link";
12
12
  import { z } from "zod";
13
- import { markMessageDelivery, SEND_FAULT } from "../audit/evidence";
13
+ import { type AuthEmailDelivery, markMessageDelivery, SEND_FAULT } from "../audit/evidence";
14
14
  import { authErrorTranslations } from "../i18n/errorCopy";
15
+ import type { VerificationLedger } from "../ledger/record";
15
16
  import type { AuthEmailMessage, SendAuthEmail } from "./auth";
16
17
  import { PROVIDER_SIGN_IN_GATE_ID, providerSignInGate } from "./providerSignInGate";
17
18
  import { refusalTransportVerdict } from "./refusalTransport";
@@ -66,6 +67,11 @@ export interface KitPluginDeps {
66
67
  * built the instance — the schema baseline, a seed, a unit test. See `./providerSignInGate`.
67
68
  */
68
69
  requestHeaders?: Headers;
70
+ /**
71
+ * The verification ledger (#829) — told what each send was and which mail carries it, once the email seam
72
+ * has answered. Absent where no instance will ever send: the schema baseline in `../migrations/pluginTables.ts`.
73
+ */
74
+ ledger?: VerificationLedger;
69
75
  }
70
76
 
71
77
  /**
@@ -186,12 +192,24 @@ async function sendAndRecord(
186
192
  ctx: { context?: unknown } | undefined,
187
193
  ): Promise<void> {
188
194
  const requestContext = ctx?.context;
195
+ const type = message.template === "magicLink" ? "magic_link" : "otp";
196
+ let delivery: AuthEmailDelivery;
189
197
  try {
190
- markMessageDelivery(requestContext, await deps.sendEmail(message));
198
+ delivery = await deps.sendEmail(message);
191
199
  } catch (error) {
192
200
  markMessageDelivery(requestContext, { delivery: "failed", reason: SEND_FAULT });
201
+ // The link exists whether or not its mail does, so the ledger counts it, with no job to join.
202
+ await deps.ledger?.issued(requestContext, { type, email: message.to, emailJobId: null });
193
203
  throw error;
194
204
  }
205
+ markMessageDelivery(requestContext, delivery);
206
+ // A withheld message has a job too — the suppressed row — and that row is what a reader joins a
207
+ // suppression on, so it is recorded exactly like a queued one.
208
+ await deps.ledger?.issued(requestContext, {
209
+ type,
210
+ email: message.to,
211
+ emailJobId: delivery.delivery === "failed" ? null : (delivery.jobId ?? null),
212
+ });
195
213
  }
196
214
 
197
215
  /** Is this value shaped like a Better Auth plugin — an object carrying a non-empty string `id`? */
@@ -0,0 +1,133 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { decodeCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
6
+ import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
7
+ import { sql } from "kysely";
8
+ import type { AdminPage } from "../admin/users";
9
+ import type { AuthDatabase } from "../data/tables";
10
+ import { VerificationOutcome, type VerificationState, VerificationType } from "../data/verificationOutcome";
11
+ import type { VerificationTypeCounts } from "../http/responses";
12
+
13
+ /**
14
+ * Reading the verification ledger (#829): what `GET {auth}/admin/verifications` answers.
15
+ *
16
+ * Two reads over one window of issue times: the counts by type and state, and the rows themselves, paged. The
17
+ * state is computed at read time — an unused row becomes expired the moment its expiry passes, with nothing
18
+ * written — so both reads take the same `now`, and a row counted as pending is listed as pending.
19
+ */
20
+
21
+ /** How far back a window reaches when the caller names no start. */
22
+ export const DEFAULT_WINDOW_DAYS = 30;
23
+
24
+ /** A window of issue times: `since` inclusive, `until` exclusive. */
25
+ export interface VerificationWindow {
26
+ since: Date;
27
+ until: Date;
28
+ }
29
+
30
+ /**
31
+ * The window a read covers. `until` defaults to now and `since` to 30 days before it; a window that ends where it
32
+ * starts, or before, is refused rather than answered with nothing, because an empty answer would read as "no
33
+ * sign-ins".
34
+ */
35
+ export function resolveVerificationWindow(input: { since?: Date; until?: Date }, now: Date): VerificationWindow {
36
+ const until = input.until ?? now;
37
+ const since = input.since ?? new Date(until.getTime() - DEFAULT_WINDOW_DAYS * 86_400_000);
38
+ if (since.getTime() >= until.getTime()) {
39
+ throw new ValidationError({
40
+ message: "The window must start before it ends.",
41
+ detail: `since ${since.toISOString()} is not before until ${until.toISOString()}`,
42
+ });
43
+ }
44
+ return { since, until };
45
+ }
46
+
47
+ /**
48
+ * The counts by type and state over a window: one aggregate, grouped by type, and every type answered — a type
49
+ * nothing was issued for reads as zeros rather than going missing, so a reader never has to tell "none" from
50
+ * "not reported".
51
+ */
52
+ export async function verificationCounts(
53
+ db: AuthDatabase,
54
+ window: VerificationWindow,
55
+ now: Date,
56
+ ): Promise<VerificationTypeCounts[]> {
57
+ const at = SQLiteDate.encode(now);
58
+ const rows = await db
59
+ .selectFrom("pithyAuthVerificationOutcomes")
60
+ .select((eb) => [
61
+ "type",
62
+ eb.fn.countAll<number>().as("issued"),
63
+ sql<number>`sum(case when ${eb.ref("usedAt")} is not null then 1 else 0 end)`.as("used"),
64
+ sql<number>`sum(case when ${eb.ref("usedAt")} is null and ${eb.ref("expiresAt")} <= ${at} then 1 else 0 end)`.as(
65
+ "expired",
66
+ ),
67
+ ])
68
+ .where("issuedAt", ">=", SQLiteDate.encode(window.since))
69
+ .where("issuedAt", "<", SQLiteDate.encode(window.until))
70
+ .groupBy("type")
71
+ .execute();
72
+ return VerificationType.options.map((type) => {
73
+ const row = rows.find((candidate) => candidate.type === type);
74
+ const issued = Number(row?.issued ?? 0);
75
+ const used = Number(row?.used ?? 0);
76
+ const expired = Number(row?.expired ?? 0);
77
+ return { type, issued, used, expired, pending: issued - used - expired };
78
+ });
79
+ }
80
+
81
+ /** What the row listing filters on and where it resumes. */
82
+ export interface ListVerificationOutcomesOptions {
83
+ window: VerificationWindow;
84
+ /** Only this type. */
85
+ type?: VerificationType | undefined;
86
+ /** Only rows in this state at `now`. */
87
+ state?: VerificationState | undefined;
88
+ /** The moment `state` is judged at — the same `now` the counts took. */
89
+ now: Date;
90
+ cursor?: string | undefined;
91
+ limit?: number | undefined;
92
+ }
93
+
94
+ /**
95
+ * The window's rows, newest issue first, paged by keyset on `(issuedAt, id)` — the index the migration built for
96
+ * exactly this. A malformed cursor is a first page, as everywhere in the kit.
97
+ */
98
+ export async function listVerificationOutcomes(
99
+ db: AuthDatabase,
100
+ options: ListVerificationOutcomesOptions,
101
+ ): Promise<AdminPage<VerificationOutcome>> {
102
+ const limit = pageLimit(options.limit);
103
+ const at = SQLiteDate.encode(options.now);
104
+ let query = db
105
+ .selectFrom("pithyAuthVerificationOutcomes")
106
+ .selectAll()
107
+ .where("issuedAt", ">=", SQLiteDate.encode(options.window.since))
108
+ .where("issuedAt", "<", SQLiteDate.encode(options.window.until))
109
+ .orderBy("issuedAt", "desc")
110
+ .orderBy("id", "desc")
111
+ .limit(limit + 1);
112
+ if (options.type) query = query.where("type", "=", options.type);
113
+ if (options.state === "used") query = query.where("usedAt", "is not", null);
114
+ if (options.state === "expired") query = query.where("usedAt", "is", null).where("expiresAt", "<=", at);
115
+ if (options.state === "pending") query = query.where("usedAt", "is", null).where("expiresAt", ">", at);
116
+
117
+ const cursor = decodeCursor(options.cursor);
118
+ const sort = cursor ? Number(cursor.sort) : Number.NaN;
119
+ const id = cursor ? Number(cursor.id) : Number.NaN;
120
+ // A cursor whose halves are not both numbers came from some other listing. It reads as a first page.
121
+ if (Number.isFinite(sort) && Number.isFinite(id)) {
122
+ query = query.where((eb) =>
123
+ eb.or([eb("issuedAt", "<", sort), eb.and([eb("issuedAt", "=", sort), eb("id", "<", id)])]),
124
+ );
125
+ }
126
+
127
+ const rows = await query.execute();
128
+ return toPage(
129
+ rows.map((row) => VerificationOutcome.parse(row)),
130
+ limit,
131
+ (row) => ({ sort: row.issuedAt.getTime(), id: row.id }),
132
+ );
133
+ }
@@ -0,0 +1,198 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import type { AuthDatabase } from "../data/tables";
6
+ import type { VerificationType } from "../data/verificationOutcome";
7
+
8
+ /**
9
+ * Writing the verification ledger (#829): a row when auth issues a sign-in link or code, a stamp when one is used.
10
+ *
11
+ * ## Four moments, one request each, and none of them knows everything
12
+ *
13
+ * Better Auth creates the verification row, then calls the kit's send callback, then — in a later request —
14
+ * consumes the row and creates a session. No single one of those holds the whole record:
15
+ *
16
+ * - **`verification.create.after`** has the row's id and expiry, and no idea what it is for: the same table
17
+ * holds OAuth state.
18
+ * - **The send callback** knows it is a sign-in link or code and, once the email seam answers, the job that
19
+ * carries it — and not the row's id, which Better Auth never hands it.
20
+ * - **`verification.delete.before`** sees the row about to be consumed, and not whether the consume wins.
21
+ * - **`session.create.after`** knows somebody signed in, and as whom, and not with what.
22
+ *
23
+ * So each moment leaves what it saw on the request, and the next one in the same request completes the record:
24
+ * the send pairs with the row created just before it, and the session pairs with the row consumed just before
25
+ * it. The request is the endpoint's own per-dispatch context object — the one `../audit/evidence.ts` keys on,
26
+ * which Better Auth hands to database hooks and send callbacks alike — held weakly, so nothing outlives it.
27
+ *
28
+ * ## Why the pairing is safe
29
+ *
30
+ * - **A row created and never sent is never recorded.** OAuth state, and a code Better Auth's own enumeration
31
+ * guard drops before the send, both stop at the first moment.
32
+ * - **A consume that loses, or one that ends in a refusal, is never stamped.** Only a session created in the
33
+ * same request stamps it, and Better Auth creates none unless the consume returned the row.
34
+ * - **A row consumed for any other reason matches nothing.** An OAuth callback deletes its state row and
35
+ * creates a session; the stamp looks for that id in the ledger and finds no row.
36
+ * - **A wrong code moves its row.** Better Auth consumes the code to check it, and on a mismatch creates a new
37
+ * row with the same value and expiry and one more attempt counted. Recognized by that expiry, the ledger row
38
+ * follows it, so the right code entered next stamps the row the mail was counted against.
39
+ *
40
+ * ## Never fatal
41
+ *
42
+ * A ledger write that fails is swallowed. The ledger reports on sign-in; it must never be the reason one fails,
43
+ * and every caller here is mid-sign-in.
44
+ *
45
+ * **Not through `delete.after`**, deliberately: every `delete.after` in this package goes through `claimedDelete`
46
+ * (`../audit/evidence.ts`), and claiming a verification removal would delete the row before the consume could
47
+ * read it. `delete.before` sees the same row and changes nothing.
48
+ */
49
+
50
+ /** What one request has seen so far. */
51
+ interface Pending {
52
+ /** The verification row created in this request, awaiting the send that says what it is for. */
53
+ created?: { id: string; issuedAt: Date; expiresAt: Date };
54
+ /** The live verification row about to be consumed in this request, awaiting the session that proves its use. */
55
+ consuming?: { id: string; expiresAt: Date };
56
+ }
57
+
58
+ /** The verification ledger's four writers. */
59
+ export interface VerificationLedger {
60
+ /** `verification.create.after`: remember the row, and move a wrong code's ledger row onto its re-issue. */
61
+ created(row: unknown, requestContext: unknown): Promise<void>;
62
+ /** `verification.delete.before`: remember the live row about to be consumed. */
63
+ consuming(row: unknown, requestContext: unknown): void;
64
+ /** The send callback, once the email seam has answered: record the row created in this request. */
65
+ issued(requestContext: unknown, input: IssuedInput): Promise<void>;
66
+ /** `session.create.after`: stamp the row consumed in this request as used, by this user. */
67
+ signedIn(requestContext: unknown, userId: unknown): Promise<void>;
68
+ }
69
+
70
+ /** What the send callback knows. The address is read to find the account and is never stored. */
71
+ export interface IssuedInput {
72
+ /** What was issued. */
73
+ type: VerificationType;
74
+ /** Who it was sent to — looked up, never written. */
75
+ email: string;
76
+ /** The `pithy_email_jobs` row that carries it, or null when the seam queued nothing. */
77
+ emailJobId: string | null;
78
+ }
79
+
80
+ /** A date off a Better Auth row: a `Date` from the adapter, an ISO string or a number from anywhere else. */
81
+ export function dateOf(value: unknown): Date | null {
82
+ const date =
83
+ value instanceof Date ? value : typeof value === "string" || typeof value === "number" ? new Date(value) : null;
84
+ return date && Number.isFinite(date.getTime()) ? date : null;
85
+ }
86
+
87
+ /** The id and dates off a verification row, or null for anything not shaped like one. */
88
+ export function verificationRowOf(row: unknown): { id: string; createdAt: Date | null; expiresAt: Date } | null {
89
+ if (typeof row !== "object" || row === null) return null;
90
+ const { id, createdAt, expiresAt } = row as { id?: unknown; createdAt?: unknown; expiresAt?: unknown };
91
+ if (typeof id !== "string" || id === "") return null;
92
+ const expires = dateOf(expiresAt);
93
+ if (!expires) return null;
94
+ return { id, createdAt: dateOf(createdAt), expiresAt: expires };
95
+ }
96
+
97
+ /** Build the ledger's writers over one database. `now` is injectable for the tests that pin a clock. */
98
+ export function verificationLedger(db: AuthDatabase, now: () => Date = () => new Date()): VerificationLedger {
99
+ const pending = new WeakMap<object, Pending>();
100
+ const stateOf = (requestContext: unknown): Pending | null => {
101
+ if (typeof requestContext !== "object" || requestContext === null) return null;
102
+ let state = pending.get(requestContext);
103
+ if (!state) {
104
+ state = {};
105
+ pending.set(requestContext, state);
106
+ }
107
+ return state;
108
+ };
109
+
110
+ return {
111
+ async created(row, requestContext) {
112
+ const state = stateOf(requestContext);
113
+ const verification = verificationRowOf(row);
114
+ if (!state || !verification) return;
115
+ const consumed = state.consuming;
116
+ // A wrong code: consumed to be checked, and re-created with the same expiry. The ledger row follows it.
117
+ if (consumed && consumed.expiresAt.getTime() === verification.expiresAt.getTime()) {
118
+ state.consuming = undefined;
119
+ await swallow(() =>
120
+ db
121
+ .updateTable("pithyAuthVerificationOutcomes")
122
+ .set({ verificationId: verification.id })
123
+ .where("verificationId", "=", consumed.id)
124
+ .execute(),
125
+ );
126
+ }
127
+ state.created = {
128
+ id: verification.id,
129
+ issuedAt: verification.createdAt ?? now(),
130
+ expiresAt: verification.expiresAt,
131
+ };
132
+ },
133
+
134
+ consuming(row, requestContext) {
135
+ const state = stateOf(requestContext);
136
+ const verification = verificationRowOf(row);
137
+ if (!state || !verification) return;
138
+ // An expired row is being swept, not consumed: Better Auth's cleanup deletes those on any read.
139
+ if (verification.expiresAt.getTime() <= now().getTime()) return;
140
+ state.consuming = { id: verification.id, expiresAt: verification.expiresAt };
141
+ },
142
+
143
+ async issued(requestContext, input) {
144
+ const state = stateOf(requestContext);
145
+ const created = state?.created;
146
+ if (!state || !created) return;
147
+ state.created = undefined;
148
+ await swallow(async () => {
149
+ const user = await db
150
+ .selectFrom("pithyAuthUsers")
151
+ .select("id")
152
+ // Better Auth stores and finds emails lowercased; `/sign-in/magic-link` hands the address on as typed.
153
+ .where("email", "=", input.email.toLowerCase())
154
+ .executeTakeFirst();
155
+ await db
156
+ .insertInto("pithyAuthVerificationOutcomes")
157
+ .values({
158
+ verificationId: created.id,
159
+ type: input.type,
160
+ userId: user?.id ?? null,
161
+ emailJobId: input.emailJobId,
162
+ issuedAt: SQLiteDate.encode(created.issuedAt),
163
+ expiresAt: SQLiteDate.encode(created.expiresAt),
164
+ usedAt: null,
165
+ })
166
+ .execute();
167
+ });
168
+ },
169
+
170
+ async signedIn(requestContext, userId) {
171
+ const state = stateOf(requestContext);
172
+ const consumed = state?.consuming;
173
+ if (!state || !consumed || typeof userId !== "string" || userId === "") return;
174
+ state.consuming = undefined;
175
+ await swallow(() =>
176
+ db
177
+ .updateTable("pithyAuthVerificationOutcomes")
178
+ .set((eb) => ({
179
+ usedAt: SQLiteDate.encode(now()),
180
+ // A sign-up's row had no account to name at issue; the one its use just created is it.
181
+ userId: eb.fn.coalesce("userId", eb.val(userId)),
182
+ }))
183
+ .where("verificationId", "=", consumed.id)
184
+ .where("usedAt", "is", null)
185
+ .execute(),
186
+ );
187
+ },
188
+ };
189
+ }
190
+
191
+ /** Run a ledger write and drop its failure: the ledger reports on sign-in and is never the reason one fails. */
192
+ async function swallow(write: () => Promise<unknown>): Promise<void> {
193
+ try {
194
+ await write();
195
+ } catch {
196
+ // Deliberately empty. See the file header: every caller is mid-sign-in.
197
+ }
198
+ }
@@ -0,0 +1,104 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
5
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
6
+ import { emitControlPlaneAction } from "../audit/emit";
7
+
8
+ /**
9
+ * Every control-plane lifecycle call is audited, including the ones that changed nothing (#621).
10
+ *
11
+ * A transition that moves the account writes its own audit event, beside the history row, in
12
+ * `./transitions.ts`. That leaves two kinds of call with no event, and both matter to somebody reading the
13
+ * trail after an incident: **a refusal** — an unknown account, a deleted one, an end in the past — which says
14
+ * a credential was trying, and **a call that found the account already where it asked to put it**, which
15
+ * says somebody pressed the button. This records both, under the same action as the transition, so one
16
+ * filter finds every attempt: a refusal is `denied` (or `failure` for a fault) with the code, and a no-op is
17
+ * a `success` with `changed: false`. A refusal is still thrown, unchanged.
18
+ *
19
+ * A body the route's validator refuses never reaches the call, so the route records it with
20
+ * {@link recordLifecycleRefusal}, on the same event, before the 400 is thrown.
21
+ */
22
+
23
+ /** Who called, about whom, and why — what every lifecycle audit event carries. */
24
+ export interface LifecycleCall {
25
+ /** The audit action the transition writes when it moves the account. */
26
+ readonly action: string;
27
+ /** The management client's verified `sub`: which person acted. */
28
+ readonly subject: string;
29
+ /** The connection the call came through. */
30
+ readonly connectionId: string;
31
+ /** The account acted on. */
32
+ readonly userId: string;
33
+ /** The reason the caller gave — `null` for a refused body that carried none. */
34
+ readonly reason: string | null;
35
+ /** The request's correlation. */
36
+ readonly ip?: string | undefined;
37
+ readonly userAgent?: string | undefined;
38
+ readonly requestId?: string | undefined;
39
+ }
40
+
41
+ /** The public code of a thrown error, or `core/internal` for anything that is not a `PithyError`. */
42
+ function codeOf(error: unknown): string {
43
+ return error instanceof PithyError ? error.payload.code : "core/internal";
44
+ }
45
+
46
+ /** A refusal this Worker made on purpose is `denied`; a fault, a 5xx or a throw that is not ours, `failure`. */
47
+ function outcomeOf(error: unknown): "denied" | "failure" {
48
+ return error instanceof PithyError && error.payload.status < 500 ? "denied" : "failure";
49
+ }
50
+
51
+ /** The event every lifecycle audit record shares, before its outcome and metadata. */
52
+ function eventOf(call: LifecycleCall) {
53
+ return {
54
+ action: call.action,
55
+ subject: call.subject,
56
+ connectionId: call.connectionId,
57
+ resourceType: "user",
58
+ resourceId: call.userId,
59
+ ip: call.ip,
60
+ userAgent: call.userAgent,
61
+ requestId: call.requestId,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Record one refused lifecycle call — `denied` with its code, or `failure` for a fault. `code` names the
67
+ * refusal when the thrown error carries none of its own, as a body Hono could not parse does not.
68
+ */
69
+ export async function recordLifecycleRefusal(
70
+ emit: AuditEmit,
71
+ call: LifecycleCall,
72
+ error: unknown,
73
+ fallback?: { code: string; outcome: "denied" | "failure" },
74
+ ): Promise<void> {
75
+ const ours = error instanceof PithyError;
76
+ await emitControlPlaneAction(emit, {
77
+ ...eventOf(call),
78
+ outcome: ours || !fallback ? outcomeOf(error) : fallback.outcome,
79
+ metadata: { reason: call.reason, changed: false, code: ours || !fallback ? codeOf(error) : fallback.code },
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Run one lifecycle call and audit whatever the transition did not. `unchanged` says whether a result is a
85
+ * call that changed nothing; the event for a call that did change something is the transition's own.
86
+ */
87
+ export async function auditedLifecycleCall<T>(
88
+ emit: AuditEmit,
89
+ call: LifecycleCall,
90
+ run: () => Promise<T>,
91
+ unchanged: (result: T) => boolean,
92
+ ): Promise<T> {
93
+ let result: T;
94
+ try {
95
+ result = await run();
96
+ } catch (error) {
97
+ await recordLifecycleRefusal(emit, call, error);
98
+ throw error;
99
+ }
100
+ if (unchanged(result)) {
101
+ await emitControlPlaneAction(emit, { ...eventOf(call), metadata: { reason: call.reason, changed: false } });
102
+ }
103
+ return result;
104
+ }
@@ -68,6 +68,14 @@ export async function lifecycleRefusalFor(
68
68
  return lifecycleRefusal(userId, standing, reason);
69
69
  }
70
70
 
71
+ /** The holder of a refused credential: whose session it is. Known because the credential itself is genuine. */
72
+ export interface RefusedHolder {
73
+ /** The account the session belongs to. */
74
+ readonly userId: string;
75
+ /** The session the request presented. */
76
+ readonly sessionId: string;
77
+ }
78
+
71
79
  /**
72
80
  * The refusal the session middleware reached for this request, keyed by the request's context.
73
81
  *
@@ -75,15 +83,57 @@ export async function lifecycleRefusalFor(
75
83
  * capability's own guards read — a refused account already has no `AuthContext`, which is the part every
76
84
  * other capability's guard needs. Keyed by the context the way `../http/resolve.ts` caches the instance, so
77
85
  * it dies with the request.
86
+ *
87
+ * **The holder rides with it (#622).** A suspended account may still delete itself — the app stores require
88
+ * that a person can always leave — and that one route has to know whose account the refused credential
89
+ * opens. Nothing else reads it: the holder is reachable only through `accountHolder`, and only that route uses it.
78
90
  */
79
- const refusals = new WeakMap<object, PithyError>();
91
+ const refusals = new WeakMap<object, { refusal: PithyError; holder: RefusedHolder | undefined }>();
80
92
 
81
- /** Remember that this request's credential belongs to an account that may not act. */
82
- export function noteRefusal(context: object, refusal: PithyError): void {
83
- refusals.set(context, refusal);
93
+ /** Remember that this request's credential belongs to an account that may not act, and whose it is. */
94
+ export function noteRefusal(context: object, refusal: PithyError, holder?: RefusedHolder): void {
95
+ refusals.set(context, { refusal, holder });
84
96
  }
85
97
 
86
98
  /** The refusal the session middleware reached for this request, if it reached one. */
87
99
  export function noticedRefusal(context: object): PithyError | undefined {
88
- return refusals.get(context);
100
+ return refusals.get(context)?.refusal;
101
+ }
102
+
103
+ /**
104
+ * The holder of a **suspended** account's credential on this request, or `undefined` (#622).
105
+ *
106
+ * Only a suspension: a deleted account has nothing left to delete, and a check that could not be made has
107
+ * established nobody. The one reader is the self-service deletion, through `../http/middleware.ts`.
108
+ */
109
+ export function suspendedHolder(context: object): RefusedHolder | undefined {
110
+ const noted = refusals.get(context);
111
+ return noted?.refusal.payload.code === "auth/account_suspended" ? noted.holder : undefined;
112
+ }
113
+
114
+ /**
115
+ * The header a sign-in carries to ask for a session that can do nothing but delete its account, and the one
116
+ * value it takes (#622).
117
+ *
118
+ * A suspension revokes every session the account holds and refuses every new one, so without this a suspended
119
+ * person would hold no credential and could get none — and the one route a suspension leaves open, deleting the
120
+ * account, would be one nobody could reach. With it, the sign-in completes: the person still proves who they are,
121
+ * by the code, the link or the provider, exactly as for any sign-in. **The session that results is still a
122
+ * suspended account's**, so the session middleware refuses it everywhere, Better Auth's own endpoints included,
123
+ * and only `DELETE /auth/account` admits it. Nothing about the header is trusted beyond that: it asks for a
124
+ * session no more capable than none, save for leaving.
125
+ */
126
+ export const ACCOUNT_DELETION_INTENT_HEADER = "x-pithy-intent";
127
+ /** The value of `ACCOUNT_DELETION_INTENT_HEADER` that asks for a deletion-only session. */
128
+ export const ACCOUNT_DELETION_INTENT = "delete-account";
129
+
130
+ /**
131
+ * Whether a sign-in refused with `refusal` may still create its session: only a **suspended** account's, and only
132
+ * when the request asks for nothing but deleting it. A deleted account has nothing left to delete, and a check
133
+ * that could not be made has established nobody, so neither is admitted.
134
+ */
135
+ export function admitsDeletionSignIn(refusal: PithyError, headers: Headers | null | undefined): boolean {
136
+ if (refusal.payload.code !== "auth/account_suspended") return false;
137
+ const asked = headers?.get(ACCOUNT_DELETION_INTENT_HEADER)?.trim().toLowerCase();
138
+ return asked === ACCOUNT_DELETION_INTENT;
89
139
  }