@pithy-sh/auth 0.11.0 → 0.12.1

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 (246) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/actions.d.ts +39 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +40 -1
  5. package/dist/audit/emit.d.ts +34 -0
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +47 -1
  8. package/dist/audit/evidence.d.ts +8 -2
  9. package/dist/audit/evidence.d.ts.map +1 -1
  10. package/dist/capability.d.ts +31 -11
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +38 -5
  13. package/dist/client/api.d.ts +55 -12
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +57 -18
  16. package/dist/client/bearer.d.ts +110 -0
  17. package/dist/client/bearer.d.ts.map +1 -0
  18. package/dist/client/bearer.js +265 -0
  19. package/dist/client/handoff.d.ts +77 -0
  20. package/dist/client/handoff.d.ts.map +1 -0
  21. package/dist/client/handoff.js +119 -0
  22. package/dist/client/mcp.d.ts +70 -0
  23. package/dist/client/mcp.d.ts.map +1 -0
  24. package/dist/client/mcp.js +65 -0
  25. package/dist/data/betterAuth.d.ts +3 -2
  26. package/dist/data/betterAuth.d.ts.map +1 -1
  27. package/dist/data/betterAuth.js +5 -3
  28. package/dist/data/kitFields.d.ts +5 -0
  29. package/dist/data/kitFields.d.ts.map +1 -1
  30. package/dist/data/kitFields.js +5 -0
  31. package/dist/data/tables.d.ts +25 -4
  32. package/dist/data/tables.d.ts.map +1 -1
  33. package/dist/data/tables.js +5 -3
  34. package/dist/data/userLifecycle.d.ts +9 -0
  35. package/dist/data/userLifecycle.d.ts.map +1 -1
  36. package/dist/data/userLifecycle.js +6 -2
  37. package/dist/data/verificationOutcome.d.ts +53 -0
  38. package/dist/data/verificationOutcome.d.ts.map +1 -0
  39. package/dist/data/verificationOutcome.js +50 -0
  40. package/dist/email/send.js +6 -2
  41. package/dist/http/adminRoutes.d.ts.map +1 -1
  42. package/dist/http/adminRoutes.js +56 -10
  43. package/dist/http/csrf.d.ts.map +1 -1
  44. package/dist/http/csrf.js +2 -1
  45. package/dist/http/guards.d.ts +15 -11
  46. package/dist/http/guards.d.ts.map +1 -1
  47. package/dist/http/guards.js +46 -11
  48. package/dist/http/handoff.d.ts +76 -0
  49. package/dist/http/handoff.d.ts.map +1 -0
  50. package/dist/http/handoff.js +316 -0
  51. package/dist/http/middleware.d.ts +12 -0
  52. package/dist/http/middleware.d.ts.map +1 -1
  53. package/dist/http/middleware.js +25 -4
  54. package/dist/http/resolve.d.ts.map +1 -1
  55. package/dist/http/resolve.js +9 -3
  56. package/dist/http/responses.d.ts +142 -0
  57. package/dist/http/responses.d.ts.map +1 -1
  58. package/dist/http/responses.js +66 -10
  59. package/dist/http/routes.d.ts +2 -0
  60. package/dist/http/routes.d.ts.map +1 -1
  61. package/dist/http/routes.js +35 -4
  62. package/dist/http/schemas.d.ts +57 -0
  63. package/dist/http/schemas.d.ts.map +1 -1
  64. package/dist/http/schemas.js +44 -1
  65. package/dist/http/views.d.ts +22 -2
  66. package/dist/http/views.d.ts.map +1 -1
  67. package/dist/http/views.js +40 -4
  68. package/dist/index.d.ts +2 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/instance/auth.d.ts +148 -10
  72. package/dist/instance/auth.d.ts.map +1 -1
  73. package/dist/instance/auth.js +86 -41
  74. package/dist/instance/plugins.d.ts +6 -0
  75. package/dist/instance/plugins.d.ts.map +1 -1
  76. package/dist/instance/plugins.js +14 -1
  77. package/dist/ledger/read.d.ts +53 -0
  78. package/dist/ledger/read.d.ts.map +1 -0
  79. package/dist/ledger/read.js +85 -0
  80. package/dist/ledger/record.d.ts +35 -0
  81. package/dist/ledger/record.d.ts.map +1 -0
  82. package/dist/ledger/record.js +98 -0
  83. package/dist/lifecycle/erasure.d.ts +9 -0
  84. package/dist/lifecycle/erasure.d.ts.map +1 -0
  85. package/dist/lifecycle/erasure.js +96 -0
  86. package/dist/lifecycle/inactivity.d.ts +19 -0
  87. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  88. package/dist/lifecycle/inactivity.js +28 -0
  89. package/dist/lifecycle/transitions.d.ts +22 -1
  90. package/dist/lifecycle/transitions.d.ts.map +1 -1
  91. package/dist/lifecycle/transitions.js +51 -4
  92. package/dist/mcp/argumentClass.d.ts +51 -0
  93. package/dist/mcp/argumentClass.d.ts.map +1 -0
  94. package/dist/mcp/argumentClass.js +69 -0
  95. package/dist/mcp/capability.d.ts +50 -0
  96. package/dist/mcp/capability.d.ts.map +1 -0
  97. package/dist/mcp/capability.js +140 -0
  98. package/dist/mcp/clientMetadata.d.ts +40 -0
  99. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  100. package/dist/mcp/clientMetadata.js +68 -0
  101. package/dist/mcp/consent.d.ts +49 -0
  102. package/dist/mcp/consent.d.ts.map +1 -0
  103. package/dist/mcp/consent.js +69 -0
  104. package/dist/mcp/dispatch.d.ts +35 -0
  105. package/dist/mcp/dispatch.d.ts.map +1 -0
  106. package/dist/mcp/dispatch.js +135 -0
  107. package/dist/mcp/floor.d.ts +37 -0
  108. package/dist/mcp/floor.d.ts.map +1 -0
  109. package/dist/mcp/floor.js +41 -0
  110. package/dist/mcp/host.d.ts +34 -0
  111. package/dist/mcp/host.d.ts.map +1 -0
  112. package/dist/mcp/host.js +2 -0
  113. package/dist/mcp/http/redirectList.d.ts +9 -0
  114. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  115. package/dist/mcp/http/redirectList.js +24 -0
  116. package/dist/mcp/http/responses.d.ts +143 -0
  117. package/dist/mcp/http/responses.d.ts.map +1 -0
  118. package/dist/mcp/http/responses.js +83 -0
  119. package/dist/mcp/http/routes.d.ts +28 -0
  120. package/dist/mcp/http/routes.d.ts.map +1 -0
  121. package/dist/mcp/http/routes.js +517 -0
  122. package/dist/mcp/http/schemas.d.ts +24 -0
  123. package/dist/mcp/http/schemas.d.ts.map +1 -0
  124. package/dist/mcp/http/schemas.js +18 -0
  125. package/dist/mcp/marker.d.ts +15 -0
  126. package/dist/mcp/marker.d.ts.map +1 -0
  127. package/dist/mcp/marker.js +15 -0
  128. package/dist/mcp/provider.d.ts +78 -0
  129. package/dist/mcp/provider.d.ts.map +1 -0
  130. package/dist/mcp/provider.js +108 -0
  131. package/dist/mcp/purge.d.ts +15 -0
  132. package/dist/mcp/purge.d.ts.map +1 -0
  133. package/dist/mcp/purge.js +31 -0
  134. package/dist/mcp/rpc.d.ts +79 -0
  135. package/dist/mcp/rpc.d.ts.map +1 -0
  136. package/dist/mcp/rpc.js +103 -0
  137. package/dist/mcp/toolAudit.d.ts +76 -0
  138. package/dist/mcp/toolAudit.d.ts.map +1 -0
  139. package/dist/mcp/toolAudit.js +86 -0
  140. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  141. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  142. package/dist/migrations/0006_verification_outcomes.js +35 -0
  143. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  144. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  145. package/dist/migrations/0007_erasure_record.js +36 -0
  146. package/dist/migrations/0008_last_active.d.ts +15 -0
  147. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  148. package/dist/migrations/0008_last_active.js +29 -0
  149. package/dist/migrations/set.d.ts +4 -1
  150. package/dist/migrations/set.d.ts.map +1 -1
  151. package/dist/migrations/set.js +8 -2
  152. package/dist/peer.d.ts +3 -2
  153. package/dist/peer.d.ts.map +1 -1
  154. package/dist/processing/activities.d.ts +6 -0
  155. package/dist/processing/activities.d.ts.map +1 -0
  156. package/dist/processing/activities.js +12 -0
  157. package/dist/purge/contribution.d.ts +20 -5
  158. package/dist/purge/contribution.d.ts.map +1 -1
  159. package/dist/purge/contribution.js +20 -6
  160. package/dist/purge/run.d.ts +75 -5
  161. package/dist/purge/run.d.ts.map +1 -1
  162. package/dist/purge/run.js +117 -14
  163. package/dist/purge/workflow.d.ts +15 -2
  164. package/dist/purge/workflow.d.ts.map +1 -1
  165. package/dist/purge/workflow.js +51 -7
  166. package/dist/test-utils/accountFootprint.d.ts +5 -2
  167. package/dist/test-utils/accountFootprint.d.ts.map +1 -1
  168. package/dist/test-utils/accountFootprint.js +7 -2
  169. package/dist/test-utils/liveApp.d.ts +6 -0
  170. package/dist/test-utils/liveApp.d.ts.map +1 -1
  171. package/dist/test-utils/liveApp.js +7 -2
  172. package/dist/token/handoff.d.ts +80 -0
  173. package/dist/token/handoff.d.ts.map +1 -0
  174. package/dist/token/handoff.js +136 -0
  175. package/dist/version.generated.d.ts +1 -1
  176. package/dist/version.generated.js +1 -1
  177. package/docs/account-lifecycle.md +59 -7
  178. package/docs/apple-signin.md +32 -4
  179. package/docs/facebook-oauth.md +2 -2
  180. package/docs/github-oauth.md +2 -2
  181. package/docs/google-oauth.md +9 -7
  182. package/docs/microsoft-oauth.md +2 -2
  183. package/package.json +11 -5
  184. package/pithy.manifest.json +2 -2
  185. package/pithy.mcp.manifest.json +36 -0
  186. package/src/audit/actions.ts +39 -0
  187. package/src/audit/emit.ts +63 -0
  188. package/src/audit/evidence.ts +8 -4
  189. package/src/capability.ts +80 -23
  190. package/src/client/api.ts +69 -19
  191. package/src/client/bearer.ts +388 -0
  192. package/src/client/handoff.ts +172 -0
  193. package/src/client/mcp.ts +140 -0
  194. package/src/data/betterAuth.ts +8 -4
  195. package/src/data/kitFields.ts +2 -0
  196. package/src/data/tables.ts +4 -2
  197. package/src/data/userLifecycle.ts +15 -3
  198. package/src/data/verificationOutcome.ts +86 -0
  199. package/src/email/send.ts +2 -2
  200. package/src/http/adminRoutes.ts +68 -3
  201. package/src/http/csrf.ts +4 -1
  202. package/src/http/guards.ts +48 -11
  203. package/src/http/handoff.ts +350 -0
  204. package/src/http/middleware.ts +29 -3
  205. package/src/http/resolve.ts +25 -25
  206. package/src/http/responses.ts +134 -8
  207. package/src/http/routes.ts +63 -4
  208. package/src/http/schemas.ts +85 -0
  209. package/src/http/views.ts +46 -2
  210. package/src/index.ts +2 -0
  211. package/src/instance/auth.ts +51 -1
  212. package/src/instance/plugins.ts +20 -2
  213. package/src/ledger/read.ts +133 -0
  214. package/src/ledger/record.ts +198 -0
  215. package/src/lifecycle/erasure.ts +118 -0
  216. package/src/lifecycle/inactivity.ts +56 -0
  217. package/src/lifecycle/transitions.ts +75 -5
  218. package/src/mcp/argumentClass.ts +112 -0
  219. package/src/mcp/capability.ts +194 -0
  220. package/src/mcp/clientMetadata.ts +81 -0
  221. package/src/mcp/consent.ts +95 -0
  222. package/src/mcp/dispatch.ts +154 -0
  223. package/src/mcp/floor.ts +62 -0
  224. package/src/mcp/host.ts +36 -0
  225. package/src/mcp/http/redirectList.ts +26 -0
  226. package/src/mcp/http/responses.ts +157 -0
  227. package/src/mcp/http/routes.ts +635 -0
  228. package/src/mcp/http/schemas.ts +37 -0
  229. package/src/mcp/marker.ts +18 -0
  230. package/src/mcp/provider.ts +151 -0
  231. package/src/mcp/purge.ts +39 -0
  232. package/src/mcp/rpc.ts +135 -0
  233. package/src/mcp/toolAudit.ts +132 -0
  234. package/src/migrations/0006_verification_outcomes.ts +51 -0
  235. package/src/migrations/0007_erasure_record.ts +43 -0
  236. package/src/migrations/0008_last_active.ts +30 -0
  237. package/src/migrations/set.ts +7 -1
  238. package/src/processing/activities.ts +14 -0
  239. package/src/purge/contribution.ts +37 -10
  240. package/src/purge/run.ts +179 -16
  241. package/src/purge/workflow.ts +65 -7
  242. package/src/seeds/example.ts +2 -2
  243. package/src/test-utils/accountFootprint.ts +10 -1
  244. package/src/test-utils/liveApp.ts +10 -1
  245. package/src/token/handoff.ts +180 -0
  246. package/src/version.generated.ts +1 -1
