@pithy-sh/audit 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/README.md +93 -0
  2. package/dist/accessHistory.d.ts +315 -0
  3. package/dist/accessHistory.d.ts.map +1 -0
  4. package/dist/accessHistory.js +299 -0
  5. package/dist/actions.d.ts +15 -1
  6. package/dist/actions.d.ts.map +1 -1
  7. package/dist/actions.js +16 -2
  8. package/dist/capability.d.ts +14 -0
  9. package/dist/capability.d.ts.map +1 -1
  10. package/dist/capability.js +106 -12
  11. package/dist/chain/append.d.ts +43 -0
  12. package/dist/chain/append.d.ts.map +1 -0
  13. package/dist/chain/append.js +110 -0
  14. package/dist/chain/checkpoint.d.ts +70 -0
  15. package/dist/chain/checkpoint.d.ts.map +1 -0
  16. package/dist/chain/checkpoint.js +133 -0
  17. package/dist/chain/lockCheck.d.ts +15 -0
  18. package/dist/chain/lockCheck.d.ts.map +1 -0
  19. package/dist/chain/lockCheck.js +75 -0
  20. package/dist/chain/prune.d.ts +84 -0
  21. package/dist/chain/prune.d.ts.map +1 -0
  22. package/dist/chain/prune.js +231 -0
  23. package/dist/chain/rows.d.ts +74 -0
  24. package/dist/chain/rows.d.ts.map +1 -0
  25. package/dist/chain/rows.js +133 -0
  26. package/dist/chain/tombstone.d.ts +21 -0
  27. package/dist/chain/tombstone.d.ts.map +1 -0
  28. package/dist/chain/tombstone.js +98 -0
  29. package/dist/chain/verify.d.ts +63 -0
  30. package/dist/chain/verify.d.ts.map +1 -0
  31. package/dist/chain/verify.js +220 -0
  32. package/dist/citations.d.ts +17 -0
  33. package/dist/citations.d.ts.map +1 -0
  34. package/dist/citations.js +48 -0
  35. package/dist/cli/emitFromCLI.d.ts +5 -0
  36. package/dist/cli/emitFromCLI.d.ts.map +1 -1
  37. package/dist/cli/emitFromCLI.js +5 -0
  38. package/dist/data/auditEvent.d.ts +4 -0
  39. package/dist/data/auditEvent.d.ts.map +1 -1
  40. package/dist/data/auditEvent.js +7 -3
  41. package/dist/data/sinkState.d.ts +23 -0
  42. package/dist/data/sinkState.d.ts.map +1 -0
  43. package/dist/data/sinkState.js +25 -0
  44. package/dist/data/tables.d.ts +14 -1
  45. package/dist/data/tables.d.ts.map +1 -1
  46. package/dist/data/tables.js +5 -1
  47. package/dist/http/guards.d.ts +39 -6
  48. package/dist/http/guards.d.ts.map +1 -1
  49. package/dist/http/guards.js +101 -17
  50. package/dist/http/responses.d.ts +503 -0
  51. package/dist/http/responses.d.ts.map +1 -1
  52. package/dist/http/responses.js +157 -5
  53. package/dist/http/routes.d.ts +25 -3
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +321 -15
  56. package/dist/http/schemas.d.ts +67 -0
  57. package/dist/http/schemas.d.ts.map +1 -1
  58. package/dist/http/schemas.js +88 -4
  59. package/dist/http/views.d.ts +25 -1
  60. package/dist/http/views.d.ts.map +1 -1
  61. package/dist/http/views.js +107 -2
  62. package/dist/migrations/0003_call_index.d.ts +21 -0
  63. package/dist/migrations/0003_call_index.d.ts.map +1 -0
  64. package/dist/migrations/0003_call_index.js +33 -0
  65. package/dist/migrations/0004_request_index.d.ts +16 -0
  66. package/dist/migrations/0004_request_index.d.ts.map +1 -0
  67. package/dist/migrations/0004_request_index.js +24 -0
  68. package/dist/migrations/0005_chain.d.ts +24 -0
  69. package/dist/migrations/0005_chain.d.ts.map +1 -0
  70. package/dist/migrations/0005_chain.js +43 -0
  71. package/dist/migrations/0006_sinks.d.ts +11 -0
  72. package/dist/migrations/0006_sinks.d.ts.map +1 -0
  73. package/dist/migrations/0006_sinks.js +20 -0
  74. package/dist/provision/resolveAuditConfig.d.ts +31 -0
  75. package/dist/provision/resolveAuditConfig.d.ts.map +1 -0
  76. package/dist/provision/resolveAuditConfig.js +43 -0
  77. package/dist/purge/contribution.d.ts +21 -0
  78. package/dist/purge/contribution.d.ts.map +1 -0
  79. package/dist/purge/contribution.js +41 -0
  80. package/dist/reach.d.ts +250 -0
  81. package/dist/reach.d.ts.map +1 -0
  82. package/dist/reach.js +244 -0
  83. package/dist/recorder.d.ts +11 -0
  84. package/dist/recorder.d.ts.map +1 -1
  85. package/dist/recorder.js +23 -5
  86. package/dist/routePattern.d.ts +60 -0
  87. package/dist/routePattern.d.ts.map +1 -0
  88. package/dist/routePattern.js +130 -0
  89. package/dist/seeds/example.d.ts.map +1 -1
  90. package/dist/seeds/example.js +23 -6
  91. package/dist/ship/consumer.d.ts +45 -0
  92. package/dist/ship/consumer.d.ts.map +1 -0
  93. package/dist/ship/consumer.js +141 -0
  94. package/dist/ship/event.d.ts +59 -0
  95. package/dist/ship/event.d.ts.map +1 -0
  96. package/dist/ship/event.js +77 -0
  97. package/dist/ship/health.d.ts +33 -0
  98. package/dist/ship/health.d.ts.map +1 -0
  99. package/dist/ship/health.js +80 -0
  100. package/dist/ship/profiles.d.ts +34 -0
  101. package/dist/ship/profiles.d.ts.map +1 -0
  102. package/dist/ship/profiles.js +62 -0
  103. package/dist/ship/queue.d.ts +57 -0
  104. package/dist/ship/queue.d.ts.map +1 -0
  105. package/dist/ship/queue.js +70 -0
  106. package/dist/ship/secrets.d.ts +7 -0
  107. package/dist/ship/secrets.d.ts.map +1 -0
  108. package/dist/ship/secrets.js +40 -0
  109. package/dist/ship/shipper.d.ts +15 -0
  110. package/dist/ship/shipper.d.ts.map +1 -0
  111. package/dist/ship/shipper.js +27 -0
  112. package/dist/ship/sinks.d.ts +54 -0
  113. package/dist/ship/sinks.d.ts.map +1 -0
  114. package/dist/ship/sinks.js +45 -0
  115. package/dist/ship/state.d.ts +27 -0
  116. package/dist/ship/state.d.ts.map +1 -0
  117. package/dist/ship/state.js +29 -0
  118. package/dist/usage.d.ts +159 -0
  119. package/dist/usage.d.ts.map +1 -0
  120. package/dist/usage.js +87 -0
  121. package/dist/version.generated.d.ts +1 -1
  122. package/dist/version.generated.js +1 -1
  123. package/dist/workflows/prune.d.ts +73 -0
  124. package/dist/workflows/prune.d.ts.map +1 -0
  125. package/dist/workflows/prune.js +128 -0
  126. package/dist/workflows/retryPolicy.d.ts +10 -0
  127. package/dist/workflows/retryPolicy.d.ts.map +1 -0
  128. package/dist/workflows/retryPolicy.js +14 -0
  129. package/dist/workflows/specs.d.ts +70 -0
  130. package/dist/workflows/specs.d.ts.map +1 -0
  131. package/dist/workflows/specs.js +70 -0
  132. package/dist/workflows/worker.d.ts +32 -0
  133. package/dist/workflows/worker.d.ts.map +1 -0
  134. package/dist/workflows/worker.js +41 -0
  135. package/package.json +5 -2
  136. package/pithy.manifest.json +36 -4
  137. package/src/accessHistory.ts +360 -0
  138. package/src/actions.ts +15 -1
  139. package/src/capability.ts +134 -12
  140. package/src/chain/append.ts +161 -0
  141. package/src/chain/checkpoint.ts +172 -0
  142. package/src/chain/lockCheck.ts +72 -0
  143. package/src/chain/prune.ts +340 -0
  144. package/src/chain/rows.ts +211 -0
  145. package/src/chain/tombstone.ts +104 -0
  146. package/src/chain/verify.ts +366 -0
  147. package/src/citations.ts +62 -0
  148. package/src/cli/emitFromCLI.ts +5 -0
  149. package/src/cloudflare-test.d.ts +1 -0
  150. package/src/data/auditEvent.ts +31 -1
  151. package/src/data/sinkState.ts +41 -0
  152. package/src/data/tables.ts +7 -1
  153. package/src/http/guards.ts +90 -6
  154. package/src/http/responses.ts +318 -3
  155. package/src/http/routes.ts +379 -7
  156. package/src/http/schemas.ts +158 -2
  157. package/src/http/views.ts +123 -1
  158. package/src/migrations/0003_call_index.ts +35 -0
  159. package/src/migrations/0004_request_index.ts +26 -0
  160. package/src/migrations/0005_chain.ts +56 -0
  161. package/src/migrations/0006_sinks.ts +28 -0
  162. package/src/provision/resolveAuditConfig.ts +60 -0
  163. package/src/purge/contribution.ts +39 -0
  164. package/src/reach.ts +454 -0
  165. package/src/recorder.ts +64 -42
  166. package/src/routePattern.ts +141 -0
  167. package/src/seeds/example.ts +13 -0
  168. package/src/ship/consumer.ts +169 -0
  169. package/src/ship/event.ts +86 -0
  170. package/src/ship/health.ts +92 -0
  171. package/src/ship/profiles.ts +99 -0
  172. package/src/ship/queue.ts +108 -0
  173. package/src/ship/secrets.ts +42 -0
  174. package/src/ship/shipper.ts +32 -0
  175. package/src/ship/sinks.ts +82 -0
  176. package/src/ship/state.ts +61 -0
  177. package/src/usage.ts +176 -0
  178. package/src/version.generated.ts +1 -1
  179. package/src/workflows/prune.ts +196 -0
  180. package/src/workflows/retryPolicy.ts +14 -0
  181. package/src/workflows/specs.ts +92 -0
  182. package/src/workflows/worker.ts +65 -0
  183. package/src/workflows/wrangler.jsonc +40 -0
