@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
@@ -7,15 +7,19 @@ 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";
14
+ import { userSessionTokens } from "../admin/users";
13
15
  import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit";
14
16
  import type { AuthWiring } from "../capability";
15
17
  import { authDatabase } from "../data/tables";
16
18
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry";
17
19
  import { noticedRefusal } from "../lifecycle/enforce";
20
+ import { lifecycleDeps } from "../lifecycle/request";
18
21
  import { isLifecycleRefusal } from "../lifecycle/state";
22
+ import { deleteUser } from "../lifecycle/transitions";
19
23
  import { PROFILE_IMAGE_PATH } from "../profile/profile";
20
24
  import {
21
25
  consumeSession,
@@ -27,13 +31,21 @@ import {
27
31
  import { registerAuthAdminRoutes } from "./adminRoutes";
28
32
  import { guardErrorCallbackURL } from "./errorCallbackUrl";
29
33
  import { apiErrorToPithy } from "./errors";
34
+ import { exchangeHandoff, handOffToApp, startNativeSignIn } from "./handoff";
30
35
  import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate";
31
- import { requireAuth } from "./middleware";
36
+ import { accountHolder, requireAccountHolder, requireAuth } from "./middleware";
32
37
  import { requireFreshAuthentication } from "./providerFreshness";
33
38
  import { collapseProviderRefusal } from "./providerRefusal";
34
39
  import { getAuthInstance, resolveDb } from "./resolve";
35
- import { MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses";
36
- import { 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";
48
+ import { accountDeletionView } from "./views";
37
49
 
38
50
  type Ctx = Context<PithyHonoEnv>;
39
51
 
@@ -65,8 +77,11 @@ function db(c: Ctx, wiring: AuthWiring) {
65
77
  * | Route | Verification | Input |
66
78
  * | -------------------------- | --------------- | --------------------------- |
67
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` |
68
82
  * | `GET /devices` | bearer/session | none |
69
83
  * | `POST /devices/revoke` | bearer/session | json `RevokeDeviceBody` |
84
+ * | `DELETE /account` | bearer/session | json `DeleteAccountBody` |
70
85
  * | `* /admin/*` | control-plane | see `./adminRoutes` |
71
86
  *
72
87
  * The catch-all takes NO validator, deliberately: `handleBetterAuth` hands Better Auth `c.req.raw`,
@@ -93,7 +108,8 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
93
108
  // string through the client projection, and a second copy of it could only be caught in production —
94
109
  // where the two disagreeing refuses every sign-in. #377, and `TURNSTILE_LOGIN_ACTION`'s docblock.
95
110
  if (wiring.turnstile) {
96
- 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 });
97
113
  app.use(`${base}/sign-in/magic-link`, guard);
98
114
  app.use(`${base}/email-otp/send-verification-otp`, guard);
99
115
  }
@@ -102,7 +118,7 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
102
118
  app.post(
103
119
  `${base}/token/rotate`,
104
120
  describeRoute({
105
- 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.",
106
122
  description:
107
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.",
108
124
  verification: ["bearer", "session"],
@@ -111,6 +127,36 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
111
127
  csrf,
112
128
  (c) => rotateToken(c, wiring),
113
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
+ );
114
160
  // Device management (bearer/session gated; the revoke is CSRF-guarded as a mutating route).
115
161
  app.get(
116
162
  `${base}/devices`,
@@ -135,6 +181,25 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
135
181
  (c) => revokeMyDevice(c, wiring, c.req.valid("json")),
136
182
  );
137
183
 
184
+ // The signed-in person deletes their own account (#622) — always soft, on the configured window. The one
185
+ // route a suspended account still reaches: the app stores require that somebody can always leave, and a
186
+ // suspension is no reason to keep them. CSRF-guarded as a mutating route; the subject is the session's own,
187
+ // and nothing in the body can name another.
188
+ app.delete(
189
+ `${base}/account`,
190
+ describeRoute({
191
+ summary: "Delete the caller's own account. Always soft: restorable until the purge window closes.",
192
+ description:
193
+ "What the App Store and Google Play require of an app with accounts. A suspended account may still delete itself, with the session a sign-in carrying `x-pithy-intent: delete-account` gets it; a deleted one is refused with `auth/account_deleted`. Every session ends, this one included. The body must carry `confirm: true`.",
194
+ verification: ["bearer", "session"],
195
+ responses: { 200: AccountDeleteResponse },
196
+ }),
197
+ requireAccountHolder(),
198
+ csrf,
199
+ validate("json", DeleteAccountBody),
200
+ (c) => deleteMyAccount(c, wiring),
201
+ );
202
+
138
203
  // **Changing which providers can sign you in requires a recent authentication — both directions.**
139
204
  // Mounted explicitly ahead of the catch-all, or neither gate runs. `http/providerFreshness.ts`
140
205
  // carries the argument: Better Auth guards the two unevenly, and its guard on the unlink side reads
@@ -350,6 +415,9 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
350
415
  return collapsed.response;
351
416
  }
352
417
 
418
+ const handedOff = await handOffToApp(c, wiring, instance, response);
419
+ if (handedOff) return handedOff;
420
+
353
421
  await auditRefusal(c, response);
354
422
  return response;
355
423
  }
@@ -484,6 +552,21 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
484
552
  });
485
553
  await emitTokenRefresh(c.var.emit, { userId: current.user.id, sessionId: next.id, ip, userAgent });
486
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
+
487
570
  // Bound the ledger: a token consumed longer ago than a full session lifetime can no longer match any
488
571
  // live session. Best-effort — a cleanup failure must never fail the rotation it rode in on.
489
572
  try {
@@ -502,6 +585,34 @@ async function listMyDevices(c: Ctx, wiring: AuthWiring): Promise<Response> {
502
585
  return c.json({ devices: await listDevices(db(c, wiring), userId) });
503
586
  }
504
587
 
588
+ /**
589
+ * Delete the caller's own account (#622): soft, on the configured window, audited as `auth/user_self_deleted`
590
+ * with them as the actor, and every session they hold ended after the columns are written — through Better
591
+ * Auth's adapter, so `onSessionRevoked` hears each. No reason: a person leaving owes nobody one.
592
+ */
593
+ async function deleteMyAccount(c: Ctx, wiring: AuthWiring): Promise<Response> {
594
+ const holder = accountHolder(c);
595
+ if (!holder) throw new UnauthorizedError({ message: "Authentication required." });
596
+ const { ip, userAgent } = correlation(c.req.raw.headers);
597
+ const deps = lifecycleDeps(c, wiring, {
598
+ ip,
599
+ userAgent,
600
+ requestId: c.req.header("cf-ray"),
601
+ metadata: { sessionId: holder.sessionId, suspended: holder.suspended },
602
+ });
603
+ const result = await deleteUser(deps, {
604
+ userId: holder.userId,
605
+ actor: { type: "user", id: holder.userId },
606
+ reason: null,
607
+ });
608
+ const tokens = await userSessionTokens(db(c, wiring), holder.userId);
609
+ const ctx = await (await getAuthInstance(c, wiring)).$context;
610
+ for (const token of tokens) {
611
+ await ctx.internalAdapter.deleteSession(token);
612
+ }
613
+ return c.json(accountDeletionView(result) satisfies AccountDeleteResponse);
614
+ }
615
+
505
616
  /** Revoke one of the authenticated user's devices: sign out its sessions, then drop the device row. */
506
617
  async function revokeMyDevice(c: Ctx, wiring: AuthWiring, body: RevokeDeviceBody): Promise<Response> {
507
618
  const userId = c.var.auth?.userId;
@@ -1,9 +1,12 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
4
5
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
5
6
  import { z } from "zod";
6
7
  import { DevicePlatform } from "../data/device";
8
+ import { VerificationState, VerificationType } from "../data/verificationOutcome";
9
+ import { MAX_REASON } from "../lifecycle/reason";
7
10
 
8
11
  /**
9
12
  * The request schemas for the auth routes Pithy owns. Validation happens at the HTTP boundary
@@ -35,6 +38,66 @@ export const RevokeDeviceBody = z
35
38
  .describe("The body identifying which device to revoke — the caller's own, or an admin-named user's.");
36
39
  export type RevokeDeviceBody = z.output<typeof RevokeDeviceBody>;
37
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
+
38
101
  /**
39
102
  * The user id in the path of every single-user admin route.
40
103
  *
@@ -98,6 +161,30 @@ export const ListDevicesQuery = z
98
161
  .describe("The device-registry query: what to filter by, how many to return, and where to resume.");
99
162
  export type ListDevicesQuery = z.output<typeof ListDevicesQuery>;
100
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
+
101
188
  /**
102
189
  * The body of `POST /admin/sessions/revoke`.
103
190
  *
@@ -116,3 +203,111 @@ export const RevokeSessionBody = z
116
203
  })
117
204
  .describe("The body identifying which single session to revoke.");
118
205
  export type RevokeSessionBody = z.output<typeof RevokeSessionBody>;
206
+
207
+ /**
208
+ * Why an account's access is changing — required on both lifecycle routes (#621).
209
+ *
210
+ * Trimmed, then bounded by the same constant the transition enforces, so a reason the transition would refuse
211
+ * is a 400 here rather than a conflict later. Required rather than defaulted: a suspension nobody explained is
212
+ * a lockout the person cannot answer, and the trail would record nothing about why.
213
+ */
214
+ const LifecycleReason = z
215
+ .string()
216
+ .trim()
217
+ .min(1)
218
+ .max(MAX_REASON)
219
+ .describe(
220
+ "Why, in a sentence written for the person. A suspension's reason is what every refused sign-in shows them.",
221
+ );
222
+
223
+ /** Whether the person is mailed. */
224
+ const Notify = z
225
+ .boolean()
226
+ .optional()
227
+ .describe(
228
+ "Whether to mail the person. Absent is true. The config can turn a lifecycle mail off for every call; this turns it off for one.",
229
+ );
230
+
231
+ /** The body of `POST /admin/users/:userId/suspend`. */
232
+ export const SuspendUserBody = z
233
+ .object({
234
+ reason: LifecycleReason,
235
+ until: JsonDate.optional().describe(
236
+ "When the suspension ends by itself, as an ISO-8601 timestamp. Must be in the future. Absent lasts until a reinstatement. Nothing is written when it passes.",
237
+ ),
238
+ notify: Notify,
239
+ })
240
+ .describe(
241
+ "A suspension: why, until when, and whether to tell the person. Suspending a suspended account restates the reason and the end.",
242
+ );
243
+ export type SuspendUserBody = z.output<typeof SuspendUserBody>;
244
+
245
+ /** The body of `POST /admin/users/:userId/reinstate`. */
246
+ export const ReinstateUserBody = z
247
+ .object({ reason: LifecycleReason, notify: Notify })
248
+ .describe("A reinstatement: why, and whether to tell the person. It restores no session.");
249
+ export type ReinstateUserBody = z.output<typeof ReinstateUserBody>;
250
+
251
+ /**
252
+ * How a deletion runs (#622). `soft` is the default and the only thing an omission reaches: the account is shut
253
+ * now and erased once the window closes, restorable until then. `hard` starts the purge at once, with no
254
+ * window, and is reached only by naming it — a typo is a 400, never either mode.
255
+ */
256
+ export const DeletionMode = z
257
+ .enum(["soft", "hard"])
258
+ .describe(
259
+ "`soft` (the default): the account is shut now and its data erased once `retention.purgeAfterDays` have passed; it can be restored until then. `hard`: the purge starts now, with no window and nothing to restore.",
260
+ );
261
+ export type DeletionMode = z.output<typeof DeletionMode>;
262
+
263
+ /** The body of `DELETE /admin/users/:userId`. */
264
+ export const DeleteUserBody = z
265
+ .object({
266
+ mode: DeletionMode.default("soft").describe(
267
+ "`soft` unless named: the window, then the purge. `hard` purges now. Anything else is refused.",
268
+ ),
269
+ reason: LifecycleReason,
270
+ notify: z
271
+ .boolean()
272
+ .optional()
273
+ .describe(
274
+ "Whether to mail the person. Absent is true. It silences the mail this call sends: the deletion-scheduled notice for `soft`, the deletion-complete notice for `hard`.",
275
+ ),
276
+ })
277
+ .describe("A deletion: soft or hard, why, and whether to tell the person.");
278
+ export type DeleteUserBody = z.output<typeof DeleteUserBody>;
279
+
280
+ /** The body of `POST /admin/users/:userId/restore`. */
281
+ export const RestoreUserBody = z
282
+ .object({ reason: LifecycleReason })
283
+ .describe("A restoration inside the purge window: why. It restores no session; the person signs in again.");
284
+ export type RestoreUserBody = z.output<typeof RestoreUserBody>;
285
+
286
+ /**
287
+ * The query of `GET /admin/users/:userId/export`. A disclosure of everything the kit holds about one person
288
+ * says why, like every lifecycle call: the reason goes on the trail beside who asked.
289
+ */
290
+ export const ExportUserQuery = z
291
+ .object({
292
+ reason: LifecycleReason.describe(
293
+ "Why this person's data is being exported — the access request it answers. Recorded on the audit trail.",
294
+ ),
295
+ })
296
+ .describe("An export: why it is being made.");
297
+ export type ExportUserQuery = z.output<typeof ExportUserQuery>;
298
+
299
+ /**
300
+ * The body of `DELETE /account`, the signed-in person deleting their own account (#622).
301
+ *
302
+ * The confirmation is the literal `true`, so a client must say it on purpose: a stray `DELETE` with an empty
303
+ * body, or a form posting `"false"`, deletes nothing. There is no field naming an account — the subject is the
304
+ * session's own, always — and a key that tries is dropped.
305
+ */
306
+ export const DeleteAccountBody = z
307
+ .object({
308
+ confirm: z
309
+ .literal(true)
310
+ .describe("Must be `true`. The person confirmed, in your app, that they want their account deleted."),
311
+ })
312
+ .describe("A self-service deletion: the person's own confirmation. Always soft, on the configured window.");
313
+ export type DeleteAccountBody = z.output<typeof DeleteAccountBody>;
package/src/http/views.ts CHANGED
@@ -1,9 +1,32 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import type { Session, User } from "../data/betterAuth";
4
+ import type { PurgeExportEntry } from "@pithy-sh/core/src/capability/purge";
5
+ import type { Account, Session, User } from "../data/betterAuth";
5
6
  import type { Device } from "../data/device";
6
- import type { AdminDeviceView, AdminSessionView, AdminUserView } from "./responses";
7
+ import type { UserLifecycleEvent } from "../data/userLifecycle";
8
+ import { type VerificationOutcome, verificationStateAt } from "../data/verificationOutcome";
9
+ import { type AccountStanding, accountStanding } from "../lifecycle/state";
10
+ import type {
11
+ DeleteTransition,
12
+ DeletionMode,
13
+ LifecycleTransition,
14
+ RestoreTransition,
15
+ SuspendTransition,
16
+ } from "../lifecycle/transitions";
17
+ import type {
18
+ AccountDeleteResponse,
19
+ AdminDeviceView,
20
+ AdminSessionView,
21
+ AdminUserDeleteResponse,
22
+ AdminUserExportResponse,
23
+ AdminUserReinstateResponse,
24
+ AdminUserRestoreResponse,
25
+ AdminUserSuspendResponse,
26
+ AdminUserView,
27
+ AdminVerificationView,
28
+ AuthUserExport,
29
+ } from "./responses";
7
30
 
8
31
  /**
9
32
  * The admin projections — what a management client is shown of a user, a session, and a device.
@@ -30,8 +53,12 @@ import type { AdminDeviceView, AdminSessionView, AdminUserView } from "./respons
30
53
  * `locale` is projected for the same reason: a support pane answering "why is this person getting
31
54
  * English emails" needs to see whether they ever chose, and null — never chosen — is the answer half
32
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.
33
60
  */
34
- export function userView(user: User): AdminUserView {
61
+ export function userView(user: User, now: Date): AdminUserView {
35
62
  return {
36
63
  id: user.id,
37
64
  email: user.email,
@@ -41,6 +68,22 @@ export function userView(user: User): AdminUserView {
41
68
  locale: user.locale,
42
69
  createdAt: user.createdAt.toISOString(),
43
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,
44
87
  };
45
88
  }
46
89
 
@@ -91,3 +134,149 @@ export function deviceView(device: Device): AdminDeviceView {
91
134
  createdAt: device.createdAt.toISOString(),
92
135
  };
93
136
  }
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
+
155
+ /**
156
+ * The suspension projection (#621): the suspension the transition left in force, and the sessions the route
157
+ * revoked after it. Dates cross as ISO-8601, like every other response here.
158
+ */
159
+ export function suspensionView(
160
+ userId: string,
161
+ result: SuspendTransition,
162
+ sessionsRevoked: number,
163
+ ): AdminUserSuspendResponse {
164
+ return {
165
+ userId,
166
+ state: "suspended",
167
+ outcome: result.updated ? "updated" : "suspended",
168
+ suspendedAt: result.suspendedAt.toISOString(),
169
+ suspendedUntil: result.suspendedUntil?.toISOString() ?? null,
170
+ sessionsRevoked,
171
+ mailed: result.mailed,
172
+ };
173
+ }
174
+
175
+ /** The reinstatement projection (#621). A call that found no suspension in force is `unchanged`. */
176
+ export function reinstatementView(userId: string, result: LifecycleTransition): AdminUserReinstateResponse {
177
+ return {
178
+ userId,
179
+ state: "active",
180
+ outcome: result.changed ? "reinstated" : "unchanged",
181
+ mailed: result.mailed,
182
+ };
183
+ }
184
+
185
+ /** What became of a deletion's purge: due later, started by the call, or due with nothing bound to start it. */
186
+ export type PurgeDisposition = AdminUserDeleteResponse["purge"];
187
+
188
+ /**
189
+ * The deletion projection (#622): the deletion the transition left in force, the sessions the route revoked
190
+ * after it, and what became of the purge.
191
+ */
192
+ export function deletionView(
193
+ userId: string,
194
+ mode: DeletionMode,
195
+ result: DeleteTransition,
196
+ purge: PurgeDisposition,
197
+ sessionsRevoked: number,
198
+ ): AdminUserDeleteResponse {
199
+ return {
200
+ userId,
201
+ state: "deleted",
202
+ mode,
203
+ outcome: result.outcome,
204
+ deletedAt: result.deletedAt.toISOString(),
205
+ purgeAfter: result.purgeAfter.toISOString(),
206
+ purge,
207
+ sessionsRevoked,
208
+ mailed: result.mailed,
209
+ };
210
+ }
211
+
212
+ /** The restoration projection (#622). A call that found the account not deleted is `unchanged`. */
213
+ export function restorationView(userId: string, result: RestoreTransition): AdminUserRestoreResponse {
214
+ return { userId, state: result.state, outcome: result.changed ? "restored" : "unchanged" };
215
+ }
216
+
217
+ /** The self-service deletion projection (#622). */
218
+ export function accountDeletionView(result: DeleteTransition): AccountDeleteResponse {
219
+ return { state: "deleted", purgeAfter: result.purgeAfter.toISOString(), mailed: result.mailed };
220
+ }
221
+
222
+ /** A date as the wire carries it, or null. */
223
+ function iso(date: Date | null | undefined): string | null {
224
+ return date ? date.toISOString() : null;
225
+ }
226
+
227
+ /**
228
+ * What auth holds about one account, as its export carries it (#622) — the person's own data, projected through
229
+ * the same views a support pane sees, so a session token, a provider token and a push token are absent here by
230
+ * the same construction that keeps them out of every other response. The operator who made a transition is
231
+ * theirs to disclose, not the person's, so the history carries the kind of actor and not its id.
232
+ */
233
+ export function authUserExportView(input: {
234
+ /** The instant the export was taken, which its `state` is judged at. */
235
+ now: Date;
236
+ user: User;
237
+ sessions: readonly Session[];
238
+ accounts: readonly Pick<Account, "providerId" | "createdAt">[];
239
+ devices: readonly Device[];
240
+ history: readonly UserLifecycleEvent[];
241
+ verifications?: readonly VerificationOutcome[];
242
+ plugins?: Record<string, Record<string, unknown>[]>;
243
+ }): AuthUserExport {
244
+ const { user } = input;
245
+ return {
246
+ user: {
247
+ ...userView(user, input.now),
248
+ suspendedAt: iso(user.suspendedAt),
249
+ suspendedUntil: iso(user.suspendedUntil),
250
+ deletedAt: iso(user.deletedAt),
251
+ purgeAfter: iso(user.purgeAfter),
252
+ },
253
+ sessions: input.sessions.map(sessionView),
254
+ providers: input.accounts.map((account) => ({
255
+ providerId: account.providerId,
256
+ createdAt: account.createdAt.toISOString(),
257
+ })),
258
+ devices: input.devices.map(deviceView),
259
+ history: input.history.map((event) => ({
260
+ action: event.action,
261
+ actorType: event.actorType,
262
+ reason: event.reason,
263
+ suspendedUntil: iso(event.suspendedUntil),
264
+ createdAt: event.createdAt.toISOString(),
265
+ })),
266
+ verifications: (input.verifications ?? []).map((row) => verificationView(row, input.now)),
267
+ plugins: input.plugins ?? {},
268
+ };
269
+ }
270
+
271
+ /** The export document (#622): who it is about, when it was read, and every capability's part. */
272
+ export function exportView(
273
+ userId: string,
274
+ exportedAt: Date,
275
+ entries: readonly PurgeExportEntry[],
276
+ ): AdminUserExportResponse {
277
+ return {
278
+ subject: { type: "user", id: userId },
279
+ exportedAt: exportedAt.toISOString(),
280
+ capabilities: entries.map((entry) => ({ ...entry })),
281
+ };
282
+ }
package/src/index.ts CHANGED
@@ -22,3 +22,5 @@ export {
22
22
  authSecretsRegistry,
23
23
  GoogleOAuthCredentials,
24
24
  } from "./instance/secrets";
25
+ export { type McpCapability, McpConfig, type McpConfigInput, mcp } from "./mcp/capability";
26
+ export { McpFloor } from "./mcp/floor";