@@ -23,6 +23,7 @@ import {
23
23
  resolveMicrosoftCredentials,
24
24
  resolveSessionSecrets,
25
25
  } from "../instance/secrets";
26
+ import { mcpAuthorizationServer } from "../mcp/provider";
26
27
  import { baseURLResolver } from "./baseUrl";
27
28
 
28
29
  /**
@@ -50,7 +51,7 @@ export function resolveDb(env: Record<string, unknown>, bindingName: string): D1
50
51
  /**
51
52
  * The language to write a sign-in email in, for one address.
52
53
  *
53
- * **The stored preference first, the request's negotiation second** (pithy-sh/pithy#441). Somebody who
54
+ * **The stored preference first, the request's negotiation second.** Somebody who
54
55
  * picked a language in a settings pane has said something durable about themselves; the device they are
55
56
  * signing in from tonight has only sent an `Accept-Language`. But most of what this is asked about is a
56
57
  * *first* sign-in, where no row exists yet — and that is precisely the message a project cannot afford
@@ -90,23 +91,11 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
90
91
  }
91
92
  const env = c.env as unknown as AuthEnv;
92
93
  // Secret resolutions hit the same per-invocation cache; run them concurrently. Six reads, and they
93
- // are not alike — which is the whole of #381.
94
- //
95
- // `resolveSessionSecret` is what an auth instance *is*: nothing signs a session without it, so its
96
- // failure stays a precondition and still fails this call. `resolveDb` below is the same. A provider
97
- // credential is one sign-in method among several, and it used to sit in this list as an equal — so a
98
- // single unreadable `auth-github-credentials` rejected the whole `Promise.all` and every magic-link
99
- // and OTP caller in the deployment got the secrets reader's own refusal instead of a sign-in:
100
- // measured, `404 secrets/not_found`, message `Secret 'auth-github-credentials' is declared but not
101
- // provisioned.` So the old behavior named the secret loudly and named it to *the browser*, on a
102
- // route that has nothing to do with GitHub. Both halves of that are fixed here.
103
- //
104
- // `resolveProvider` catches per provider and hands back a state rather than a rejection, so this
105
- // `Promise.all` settles whenever the session secret does. What the instance then lacks is one
106
- // provider, and `makeAuth`'s `before` hook answers a caller who asks for it — see `instance/providers.ts`.
107
- //
108
- // A held failure belongs to its own secret (#170), so an unreadable provider credential does not
109
- // disturb the session secret's own read, and a *disabled* provider never calls `.get()` at all.
94
+ // are not alike. The session secret is what an auth instance *is*, so its failure fails this call, as
95
+ // `resolveDb` below does. A provider credential is one sign-in method among several: `resolveProvider`
96
+ // hands back a state rather than a rejection, so one unreadable credential costs that provider alone,
97
+ // answered by `makeAuth`'s `before` hook (`instance/providers.ts`), and never reaches a caller signing in
98
+ // another way. A disabled provider never reads its secret at all.
110
99
  const [sessionSecrets, google, apple, facebook, github, microsoft] = await Promise.all([
111
100
  resolveSessionSecrets(env),
112
101
  resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
@@ -117,7 +106,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
117
106
  ]);
118
107
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
119
108
  const d1 = resolveDb(c.env, cfg.database);
120
- // The current version signs; every retained one opens (#602). A version set with no current entry is a
109
+ // The current version signs; every retained one opens. A version set with no current entry is a
121
110
  // corrupt envelope, and the store's own reader has already refused that — this narrows it for the type.
122
111
  const secret = sessionSecrets.versions[sessionSecrets.currentVersion];
123
112
  if (secret === undefined) {
@@ -139,6 +128,9 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
139
128
  log: (c.get("log") ?? createWorkerLogger({ name: "auth" })).child("auth"),
140
129
  });
141
130
  const listener = wiring.onSessionRevoked;
131
+ // Never `cfg.baseURL` directly — see the `baseURL` key below. Named once, because the MCP endpoint's resource is
132
+ // built from the same address the instance runs under.
133
+ const baseURL = baseURLResolver(cfg.baseURL)(c.req.raw);
142
134
  return makeAuth({
143
135
  db: authDatabase(d1),
144
136
  // The adopter's listener, bound to *this* request's binding. The instance is built per request, so
@@ -152,10 +144,10 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
152
144
  // one of those has to name the address this run is actually serving on — not the production origin
153
145
  // the config records. The gate lives in `baseURLResolver` and nowhere else; outside `dev` this is
154
146
  // `cfg.baseURL`, unchanged. Resolved here because the instance is itself built per request.
155
- baseURL: baseURLResolver(cfg.baseURL)(c.req.raw),
147
+ baseURL,
156
148
  // The language this request negotiated, for the translator plugin. `c.var.locale` is the project's
157
149
  // own chain already resolved — never a second negotiation of Better Auth's, which would let the
158
- // screens and the refusals disagree about who is reading (#452). `null` when nothing negotiated,
150
+ // screens and the refusals disagree about who is reading. `null` when nothing negotiated,
159
151
  // which is every project that does not compose `i18n`, and which means English.
160
152
  locale: c.var.locale?.catalogLocale ?? null,
161
153
  basePath: cfg.basePath,
@@ -175,9 +167,8 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
175
167
  verificationExpiresIn: cfg.verificationExpiresIn,
176
168
  otpLength: cfg.otpLength,
177
169
  disableSignUp: cfg.disableSignUp,
178
- // Per provider, and separate from the line above on purpose: `disableSignUp` governs magic link and
179
- // OTP, this governs one OAuth provider. A project wanting email sign-up and no GitHub sign-up could
180
- // not say so before, which is how an orphan user appeared (#554).
170
+ // Per provider, and separate from the line above: `disableSignUp` governs magic link and OTP, this
171
+ // governs one OAuth provider, so a project can take email sign-up and refuse GitHub sign-up.
181
172
  providerSignUp: {
182
173
  google: cfg.google.allowSignUp,
183
174
  apple: cfg.apple.allowSignUp,
@@ -195,6 +186,15 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
195
186
  // The adopter's additional Better Auth plugins, exactly as `auth({ plugins: [...] })` declared them
196
187
  // and already checked for additivity at `auth()` call time. The same list the derived migrations
197
188
  // were built from — the routes a plugin serves and the tables it needs come from one declaration.
198
- plugins: cfg.plugins,
189
+ plugins: wiring.mcp
190
+ ? [
191
+ ...cfg.plugins,
192
+ ...mcpAuthorizationServer({
193
+ resource: `${baseURL}${wiring.mcp.path}`,
194
+ consentPage: wiring.mcp.consentPage,
195
+ clientDiscovery: wiring.mcp.clientDiscovery,
196
+ }),
197
+ ]
198
+ : cfg.plugins,
199
199
  });
200
200
  }
@@ -4,6 +4,7 @@
4
4
  import { Locale } from "@pithy-sh/core/src/i18n/locale";
5
5
  import { z } from "zod";
6
6
  import { DevicePlatform } from "../data/device";
7
+ import { VerificationState, VerificationType } from "../data/verificationOutcome";
7
8
 
8
9
  /**
9
10
  * What the auth admin routes return, as Zod objects a management client can validate against.
@@ -59,6 +60,28 @@ export const AdminUserView = z
59
60
  ),
60
61
  createdAt: z.iso.datetime().describe("When the user was created, ISO-8601."),
61
62
  updatedAt: z.iso.datetime().describe("When the row was last written, ISO-8601."),
63
+ // Where the account stands (#813), on the organization view's shape. Each optional: absent from a Worker
64
+ // older than the field. No reason and no actor — the reason is on the trail, and the trail is audit's.
65
+ state: z
66
+ .enum(["active", "suspended", "deleted"])
67
+ .optional()
68
+ .describe(
69
+ "Where the account stands now: `active`; `suspended`, refused until it is reinstated or its end passes; or `deleted`, refused and restorable until `purgeAfter`. A suspension whose end has passed reads `active`, as enforcement reads it. Absent when the Worker that answered predates the field.",
70
+ ),
71
+ suspendedUntil: z.iso
72
+ .datetime()
73
+ .nullable()
74
+ .optional()
75
+ .describe(
76
+ "When a suspension in force ends by itself, ISO-8601. Null for one that lasts until a reinstatement, and in every other state. Absent when the Worker predates the field.",
77
+ ),
78
+ purgeAfter: z.iso
79
+ .datetime()
80
+ .nullable()
81
+ .optional()
82
+ .describe(
83
+ "For a deleted account, when the purge may erase it, ISO-8601 — restorable until then. Null in every other state. Absent when the Worker predates the field.",
84
+ ),
62
85
  })
63
86
  .describe("One user as a management client sees them. The table holds no credential, so nothing is withheld.");
64
87
  export type AdminUserView = z.output<typeof AdminUserView>;
@@ -177,6 +200,70 @@ export const AdminDevicesResponse = z
177
200
  .describe("A page of the device registry.");
178
201
  export type AdminDevicesResponse = z.output<typeof AdminDevicesResponse>;
179
202
 
203
+ /**
204
+ * One sign-in link or code from the verification ledger (#829), as a management client sees it.
205
+ *
206
+ * Never the token and never the address: the ledger holds neither. The mail is named by its job id, which is how
207
+ * a reader holding `email:jobs:read` joins this to a bounce, a deferral or a suppression.
208
+ */
209
+ export const AdminVerificationView = z
210
+ .object({
211
+ verificationId: z.string().describe("The verification row that carries it. Opaque; not a credential."),
212
+ type: VerificationType.describe("What was issued."),
213
+ state: VerificationState.describe("Where it stood at the moment of the read."),
214
+ userId: z
215
+ .string()
216
+ .nullable()
217
+ .describe(
218
+ "The account it signs in to — known at issue, or created by its use. Null for a sign-up nobody completed.",
219
+ ),
220
+ emailJobId: z
221
+ .string()
222
+ .nullable()
223
+ .describe(
224
+ "The `pithy_email_jobs` row that carried it, under `email:jobs:read`. Null when the email seam failed and nothing was queued.",
225
+ ),
226
+ issuedAt: z.iso.datetime().describe("When it was issued, ISO-8601."),
227
+ expiresAt: z.iso.datetime().describe("When it stops working, used or not, ISO-8601."),
228
+ usedAt: z.iso.datetime().nullable().describe("When it signed somebody in, ISO-8601, or null."),
229
+ })
230
+ .describe("One sign-in link or code: what it was, whose, the mail that carried it, and where it stands.");
231
+ export type AdminVerificationView = z.output<typeof AdminVerificationView>;
232
+
233
+ /** How many of one type were issued over the window, and where they stand. */
234
+ export const VerificationTypeCounts = z
235
+ .object({
236
+ type: VerificationType.describe("Which type these counts are for."),
237
+ issued: z.number().int().min(0).describe("How many were issued in the window."),
238
+ used: z.number().int().min(0).describe("How many of those signed somebody in."),
239
+ expired: z.number().int().min(0).describe("How many ran out unused."),
240
+ pending: z.number().int().min(0).describe("How many are unused and still work. The three add up to `issued`."),
241
+ })
242
+ .describe("One type's counts over the window, by state.");
243
+ export type VerificationTypeCounts = z.output<typeof VerificationTypeCounts>;
244
+
245
+ /**
246
+ * `GET {base}/admin/verifications` (#829): the window it covered, the counts by type and state over all of it,
247
+ * and a page of its rows, newest issue first.
248
+ *
249
+ * The counts cover every row in the window whatever the page or the filters say, and every type, with zeros —
250
+ * so a pane reading "sign-in links: 0 issued" can tell it from a Worker that did not say.
251
+ */
252
+ export const AdminVerificationsResponse = z
253
+ .object({
254
+ window: z
255
+ .object({
256
+ since: z.iso.datetime().describe("The window's start, inclusive, ISO-8601."),
257
+ until: z.iso.datetime().describe("The window's end, exclusive, ISO-8601."),
258
+ })
259
+ .describe("The window of issue times the counts and the rows cover."),
260
+ counts: z.array(VerificationTypeCounts).describe("Every type's counts over the whole window, by state."),
261
+ verifications: z.array(AdminVerificationView).describe("The page of rows, newest issue first."),
262
+ nextCursor: NextCursor,
263
+ })
264
+ .describe("The verification ledger over a window: counts by type and state, and the rows, paged.");
265
+ export type AdminVerificationsResponse = z.output<typeof AdminVerificationsResponse>;
266
+
180
267
  /**
181
268
  * `POST {base}/admin/sessions/revoke` and `POST {base}/admin/users/:userId/sessions/revoke`.
182
269
  *
@@ -325,7 +412,9 @@ const AuthExportTransition = z
325
412
  .object({
326
413
  action: z
327
414
  .string()
328
- .describe("What happened: `suspended`, `reinstated`, `deleted`, `restored`, `purge_step`, `purged`."),
415
+ .describe(
416
+ "What happened: `suspended`, `reinstated`, `deleted`, `restored`, `purge_step`, `purge_retained`, `purge_failed`, `purged`.",
417
+ ),
329
418
  actorType: z.string().describe("Who made it: `control-plane`, `user` (the account's holder), or `system`."),
330
419
  reason: z.string().nullable().describe("The reason given, in the words of whoever made the transition, or null."),
331
420
  suspendedUntil: z.iso.datetime().nullable().describe("For a suspension, when it ends by itself, ISO-8601."),
@@ -357,6 +446,12 @@ export const AuthUserExport = z
357
446
  .array(AdminDeviceView)
358
447
  .describe("Every registered device, most recently seen first. Without push tokens."),
359
448
  history: z.array(AuthExportTransition).describe("Every lifecycle transition, oldest first."),
449
+ verifications: z
450
+ .array(AdminVerificationView)
451
+ .optional()
452
+ .describe(
453
+ "Every sign-in link and code the verification ledger records for the account, newest first (#829). Absent from a Worker that predates the ledger.",
454
+ ),
360
455
  plugins: z
361
456
  .record(z.string(), z.array(z.record(z.string(), z.unknown())))
362
457
  .describe(
@@ -368,8 +463,20 @@ export type AuthUserExport = z.output<typeof AuthUserExport>;
368
463
 
369
464
  /** Fields every capability's export entry carries. */