@@ -1,8 +1,10 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
 
4
+ import type { R2Bucket } from "@cloudflare/workers-types";
4
5
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
6
  import type { ControlPlaneContext } from "@pithy-sh/core/src/controlPlane/context";
7
+ import type { AdminRoute } from "@pithy-sh/core/src/controlPlane/discovery/adminRoute";
6
8
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
7
9
  import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/scope";
8
10
  import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
@@ -10,31 +12,69 @@ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
10
12
  import { validate } from "@pithy-sh/core/src/http/validation";
11
13
  import type { VerificationStrategy } from "@pithy-sh/core/src/http/verification";
12
14
  import type { Context, Hono } from "hono";
15
+ import { accessHistory } from "../accessHistory";
13
16
  import { AuditTrailActions } from "../actions";
17
+ import { exportChainRange, verifyChainRange } from "../chain/verify";
14
18
  import type { AuditDatabase } from "../data/tables";
15
19
  import { pageAuditEvents, readAuditEvent } from "../query";
16
- import { AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE } from "./guards";
17
- import { AuditEventResponse, AuditEventsResponse } from "./responses";
18
- import { AuditEventIdParam, ListAuditEventsQuery } from "./schemas";
19
- import { auditEventDetailView, auditEventView } from "./views";
20
+ import { controlPlaneReach, controlPlaneReachSubjects } from "../reach";
21
+ import { reachPatterns } from "../routePattern";
22
+ import { controlPlaneUsage } from "../usage";
23
+ import { AUDIT_CHAIN_EXPORT_SCOPE, AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE } from "./guards";
24
+ import {
25
+ AccessHistoryResponse,
26
+ AuditEventResponse,
27
+ AuditEventsResponse,
28
+ ChainExportResponse,
29
+ ChainVerifyResponse,
30
+ ControlPlaneReachResponse,
31
+ ControlPlaneUsageResponse,
32
+ } from "./responses";
33
+ import {
34
+ AccessHistoryQuery,
35
+ AuditEventIdParam,
36
+ ChainExportQuery,
37
+ ChainVerifyQuery,
38
+ ControlPlaneReachQuery,
39
+ ControlPlaneUsageQuery,
40
+ ListAuditEventsQuery,
41
+ } from "./schemas";
42
+ import {
43
+ accessChangeView,
44
+ auditEventDetailView,
45
+ auditEventView,
46
+ controlPlaneReachSubjectView,
47
+ controlPlaneReachView,
48
+ controlPlaneUsageView,
49
+ } from "./views";
20
50
 
