@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
@@ -9,13 +9,18 @@ import { noticedRefusal } from "../lifecycle/enforce.js";
9
9
  import { PROFILE_IMAGE_PATH } from "../profile/profile.js";
10
10
  import { collapseProviderRefusal } from "./providerRefusal.js";
11
11
  import { getAuthInstance, resolveDb } from "./resolve.js";
12
- import { requireAuth } from "./middleware.js";
12
+ import { accountHolder, requireAccountHolder, requireAuth } from "./middleware.js";
13
+ import { userSessionTokens } from "../admin/users.js";
14
+ import { lifecycleDeps } from "../lifecycle/request.js";
15
+ import { deleteUser } from "../lifecycle/transitions.js";
13
16
  import { consumeSession, findConsumedToken, pruneConsumedTokens, recordConsumedToken, revokeFamily } from "../token/rotation.js";
14
- import { MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses.js";
15
- import { RevokeDeviceBody } from "./schemas.js";
17
+ import { AccountDeleteResponse, HandoffExchangeResponse, MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses.js";
18
+ import { DeleteAccountBody, HandoffExchangeBody, RevokeDeviceBody, SocialSignInStartQuery } from "./schemas.js";
19
+ import { accountDeletionView } from "./views.js";
16
20
  import { registerAuthAdminRoutes } from "./adminRoutes.js";
17
21
  import { guardErrorCallbackURL } from "./errorCallbackUrl.js";
18
22
  import { apiErrorToPithy } from "./errors.js";
23
+ import { exchangeHandoff, handOffToApp, startNativeSignIn } from "./handoff.js";
19
24
  import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate.js";
20
25
  import { NotFoundError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
21
26
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
@@ -23,6 +28,7 @@ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
23
28
  import { validate } from "@pithy-sh/core/src/http/validation";
24
29
  import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
25
30
  import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
31
+ import { announceSessionRotated } from "@pithy-sh/core/src/session/rotated";
26
32
  import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
27
33
  //#region src/http/routes.ts
28
34
  /**
@@ -51,8 +57,11 @@ function db(c, wiring) {
51
57
  * | Route | Verification | Input |
52
58
  * | -------------------------- | --------------- | --------------------------- |
53
59
  * | `POST /token/rotate` | bearer/session | none — the credential only |
60
+ * | `GET /sign-in/social/start` | public | query `SocialSignInStartQuery` |
61
+ * | `POST /handoff` | public | json `HandoffExchangeBody` |
54
62
  * | `GET /devices` | bearer/session | none |
55
63
  * | `POST /devices/revoke` | bearer/session | json `RevokeDeviceBody` |
64
+ * | `DELETE /account` | bearer/session | json `DeleteAccountBody` |
56
65
  * | `* /admin/*` | control-plane | see `./adminRoutes` |
57
66
  *
58
67
  * The catch-all takes NO validator, deliberately: `handleBetterAuth` hands Better Auth `c.req.raw`,
@@ -71,19 +80,34 @@ function createAuthRoutes(wiring) {
71
80
  const base = wiring.config.basePath;
72
81
  const csrf = requireSameOrigin();
73
82
  if (wiring.turnstile) {
83
+ const { mode, token } = wiring.turnstile;
74
84
  const guard = turnstile({
75
- mode: wiring.turnstile.mode,
85
+ mode,
86
+ field: token.field,
87
+ header: token.header,
76
88
  action: TURNSTILE_LOGIN_ACTION
77
89
  });
78
90
  app.use(`${base}/sign-in/magic-link`, guard);
79
91
  app.use(`${base}/email-otp/send-verification-otp`, guard);
80
92
  }
81
93
  app.post(`${base}/token/rotate`, describeRoute({
82
- summary: "Trade the current refresh credential for a new access token and its successor.",
94
+ summary: "Trade the current session token for its successor, and a JWT for services outside this Worker.",
83
95
  description: "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.",
84
96
  verification: ["bearer", "session"],
85
97
  responses: { 200: TokenRotateResponse }
86
98
  }), csrf, (c) => rotateToken(c, wiring));
99
+ app.get(`${base}/sign-in/social/start`, describeRoute({
100
+ summary: "Start a native app's redirect sign-in inside the system browser.",
101
+ description: "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`.",
102
+ verification: ["public"],
103
+ responses: { 302: { description: "A redirect to the provider's authorization page, setting the sign-in's state cookie." } }
104
+ }), validate("query", SocialSignInStartQuery), (c) => startNativeSignIn(c, wiring, c.req.valid("query")));
105
+ app.post(`${base}/handoff`, describeRoute({
106
+ summary: "Trade the one-time code a redirect sign-in left on an app's link for the session token.",
107
+ description: "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.",
108
+ verification: ["public"],
109
+ responses: { 200: HandoffExchangeResponse }
110
+ }), validate("json", HandoffExchangeBody), (c) => exchangeHandoff(c, wiring, c.req.valid("json")));
87
111
  app.get(`${base}/devices`, describeRoute({
88
112
  summary: "List the caller's own registered devices.",
89
113
  verification: ["bearer", "session"],
@@ -94,6 +118,12 @@ function createAuthRoutes(wiring) {
94
118
  verification: ["bearer", "session"],
95
119
  responses: { 200: MyDeviceRevokeResponse }
96
120
  }), requireAuth(), csrf, validate("json", RevokeDeviceBody), (c) => revokeMyDevice(c, wiring, c.req.valid("json")));
121
+ app.delete(`${base}/account`, describeRoute({
122
+ summary: "Delete the caller's own account. Always soft: restorable until the purge window closes.",
123
+ description: "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`.",
124
+ verification: ["bearer", "session"],
125
+ responses: { 200: AccountDeleteResponse }
126
+ }), requireAccountHolder(), csrf, validate("json", DeleteAccountBody), (c) => deleteMyAccount(c, wiring));
97
127
  app.post(`${base}/link-social`, describeRoute({
98
128
  summary: "Connect another sign-in provider to the caller's account.",
99
129
  description: "Better Auth's endpoint, behind a kit gate: the caller must have signed in within the last fifteen minutes, or it is refused with `auth/session_not_fresh`.",
@@ -229,6 +259,8 @@ async function handleBetterAuth(c, wiring) {
229
259
  });
230
260
  return collapsed.response;
231
261
  }
262
+ const handedOff = await handOffToApp(c, wiring, instance, response);
263
+ if (handedOff) return handedOff;
232
264
  await auditRefusal(c, response);
233
265
  return response;
234
266
  }
@@ -324,6 +356,16 @@ async function rotateToken(c, wiring) {
324
356
  ip,
325
357
  userAgent
326
358
  });
359
+ const failures = await announceSessionRotated(wiring.composed ?? [], {
360
+ previousSessionId: current.session.id,
361
+ sessionId: next.id,
362
+ userId: current.user.id,
363
+ env: c.env
364
+ });
365
+ for (const failure of failures) c.var.log?.child("auth").warn("a session-rotated listener failed; its state stayed on the spent session", {
366
+ capability: failure.capability,
367
+ error: failure.error instanceof Error ? failure.error.message : String(failure.error)
368
+ });
327
369
  try {
328
370
  await pruneConsumedTokens(database, /* @__PURE__ */ new Date(Date.now() - wiring.config.sessionExpiresIn * 1e3));
329
371
  } catch {}
@@ -339,6 +381,37 @@ async function listMyDevices(c, wiring) {
339
381
  if (!userId) throw new UnauthorizedError({ message: "Authentication required." });
340
382
  return c.json({ devices: await listDevices(db(c, wiring), userId) });
341
383
  }
384
+ /**
385
+ * Delete the caller's own account (#622): soft, on the configured window, audited as `auth/user_self_deleted`
386
+ * with them as the actor, and every session they hold ended after the columns are written — through Better
387
+ * Auth's adapter, so `onSessionRevoked` hears each. No reason: a person leaving owes nobody one.
388
+ */
389
+ async function deleteMyAccount(c, wiring) {
390
+ const holder = accountHolder(c);
391
+ if (!holder) throw new UnauthorizedError({ message: "Authentication required." });
392
+ const { ip, userAgent } = correlation(c.req.raw.headers);
393
+ const deps = lifecycleDeps(c, wiring, {
394
+ ip,
395
+ userAgent,
396
+ requestId: c.req.header("cf-ray"),
397
+ metadata: {
398
+ sessionId: holder.sessionId,
399
+ suspended: holder.suspended
400
+ }
401
+ });
402
+ const result = await deleteUser(deps, {
403
+ userId: holder.userId,
404
+ actor: {
405
+ type: "user",
406
+ id: holder.userId
407
+ },
408
+ reason: null
409
+ });
410
+ const tokens = await userSessionTokens(db(c, wiring), holder.userId);
411
+ const ctx = await (await getAuthInstance(c, wiring)).$context;
412
+ for (const token of tokens) await ctx.internalAdapter.deleteSession(token);
413
+ return c.json(accountDeletionView(result));
414
+ }
342
415
  /** Revoke one of the authenticated user's devices: sign out its sessions, then drop the device row. */
343
416
  async function revokeMyDevice(c, wiring, body) {
344
417
  const userId = c.var.auth?.userId;
@@ -23,6 +23,42 @@ export declare const RevokeDeviceBody: z.ZodObject<{
23
23
  deviceId: z.ZodString;
24
24
  }, z.core.$strip>;
25
25
  export type RevokeDeviceBody = z.output<typeof RevokeDeviceBody>;
26
+ /**
27
+ * The body of `POST /handoff`: the one-time code a redirect sign-in left on the app's link, and the verifier whose
28
+ * challenge the sign-in carried. Bounded rather than shape-checked, so a malformed code or verifier is refused, and
29
+ * the code spent, by the same trade that refuses a spent code, with the same answer.
30
+ */
31
+ export declare const HandoffExchangeBody: z.ZodObject<{
32
+ code: z.ZodString;
33
+ verifier: z.ZodString;
34
+ }, z.core.$strip>;
35
+ export type HandoffExchangeBody = z.output<typeof HandoffExchangeBody>;
36
+ /** The providers a native app can sign in with through the system browser: every redirect provider auth offers. */
37
+ export declare const RedirectProvider: z.ZodEnum<{
38
+ apple: "apple";
39
+ facebook: "facebook";
40
+ github: "github";
41
+ google: "google";
42
+ microsoft: "microsoft";
43
+ }>;
44
+ export type RedirectProvider = z.output<typeof RedirectProvider>;
45
+ /**
46
+ * The query of `GET /sign-in/social/start`, the address a native app opens in the system browser's sign-in sheet.
47
+ * Bounded rather than shape-checked: the handler holds `callbackURL` to `trustedOrigins` and to carrying a
48
+ * `handoff_challenge`, and Better Auth checks both URLs again when the sign-in starts.
49
+ */
50
+ export declare const SocialSignInStartQuery: z.ZodObject<{
51
+ provider: z.ZodEnum<{
52
+ apple: "apple";
53
+ facebook: "facebook";
54
+ github: "github";
55
+ google: "google";
56
+ microsoft: "microsoft";
57
+ }>;
58
+ callbackURL: z.ZodString;
59
+ errorCallbackURL: z.ZodOptional<z.ZodString>;
60
+ }, z.core.$strip>;
61
+ export type SocialSignInStartQuery = z.output<typeof SocialSignInStartQuery>;
26
62
  /**
27
63
  * The user id in the path of every single-user admin route.
28
64
  *
@@ -53,6 +89,27 @@ export declare const ListDevicesQuery: z.ZodObject<{
53
89
  limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
54
90
  }, z.core.$strip>;
55
91
  export type ListDevicesQuery = z.output<typeof ListDevicesQuery>;
92
+ /**
93
+ * The verification ledger read's query (#829): a window of issue times, what to narrow it to, and where to resume.
94
+ * Both bounds are optional — the last 30 days, ending now — and a window that ends before it starts is refused by
95
+ * the handler, which is where the default is known.
96
+ */
97
+ export declare const ListVerificationsQuery: z.ZodObject<{
98
+ since: z.ZodOptional<z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>>;
99
+ until: z.ZodOptional<z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>>;
100
+ type: z.ZodOptional<z.ZodEnum<{
101
+ magic_link: "magic_link";
102
+ otp: "otp";
103
+ }>>;
104
+ state: z.ZodOptional<z.ZodEnum<{
105
+ expired: "expired";
106
+ pending: "pending";
107
+ used: "used";
108
+ }>>;
109
+ cursor: z.ZodOptional<z.ZodString>;
110
+ limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
111
+ }, z.core.$strip>;
112
+ export type ListVerificationsQuery = z.output<typeof ListVerificationsQuery>;
56
113
  /**
57
114
  * The body of `POST /admin/sessions/revoke`.
58
115
  *
@@ -65,4 +122,61 @@ export declare const RevokeSessionBody: z.ZodObject<{
65
122
  sessionId: z.ZodString;
66
123
  }, z.core.$strip>;
67
124
  export type RevokeSessionBody = z.output<typeof RevokeSessionBody>;
125
+ /** The body of `POST /admin/users/:userId/suspend`. */
126
+ export declare const SuspendUserBody: z.ZodObject<{
127
+ reason: z.ZodString;
128
+ until: z.ZodOptional<z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>>;
129
+ notify: z.ZodOptional<z.ZodBoolean>;
130
+ }, z.core.$strip>;
131
+ export type SuspendUserBody = z.output<typeof SuspendUserBody>;
132
+ /** The body of `POST /admin/users/:userId/reinstate`. */
133
+ export declare const ReinstateUserBody: z.ZodObject<{
134
+ reason: z.ZodString;
135
+ notify: z.ZodOptional<z.ZodBoolean>;
136
+ }, z.core.$strip>;
137
+ export type ReinstateUserBody = z.output<typeof ReinstateUserBody>;
138
+ /**
139
+ * How a deletion runs (#622). `soft` is the default and the only thing an omission reaches: the account is shut
140
+ * now and erased once the window closes, restorable until then. `hard` starts the purge at once, with no
141
+ * window, and is reached only by naming it — a typo is a 400, never either mode.
142
+ */
143
+ export declare const DeletionMode: z.ZodEnum<{
144
+ hard: "hard";
145
+ soft: "soft";
146
+ }>;
147
+ export type DeletionMode = z.output<typeof DeletionMode>;
148
+ /** The body of `DELETE /admin/users/:userId`. */
149
+ export declare const DeleteUserBody: z.ZodObject<{
150
+ mode: z.ZodDefault<z.ZodEnum<{
151
+ hard: "hard";
152
+ soft: "soft";
153
+ }>>;
154
+ reason: z.ZodString;
155
+ notify: z.ZodOptional<z.ZodBoolean>;
156
+ }, z.core.$strip>;
157
+ export type DeleteUserBody = z.output<typeof DeleteUserBody>;
158
+ /** The body of `POST /admin/users/:userId/restore`. */
159
+ export declare const RestoreUserBody: z.ZodObject<{
160
+ reason: z.ZodString;
161
+ }, z.core.$strip>;
162
+ export type RestoreUserBody = z.output<typeof RestoreUserBody>;
163
+ /**
164
+ * The query of `GET /admin/users/:userId/export`. A disclosure of everything the kit holds about one person
165
+ * says why, like every lifecycle call: the reason goes on the trail beside who asked.
166
+ */
167
+ export declare const ExportUserQuery: z.ZodObject<{
168
+ reason: z.ZodString;
169
+ }, z.core.$strip>;
170
+ export type ExportUserQuery = z.output<typeof ExportUserQuery>;
171
+ /**
172
+ * The body of `DELETE /account`, the signed-in person deleting their own account (#622).
173
+ *
174
+ * The confirmation is the literal `true`, so a client must say it on purpose: a stray `DELETE` with an empty
175
+ * body, or a form posting `"false"`, deletes nothing. There is no field naming an account — the subject is the
176
+ * session's own, always — and a key that tries is dropped.
177
+ */
178
+ export declare const DeleteAccountBody: z.ZodObject<{
179
+ confirm: z.ZodLiteral<true>;
180
+ }, z.core.$strip>;
181
+ export type DeleteAccountBody = z.output<typeof DeleteAccountBody>;
68
182
  //# sourceMappingURL=schemas.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/http/schemas.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;;;;;;;;GAWG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB;;iBAQ2E,CAAC;AACzG,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE;;;;;;GAMG;AACH,eAAO,MAAM,WAAW;;iBAIoD,CAAC;AAC7E,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAkBvD,8BAA8B;AAC9B,eAAO,MAAM,cAAc;;;;iBAawE,CAAC;AACpG,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D,yCAAyC;AACzC,eAAO,MAAM,gBAAgB;;;;;;;;;iBAYwE,CAAC;AACtG,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;A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+E,CAAC;AAC9G,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
@@ -1,7 +1,10 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { DevicePlatform } from "../data/device.js";
4
+ import { VerificationState, VerificationType } from "../data/verificationOutcome.js";
5
+ import "../lifecycle/reason.js";
4
6
  import { z } from "zod";
7
+ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
5
8
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
6
9
  //#region src/http/schemas.ts
7
10
  /**
@@ -24,6 +27,33 @@ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
24
27
  */
25
28
  const RevokeDeviceBody = z.object({ deviceId: z.string().min(1).max(256).describe("The id of the device to revoke — the client-generated id it registered at sign-in.") }).describe("The body identifying which device to revoke — the caller's own, or an admin-named user's.");
26
29
  /**
30
+ * The body of `POST /handoff`: the one-time code a redirect sign-in left on the app's link, and the verifier whose
31
+ * challenge the sign-in carried. Bounded rather than shape-checked, so a malformed code or verifier is refused, and
32
+ * the code spent, by the same trade that refuses a spent code, with the same answer.
33
+ */
34
+ const HandoffExchangeBody = z.object({
35
+ code: z.string().min(1).max(256).describe("The one-time code from the `code` parameter of the deep link the sign-in returned to."),
36
+ verifier: z.string().min(1).max(256).describe("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.")
37
+ }).describe("The code a native app trades for its session after a redirect sign-in, with the verifier that binds it.");
38
+ /** The providers a native app can sign in with through the system browser: every redirect provider auth offers. */
39
+ const RedirectProvider = z.enum([
40
+ "apple",
41
+ "facebook",
42
+ "github",
43
+ "google",
44
+ "microsoft"
45
+ ]).describe("A sign-in provider that completes in the browser, by redirect. Whether this Worker enables it is its config's call.");
46
+ /**
47
+ * The query of `GET /sign-in/social/start`, the address a native app opens in the system browser's sign-in sheet.
48
+ * Bounded rather than shape-checked: the handler holds `callbackURL` to `trustedOrigins` and to carrying a
49
+ * `handoff_challenge`, and Better Auth checks both URLs again when the sign-in starts.
50
+ */
51
+ const SocialSignInStartQuery = z.object({
52
+ provider: RedirectProvider,
53
+ callbackURL: z.string().min(1).max(2048).describe("The app's own link, in `trustedOrigins`, carrying the `handoff_challenge` the app made: where the sign-in returns with a one-time code."),
54
+ errorCallbackURL: z.string().min(1).max(2048).optional().describe("Where a refused sign-in returns, with an `error` parameter. In `trustedOrigins`. Absent, a refusal lands on the auth error page.")
55
+ }).describe("A native redirect sign-in, started in the system browser so the provider's state cookie lands in its jar.");
56
+ /**
27
57
  * The user id in the path of every single-user admin route.
28
58
  *
29
59
  * Bounded rather than `.uuid()`: Better Auth's id generator is configurable and its default is not a
@@ -48,6 +78,21 @@ const ListDevicesQuery = z.object({
48
78
  cursor: PageCursorParam,
49
79
  limit: PageLimit
50
80
  }).describe("The device-registry query: what to filter by, how many to return, and where to resume.");
81
+ /** A window bound on the verification read: ISO-8601 with an offset, decoded to a `Date` here so no handler parses it. */
82
+ const WindowBound = z.iso.datetime({ offset: true }).transform((value) => new Date(value));
83
+ /**
84
+ * The verification ledger read's query (#829): a window of issue times, what to narrow it to, and where to resume.
85
+ * Both bounds are optional — the last 30 days, ending now — and a window that ends before it starts is refused by
86
+ * the handler, which is where the default is known.
87
+ */
88
+ const ListVerificationsQuery = z.object({
89
+ since: WindowBound.optional().describe("The window's start, inclusive, on issue time, ISO-8601. Defaults to 30 days before `until`."),
90
+ until: WindowBound.optional().describe("The window's end, exclusive, on issue time, ISO-8601. Defaults to now."),
91
+ type: VerificationType.optional().describe("Narrow the rows to one type. The counts always cover every type."),
92
+ state: VerificationState.optional().describe("Narrow the rows to one state, judged at the moment of the read. The counts always cover every state."),
93
+ cursor: PageCursorParam,
94
+ limit: PageLimit
95
+ }).describe("The verification ledger query: the window, what to narrow the rows to, how many, and where to resume.");
51
96
  /**
52
97
  * The body of `POST /admin/sessions/revoke`.
53
98
  *
@@ -57,5 +102,53 @@ const ListDevicesQuery = z.object({
57
102
  * the read routes project.
58
103
  */
59
104
  const RevokeSessionBody = z.object({ sessionId: z.string().min(1).max(255).describe("The session's id, as the admin read routes report it. Not the session token.") }).describe("The body identifying which single session to revoke.");
105
+ /**
106
+ * Why an account's access is changing — required on both lifecycle routes (#621).
107
+ *
108
+ * Trimmed, then bounded by the same constant the transition enforces, so a reason the transition would refuse
109
+ * is a 400 here rather than a conflict later. Required rather than defaulted: a suspension nobody explained is
110
+ * a lockout the person cannot answer, and the trail would record nothing about why.
111
+ */
112
+ const LifecycleReason = z.string().trim().min(1).max(500).describe("Why, in a sentence written for the person. A suspension's reason is what every refused sign-in shows them.");
113
+ /** Whether the person is mailed. */
114
+ const Notify = z.boolean().optional().describe("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.");
115
+ /** The body of `POST /admin/users/:userId/suspend`. */
116
+ const SuspendUserBody = z.object({
117
+ reason: LifecycleReason,
118
+ until: JsonDate.optional().describe("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."),
119
+ notify: Notify
120
+ }).describe("A suspension: why, until when, and whether to tell the person. Suspending a suspended account restates the reason and the end.");
121
+ /** The body of `POST /admin/users/:userId/reinstate`. */
122
+ const ReinstateUserBody = z.object({
123
+ reason: LifecycleReason,
124
+ notify: Notify
125
+ }).describe("A reinstatement: why, and whether to tell the person. It restores no session.");
126
+ /**
127
+ * How a deletion runs (#622). `soft` is the default and the only thing an omission reaches: the account is shut
128
+ * now and erased once the window closes, restorable until then. `hard` starts the purge at once, with no
129
+ * window, and is reached only by naming it — a typo is a 400, never either mode.
130
+ */
131
+ const DeletionMode = z.enum(["soft", "hard"]).describe("`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.");
132
+ /** The body of `DELETE /admin/users/:userId`. */
133
+ const DeleteUserBody = z.object({
134
+ mode: DeletionMode.default("soft").describe("`soft` unless named: the window, then the purge. `hard` purges now. Anything else is refused."),
135
+ reason: LifecycleReason,
136
+ notify: z.boolean().optional().describe("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`.")
137
+ }).describe("A deletion: soft or hard, why, and whether to tell the person.");
138
+ /** The body of `POST /admin/users/:userId/restore`. */
139
+ const RestoreUserBody = z.object({ reason: LifecycleReason }).describe("A restoration inside the purge window: why. It restores no session; the person signs in again.");
140
+ /**
141
+ * The query of `GET /admin/users/:userId/export`. A disclosure of everything the kit holds about one person
142
+ * says why, like every lifecycle call: the reason goes on the trail beside who asked.
143
+ */
144
+ const ExportUserQuery = z.object({ reason: LifecycleReason.describe("Why this person's data is being exported — the access request it answers. Recorded on the audit trail.") }).describe("An export: why it is being made.");
145
+ /**
146
+ * The body of `DELETE /account`, the signed-in person deleting their own account (#622).
147
+ *
148
+ * The confirmation is the literal `true`, so a client must say it on purpose: a stray `DELETE` with an empty
149
+ * body, or a form posting `"false"`, deletes nothing. There is no field naming an account — the subject is the
150
+ * session's own, always — and a key that tries is dropped.
151
+ */
152
+ const DeleteAccountBody = z.object({ confirm: z.literal(true).describe("Must be `true`. The person confirmed, in your app, that they want their account deleted.") }).describe("A self-service deletion: the person's own confirmation. Always soft, on the configured window.");
60
153
  //#endregion
61
- export { ListDevicesQuery, ListUsersQuery, RevokeDeviceBody, RevokeSessionBody, UserIdParam };
154
+ export { DeleteAccountBody, DeleteUserBody, DeletionMode, ExportUserQuery, HandoffExchangeBody, ListDevicesQuery, ListUsersQuery, ListVerificationsQuery, RedirectProvider, ReinstateUserBody, RestoreUserBody, RevokeDeviceBody, RevokeSessionBody, SocialSignInStartQuery, SuspendUserBody, UserIdParam };
@@ -1,8 +1,13 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import type { Session, User } from "../data/betterAuth";
3
+ import type { PurgeExportEntry } from "@pithy-sh/core/src/capability/purge";
4
+ import type { Account, Session, User } from "../data/betterAuth";
4
5
  import type { Device } from "../data/device";
5
- import type { AdminDeviceView, AdminSessionView, AdminUserView } from "./responses";
6
+ import type { UserLifecycleEvent } from "../data/userLifecycle";
7
+ import { type VerificationOutcome } from "../data/verificationOutcome";
8
+ import { type AccountStanding } from "../lifecycle/state";
9
+ import type { DeleteTransition, DeletionMode, LifecycleTransition, RestoreTransition, SuspendTransition } from "../lifecycle/transitions";
10
+ import type { AccountDeleteResponse, AdminDeviceView, AdminSessionView, AdminUserDeleteResponse, AdminUserExportResponse, AdminUserReinstateResponse, AdminUserRestoreResponse, AdminUserSuspendResponse, AdminUserView, AdminVerificationView, AuthUserExport } from "./responses";
6
11
  /**
7
12
  * The admin projections — what a management client is shown of a user, a session, and a device.
8
13
  *
@@ -27,8 +32,18 @@ import type { AdminDeviceView, AdminSessionView, AdminUserView } from "./respons
27
32
  * `locale` is projected for the same reason: a support pane answering "why is this person getting
28
33
  * English emails" needs to see whether they ever chose, and null — never chosen — is the answer half
29
34
  * the time. It is a preference, not a credential.
35
+ *
36
+ * Where the account stands is projected too (#813), judged at `now`: the listing does not filter a suspended or
37
+ * deleted account out, so without it a pane sees the person and cannot tell whether to offer suspend or reinstate.
38
+ * Not the reason and not who acted — those are the trail's.
39
+ */
40
+ export declare function userView(user: User, now: Date): AdminUserView;
41
+ /**
42
+ * Where an account stands, as the wire carries it (#813) — the organization view's shape: the state, the end of a
43
+ * suspension in force, and the last day a deletion can be undone. Read through `accountStanding`, the function
44
+ * every enforcement point reads, so a suspension past its end reads `active` here exactly as it does at the door.
30
45
  */
31
- export declare function userView(user: User): AdminUserView;
46
+ export declare function standingView(standing: AccountStanding): Required<Pick<AdminUserView, "state" | "suspendedUntil" | "purgeAfter">>;
32
47
  /**
33
48
  * The session projection — **without the token**.
34
49
  *
@@ -52,4 +67,46 @@ export declare function sessionView(session: Session): AdminSessionView;
52
67
  * adopter's users under the adopter's own app identity. It never leaves the Worker.
53
68
  */
54
69
  export declare function deviceView(device: Device): AdminDeviceView;
70
+ /**
71
+ * One verification ledger row, as a management client sees it (#829). `state` is judged at `now`, the moment the
72
+ * read took, so it agrees with the counts beside it.
73
+ */
74
+ export declare function verificationView(row: VerificationOutcome, now: Date): AdminVerificationView;
75
+ /**
76
+ * The suspension projection (#621): the suspension the transition left in force, and the sessions the route
77
+ * revoked after it. Dates cross as ISO-8601, like every other response here.
78
+ */
79
+ export declare function suspensionView(userId: string, result: SuspendTransition, sessionsRevoked: number): AdminUserSuspendResponse;
80
+ /** The reinstatement projection (#621). A call that found no suspension in force is `unchanged`. */
81
+ export declare function reinstatementView(userId: string, result: LifecycleTransition): AdminUserReinstateResponse;
82
+ /** What became of a deletion's purge: due later, started by the call, or due with nothing bound to start it. */
83
+ export type PurgeDisposition = AdminUserDeleteResponse["purge"];
84
+ /**
85
+ * The deletion projection (#622): the deletion the transition left in force, the sessions the route revoked
86
+ * after it, and what became of the purge.
87
+ */
88
+ export declare function deletionView(userId: string, mode: DeletionMode, result: DeleteTransition, purge: PurgeDisposition, sessionsRevoked: number): AdminUserDeleteResponse;
89
+ /** The restoration projection (#622). A call that found the account not deleted is `unchanged`. */
90
+ export declare function restorationView(userId: string, result: RestoreTransition): AdminUserRestoreResponse;
91
+ /** The self-service deletion projection (#622). */
92
+ export declare function accountDeletionView(result: DeleteTransition): AccountDeleteResponse;
93
+ /**
94
+ * What auth holds about one account, as its export carries it (#622) — the person's own data, projected through
95
+ * the same views a support pane sees, so a session token, a provider token and a push token are absent here by
96
+ * the same construction that keeps them out of every other response. The operator who made a transition is
97
+ * theirs to disclose, not the person's, so the history carries the kind of actor and not its id.
98
+ */
99
+ export declare function authUserExportView(input: {
100
+ /** The instant the export was taken, which its `state` is judged at. */
101
+ now: Date;
102
+ user: User;
103
+ sessions: readonly Session[];
104
+ accounts: readonly Pick<Account, "providerId" | "createdAt">[];
105
+ devices: readonly Device[];
106
+ history: readonly UserLifecycleEvent[];
107
+ verifications?: readonly VerificationOutcome[];
108
+ plugins?: Record<string, Record<string, unknown>[]>;
109
+ }): AuthUserExport;
110
+ /** The export document (#622): who it is about, when it was read, and every capability's part. */
111
+ export declare function exportView(userId: string, exportedAt: Date, entries: readonly PurgeExportEntry[]): AdminUserExportResponse;
55
112
  //# sourceMappingURL=views.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"views.d.ts","sourceRoot":"","sources":["../../src/http/views.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEpF;;;;;;;;;;;;GAYG;AAEH;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,aAAa,CAWlD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,gBAAgB,CAU9D;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CAa1D"}
1
+ {"version":3,"file":"views.d.ts","sourceRoot":"","sources":["../../src/http/views.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,KAAK,mBAAmB,EAAuB,MAAM,6BAA6B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