370
465
  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."),
466
+ capability: z.string().describe("The capability whose rows these are — the purge step that erases or keeps them."),
467
+ summary: z.string().describe("What that capability's purge erases, anonymizes or keeps, in its own sentence."),
468
+ disposition: z
469
+ .enum(["erase", "retain"])
470
+ .optional()
471
+ .describe(
472
+ "What a purge does with these rows: `erase` (erased or anonymized) or `retain` (kept, for the reason in `basis`) (#814). Absent from a Worker that predates it, where every entry is `erase`.",
473
+ ),
474
+ basis: z
475
+ .string()
476
+ .optional()
477
+ .describe(
478
+ "For a `retain` entry, why the rows are kept, in one sentence written for the person — `Kept for tax records.` Absent for `erase`.",
479
+ ),
373
480
  };
374
481
 
375
482
  /** One capability's part of an export. */
@@ -382,7 +489,7 @@ const AdminUserExportEntry = z
382
489
  data: z
383
490
  .record(z.string(), z.unknown())
384
491
  .describe(
385
- "What it holds about the account, in the shape that capability exports. `auth`'s is `AuthUserExport`.",
492
+ "What it holds about the account, in the shape that capability exports. `auth`'s is `AuthUserExport`. For a `retain` entry, the rows a purge keeps.",
386
493
  ),