21
51
  /**
22
52
  * The audit routes, their verification strategies, and what each accepts:
23
53
  *
24
54
  * GET /audit/events → a page of the trail (control-plane: audit:events:read) query: ListAuditEventsQuery
25
55
  * GET /audit/events/:eventId → one event in full (control-plane: audit:events:read_detail) param: AuditEventIdParam
56
+ * GET /audit/control-plane/access-history → every access change in a window, before and after
57
+ * (control-plane: audit:events:read) query: AccessHistoryQuery
58
+ * GET /audit/control-plane/reach → what one credential reached, by tenant, route and outcome
59
+ * (control-plane: audit:events:read) query: ControlPlaneReachQuery
60
+ * GET /audit/control-plane/usage → one connection's calls, counted by scope and key
61
+ * (control-plane: audit:events:read) query: ControlPlaneUsageQuery
62
+ * GET /audit/control-plane/verify → whether one tenant's hash chain is whole, or where it breaks
63
+ * (control-plane: audit:events:export) query: ChainVerifyQuery
64
+ * GET /audit/control-plane/export → one tenant's chain in canonical form, with its checkpoints
65
+ * (control-plane: audit:events:export) query: ChainExportQuery
26
66
  *
27
- * **Both are reads, and there is nothing else.** The trail is append-only: no route here deletes,
67
+ * **All are reads, and there is nothing else.** The trail is append-only: no route here deletes,
28
68
  * edits, or prunes, because a management credential that could erase an audit row could erase the
29
69
  * evidence of its own use. Retention is a lifecycle concern for a Workflow, not a button on a
30
70
  * dashboard.
31
71
  *
32
- * **Neither has an end-user surface.** A user does not call the record of themselves being audited,
72
+ * **None has an end-user surface.** A user does not call the record of themselves being audited,
33
73
  * so `requireAuth()` appears nowhere in this file — and must not: the seam leaves `c.var.auth` null
34
74
  * for a control-plane caller by design, so an auth gate would deny every legitimate management call
35
75
  * permanently, with no credential able to fix it.
36
76
  *
37
- * **Validators sit after the gate on both lines.** A validator ahead of it turns a 403 into a 400 and
77
+ * **Validators sit after the gate on every line.** A validator ahead of it turns a 403 into a 400 and
38
78
  * tells an unverified caller which requests were well-formed — here that is a live oracle for which
39
79
  * projects, Workers, and action codes this deployment records.
40
80
  */
