@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
@@ -2,13 +2,16 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
+ import { purgeExports } from "@pithy-sh/core/src/capability/purge";
5
6
  import type { ControlPlaneContext } from "@pithy-sh/core/src/controlPlane/context";
6
7
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
7
8
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
8
9
  import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
9
10
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
10
11
  import { validate } from "@pithy-sh/core/src/http/validation";
12
+ import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
11
13
  import type { Context, Hono } from "hono";
14
+ import type { z } from "zod";
12
15
  import {
13
16
  type AdminSubList,
14
17
  findSessionById,
@@ -25,23 +28,72 @@ import { correlation, emitControlPlaneAction } from "../audit/emit";
25
28
  import type { AuthWiring } from "../capability";
26
29
  import { authDatabase } from "../data/tables";
27
30
  import { deleteDevice, deviceSessionTokens } from "../device/registry";
31
+ import { listVerificationOutcomes, resolveVerificationWindow, verificationCounts } from "../ledger/read";
32
+ import { auditedLifecycleCall, recordLifecycleRefusal } from "../lifecycle/audited";
33
+ import { MAX_REASON } from "../lifecycle/reason";
34
+ import { lifecycleDeps } from "../lifecycle/request";
35
+ import {
36
+ type DeleteTransition,
37
+ deleteUser,
38
+ type LifecycleActor,
39
+ purgeAddress,
40
+ reinstateUser,
41
+ requirePresent,
42
+ restoreUser,
43
+ suspendUser,
44
+ } from "../lifecycle/transitions";
45
+ import { AUTH_PURGE_BINDING } from "../purge/specs";
46
+ import { startPurgeInstance } from "../purge/start";
28
47
  import {
29
48
  AUTH_DEVICES_READ_SCOPE,
30
49
  AUTH_DEVICES_REVOKE_SCOPE,
31
50
  AUTH_SESSIONS_REVOKE_SCOPE,
51
+ AUTH_USERS_DELETE_SCOPE,
52
+ AUTH_USERS_EXPORT_SCOPE,
32
53
  AUTH_USERS_LOGOUT_SCOPE,
33
54
  AUTH_USERS_READ_SCOPE,
55
+ AUTH_USERS_SUSPEND_SCOPE,
56
+ AUTH_VERIFICATIONS_READ_SCOPE,
34
57
  } from "./guards";
35
58
  import { getAuthInstance, resolveDb } from "./resolve";
36
59
  import {
37
60
  AdminDeviceRevokeResponse,
38
61
  AdminDevicesResponse,
39
62
  AdminRevokeResponse,
63
+ AdminUserDeleteResponse,
64
+ AdminUserExportResponse,
65
+ AdminUserReinstateResponse,
40
66
  AdminUserResponse,
67
+ AdminUserRestoreResponse,
68
+ AdminUserSuspendResponse,
41
69
  AdminUsersResponse,
70
+ AdminVerificationsResponse,
42
71
  } from "./responses";
43
- import { ListDevicesQuery, ListUsersQuery, RevokeDeviceBody, RevokeSessionBody, UserIdParam } from "./schemas";
44
- import { deviceView, sessionView, userView } from "./views";
72
+ import {
73
+ DeleteUserBody,
74
+ ExportUserQuery,
75
+ ListDevicesQuery,
76
+ ListUsersQuery,
77
+ ListVerificationsQuery,
78
+ ReinstateUserBody,
79
+ RestoreUserBody,
80
+ RevokeDeviceBody,
81
+ RevokeSessionBody,
82
+ SuspendUserBody,
83
+ UserIdParam,
84
+ } from "./schemas";
85
+ import {
86
+ deletionView,
87
+ deviceView,
88
+ exportView,
89
+ type PurgeDisposition,
90
+ reinstatementView,
91
+ restorationView,
92
+ sessionView,
93
+ suspensionView,
94
+ userView,
95
+ verificationView,
96
+ } from "./views";
45
97
 
46
98
  type Ctx = Context<PithyHonoEnv>;
47
99
 
@@ -52,9 +104,15 @@ type Ctx = Context<PithyHonoEnv>;
52
104
  * GET {base}/admin/users auth:users:read query: ListUsersQuery
53
105
  * GET {base}/admin/users/:userId auth:users:read param: UserIdParam
54
106
  * GET {base}/admin/devices auth:devices:read query: ListDevicesQuery
107
+ * GET {base}/admin/verifications auth:verifications:read query: ListVerificationsQuery
55
108
  * POST {base}/admin/sessions/revoke auth:sessions:revoke json: RevokeSessionBody
56
109
  * POST {base}/admin/users/:userId/sessions/revoke auth:users:logout param: UserIdParam
57
110
  * POST {base}/admin/users/:userId/devices/revoke auth:devices:revoke param + json
111
+ * POST {base}/admin/users/:userId/suspend auth:users:suspend param + json: SuspendUserBody
112
+ * POST {base}/admin/users/:userId/reinstate auth:users:suspend param + json: ReinstateUserBody
113
+ * DELETE {base}/admin/users/:userId auth:users:delete param + json: DeleteUserBody
114
+ * POST {base}/admin/users/:userId/restore auth:users:delete param + json: RestoreUserBody
115
+ * GET {base}/admin/users/:userId/export auth:users:export param + query: ExportUserQuery
58
116
  *
59
117
  * ## Registered before the catch-all, or dead
60
118
  *
@@ -169,6 +227,122 @@ async function revokeTokens(c: Ctx, wiring: AuthWiring, tokens: readonly string[
169
227
  return tokens.length;
170
228
  }
171
229
 
230
+ /**
231
+ * What a lifecycle route hands `../lifecycle/`: the transitions' dependencies, with the request's correlation
232
+ * and the connection on every audit event they write, and the operator as the actor.
233
+ *
234
+ * The actor is the token's verified `sub` — which person at the dashboard — the same id every other admin
235
+ * event records, so the trail and the history table name the same somebody.
236
+ */
237
+ function lifecycleCall(c: Ctx, wiring: AuthWiring, caller: ControlPlaneContext, userId: string, reason: string) {
238
+ const correlated = context(c);
239
+ return {
240
+ deps: lifecycleDeps(c, wiring, { ...correlated, metadata: { connectionId: caller.connectionId } }),
241
+ actor: { type: "control-plane", id: caller.subject } satisfies LifecycleActor,
242
+ // Named so the refusal for a deleted account says which route comes first.
243
+ restoreRoute: `POST ${wiring.config.basePath}/admin/users/${userId}/restore`,
244
+ audit: { subject: caller.subject, connectionId: caller.connectionId, userId, reason, ...correlated },
245
+ };
246
+ }
247
+
248
+ /**
249
+ * A lifecycle route's body validator, which audits the bodies it refuses (#621). Every call is on the trail,
250
+ * a refusal included, and a body the validator turns away never reaches `auditedLifecycleCall`. So it is
251
+ * recorded here, as `denied` under the route's own action, with whatever reason the body carried — cut to the
252
+ * reason's own limit, so a refused essay is not stored whole — and the 400 is thrown as before.
253
+ */
254
+ function lifecycleBody<Schema extends z.ZodType>(schema: Schema, action: string | ((body: unknown) => string)) {
255
+ return validate("json", schema, async (raw, error, body) => {
256
+ // The route validated its `:userId` before its body, so it is readable here.
257
+ const c = raw as Context<PithyHonoEnv, string, { out: { param: z.output<typeof UserIdParam> } }>;
258
+ const caller = controlPlaneCaller(c);
259
+ const reason = body && typeof body === "object" ? (body as { reason?: unknown }).reason : undefined;
260
+ await recordLifecycleRefusal(
261
+ c.var.emit,
262
+ {
263
+ action: typeof action === "string" ? action : action(body),
264
+ subject: caller.subject,
265
+ connectionId: caller.connectionId,
266
+ userId: c.req.valid("param").userId,
267
+ reason: typeof reason === "string" ? reason.slice(0, MAX_REASON) : null,
268
+ ...context(c),
269
+ },
270
+ error,
271
+ // Hono's own refusal of a body that is not JSON carries no code; the client sees this one.
272
+ { code: "validation/invalid_input", outcome: "denied" },
273
+ );
274
+ });
275
+ }
276
+
277
+ /**
278
+ * End every session an account holds, after its columns are written — never before, for the reason the suspend
279
+ * route gives: enforcement refuses the account the moment the columns land, and revoking first would leave a
280
+ * window for a sign-in the revocation never saw. Through Better Auth's adapter, so `onSessionRevoked` hears
281
+ * each, and recorded under `auth/admin_user_sessions_revoked` with the cause.
282
+ */
283
+ async function endSessions(
284
+ c: Ctx,
285
+ wiring: AuthWiring,
286
+ caller: ControlPlaneContext,
287
+ userId: string,
288
+ cause: string,
289
+ ): Promise<number> {
290
+ const revoked = await revokeTokens(c, wiring, await userSessionTokens(db(c, wiring), userId));
291
+ await emitControlPlaneAction(c.var.emit, {
292
+ action: AuthAuditActions.adminUserSessionsRevoked,
293
+ subject: caller.subject,
294
+ connectionId: caller.connectionId,
295
+ resourceType: "user",
296
+ resourceId: userId,
297
+ ...context(c),
298
+ metadata: { revoked, cause },
299
+ });
300
+ return revoked;
301
+ }
302
+
303
+ /**
304
+ * Start the purge of one account now (#622): `started` when this Worker binds the purge Workflow and it took the
305
+ * instance — or already held it — and `pending` when it binds none or the start failed; the account is due
306
+ * either way, and the daily pass starts it. A failed start is not this call's failure: the deletion is already
307
+ * written, and a 500 over it would invite a retry that finds the account deleted and says nothing new.
308
+ *
309
+ * Under the instance id the deletion names (`../purge/start.ts`), so a hard deletion repeated, or one the daily
310
+ * pass also finds due, is the one purge and never a second.
311
+ */
312
+ async function startPurge(
313
+ c: Ctx,
314
+ result: DeleteTransition,
315
+ userId: string,
316
+ notify: boolean | undefined,
317
+ ): Promise<PurgeDisposition> {
318
+ const log = c.var.log.child("auth");
319
+ const binding = workflowBindingFor(c.env as Record<string, unknown>, AUTH_PURGE_BINDING);
320
+ if (!binding) {
321
+ log.warn("a deletion found no purge Workflow bound; the purge is pending", { userId });
322
+ return "pending";
323
+ }
324
+ try {
325
+ await startPurgeInstance(binding, {
326
+ userId,
327
+ deletedAt: result.deletedAt.getTime(),
328
+ ...(notify === undefined ? {} : { notify }),
329
+ at: new Date(),
330
+ });
331
+ return "started";
332
+ } catch (error) {
333
+ log.warn("the purge could not be started; the daily pass will start it", {
334
+ userId,
335
+ reason: error instanceof Error ? error.message : String(error),
336
+ });
337
+ return "pending";
338
+ }
339
+ }
340
+
341
+ /** What becomes of a soft deletion's purge: due later, or — when its window has already closed — due now. */
342
+ function scheduledOrDue(result: DeleteTransition): PurgeDisposition | "due" {
343
+ return result.purgeAfter.getTime() > Date.now() ? "scheduled" : "due";
344
+ }
345
+
172
346
  /**
173
347
  * Register the control-plane admin routes. Called by `createAuthRoutes` **before** the Better Auth
174
348
  * catch-all; see the file header for why that ordering is load-bearing.
@@ -204,7 +378,12 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
204
378
  // makes an exfiltration pattern visible; the string itself adds nothing to that.
205
379
  metadata: { searched: query.search !== undefined, returned: page.items.length },
206
380
  });
207
- return c.json({ users: page.items.map(userView), nextCursor: page.nextCursor } satisfies AdminUsersResponse);
381
+ // One instant for the page, so every user on it is judged at the same moment.
382
+ const now = new Date();
383
+ return c.json({
384
+ users: page.items.map((user) => userView(user, now)),
385
+ nextCursor: page.nextCursor,
386
+ } satisfies AdminUsersResponse);
208
387
  },
209
388
  );
210
389
 
@@ -256,7 +435,7 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
256
435
  });
257
436
 
258
437
  return c.json({
259
- user: userView(user),
438
+ user: userView(user, new Date()),
260
439
  providers,
261
440
  sessions,
262
441
  devices,
@@ -294,6 +473,56 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
294
473
  },
295
474
  );
296
475
 
476
+ app.get(
477
+ `${base}/admin/verifications`,
478
+ describeRoute({
479
+ summary:
480
+ "Count the sign-in links and codes sent over a window by type and state, and page through them, newest first.",
481
+ verification: "control-plane",
482
+ scopes: [AUTH_VERIFICATIONS_READ_SCOPE],
483
+ responses: { 200: AdminVerificationsResponse },
484
+ }),
485
+ requireControlPlane(AUTH_VERIFICATIONS_READ_SCOPE),
486
+ validate("query", ListVerificationsQuery),
487
+ async (c) => {
488
+ const query = c.req.valid("query");
489
+ const caller = controlPlaneCaller(c);
490
+ // One `now` for both reads, so a row the counts call pending is listed as pending.
491
+ const now = new Date();
492
+ const window = resolveVerificationWindow(query, now);
493
+ const database = db(c, wiring);
494
+ const [counts, page] = await Promise.all([
495
+ verificationCounts(database, window, now),
496
+ listVerificationOutcomes(database, {
497
+ window,
498
+ now,
499
+ type: query.type,
500
+ state: query.state,
501
+ cursor: query.cursor,
502
+ limit: query.limit,
503
+ }),
504
+ ]);
505
+ await emitControlPlaneAction(c.var.emit, {
506
+ action: AuthAuditActions.adminVerificationsListed,
507
+ subject: caller.subject,
508
+ connectionId: caller.connectionId,
509
+ resourceType: "verification",
510
+ ...context(c),
511
+ metadata: {
512
+ since: window.since.toISOString(),
513
+ until: window.until.toISOString(),
514
+ returned: page.items.length,
515
+ },
516
+ });
517
+ return c.json({
518
+ window: { since: window.since.toISOString(), until: window.until.toISOString() },
519
+ counts,
520
+ verifications: page.items.map((row) => verificationView(row, now)),
521
+ nextCursor: page.nextCursor,
522
+ } satisfies AdminVerificationsResponse);
523
+ },
524
+ );
525
+
297
526
  app.post(
298
527
  `${base}/admin/sessions/revoke`,
299
528
  describeRoute({
@@ -400,5 +629,237 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
400
629
  return c.json({ revoked, removed } satisfies AdminDeviceRevokeResponse);
401
630
  },
402
631
  );
632
+
633
+ app.post(
634
+ `${base}/admin/users/:userId/suspend`,
635
+ describeRoute({
636
+ summary: "Suspend one user, with a reason: their sessions end and every sign-in is refused.",
637
+ verification: "control-plane",
638
+ scopes: [AUTH_USERS_SUSPEND_SCOPE],
639
+ responses: { 200: AdminUserSuspendResponse },
640
+ }),
641
+ requireControlPlane(AUTH_USERS_SUSPEND_SCOPE),
642
+ validate("param", UserIdParam),
643
+ lifecycleBody(SuspendUserBody, AuthAuditActions.adminUserSuspended),
644
+ async (c) => {
645
+ const { userId } = c.req.valid("param");
646
+ const { reason, until, notify } = c.req.valid("json");
647
+ const caller = controlPlaneCaller(c);
648
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
649
+
650
+ // Every call is audited: the transition audits a suspension it writes, and this records the refusals.
651
+ // A suspension always writes — a fresh one or a restatement — so there is no no-op to record.
652
+ const result = await auditedLifecycleCall(
653
+ c.var.emit,
654
+ { action: AuthAuditActions.adminUserSuspended, ...call.audit },
655
+ () =>
656
+ suspendUser(call.deps, {
657
+ userId,
658
+ actor: call.actor,
659
+ reason,
660
+ until: until ?? null,
661
+ ...(notify === undefined ? {} : { notify }),
662
+ restoreRoute: call.restoreRoute,
663
+ }),
664
+ () => false,
665
+ );
666
+
667
+ // After the columns, never before. Enforcement refuses the account the moment they are written, so a
668
+ // session alive in between meets `auth/account_suspended`; revoking first would leave a window where a
669
+ // sign-in could mint one the revocation never saw. Every call revokes, a restatement included, so a
670
+ // credential that slipped past an earlier one does not outlive this one. Through Better Auth's adapter,
671
+ // so `onSessionRevoked` hears each. A refresh token is a session token here, so this ends both.
672
+ const revoked = await revokeTokens(c, wiring, await userSessionTokens(db(c, wiring), userId));
673
+ await emitControlPlaneAction(c.var.emit, {
674
+ action: AuthAuditActions.adminUserSessionsRevoked,
675
+ subject: caller.subject,
676
+ connectionId: caller.connectionId,
677
+ resourceType: "user",
678
+ resourceId: userId,
679
+ ...context(c),
680
+ metadata: { revoked, cause: "suspended" },
681
+ });
682
+
683
+ return c.json(suspensionView(userId, result, revoked) satisfies AdminUserSuspendResponse);
684
+ },
685
+ );
686
+
687
+ app.post(
688
+ `${base}/admin/users/:userId/reinstate`,
689
+ describeRoute({
690
+ summary: "Lift one user's suspension, with a reason. They sign in again; no session is restored.",
691
+ verification: "control-plane",
692
+ scopes: [AUTH_USERS_SUSPEND_SCOPE],
693
+ responses: { 200: AdminUserReinstateResponse },
694
+ }),
695
+ requireControlPlane(AUTH_USERS_SUSPEND_SCOPE),
696
+ validate("param", UserIdParam),
697
+ lifecycleBody(ReinstateUserBody, AuthAuditActions.adminUserReinstated),
698
+ async (c) => {
699
+ const { userId } = c.req.valid("param");
700
+ const { reason, notify } = c.req.valid("json");
701
+ const caller = controlPlaneCaller(c);
702
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
703
+
704
+ // An account with no suspension in force is a 200 that changed nothing — the state the caller asked
705
+ // for already holds — and is audited as exactly that.
706
+ const result = await auditedLifecycleCall(
707
+ c.var.emit,
708
+ { action: AuthAuditActions.adminUserReinstated, ...call.audit },
709
+ () =>
710
+ reinstateUser(call.deps, {
711
+ userId,
712
+ actor: call.actor,
713
+ reason,
714
+ ...(notify === undefined ? {} : { notify }),
715
+ restoreRoute: call.restoreRoute,
716
+ }),
717
+ (outcome) => !outcome.changed,
718
+ );
719
+
720
+ return c.json(reinstatementView(userId, result) satisfies AdminUserReinstateResponse);
721
+ },
722
+ );
723
+
724
+ app.delete(
725
+ `${base}/admin/users/:userId`,
726
+ describeRoute({
727
+ summary:
728
+ "Delete one user, with a reason: soft by default, restorable until the purge window closes; hard when named, purged now.",
729
+ verification: "control-plane",
730
+ scopes: [AUTH_USERS_DELETE_SCOPE],
731
+ responses: { 200: AdminUserDeleteResponse },
732
+ }),
733
+ requireControlPlane(AUTH_USERS_DELETE_SCOPE),
734
+ validate("param", UserIdParam),
735
+ // A refused body is recorded under the mode it asked for, so a malformed hard deletion is on the trail as
736
+ // an attempt at one. Only the exact `"hard"` reads as hard, as only it parses as hard.
737
+ lifecycleBody(DeleteUserBody, (body) =>
738
+ (body as { mode?: unknown } | null)?.mode === "hard"
739
+ ? AuthAuditActions.adminUserHardDeleted
740
+ : AuthAuditActions.adminUserSoftDeleted,
741
+ ),
742
+ async (c) => {
743
+ const { userId } = c.req.valid("param");
744
+ const { mode, reason, notify } = c.req.valid("json");
745
+ const caller = controlPlaneCaller(c);
746
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
747
+ const action = mode === "hard" ? AuthAuditActions.adminUserHardDeleted : AuthAuditActions.adminUserSoftDeleted;
748
+
749
+ // Every call is audited: the transition audits a deletion it writes, this records the refusals and the
750
+ // call that found the account already deleted.
751
+ const result = await auditedLifecycleCall(
752
+ c.var.emit,
753
+ { action, ...call.audit },
754
+ () =>
755
+ deleteUser(call.deps, {
756
+ userId,
757
+ actor: call.actor,
758
+ reason,
759
+ mode,
760
+ ...(notify === undefined ? {} : { notify }),
761
+ }),
762
+ (outcome) => outcome.outcome === "unchanged",
763
+ );
764
+
765
+ const sessionsRevoked = await endSessions(c, wiring, caller, userId, "deleted");
766
+ // A hard deletion starts its purge here. A soft one waits for the daily pass — unless its window has
767
+ // already closed, in which case it is due now and is started like a hard one.
768
+ const disposition = mode === "hard" ? "due" : scheduledOrDue(result);
769
+ const purge =
770
+ disposition === "due"
771
+ ? await startPurge(c, result, userId, mode === "hard" ? notify : undefined)
772
+ : disposition;
773
+ return c.json(deletionView(userId, mode, result, purge, sessionsRevoked) satisfies AdminUserDeleteResponse);
774
+ },
775
+ );
776
+
777
+ app.post(
778
+ `${base}/admin/users/:userId/restore`,
779
+ describeRoute({
780
+ summary:
781
+ "Restore one deleted user inside the purge window, with a reason. They sign in again; no session is restored.",
782
+ verification: "control-plane",
783
+ scopes: [AUTH_USERS_DELETE_SCOPE],
784
+ responses: { 200: AdminUserRestoreResponse },
785
+ }),
786
+ requireControlPlane(AUTH_USERS_DELETE_SCOPE),
787
+ validate("param", UserIdParam),
788
+ lifecycleBody(RestoreUserBody, AuthAuditActions.adminUserRestored),
789
+ async (c) => {
790
+ const { userId } = c.req.valid("param");
791
+ const { reason } = c.req.valid("json");
792
+ const caller = controlPlaneCaller(c);
793
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
794
+
795
+ // After the purge there is no account, and the transition's 404 says the data is gone. A window that has
796
+ // closed is a conflict naming when. Both are refusals, and both are on the trail.
797
+ const result = await auditedLifecycleCall(
798
+ c.var.emit,
799
+ { action: AuthAuditActions.adminUserRestored, ...call.audit },
800
+ () => restoreUser(call.deps, { userId, actor: call.actor, reason }),
801
+ (outcome) => !outcome.changed,
802
+ );
803
+
804
+ return c.json(restorationView(userId, result) satisfies AdminUserRestoreResponse);
805
+ },
806
+ );
807
+
808
+ app.get(
809
+ `${base}/admin/users/:userId/export`,
810
+ describeRoute({
811
+ summary: "Export everything the kit holds about one user, from every composed capability, as one document.",
812
+ description:
813
+ "The answer to an access request. One entry per composed capability that declares a purge contribution, in the order the purge erases them. Audited as a disclosure, with the reason.",
814
+ verification: "control-plane",
815
+ scopes: [AUTH_USERS_EXPORT_SCOPE],
816
+ responses: { 200: AdminUserExportResponse },
817
+ }),
818
+ requireControlPlane(AUTH_USERS_EXPORT_SCOPE),
819
+ validate("param", UserIdParam),
820
+ validate("query", ExportUserQuery),
821
+ async (c) => {
822
+ const { userId } = c.req.valid("param");
823
+ const { reason } = c.req.valid("query");
824
+ const caller = controlPlaneCaller(c);
825
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
826
+ const exportedAt = new Date();
827
+
828
+ // The account first, so an unknown or purged one is a 404 — the purged one saying its data is gone —
829
+ // and never a document of empty parts. Then every composed capability's part, each guarded on its own.
830
+ const entries = await auditedLifecycleCall(
831
+ c.var.emit,
832
+ { action: AuthAuditActions.adminUserExported, ...call.audit },
833
+ async () => {
834
+ const database = db(c, wiring);
835
+ await requirePresent(database, userId);
836
+ return purgeExports(wiring.purgeSteps ?? [], {
837
+ subject: { type: "user", id: userId },
838
+ env: c.env as Record<string, unknown>,
839
+ // A capability holding rows by address — a suppression, a tester's membership — reads it here (#814).
840
+ address: () => purgeAddress(database, userId),
841
+ });
842
+ },
843
+ () => false,
844
+ );
845
+
846
+ // A disclosure, recorded with who asked, why, and which parts answered — never with any of the data.
847
+ await emitControlPlaneAction(c.var.emit, {
848
+ action: AuthAuditActions.adminUserExported,
849
+ subject: caller.subject,
850
+ connectionId: caller.connectionId,
851
+ resourceType: "user",
852
+ resourceId: userId,
853
+ ...context(c),
854
+ metadata: {
855
+ reason,
856
+ disclosure: true,
857
+ capabilities: entries.map((entry) => `${entry.capability}:${entry.state}`),
858
+ },
859
+ });
860
+
861
+ return c.json(exportView(userId, exportedAt, entries) satisfies AdminUserExportResponse);
862
+ },
863
+ );
403
864
  };
404
865
  }
package/src/http/csrf.ts CHANGED
@@ -6,6 +6,7 @@ import { type AmbientEnv, ambientEnv } from "@pithy-sh/core/src/env/ambient";
6
6
  import { ForbiddenError } from "@pithy-sh/core/src/error/pithyError";
7
7
  import type { SameOriginGate } from "@pithy-sh/core/src/http/sameOrigin";
8
8
  import type { AuthWiring } from "../capability";
9
+ import { dispatchedAuth } from "../mcp/dispatch";
9
10
  import { baseURLResolver, type ResolveBaseURL } from "./baseUrl";
10
11
 
11
12
  /**
@@ -50,7 +51,9 @@ function sameOriginGate(allowedOrigins: readonly string[], resolveBaseURL: Resol
50
51
  const allowed = new Set(allowedOrigins);
51
52
  return async (c, next) => {
52
53
  // A bearer request has no ambient credential to forge — CSRF-exempt.
53
- if (c.req.raw.headers.has("authorization")) {
54
+ // Nor does a tool call the MCP endpoint dispatched in process: it carries no credential at all, and the
55
+ // bearer token it was verified against was checked before it was built.
56
+ if (c.req.raw.headers.has("authorization") || dispatchedAuth(c.req.raw) !== undefined) {
54
57
  await next();
55
58
  return;
56
59
  }