387
494
  })
388
495
  .describe("A capability's rows about the account."),
@@ -391,7 +498,9 @@ const AdminUserExportEntry = z
391
498
  ...exportEntry,
392
499
  state: z
393
500
  .literal("not_exported")
394
- .describe("The capability erases rows about the account and does not say how to export them."),
501
+ .describe(
502
+ "The capability erases rows about the account and does not say how to export them. No kit capability answers it; an adopter's own may.",
503
+ ),
395
504
  })
396
505
  .describe("A capability that holds rows it does not export. Ask its owner."),
397
506
  z
@@ -437,17 +546,34 @@ export const TokenRotateResponse = z
437
546
  .object({
438
547
  accessToken: z
439
548
  .string()
440
- .describe("A fresh short-lived access token (a JWT) for the `Authorization: Bearer` header."),
549
+ .describe(
550
+ "A short-lived JWT for a service outside this Worker, which verifies it against `/jwks`. The kit's own routes do not accept it: send `refreshToken` as the bearer.",
551
+ ),
441
552
  refreshToken: z
442
553
  .string()
443
554
  .describe(
444
- "The successor refresh credential: a new session token. The one presented is spent, and presenting it again past a short grace window revokes the whole family.",
555
+ "The successor session token: the bearer credential for `Authorization: Bearer` on the kit's routes, and what the next rotation takes. The one presented is spent, and presenting it again past a short grace window revokes the whole family.",
445
556
  ),
446
557
  expiresAt: z.iso.datetime().describe("When the successor session lapses, ISO-8601."),
447
558
  })