@@ -61,6 +101,11 @@ export interface AuditRouteDeclaration {
61
101
  export const AUDIT_ROUTES: readonly AuditRouteDeclaration[] = [
62
102
  { method: "GET", path: "/events", strategy: "control-plane", scope: AUDIT_TRAIL_READ_SCOPE },
63
103
  { method: "GET", path: "/events/:eventId", strategy: "control-plane", scope: AUDIT_EVENT_DETAIL_READ_SCOPE },
104
+ { method: "GET", path: "/control-plane/access-history", strategy: "control-plane", scope: AUDIT_TRAIL_READ_SCOPE },
105
+ { method: "GET", path: "/control-plane/reach", strategy: "control-plane", scope: AUDIT_TRAIL_READ_SCOPE },
106
+ { method: "GET", path: "/control-plane/usage", strategy: "control-plane", scope: AUDIT_TRAIL_READ_SCOPE },
107
+ { method: "GET", path: "/control-plane/verify", strategy: "control-plane", scope: AUDIT_CHAIN_EXPORT_SCOPE },
108
+ { method: "GET", path: "/control-plane/export", strategy: "control-plane", scope: AUDIT_CHAIN_EXPORT_SCOPE },
64
109
  ];
65
110
 
66
111
  /** How the audit sub-router is built. */
@@ -74,6 +119,16 @@ export interface AuditRoutesOptions {
74
119
  basePath: string;
75
120
  /** The audit database for this request — resolved by the capability, which owns the registry key. */
76
121
  database: (c: Context<PithyHonoEnv>) => AuditDatabase;
122
+ /**
123
+ * Every admin route the composed Worker declares — what the manifest reports, and what a credential's reach groups
124
+ * its called paths by. A function, because the capability learns them at `compose`, after these routes are built.
125
+ */
126
+ adminRoutes: () => readonly AdminRoute[];
127
+ /**
128
+ * The checkpoint bucket for this request, or null when the Worker binds none (#822). Absent, verify checks links
129
+ * alone and says so, and an export carries no checkpoints.
130
+ */
131
+ checkpoints?: (c: Context<PithyHonoEnv>) => R2Bucket | null;
77
132
  }
78
133
 
79
134
  /**
@@ -121,6 +176,8 @@ function askedFor(query: ListAuditEventsQuery): Record<string, unknown> {
121
176
  export function registerAuditRoutes(options: AuditRoutesOptions): (app: Hono<PithyHonoEnv>) => void {
122
177
  const base = options.basePath;
123
178
  const database = options.database;
179
+ const adminRoutes = options.adminRoutes;
180
+ const checkpoints = options.checkpoints ?? (() => null);
124
181
 
125
182
  return (app) => {
126
183
  /**
@@ -214,5 +271,320 @@ export function registerAuditRoutes(options: AuditRoutesOptions): (app: Hono<Pit
214
271
  return c.json({ event: auditEventDetailView(row) } satisfies AuditEventResponse, 200);
215
272
  },
216
273
  );
274
+
275
+ /**
276
+ * CONTROL-PLANE READ (#831). Who could do what, over time: every membership, connection and key change in a
277
+ * window, oldest first, with its before and after — one SQL statement per page, never a walk of events here.
278
+ * Behind the listing scope, not the detail one: it lifts named metadata keys and never an IP or a user-agent.
279
+ */
280
+ app.get(
281
+ `${base}/control-plane/access-history`,
282
+ describeRoute({
283
+ summary:
284
+ "Replay every membership, connection and key change in a window, oldest first, with its before and after.",
285
+ verification: "control-plane",
286
+ scopes: [AUDIT_TRAIL_READ_SCOPE],
287
+ responses: { 200: AccessHistoryResponse },
288
+ }),
289
+ requireControlPlane(AUDIT_TRAIL_READ_SCOPE),
290
+ validate("query", AccessHistoryQuery),
291
+ async (c) => {
292
+ const operator = caller(c);
293
+ const query = c.req.valid("query");
294
+ const window = { since: query.since, until: query.until ?? new Date() };
295
+ const page = await accessHistory(database(c), { ...window, cursor: query.cursor, limit: query.limit });
296
+ // Audited like the listing: replaying who held what across every account is a read of everyone's access,
297
+ // and the trail should answer who asked, for which window, and how much came back.
298
+ await c.var.emit({
299
+ action: AuditTrailActions.accessHistoryRead,
300
+ outcome: "success",
301
+ actorType: "control-plane",
302
+ actorId: operator.subject,
303
+ resourceType: "audit_trail",
304
+ requestId: c.req.header("cf-ray"),
305
+ ip: c.req.header("cf-connecting-ip"),
306
+ userAgent: c.req.header("user-agent"),
307
+ metadata: {
308
+ connectionId: operator.connectionId,
309
+ query: {
310
+ since: window.since.toISOString(),
311
+ until: window.until.toISOString(),
312
+ resumed: query.cursor !== undefined,
313
+ },
314
+ returned: page.changes.length,
315
+ more: page.nextCursor !== null,
316
+ },
317
+ });
318
+ return c.json(
319
+ {
320
+ since: window.since.toISOString(),
321
+ until: window.until.toISOString(),
322
+ changes: page.changes.map(accessChangeView),
323
+ nextCursor: page.nextCursor,
324
+ } satisfies AccessHistoryResponse,
325
+ 200,
326
+ );
327
+ },
328
+ );
329
+
330
+ /**
331
+ * CONTROL-PLANE READ (#828). What one credential reached — by tenant, action, method, route and outcome — over a
332
+ * window, in one SQL statement, never by paging events here. `subjects=true` expands one route into the subject
333
+ * ids its called paths name. Behind the listing scope, not the detail one: the answer is the tenant, the route,
334
+ * the scope and ids the listing already shows, and never an IP, a user-agent or any other metadata key.
335
+ */
336
+ app.get(
337
+ `${base}/control-plane/reach`,
338
+ describeRoute({
339
+ summary: "Read what one control-plane credential reached, by tenant, route and outcome, over a window.",
340
+ verification: "control-plane",
341
+ scopes: [AUDIT_TRAIL_READ_SCOPE],
342
+ responses: { 200: ControlPlaneReachResponse },
343
+ }),
344
+ requireControlPlane(AUDIT_TRAIL_READ_SCOPE),
345
+ validate("query", ControlPlaneReachQuery),
346
+ async (c) => {
347
+ const operator = caller(c);
348
+ const query = c.req.valid("query");
349
+ const filter = {
350
+ connectionId: query.connectionId,
351
+ since: query.since,
352
+ until: query.until ?? new Date(),
353
+ ...(query.keyId !== undefined ? { keyId: query.keyId } : {}),
354
+ ...(query.route !== undefined ? { route: query.route } : {}),
355
+ };
356
+ const patterns = reachPatterns(adminRoutes());
357
+ const expanded =
358
+ query.subjects === "true" && filter.route !== undefined
359
+ ? await controlPlaneReachSubjects(database(c), { ...filter, route: filter.route }, patterns)
360
+ : { reach: await controlPlaneReach(database(c), filter, patterns), subjects: undefined };
361
+ // Audited like the listing, and against the connection whose reach was read: "who reviewed what this
362
+ // credential touched" is a question the trail should answer about that credential.
363
+ await c.var.emit({
364
+ action: AuditTrailActions.reachRead,
365
+ outcome: "success",
366
+ actorType: "control-plane",
367
+ actorId: operator.subject,
368
+ resourceType: "controlplane_connection",
369
+ resourceId: query.connectionId,
370
+ requestId: c.req.header("cf-ray"),
371
+ ip: c.req.header("cf-connecting-ip"),
372
+ userAgent: c.req.header("user-agent"),
373
+ metadata: {
374
+ connectionId: operator.connectionId,
375
+ query: {
376
+ connectionId: filter.connectionId,
377
+ keyId: filter.keyId ?? null,
378
+ since: filter.since.toISOString(),
379
+ until: filter.until.toISOString(),
380
+ route: filter.route ?? null,
381
+ subjects: expanded.subjects !== undefined,
382
+ },
383
+ returned: expanded.reach.length,
384
+ ...(expanded.subjects !== undefined ? { subjects: expanded.subjects.length } : {}),
385
+ },
386
+ });
387
+ return c.json(
388
+ {
389
+ connectionId: filter.connectionId,
390
+ keyId: filter.keyId ?? null,
391
+ since: filter.since.toISOString(),
392
+ until: filter.until.toISOString(),
393
+ reach: expanded.reach.map(controlPlaneReachView),
394
+ ...(expanded.subjects !== undefined
395
+ ? { subjects: expanded.subjects.map(controlPlaneReachSubjectView) }
396
+ : {}),
397
+ } satisfies ControlPlaneReachResponse,
398
+ 200,
399
+ );
400
+ },
401
+ );
402
+
403
+ /**
404
+ * CONTROL-PLANE READ (#812). Which scopes one connection exercised and was refused, by key, over a window —
405
+ * counted in one SQL statement, never by paging events here. Behind the listing scope, not the detail one: the
406
+ * answer is the scope, the key, and the last allowed call's method and path, and never an IP, a user-agent or any
407
+ * other metadata key.
408
+ */
409
+ app.get(
410
+ `${base}/control-plane/usage`,
411
+ describeRoute({
412
+ summary: "Count which scopes one control-plane connection exercised and was refused, by key, over a window.",
413
+ verification: "control-plane",
414
+ scopes: [AUDIT_TRAIL_READ_SCOPE],
415
+ responses: { 200: ControlPlaneUsageResponse },
416
+ }),
417
+ requireControlPlane(AUDIT_TRAIL_READ_SCOPE),
418
+ validate("query", ControlPlaneUsageQuery),
419
+ async (c) => {
420
+ const operator = caller(c);
421
+ const query = c.req.valid("query");
422
+ const window = { since: query.since, until: query.until ?? new Date() };
423
+ const result = await controlPlaneUsage(database(c), { connectionId: query.connectionId, ...window });
424
+ // Audited like the listing, and against the connection whose usage was read: "who reviewed this
425
+ // connection's grants" is a question the trail should answer about that connection.
426
+ await c.var.emit({
427
+ action: AuditTrailActions.usageRead,
428
+ outcome: "success",
429
+ actorType: "control-plane",
430
+ actorId: operator.subject,
431
+ resourceType: "controlplane_connection",
432
+ resourceId: query.connectionId,
433
+ requestId: c.req.header("cf-ray"),
434
+ ip: c.req.header("cf-connecting-ip"),
435
+ userAgent: c.req.header("user-agent"),
436
+ metadata: {
437
+ connectionId: operator.connectionId,
438
+ query: {
439
+ connectionId: query.connectionId,
440
+ since: window.since.toISOString(),
441
+ until: window.until.toISOString(),
442
+ },
443
+ returned: result.usage.length,
444
+ },
445
+ });
446
+ return c.json(
447
+ {
448
+ connectionId: query.connectionId,
449
+ since: window.since.toISOString(),
450
+ until: window.until.toISOString(),
451
+ usage: result.usage.map(controlPlaneUsageView),
452
+ oldestEventAt: result.oldestEventAt?.toISOString() ?? null,
453
+ } satisfies ControlPlaneUsageResponse,
454
+ 200,
455
+ );
456
+ },
457
+ );
458
+
459
+ /**
460
+ * CONTROL-PLANE READ (#822). Walk one tenant's hash chain over a window — every link, every hash, the
461
+ * checkpoints covering it — and answer intact or the first break. Reads only: it proves the trail whole and
462
+ * changes nothing.
463
+ */
464
+ app.get(
465
+ `${base}/control-plane/verify`,
466
+ describeRoute({
467
+ summary: "Walk one tenant's audit chain against its checkpoints, and say whether it is whole.",
468
+ verification: "control-plane",
469
+ scopes: [AUDIT_CHAIN_EXPORT_SCOPE],
470
+ responses: { 200: ChainVerifyResponse },
471
+ }),
472
+ requireControlPlane(AUDIT_CHAIN_EXPORT_SCOPE),
473
+ validate("query", ChainVerifyQuery),
474
+ async (c) => {
475
+ const operator = caller(c);
476
+ const query = c.req.valid("query");
477
+ const bucket = checkpoints(c);
478
+ const range = {
479
+ tenant: query.tenant,
480
+ ...(query.since ? { since: query.since } : {}),
481
+ ...(query.until ? { until: query.until } : {}),
482
+ };
483
+ const found = await verifyChainRange(database(c), bucket, range);
484
+ // Audited like every read here. A failed verify is recorded as one: a break is exactly what the trail
485
+ // should say somebody saw, and when.
486
+ await c.var.emit({
487
+ action: AuditTrailActions.chainVerified,
488
+ outcome: found.intact ? "success" : "failure",
489
+ severity: found.intact ? "info" : "critical",
490
+ actorType: "control-plane",
491
+ actorId: operator.subject,
492
+ resourceType: "audit_chain",
493
+ requestId: c.req.header("cf-ray"),
494
+ ip: c.req.header("cf-connecting-ip"),
495
+ userAgent: c.req.header("user-agent"),
496
+ metadata: {
497
+ connectionId: operator.connectionId,
498
+ query: {
499
+ tenant: query.tenant,
500
+ since: query.since?.toISOString() ?? null,
501
+ until: query.until?.toISOString() ?? null,
502
+ },
503
+ checked: found.checked,
504
+ checkpoints: found.checkpoints,
505
+ ...(found.break ? { break: found.break } : {}),
506
+ },
507
+ });
508
+ return c.json(
509
+ {
510
+ tenant: query.tenant,
511
+ since: query.since?.toISOString() ?? null,
512
+ until: query.until?.toISOString() ?? null,
513
+ intact: found.intact,
514
+ checked: found.checked,
515
+ checkpoints: found.checkpoints,
516
+ pruned: found.pruned,
517
+ checkpointStore: bucket ? "bound" : "absent",
518
+ beforeChain: found.beforeChain,
519
+ outsideChain: found.outsideChain,
520
+ break: found.break,
521
+ head: found.head,
522
+ } satisfies ChainVerifyResponse,
523
+ 200,
524
+ );
525
+ },
526
+ );
527
+
528
+ /**
529
+ * CONTROL-PLANE READ (#822). One page of one tenant's chain in canonical form, each event with its hash, the
530
+ * link before the page and the checkpoints covering it — what `pithy audit verify` checks offline. The IP,
531
+ * user-agent and metadata values ride along only when the connection also holds the detail scope.
532
+ */
533
+ app.get(
534
+ `${base}/control-plane/export`,
535
+ describeRoute({
536
+ summary: "Export one tenant's audit chain in canonical form, with its checkpoints, to verify offline.",
537
+ verification: "control-plane",
538
+ scopes: [AUDIT_CHAIN_EXPORT_SCOPE],
539
+ responses: { 200: ChainExportResponse },
540
+ }),
541
+ requireControlPlane(AUDIT_CHAIN_EXPORT_SCOPE),
542
+ validate("query", ChainExportQuery),
543
+ async (c) => {
544
+ const operator = caller(c);
545
+ const query = c.req.valid("query");
546
+ // Read from the adopter's own grant, never from the token: a token is minted for one scope, and the
547
+ // question is whether the connection may also see what the detail scope discloses.
548
+ const detail = operator.grantedScopes.includes(AUDIT_EVENT_DETAIL_READ_SCOPE);
549
+ const page = await exportChainRange(
550
+ database(c),
551
+ checkpoints(c),
552
+ {
553
+ tenant: query.tenant,
554
+ ...(query.since ? { since: query.since } : {}),
555
+ ...(query.until ? { until: query.until } : {}),
556
+ },
557
+ {
558
+ detail,
559
+ limit: query.limit ?? 500,
560
+ now: new Date(),
561
+ ...(query.cursor !== undefined ? { cursor: query.cursor } : {}),
562
+ },
563
+ );
564
+ await c.var.emit({
565
+ action: AuditTrailActions.chainExported,
566
+ outcome: "success",
567
+ actorType: "control-plane",
568
+ actorId: operator.subject,
569
+ resourceType: "audit_chain",
570
+ requestId: c.req.header("cf-ray"),
571
+ ip: c.req.header("cf-connecting-ip"),
572
+ userAgent: c.req.header("user-agent"),
573
+ metadata: {
574
+ connectionId: operator.connectionId,
575
+ query: {
576
+ tenant: query.tenant,
577
+ since: query.since?.toISOString() ?? null,
578
+ until: query.until?.toISOString() ?? null,
579
+ resumed: query.cursor !== undefined,
580
+ },
581
+ detail,
582
+ returned: page.events.length,
583
+ more: page.nextCursor !== null,
584
+ },
585
+ });
586
+ return c.json(page satisfies ChainExportResponse, 200);
587
+ },
588
+ );
217
589
  };