448
- .describe("The rotated credential pair: a new access token and the session token that replaces the one presented.");
559
+ .describe(
560
+ "The rotated credentials: the session token that replaces the one presented, and a JWT for outside verifiers.",
561
+ );
449
562
  export type TokenRotateResponse = z.output<typeof TokenRotateResponse>;
450
563
 
564
+ /** `POST {base}/handoff`. */
565
+ export const HandoffExchangeResponse = z
566
+ .object({
567
+ token: z
568
+ .string()
569
+ .describe(
570
+ "The raw session token: the bearer credential for `Authorization: Bearer`, and the refresh credential `/token/rotate` takes. Hold it in secure storage.",
571
+ ),
572
+ expiresAt: z.iso.datetime().describe("When the session lapses unless it is rotated first, ISO-8601."),
573
+ })
574
+ .describe("The session a redirect sign-in made, handed to the native app that started it.");
575
+ export type HandoffExchangeResponse = z.output<typeof HandoffExchangeResponse>;
576
+
451
577
  /** One of the caller's own registered devices. */
452
578
  export const MyDeviceView = z
453
579
  .object({
@@ -7,6 +7,7 @@ import { describeRoute, type RouteResponse } from "@pithy-sh/core/src/http/route
7
7
  import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
8
8
  import { validate } from "@pithy-sh/core/src/http/validation";
9
9
  import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
10
+ import { announceSessionRotated } from "@pithy-sh/core/src/session/rotated";
10
11
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
11
12
  import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
12
13
  import type { Context, Hono } from "hono";
@@ -30,13 +31,20 @@ import {
30
31
  import { registerAuthAdminRoutes } from "./adminRoutes";
31
32
  import { guardErrorCallbackURL } from "./errorCallbackUrl";
32
33
  import { apiErrorToPithy } from "./errors";
34
+ import { exchangeHandoff, handOffToApp, startNativeSignIn } from "./handoff";
33
35
  import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate";
34
36
  import { accountHolder, requireAccountHolder, requireAuth } from "./middleware";
35
37
  import { requireFreshAuthentication } from "./providerFreshness";
36
38
  import { collapseProviderRefusal } from "./providerRefusal";
37
39
  import { getAuthInstance, resolveDb } from "./resolve";
38
- import { AccountDeleteResponse, MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses";
39
- import { DeleteAccountBody, RevokeDeviceBody } from "./schemas";
40
+ import {
41
+ AccountDeleteResponse,
42
+ HandoffExchangeResponse,
43
+ MyDeviceRevokeResponse,
44
+ MyDevicesResponse,
45
+ TokenRotateResponse,
46
+ } from "./responses";
47
+ import { DeleteAccountBody, HandoffExchangeBody, RevokeDeviceBody, SocialSignInStartQuery } from "./schemas";
40
48
  import { accountDeletionView } from "./views";
41
49
 
42
50
  type Ctx = Context<PithyHonoEnv>;
@@ -69,6 +77,8 @@ function db(c: Ctx, wiring: AuthWiring) {
69
77
  * | Route | Verification | Input |
70
78
  * | -------------------------- | --------------- | --------------------------- |
71
79
  * | `POST /token/rotate` | bearer/session | none — the credential only |
80
+ * | `GET /sign-in/social/start` | public | query `SocialSignInStartQuery` |
81
+ * | `POST /handoff` | public | json `HandoffExchangeBody` |
72
82
  * | `GET /devices` | bearer/session | none |
73
83
  * | `POST /devices/revoke` | bearer/session | json `RevokeDeviceBody` |
74
84
  * | `DELETE /account` | bearer/session | json `DeleteAccountBody` |
@@ -98,7 +108,8 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
98
108
  // string through the client projection, and a second copy of it could only be caught in production —
99
109
  // where the two disagreeing refuses every sign-in. #377, and `TURNSTILE_LOGIN_ACTION`'s docblock.
100
110
  if (wiring.turnstile) {
101
- const guard = turnstile({ mode: wiring.turnstile.mode, action: TURNSTILE_LOGIN_ACTION });
111
+ const { mode, token } = wiring.turnstile;
112
+ const guard = turnstile({ mode, field: token.field, header: token.header, action: TURNSTILE_LOGIN_ACTION });
102
113
  app.use(`${base}/sign-in/magic-link`, guard);
103
114
  app.use(`${base}/email-otp/send-verification-otp`, guard);
104
115
  }
@@ -107,7 +118,7 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
107
118
  app.post(
108
119
  `${base}/token/rotate`,
109
120
  describeRoute({
110
- summary: "Trade the current refresh credential for a new access token and its successor.",
121
+ summary: "Trade the current session token for its successor, and a JWT for services outside this Worker.",
111
122
  description:
112
123
  "The presented session is spent. Presenting it again after a short grace window is read as theft, and revokes every session descended from the same sign-in.",
113
124
  verification: ["bearer", "session"],
@@ -116,6 +127,36 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
116
127
  csrf,
117
128
  (c) => rotateToken(c, wiring),
118
129
  );
130
+ // The address a native app opens in the system browser's sign-in sheet to start a redirect sign-in, so the
131
+ // provider's state cookie lands in the sheet's jar. Public, like `POST /sign-in/social`; the edge limiter covers it.
132
+ app.get(
133
+ `${base}/sign-in/social/start`,
134
+ describeRoute({
135
+ summary: "Start a native app's redirect sign-in inside the system browser.",
136
+ description:
137
+ "A native app opens this address in the system browser's sign-in sheet (ASWebAuthenticationSession, a Custom Tab) instead of posting `/sign-in/social` itself, so the signed `state` cookie Better Auth checks at the provider's callback lands in the browser that completes it. The answer is a redirect to the provider carrying that cookie. Only for the handoff: `callbackURL` must be in `trustedOrigins` and carry a well-formed `handoff_challenge`, or it is refused, and so is an `errorCallbackURL` outside `trustedOrigins`, and a navigation another page started (`Sec-Fetch-Site` other than `none`). A provider this Worker does not enable answers `core/not_found`. A web page keeps the JSON `POST /sign-in/social`.",
138
+ verification: ["public"],
139
+ responses: {
140
+ 302: { description: "A redirect to the provider's authorization page, setting the sign-in's state cookie." },
141
+ },
142
+ }),
143
+ validate("query", SocialSignInStartQuery),
144
+ (c) => startNativeSignIn(c, wiring, c.req.valid("query")),
145
+ );
146
+ // A native app trades the one-time code a redirect sign-in left on its app link for the session. Public: the
147
+ // code and its verifier are the credential, single use and a minute long, and the edge limiter covers this path.
148
+ app.post(
149
+ `${base}/handoff`,
150
+ describeRoute({
151
+ summary: "Trade the one-time code a redirect sign-in left on an app's link for the session token.",
152
+ description:
153
+ "A social sign-in whose `callbackURL` is in `trustedOrigins` and carries a `handoff_challenge` (the S256 digest of a verifier the app holds) returns to that link with a `code` parameter instead of a cookie, whether the link is an https universal link or app link or a custom scheme. The code is good once, for sixty seconds, and only with the verifier. A spent, expired or unknown code, or a wrong or malformed verifier, is refused with `auth/handoff_invalid`, and any attempt spends the code. A custom-scheme link with no challenge gets `error=handoff_challenge_required` and no code; an https link with no challenge is a web page and gets its cookie. A magic link is handed off only to an https link: one to a custom scheme gets `error=handoff_scheme_refused`, and no session is kept. Device headers sent here register the device against the session.",
154
+ verification: ["public"],
155
+ responses: { 200: HandoffExchangeResponse },
156
+ }),
157
+ validate("json", HandoffExchangeBody),
158
+ (c) => exchangeHandoff(c, wiring, c.req.valid("json")),
159
+ );
119
160
  // Device management (bearer/session gated; the revoke is CSRF-guarded as a mutating route).
120
161
  app.get(
121
162
  `${base}/devices`,
@@ -374,6 +415,9 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
374
415
  return collapsed.response;
375
416
  }
376
417
 
418
+ const handedOff = await handOffToApp(c, wiring, instance, response);
419
+ if (handedOff) return handedOff;
420
+
377
421
  await auditRefusal(c, response);
378
422
  return response;
379
423
  }
@@ -508,6 +552,21 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
508
552
  });
509
553
  await emitTokenRefresh(c.var.emit, { userId: current.user.id, sessionId: next.id, ip, userAgent });
510
554
 
555
+ // State another capability keyed on the spent session follows it to the successor. A listener's failure is
556
+ // logged and never fails the rotation, which has already happened.
557
+ const failures = await announceSessionRotated(wiring.composed ?? [], {
558
+ previousSessionId: current.session.id,
559
+ sessionId: next.id,
560
+ userId: current.user.id,
561
+ env: c.env as unknown as Record<string, unknown>,
562
+ });
563
+ for (const failure of failures) {
564
+ c.var.log?.child("auth").warn("a session-rotated listener failed; its state stayed on the spent session", {
565
+ capability: failure.capability,
566
+ error: failure.error instanceof Error ? failure.error.message : String(failure.error),
567
+ });
568
+ }
569
+
511
570
  // Bound the ledger: a token consumed longer ago than a full session lifetime can no longer match any
512
571
  // live session. Best-effort — a cleanup failure must never fail the rotation it rode in on.
513
572
  try {
@@ -5,6 +5,7 @@ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
5
5
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
6
6
  import { z } from "zod";
7
7
  import { DevicePlatform } from "../data/device";
8
+ import { VerificationState, VerificationType } from "../data/verificationOutcome";
8
9
  import { MAX_REASON } from "../lifecycle/reason";
9
10
 
10
11
  /**
@@ -37,6 +38,66 @@ export const RevokeDeviceBody = z
37
38
  .describe("The body identifying which device to revoke — the caller's own, or an admin-named user's.");
38
39
  export type RevokeDeviceBody = z.output<typeof RevokeDeviceBody>;
39
40
 
41
+ /**
42
+ * The body of `POST /handoff`: the one-time code a redirect sign-in left on the app's link, and the verifier whose
43
+ * challenge the sign-in carried. Bounded rather than shape-checked, so a malformed code or verifier is refused, and
44
+ * the code spent, by the same trade that refuses a spent code, with the same answer.
45
+ */
46
+ export const HandoffExchangeBody = z
47
+ .object({
48
+ code: z
49
+ .string()
50
+ .min(1)
51
+ .max(256)
52
+ .describe("The one-time code from the `code` parameter of the deep link the sign-in returned to."),
53
+ verifier: z
54
+ .string()
55
+ .min(1)
56
+ .max(256)
57
+ .describe(
58
+ "The random verifier the app made before the sign-in started: 43 to 128 characters from `A-Z a-z 0-9 - . _ ~`, as RFC 7636 shapes it. Its S256 digest is the `handoff_challenge` the sign-in's `callbackURL` carried.",
59
+ ),
60
+ })
61
+ .describe("The code a native app trades for its session after a redirect sign-in, with the verifier that binds it.");
62
+ export type HandoffExchangeBody = z.output<typeof HandoffExchangeBody>;
63
+
64
+ /** The providers a native app can sign in with through the system browser: every redirect provider auth offers. */
65
+ export const RedirectProvider = z
66
+ .enum(["apple", "facebook", "github", "google", "microsoft"])
67
+ .describe(
68
+ "A sign-in provider that completes in the browser, by redirect. Whether this Worker enables it is its config's call.",
69
+ );
70
+ export type RedirectProvider = z.output<typeof RedirectProvider>;
71
+
72
+ /**
73
+ * The query of `GET /sign-in/social/start`, the address a native app opens in the system browser's sign-in sheet.
74
+ * Bounded rather than shape-checked: the handler holds `callbackURL` to `trustedOrigins` and to carrying a
75
+ * `handoff_challenge`, and Better Auth checks both URLs again when the sign-in starts.
76
+ */
77
+ export const SocialSignInStartQuery = z
78
+ .object({
79
+ provider: RedirectProvider,
80
+ callbackURL: z
81
+ .string()
82
+ .min(1)
83
+ .max(2048)
84
+ .describe(
85
+ "The app's own link, in `trustedOrigins`, carrying the `handoff_challenge` the app made: where the sign-in returns with a one-time code.",
86
+ ),
87
+ errorCallbackURL: z
88
+ .string()
89
+ .min(1)
90
+ .max(2048)
91
+ .optional()
92
+ .describe(
93
+ "Where a refused sign-in returns, with an `error` parameter. In `trustedOrigins`. Absent, a refusal lands on the auth error page.",
94
+ ),
95
+ })
96
+ .describe(
97
+ "A native redirect sign-in, started in the system browser so the provider's state cookie lands in its jar.",
98
+ );
99
+ export type SocialSignInStartQuery = z.output<typeof SocialSignInStartQuery>;
100
+
40
101
  /**
41
102
  * The user id in the path of every single-user admin route.
42
103
  *
@@ -100,6 +161,30 @@ export const ListDevicesQuery = z
100
161
  .describe("The device-registry query: what to filter by, how many to return, and where to resume.");
101
162
  export type ListDevicesQuery = z.output<typeof ListDevicesQuery>;
102
163
 
164
+ /** A window bound on the verification read: ISO-8601 with an offset, decoded to a `Date` here so no handler parses it. */
165
+ const WindowBound = z.iso.datetime({ offset: true }).transform((value) => new Date(value));
166
+
167
+ /**
168
+ * The verification ledger read's query (#829): a window of issue times, what to narrow it to, and where to resume.
169
+ * Both bounds are optional — the last 30 days, ending now — and a window that ends before it starts is refused by
170
+ * the handler, which is where the default is known.
171
+ */
172
+ export const ListVerificationsQuery = z
173
+ .object({
174
+ since: WindowBound.optional().describe(
175
+ "The window's start, inclusive, on issue time, ISO-8601. Defaults to 30 days before `until`.",
176
+ ),
177
+ until: WindowBound.optional().describe("The window's end, exclusive, on issue time, ISO-8601. Defaults to now."),
178
+ type: VerificationType.optional().describe("Narrow the rows to one type. The counts always cover every type."),
179
+ state: VerificationState.optional().describe(
180
+ "Narrow the rows to one state, judged at the moment of the read. The counts always cover every state.",
181
+ ),
182
+ cursor: PageCursorParam,
183
+ limit: PageLimit,
184
+ })
185
+ .describe("The verification ledger query: the window, what to narrow the rows to, how many, and where to resume.");
186
+ export type ListVerificationsQuery = z.output<typeof ListVerificationsQuery>;
187
+
103
188
  /**
104
189
  * The body of `POST /admin/sessions/revoke`.
105
190
  *
package/src/http/views.ts CHANGED
@@ -5,6 +5,8 @@ import type { PurgeExportEntry } from "@pithy-sh/core/src/capability/purge";
5
5
  import type { Account, Session, User } from "../data/betterAuth";
6
6
  import type { Device } from "../data/device";
7
7
  import type { UserLifecycleEvent } from "../data/userLifecycle";
8
+ import { type VerificationOutcome, verificationStateAt } from "../data/verificationOutcome";
9
+ import { type AccountStanding, accountStanding } from "../lifecycle/state";
8
10
  import type {
9
11
  DeleteTransition,
10
12
  DeletionMode,
@@ -22,6 +24,7 @@ import type {
22
24
  AdminUserRestoreResponse,
23
25
  AdminUserSuspendResponse,
24
26
  AdminUserView,
27
+ AdminVerificationView,
25
28
  AuthUserExport,
26
29
  } from "./responses";
27
30
 
@@ -50,8 +53,12 @@ import type {
50
53
  * `locale` is projected for the same reason: a support pane answering "why is this person getting
51
54
  * English emails" needs to see whether they ever chose, and null — never chosen — is the answer half
52
55
  * the time. It is a preference, not a credential.
56
+ *
57
+ * Where the account stands is projected too (#813), judged at `now`: the listing does not filter a suspended or
58
+ * deleted account out, so without it a pane sees the person and cannot tell whether to offer suspend or reinstate.
59
+ * Not the reason and not who acted — those are the trail's.
53
60
  */
54
- export function userView(user: User): AdminUserView {
61
+ export function userView(user: User, now: Date): AdminUserView {
55
62
  return {
56
63
  id: user.id,
57
64
  email: user.email,
@@ -61,6 +68,22 @@ export function userView(user: User): AdminUserView {
61
68
  locale: user.locale,
62
69
  createdAt: user.createdAt.toISOString(),
63
70
  updatedAt: user.updatedAt.toISOString(),
71
+ ...standingView(accountStanding(user, now)),
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Where an account stands, as the wire carries it (#813) — the organization view's shape: the state, the end of a
77
+ * suspension in force, and the last day a deletion can be undone. Read through `accountStanding`, the function
78
+ * every enforcement point reads, so a suspension past its end reads `active` here exactly as it does at the door.
79
+ */
80
+ export function standingView(
81
+ standing: AccountStanding,
82
+ ): Required<Pick<AdminUserView, "state" | "suspendedUntil" | "purgeAfter">> {
83
+ return {
84
+ state: standing.state,
85
+ suspendedUntil: standing.state === "suspended" ? iso(standing.until) : null,
86
+ purgeAfter: standing.state === "deleted" ? iso(standing.purgeAfter) : null,
64
87
  };
65
88
  }
66
89
 
@@ -112,6 +135,23 @@ export function deviceView(device: Device): AdminDeviceView {
112
135
  };
113
136
  }
114
137
 
138
+ /**
139
+ * One verification ledger row, as a management client sees it (#829). `state` is judged at `now`, the moment the
140
+ * read took, so it agrees with the counts beside it.
141
+ */
142
+ export function verificationView(row: VerificationOutcome, now: Date): AdminVerificationView {
143
+ return {
144
+ verificationId: row.verificationId,
145
+ type: row.type,
146
+ state: verificationStateAt(row, now),
147
+ userId: row.userId,
148
+ emailJobId: row.emailJobId,
149
+ issuedAt: row.issuedAt.toISOString(),
150
+ expiresAt: row.expiresAt.toISOString(),
151
+ usedAt: row.usedAt?.toISOString() ?? null,
152
+ };
153
+ }
154
+
115
155
  /**
116
156
  * The suspension projection (#621): the suspension the transition left in force, and the sessions the route
117
157
  * revoked after it. Dates cross as ISO-8601, like every other response here.
@@ -191,17 +231,20 @@ function iso(date: Date | null | undefined): string | null {
191
231
  * theirs to disclose, not the person's, so the history carries the kind of actor and not its id.
192
232
  */
193
233
  export function authUserExportView(input: {
234
+ /** The instant the export was taken, which its `state` is judged at. */
235
+ now: Date;
194
236
  user: User;
195
237
  sessions: readonly Session[];
196
238
  accounts: readonly Pick<Account, "providerId" | "createdAt">[];
197
239
  devices: readonly Device[];
198
240
  history: readonly UserLifecycleEvent[];
241
+ verifications?: readonly VerificationOutcome[];
199
242
  plugins?: Record<string, Record<string, unknown>[]>;
200
243
  }): AuthUserExport {
201
244
  const { user } = input;
202
245
  return {
203
246
  user: {
204
- ...userView(user),
247
+ ...userView(user, input.now),
205
248
  suspendedAt: iso(user.suspendedAt),
206
249
  suspendedUntil: iso(user.suspendedUntil),
207
250
  deletedAt: iso(user.deletedAt),
@@ -220,6 +263,7 @@ export function authUserExportView(input: {
220
263
  suspendedUntil: iso(event.suspendedUntil),
221
264
  createdAt: event.createdAt.toISOString(),
222
265
  })),
266
+ verifications: (input.verifications ?? []).map((row) => verificationView(row, input.now)),
223
267
  plugins: input.plugins ?? {},
224
268
  };
225
269
  }