218
590
  }
@@ -7,7 +7,7 @@ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
7
7
  import { z } from "zod";
8
8
 
9
9
  /**
10
- * The request contracts audit's two routes declare (CLAUDE.md §HTTP).
10
+ * The request contracts audit's routes declare (CLAUDE.md §HTTP).
11
11
  *
12
12
  * Every one of these is a **bound on something a caller chose**, which is the whole job here: a
13
13
  * control-plane credential is verified, but verified is not trusted, and a management client with a
@@ -77,7 +77,7 @@ export const ListAuditEventsQuery = z
77
77
  ),
78
78
  actorId: FilterValue.optional().describe("Filter to one principal — a user id, a service name, a token subject."),
79
79
  actorKind: ControlPlaneActorKind.optional().describe(
80
- "Filter to one kind of management client: `agent`, `dashboard` or `script`. What `actorType=control-plane` cannot say on its own.",
80
+ "Filter to one kind of client: `agent`, `dashboard` or `script`. `agent` finds a management agent's rows and every row a user's MCP client wrote, on both paths.",
81
81
  ),
82
82
  action: AuditAction.max(MAX_FILTER_LENGTH)
83
83
  .optional()
@@ -113,3 +113,159 @@ export const ListAuditEventsQuery = z
113
113
  })
114
114
  .describe("The audit trail query: what to filter the trail by, and where to resume reading it.");
115
115
  export type ListAuditEventsQuery = z.infer<typeof ListAuditEventsQuery>;
116
+
117
+ /**
118
+ * The access-history query: over what window, and where to resume.
119
+ *
120
+ * `since` is required, so an unbounded replay of the whole trail is a 400 before any query runs; `until` defaults to
121
+ * now in the handler, the one value a schema cannot compute for a request. A window that ends before it starts is
122
+ * refused rather than answered with nothing, because nothing would read as nobody's access having changed.
123
+ */
124
+ export const AccessHistoryQuery = z
125
+ .object({
126
+ since: TimeBound.describe("Inclusive lower bound on when a change happened, ISO-8601. Required."),
127
+ until: TimeBound.optional().describe("Inclusive upper bound on when a change happened, ISO-8601. Defaults to now."),
128
+ cursor: z
129
+ .string()
130
+ .max(512)
131
+ .optional()
132
+ .describe("Where to resume, from the previous page's `nextCursor`. Opaque; a malformed one is a first page."),
133
+ limit: z.coerce
134
+ .number()
135
+ .int()
136
+ .min(1)
137
+ .max(MAX_PAGE_SIZE)
138
+ .optional()
139
+ .describe("How many changes to return. Bounded, because a verified client can still have a bug."),
140
+ })
141
+ .refine((query) => query.until === undefined || query.until.getTime() >= query.since.getTime(), {
142
+ message: "`until` must not be before `since`.",
143
+ path: ["until"],
144
+ })
145
+ .describe("The access-history query: a window, oldest first, and where to resume reading it.");
146
+ export type AccessHistoryQuery = z.infer<typeof AccessHistoryQuery>;
147
+
148
+ /** A declared route pattern or a called path, as the reach answer names it. */
149
+ const RouteValue = z.string().min(1).max(512).startsWith("/");
150
+
151
+ /**
152
+ * The reach query: whose calls to read, over what window, and whether to expand one route into its subjects.
153
+ *
154
+ * `connectionId` and `since` are required, so a missing one is a 400 before any query runs: an unbounded read over
155
+ * every credential is not a question this route answers. `until` defaults to now in the handler, which is the one
156
+ * value a schema cannot compute for a request. A window that ends before it starts is refused rather than answered
157
+ * with nothing, because nothing would read as a credential that reached nothing. `subjects=true` needs a `route`:
158
+ * the expansion is one route's subject list, never every route's.
159
+ */
160
+ export const ControlPlaneReachQuery = z
161
+ .object({
162
+ connectionId: FilterValue.describe(
163
+ "The control-plane connection whose reach to read — the `resourceId` its call rows carry. Required.",
164
+ ),
165
+ keyId: FilterValue.optional().describe(
166
+ "Narrow to the calls one registered key signed. The leaked-key question: omit it for the whole connection.",
167
+ ),
168
+ since: TimeBound.describe("Inclusive lower bound on when a call landed, ISO-8601. Required."),
169
+ until: TimeBound.optional().describe("Inclusive upper bound on when a call landed, ISO-8601. Defaults to now."),
170
+ route: RouteValue.optional().describe(
171
+ "Narrow to one route: a declared pattern such as `/admin/users/:userId`, or the called path of an unmatched row.",
172
+ ),
173
+ subjects: z
174
+ .enum(["true", "false"])
175
+ .optional()
176
+ .describe(
177
+ "`true` expands `route` into the paths it was called with and the subject ids they name. Needs `route`.",
178
+ ),
179
+ })
180
+ .refine((query) => query.until === undefined || query.until.getTime() >= query.since.getTime(), {
181
+ message: "`until` must not be before `since`.",
182
+ path: ["until"],
183
+ })
184
+ .refine((query) => query.subjects !== "true" || query.route !== undefined, {
185
+ message: "`subjects=true` needs a `route` to expand.",
186
+ path: ["route"],
187
+ })
188
+ .describe("The control-plane reach query: one connection, over a window, optionally one key and one route.");
189
+ export type ControlPlaneReachQuery = z.infer<typeof ControlPlaneReachQuery>;
190
+
191
+ /**
192
+ * The usage query: whose calls to count, and over what window.
193
+ *
194
+ * `connectionId` and `since` are required, so a missing one is a 400 before any query runs — an unbounded window over
195
+ * every connection is not a question this route answers. `until` defaults to now in the handler, which is the one
196
+ * value a schema cannot compute for a request. A window that ends before it starts is refused rather than answered
197
+ * with nothing, because nothing would read as an idle connection.
198
+ */
199
+ export const ControlPlaneUsageQuery = z
200
+ .object({
201
+ connectionId: FilterValue.describe(
202
+ "The control-plane connection whose calls to count — the `resourceId` its call rows carry. Required.",
203
+ ),
204
+ since: TimeBound.describe("Inclusive lower bound on when a call landed, ISO-8601. Required."),
205
+ until: TimeBound.optional().describe("Inclusive upper bound on when a call landed, ISO-8601. Defaults to now."),
206
+ })
207
+ .refine((query) => query.until === undefined || query.until.getTime() >= query.since.getTime(), {
208
+ message: "`until` must not be before `since`.",
209
+ path: ["until"],
210
+ })
211
+ .describe("The control-plane usage query: one connection, over a window.");
212
+ export type ControlPlaneUsageQuery = z.infer<typeof ControlPlaneUsageQuery>;
213
+
214
+ /**
215
+ * The tenant whose chain to read. **Required**, because there is no "every chain": a chain is one tenant's.
216
+ * Send it empty (`?tenant=`) for the untenanted chain — the same encoding the listing's filter uses.
217
+ */
218
+ const ChainTenant = TenantFilter.describe(
219
+ "The tenant whose chain to read. Send it empty (`?tenant=`) for the chain of events that belong to no tenant. Required: a chain is one tenant's.",
220
+ );
221
+
222
+ /** The chain verify query: whose chain, and over what window. */
223
+ export const ChainVerifyQuery = z
224
+ .object({
225
+ tenant: ChainTenant,
226
+ since: TimeBound.optional().describe(
227
+ "Inclusive start of the window, ISO-8601. Omitted, the walk starts at the chain's first event.",
228
+ ),
229
+ until: TimeBound.optional().describe(
230
+ "Inclusive end of the window, ISO-8601. Omitted, the walk runs to the chain's head, and a checkpoint past it is a truncation.",
231
+ ),
232
+ })
233
+ .refine((query) => query.until === undefined || query.since === undefined || query.until >= query.since, {
234
+ message: "`until` must not be before `since`.",
235
+ path: ["until"],
236
+ })
237
+ .describe("The chain verify query: one tenant's chain, over a window.");
238
+ export type ChainVerifyQuery = z.infer<typeof ChainVerifyQuery>;
239
+
240
+ /** The most events one export page carries. */
241
+ export const MAX_EXPORT_PAGE = 1000;
242
+
243
+ /** The chain export query: whose chain, over what window, and where to resume. */
244
+ export const ChainExportQuery = z
245
+ .object({
246
+ tenant: ChainTenant,
247
+ since: TimeBound.optional().describe(
248
+ "Inclusive start of the window, ISO-8601. Omitted, the export starts at the chain's first event.",
249
+ ),
250
+ until: TimeBound.optional().describe(
251
+ "Inclusive end of the window, ISO-8601. Omitted, the export runs to the chain's head.",
252
+ ),
253
+ cursor: z
254
+ .string()
255
+ .max(32)
256
+ .optional()
257
+ .describe("Where to resume, from the previous page's `nextCursor`. A malformed one is a first page."),
258
+ limit: z.coerce
259
+ .number()
260
+ .int()
261
+ .min(1)
262
+ .max(MAX_EXPORT_PAGE)
263
+ .optional()
264
+ .describe(`How many events one page carries. At most ${MAX_EXPORT_PAGE}; defaults to 500.`),
265
+ })
266
+ .refine((query) => query.until === undefined || query.since === undefined || query.until >= query.since, {
267
+ message: "`until` must not be before `since`.",
268
+ path: ["until"],
269
+ })
270
+ .describe("The chain export query: one tenant's chain, over a window, a page at a time.");
271
+ export type ChainExportQuery = z.infer<typeof ChainExportQuery>;