@pithy-sh/audit 0.7.1 → 0.9.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 (46) hide show
  1. package/README.md +1 -1
  2. package/dist/capability.d.ts +1 -1
  3. package/dist/capability.d.ts.map +1 -1
  4. package/dist/capability.js +4 -3
  5. package/dist/http/guards.d.ts +7 -3
  6. package/dist/http/guards.d.ts.map +1 -1
  7. package/dist/http/guards.js +16 -4
  8. package/dist/http/responses.d.ts +122 -0
  9. package/dist/http/responses.d.ts.map +1 -1
  10. package/dist/http/responses.js +38 -1
  11. package/dist/http/routes.d.ts +8 -3
  12. package/dist/http/routes.d.ts.map +1 -1
  13. package/dist/http/routes.js +48 -16
  14. package/dist/http/schemas.d.ts +7 -5
  15. package/dist/http/schemas.d.ts.map +1 -1
  16. package/dist/http/schemas.js +9 -7
  17. package/dist/http/views.d.ts +20 -5
  18. package/dist/http/views.d.ts.map +1 -1
  19. package/dist/http/views.js +53 -5
  20. package/dist/query.d.ts +2 -0
  21. package/dist/query.d.ts.map +1 -1
  22. package/dist/query.js +1 -0
  23. package/dist/ship/consumer.js +1 -1
  24. package/dist/ship/delivery.d.ts +13 -0
  25. package/dist/ship/delivery.d.ts.map +1 -0
  26. package/dist/ship/delivery.js +21 -0
  27. package/dist/ship/health.d.ts +2 -11
  28. package/dist/ship/health.d.ts.map +1 -1
  29. package/dist/ship/health.js +4 -18
  30. package/dist/usage.d.ts +29 -12
  31. package/dist/usage.d.ts.map +1 -1
  32. package/dist/usage.js +23 -9
  33. package/dist/version.generated.d.ts +1 -1
  34. package/dist/version.generated.js +1 -1
  35. package/package.json +3 -3
  36. package/src/capability.ts +19 -20
  37. package/src/http/guards.ts +17 -4
  38. package/src/http/responses.ts +109 -0
  39. package/src/http/routes.ts +74 -20
  40. package/src/http/schemas.ts +21 -8
  41. package/src/http/views.ts +58 -5
  42. package/src/query.ts +7 -0
  43. package/src/ship/delivery.ts +23 -0
  44. package/src/ship/health.ts +3 -21
  45. package/src/usage.ts +37 -16
  46. package/src/version.generated.ts +1 -1
@@ -54,7 +54,8 @@ const ListAuditEventsQuery = z.object({
54
54
  actorType: AuditActorType.optional().describe("Filter to one kind of principal. `control-plane` is the one that separates a management client's own actions from the adopter's users'."),
55
55
  actorId: FilterValue.optional().describe("Filter to one principal — a user id, a service name, a token subject."),
56
56
  actorKind: ControlPlaneActorKind.optional().describe("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."),
57
- action: AuditAction.max(MAX_FILTER_LENGTH).optional().describe("Filter to one exact `domain/reason` action code. Exact, never a prefix — the taxonomy is federated."),
57
+ action: AuditAction.max(MAX_FILTER_LENGTH).optional().describe("Filter to one exact `domain/reason` action code. Exact; `actionPrefix` is the domain-wide filter."),
58
+ actionPrefix: z.string().regex(/^[a-z][a-z0-9]*\/?$/, "An action prefix is one domain, lowercase, with or without its trailing `/` (e.g. `auth` or `auth/`).").max(MAX_FILTER_LENGTH).transform((value) => value.replace(/\/$/, "")).optional().describe("Filter to every action under one domain — `auth` or `auth/` matches `auth/login` and `auth/logout`, never `authority/granted`. The domain is the only prefix: a reason is never matched by its start."),
58
59
  outcome: AuditOutcome.optional().describe("Filter to one outcome. `denied` is the one worth watching: a run of denials is what a credential being probed looks like."),
59
60
  severity: AuditSeverity.optional().describe("Filter to one severity."),
60
61
  resourceType: FilterValue.optional().describe("Filter to the kind of thing acted on (`user`, `secret`)."),
@@ -112,19 +113,20 @@ const ControlPlaneReachQuery = z.object({
112
113
  /**
113
114
  * The usage query: whose calls to count, and over what window.
114
115
  *
115
- * `connectionId` and `since` are required, so a missing one is a 400 before any query runs — an unbounded window over
116
- * every connection is not a question this route answers. `until` defaults to now in the handler, which is the one
117
- * value a schema cannot compute for a request. A window that ends before it starts is refused rather than answered
118
- * with nothing, because nothing would read as an idle connection.
116
+ * `since` is required, so a missing one is a 400 before any query runs — an unbounded window is not a question this
117
+ * route answers. `connectionId` is optional: named, the route counts that connection's calls; left out, it counts every
118
+ * connection's, which is the over-grant question across a Worker in one read. `until` defaults to now in the
119
+ * handler, which is the one value a schema cannot compute for a request. A window that ends before it starts is
120
+ * refused rather than answered with nothing, because nothing would read as an idle connection.
119
121
  */
120
122
  const ControlPlaneUsageQuery = z.object({
121
- connectionId: FilterValue.describe("The control-plane connection whose calls to count — the `resourceId` its call rows carry. Required."),
123
+ connectionId: FilterValue.optional().describe("The control-plane connection whose calls to count — the `resourceId` its call rows carry. Omit it to count every connection's."),
122
124
  since: TimeBound.describe("Inclusive lower bound on when a call landed, ISO-8601. Required."),
123
125
  until: TimeBound.optional().describe("Inclusive upper bound on when a call landed, ISO-8601. Defaults to now.")
124
126
  }).refine((query) => query.until === void 0 || query.until.getTime() >= query.since.getTime(), {
125
127
  message: "`until` must not be before `since`.",
126
128
  path: ["until"]
127
- }).describe("The control-plane usage query: one connection, over a window.");
129
+ }).describe("The control-plane usage query: one connection or every connection, over a window.");
128
130
  /**
129
131
  * The tenant whose chain to read. **Required**, because there is no "every chain": a chain is one tenant's.
130
132
  * Send it empty (`?tenant=`) for the untenanted chain — the same encoding the listing's filter uses.
@@ -2,9 +2,11 @@
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import type { AccessHistoryRow } from "../accessHistory";
4
4
  import type { AuditEventRow } from "../data/auditEvent";
5
+ import type { AuditSinkStateRow } from "../data/sinkState";
5
6
  import type { ControlPlaneReachRow, ControlPlaneReachSubjectRow } from "../reach";
7
+ import type { AuditSinks } from "../ship/sinks";
6
8
  import type { ControlPlaneUsageRow } from "../usage";
7
- import type { AccessChangeView, AuditEventDetailView, AuditEventView, ControlPlaneReachSubjectView, ControlPlaneReachView, ControlPlaneUsageView } from "./responses";
9
+ import type { AccessChangeView, AuditEventDetailView, AuditEventView, AuditSinkView, ControlPlaneConnectionUsageView, ControlPlaneReachSubjectView, ControlPlaneReachView, ControlPlaneUsageView } from "./responses";
8
10
  /**
9
11
  * What a management client is shown of an audit event — decided here, once, rather than by whichever
10
12
  * columns a query happened to select.
@@ -56,7 +58,7 @@ export declare function auditEventView(row: AuditEventRow): AuditEventView;
56
58
  /** Project one row for the single-event read, network identifiers and metadata included. */
57
59
  export declare function auditEventDetailView(row: AuditEventRow): AuditEventDetailView;
58
60
  /**
59
- * Project one access change (#831) into the wire union, by what changed.
61
+ * Project one access change into the wire union, by what changed.
60
62
  *
61
63
  * The statement already read nothing but the named metadata keys, so this drops nothing personal; what it does is
62
64
  * keep each subject's fields to that subject, so a member change never carries a null `scopesBefore` a client could
@@ -64,16 +66,29 @@ export declare function auditEventDetailView(row: AuditEventRow): AuditEventDeta
64
66
  */
65
67
  export declare function accessChangeView(row: AccessHistoryRow): AccessChangeView;
66
68
  /**
67
- * Project one reach row (#828). Field for field, with the instants as ISO-8601: the statement already read nothing
69
+ * Project one reach row. Field for field, with the instants as ISO-8601: the statement already read nothing
68
70
  * but the scope, the key, the method and the path out of `metadata`, and the tenant out of the handler's events, so
69
71
  * there is nothing here to drop.
70
72
  */
71
73
  export declare function controlPlaneReachView(row: ControlPlaneReachRow): ControlPlaneReachView;
72
- /** Project one subject row (#828), field for field, the same way — never a spread a new field would ride out on. */
74
+ /** Project one subject row, field for field, the same way — never a spread a new field would ride out on. */
73
75
  export declare function controlPlaneReachSubjectView(row: ControlPlaneReachSubjectRow): ControlPlaneReachSubjectView;
74
76
  /**
75
- * Project one usage row (#812). Field for field, with the instants as ISO-8601: the aggregate already read nothing but
77
+ * Project one usage row. Field for field, with the instants as ISO-8601: the aggregate already read nothing but
76
78
  * the scope, the key, and the last allowed call's method and path out of `metadata`, so there is nothing here to drop.
77
79
  */
78
80
  export declare function controlPlaneUsageView(row: ControlPlaneUsageRow): ControlPlaneUsageView;
81
+ /**
82
+ * Fold every connection's usage rows into one entry per connection, in the order the aggregate returned them —
83
+ * by connection, then scope, then key — so each connection's rows keep the order a named read gives them.
84
+ */
85
+ export declare function controlPlaneConnectionUsageViews(rows: readonly ControlPlaneUsageRow[]): ControlPlaneConnectionUsageView[];
86
+ /**
87
+ * Project the declared sinks, in declaration order, each beside its own state row. A sink with no row has never been
88
+ * attempted and answers null times, zero counts and `idle`; a row whose sink is no longer declared is not answered.
89
+ *
90
+ * Named fields, never a spread of the config: a sink's URL path and query may carry a key, and its secret name says
91
+ * where its token lives, so neither leaves. The host is the URL's host and port, as `pithy doctor` prints it.
92
+ */
93
+ export declare function auditSinkViews(sinks: AuditSinks, states: readonly AuditSinkStateRow[]): AuditSinkView[];
79
94
  //# sourceMappingURL=views.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"views.d.ts","sourceRoot":"","sources":["../../src/http/views.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AAClF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,KAAK,EACV,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,EACd,4BAA4B,EAC5B,qBAAqB,EACrB,qBAAqB,EACtB,MAAM,aAAa,CAAC;AAErB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,aAAa,GAAG,cAAc,CA6BjE;AAED,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,aAAa,GAAG,oBAAoB,CAE7E;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,CA2CxE;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,oBAAoB,GAAG,qBAAqB,CActF;AAED,oHAAoH;AACpH,wBAAgB,4BAA4B,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,GAAG,EAAE,oBAAoB,GAAG,qBAAqB,CAWtF;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,CAC9C,IAAI,EAAE,SAAS,oBAAoB,EAAE,GACpC,+BAA+B,EAAE,CAQnC;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,iBAAiB,EAAE,GAAG,aAAa,EAAE,CAuBvG"}
@@ -1,5 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { shipDelivery } from "../ship/delivery.js";
3
4
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
4
5
  //#region src/http/views.ts
5
6
  /**
@@ -81,7 +82,7 @@ function auditEventDetailView(row) {
81
82
  };
82
83
  }
83
84
  /**
84
- * Project one access change (#831) into the wire union, by what changed.
85
+ * Project one access change into the wire union, by what changed.
85
86
  *
86
87
  * The statement already read nothing but the named metadata keys, so this drops nothing personal; what it does is
87
88
  * keep each subject's fields to that subject, so a member change never carries a null `scopesBefore` a client could
@@ -130,7 +131,7 @@ function accessChangeView(row) {
130
131
  };
131
132
  }
132
133
  /**
133
- * Project one reach row (#828). Field for field, with the instants as ISO-8601: the statement already read nothing
134
+ * Project one reach row. Field for field, with the instants as ISO-8601: the statement already read nothing
134
135
  * but the scope, the key, the method and the path out of `metadata`, and the tenant out of the handler's events, so
135
136
  * there is nothing here to drop.
136
137
  */
@@ -149,7 +150,7 @@ function controlPlaneReachView(row) {
149
150
  lastAt: row.lastAt.toISOString()
150
151
  };
151
152
  }
152
- /** Project one subject row (#828), field for field, the same way — never a spread a new field would ride out on. */
153
+ /** Project one subject row, field for field, the same way — never a spread a new field would ride out on. */
153
154
  function controlPlaneReachSubjectView(row) {
154
155
  return {
155
156
  tenant: row.tenant,
@@ -168,7 +169,7 @@ function controlPlaneReachSubjectView(row) {
168
169
  };
169
170
  }
170
171
  /**
171
- * Project one usage row (#812). Field for field, with the instants as ISO-8601: the aggregate already read nothing but
172
+ * Project one usage row. Field for field, with the instants as ISO-8601: the aggregate already read nothing but
172
173
  * the scope, the key, and the last allowed call's method and path out of `metadata`, so there is nothing here to drop.
173
174
  */
174
175
  function controlPlaneUsageView(row) {
@@ -183,5 +184,52 @@ function controlPlaneUsageView(row) {
183
184
  lastDeniedAt: row.lastDeniedAt?.toISOString() ?? null
184
185
  };
185
186
  }
187
+ /**
188
+ * Fold every connection's usage rows into one entry per connection, in the order the aggregate returned them —
189
+ * by connection, then scope, then key — so each connection's rows keep the order a named read gives them.
190
+ */
191
+ function controlPlaneConnectionUsageViews(rows) {
192
+ const byConnection = /* @__PURE__ */ new Map();
193
+ for (const row of rows) {
194
+ const usage = byConnection.get(row.connectionId) ?? [];
195
+ usage.push(controlPlaneUsageView(row));
196
+ byConnection.set(row.connectionId, usage);
197
+ }
198
+ return [...byConnection].map(([connectionId, usage]) => ({
199
+ connectionId,
200
+ usage
201
+ }));
202
+ }
203
+ /**
204
+ * Project the declared sinks, in declaration order, each beside its own state row. A sink with no row has never been
205
+ * attempted and answers null times, zero counts and `idle`; a row whose sink is no longer declared is not answered.
206
+ *
207
+ * Named fields, never a spread of the config: a sink's URL path and query may carry a key, and its secret name says
208
+ * where its token lives, so neither leaves. The host is the URL's host and port, as `pithy doctor` prints it.
209
+ */
210
+ function auditSinkViews(sinks, states) {
211
+ const byName = new Map(states.map((state) => [state.sink, state]));
212
+ return Object.entries(sinks).map(([name, sink]) => {
213
+ const state = byName.get(name) ?? {
214
+ sink: name,
215
+ lastDeliveredAt: null,
216
+ lastFailedAt: null,
217
+ retrying: 0,
218
+ deadLettered: 0
219
+ };
220
+ return {
221
+ name,
222
+ profile: sink.profile,
223
+ host: new URL(sink.url).host,
224
+ detail: sink.detail,
225
+ actions: sink.actions === void 0 ? null : [...sink.actions],
226
+ lastDeliveredAt: state.lastDeliveredAt?.toISOString() ?? null,
227
+ lastFailedAt: state.lastFailedAt?.toISOString() ?? null,
228
+ retrying: state.retrying,
229
+ deadLettered: state.deadLettered,
230
+ delivery: shipDelivery([state])
231
+ };
232
+ });
233
+ }
186
234
  //#endregion
187
- export { accessChangeView, auditEventDetailView, auditEventView, controlPlaneReachSubjectView, controlPlaneReachView, controlPlaneUsageView };
235
+ export { accessChangeView, auditEventDetailView, auditEventView, auditSinkViews, controlPlaneConnectionUsageViews, controlPlaneReachSubjectView, controlPlaneReachView, controlPlaneUsageView };
package/dist/query.d.ts CHANGED
@@ -26,6 +26,8 @@ export interface AuditQuery {
26
26
  actorKind?: ControlPlaneActorKind;
27
27
  /** Match an exact `domain/reason` action code. */
28
28
  action?: string;
29
+ /** Match every action under one domain — `auth` matches `auth/login`, never `authority/granted`. */
30
+ actionPrefix?: string;
29
31
  /** Match the outcome (`success` | `failure` | `denied`). */
30
32
  outcome?: AuditOutcome;
31
33
  /** Match the severity (`info` | `warning` | `critical`). */
@@ -1 +1 @@
1
- {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACvG,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iDAAiD,CAAC;AAG7F,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,UAAU;IACzB,yCAAyC;IACzC,SAAS,CAAC,EAAE,cAAc,CAAC;IAC3B,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yFAAyF;IACzF,SAAS,CAAC,EAAE,qBAAqB,CAAC;IAClC,kDAAkD;IAClD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4DAA4D;IAC5D,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,4DAA4D;IAC5D,QAAQ,CAAC,E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,MAAM,GAAG,IAAI,CAAC;CAC3B;AA8DD;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,aAAa,EAAE,MAAM,GAAE,UAAe,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAK3G;AAED;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CAAC,EAAE,EAAE,aAAa,EAAE,MAAM,GAAE,UAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CAuBzG;AAED;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAAC,EAAE,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAGtG"}
package/dist/query.js CHANGED
@@ -18,6 +18,7 @@ function auditEventQuery(db, filter) {
18
18
  if (filter.actorId !== void 0) query = query.where("actorId", "=", filter.actorId);
19
19
  if (filter.actorKind !== void 0) query = query.where("actorKind", "=", filter.actorKind);
20
20
  if (filter.action !== void 0) query = query.where("action", "=", filter.action);
21
+ if (filter.actionPrefix !== void 0) query = query.where("action", ">=", `${filter.actionPrefix}/`).where("action", "<", `${filter.actionPrefix}0`);
21
22
  if (filter.outcome !== void 0) query = query.where("outcome", "=", filter.outcome);
22
23
  if (filter.severity !== void 0) query = query.where("severity", "=", filter.severity);
23
24
  if (filter.resourceType !== void 0) query = query.where("resourceType", "=", filter.resourceType);
@@ -1,10 +1,10 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import { readRowsByEventId } from "../chain/rows.js";
4
+ import { recordSinkOutcome } from "./state.js";
4
5
  import { shippedEventOf } from "./event.js";
5
6
  import { sinkDelivery } from "./profiles.js";
6
7
  import { ShipMessage, isFinalAttempt, retryDelaySeconds } from "./queue.js";
7
- import { recordSinkOutcome } from "./state.js";
8
8
  //#region src/ship/consumer.ts
9
9
  /**
10
10
  * **The shipping consumer (#824): one request per sink per batch, at least once.**
@@ -0,0 +1,13 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import type { AuditSinkStateRow } from "../data/sinkState";
4
+ /**
5
+ * The values a delivery state takes: per sink on the sinks read, and across every sink on the manifest's
6
+ * `auditShipDelivery`. `failing` when any sink's last attempt failed; `delivering` when every sink that has been
7
+ * attempted last took a delivery; `idle` when no sink has been attempted yet.
8
+ */
9
+ export declare const SHIP_DELIVERY_STATES: readonly ["delivering", "failing", "idle"];
10
+ export type ShipDeliveryState = (typeof SHIP_DELIVERY_STATES)[number];
11
+ /** How delivery stands, from the given sinks' rows: one sink's for its own state, every declared sink's for the total. */
12
+ export declare function shipDelivery(states: readonly AuditSinkStateRow[]): ShipDeliveryState;
13
+ //# sourceMappingURL=delivery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delivery.d.ts","sourceRoot":"","sources":["../../src/ship/delivery.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAE3D;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,YAAI,YAAY,EAAE,SAAS,EAAE,MAAM,CAAU,CAAC;AAC/E,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEtE,0HAA0H;AAC1H,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,iBAAiB,EAAE,GAAG,iBAAiB,CAQpF"}
@@ -0,0 +1,21 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ //#region src/ship/delivery.ts
4
+ /**
5
+ * The values a delivery state takes: per sink on the sinks read, and across every sink on the manifest's
6
+ * `auditShipDelivery`. `failing` when any sink's last attempt failed; `delivering` when every sink that has been
7
+ * attempted last took a delivery; `idle` when no sink has been attempted yet.
8
+ */
9
+ const SHIP_DELIVERY_STATES = [
10
+ "delivering",
11
+ "failing",
12
+ "idle"
13
+ ];
14
+ /** How delivery stands, from the given sinks' rows: one sink's for its own state, every declared sink's for the total. */
15
+ function shipDelivery(states) {
16
+ const attempted = states.filter((state) => state.lastDeliveredAt !== null || state.lastFailedAt !== null);
17
+ if (attempted.length === 0) return "idle";
18
+ return attempted.some((state) => state.lastFailedAt !== null && (state.lastDeliveredAt === null || state.lastFailedAt > state.lastDeliveredAt)) ? "failing" : "delivering";
19
+ }
20
+ //#endregion
21
+ export { SHIP_DELIVERY_STATES, shipDelivery };
@@ -3,11 +3,10 @@
3
3
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
4
  import { type CapabilityHealth } from "@pithy-sh/core/src/controlPlane/discovery/health";
5
5
  import type { Context } from "hono";
6
- import type { AuditSinkStateRow } from "../data/sinkState";
7
6
  import type { AuditDatabase } from "../data/tables";
8
7
  import type { AuditSinks } from "./sinks";
9
8
  /**
10
- * **Shipping's health, on audit's manifest entry (#824)** — whether the trail is reaching its sinks.
9
+ * **Shipping's health, on audit's manifest entry** — whether the trail is reaching its sinks.
11
10
  *
12
11
  * Three keys, all behind `audit:events:read`, the scope the listing already requires: a backlog, a dead-letter
13
12
  * count, and a state. Each is read off `pithy_audit_sinks` by primary key, one row per declared sink, so the bound
@@ -18,16 +17,8 @@ import type { AuditSinks } from "./sinks";
18
17
  export declare const AUDIT_SHIP_BACKLOG = "auditShipBacklog";
19
18
  /** Events given up on, across every sink: their last retry failed and they went to the dead-letter queue. */
20
19
  export declare const AUDIT_SHIP_DEAD_LETTERED = "auditShipDeadLettered";
21
- /** How delivery stands, across every sink. */
20
+ /** How delivery stands, across every sink: {@link shipDelivery} over every declared sink's row. */
22
21
  export declare const AUDIT_SHIP_DELIVERY = "auditShipDelivery";
23
- /**
24
- * The values {@link AUDIT_SHIP_DELIVERY} takes. `failing` when any sink's last attempt failed; `delivering` when
25
- * every sink that has been attempted last took a delivery; `idle` when no sink has been attempted yet.
26
- */
27
- export declare const SHIP_DELIVERY_STATES: readonly ["delivering", "failing", "idle"];
28
- export type ShipDeliveryState = (typeof SHIP_DELIVERY_STATES)[number];
29
- /** How delivery stands, from the declared sinks' rows. */
30
- export declare function shipDelivery(states: readonly AuditSinkStateRow[]): ShipDeliveryState;
31
22
  /** Declare shipping's health keys over the declared sinks. */
32
23
  export declare function shipHealth(sinks: AuditSinks, database: (c: Context<PithyHonoEnv>) => AuditDatabase): CapabilityHealth;
33
24
  //# sourceMappingURL=health.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"health.d.ts","sourceRoot":"","sources":["../../src/ship/health.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,KAAK,gBAAgB,EAA0B,MAAM,kDAAkD,CAAC;AACjH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG1C;;;;;;;GAOG;AAEH,oDAAoD;AACpD,eAAO,MAAM,kBAAkB,qBAAqB,CAAC;AAErD,6GAA6G;AAC7G,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAEhE,8CAA8C;AAC9C,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;AAEvD;;;GAGG;AACH,eAAO,MAAM,oBAAoB,YAAI,YAAY,EAAE,SAAS,EAAE,MAAM,CAAU,CAAC;AAC/E,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEtE,0DAA0D;AAC1D,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,iBAAiB,EAAE,GAAG,iBAAiB,CAQpF;AAED,8DAA8D;AAC9D,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,aAAa,GAAG,gBAAgB,CA0CrH"}
1
+ {"version":3,"file":"health.d.ts","sourceRoot":"","sources":["../../src/ship/health.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,KAAK,gBAAgB,EAA0B,MAAM,kDAAkD,CAAC;AACjH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAGpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAG1C;;;;;;;GAOG;AAEH,oDAAoD;AACpD,eAAO,MAAM,kBAAkB,qBAAqB,CAAC;AAErD,6GAA6G;AAC7G,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAEhE,mGAAmG;AACnG,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;AAEvD,8DAA8D;AAC9D,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,aAAa,GAAG,gBAAgB,CA0CrH"}
@@ -2,10 +2,11 @@
2
2
  // SPDX-License-Identifier: FSL-1.1-MIT
3
3
  import { AUDIT_TRAIL_READ_SCOPE } from "../http/guards.js";
4
4
  import { readSinkStates } from "./state.js";
5
+ import { SHIP_DELIVERY_STATES, shipDelivery } from "./delivery.js";
5
6
  import { defineCapabilityHealth } from "@pithy-sh/core/src/controlPlane/discovery/health";
6
7
  //#region src/ship/health.ts
7
8
  /**
8
- * **Shipping's health, on audit's manifest entry (#824)** — whether the trail is reaching its sinks.
9
+ * **Shipping's health, on audit's manifest entry** — whether the trail is reaching its sinks.
9
10
  *
10
11
  * Three keys, all behind `audit:events:read`, the scope the listing already requires: a backlog, a dead-letter
11
12
  * count, and a state. Each is read off `pithy_audit_sinks` by primary key, one row per declared sink, so the bound
@@ -16,23 +17,8 @@ import { defineCapabilityHealth } from "@pithy-sh/core/src/controlPlane/discover
16
17
  const AUDIT_SHIP_BACKLOG = "auditShipBacklog";
17
18
  /** Events given up on, across every sink: their last retry failed and they went to the dead-letter queue. */
18
19
  const AUDIT_SHIP_DEAD_LETTERED = "auditShipDeadLettered";
19
- /** How delivery stands, across every sink. */
20
+ /** How delivery stands, across every sink: {@link shipDelivery} over every declared sink's row. */
20
21
  const AUDIT_SHIP_DELIVERY = "auditShipDelivery";
21
- /**
22
- * The values {@link AUDIT_SHIP_DELIVERY} takes. `failing` when any sink's last attempt failed; `delivering` when
23
- * every sink that has been attempted last took a delivery; `idle` when no sink has been attempted yet.
24
- */
25
- const SHIP_DELIVERY_STATES = [
26
- "delivering",
27
- "failing",
28
- "idle"
29
- ];
30
- /** How delivery stands, from the declared sinks' rows. */
31
- function shipDelivery(states) {
32
- const attempted = states.filter((state) => state.lastDeliveredAt !== null || state.lastFailedAt !== null);
33
- if (attempted.length === 0) return "idle";
34
- return attempted.some((state) => state.lastFailedAt !== null && (state.lastDeliveredAt === null || state.lastFailedAt > state.lastDeliveredAt)) ? "failing" : "delivering";
35
- }
36
22
  /** Declare shipping's health keys over the declared sinks. */
37
23
  function shipHealth(sinks, database) {
38
24
  const names = Object.keys(sinks);
@@ -77,4 +63,4 @@ function shipHealth(sinks, database) {
77
63
  });
78
64
  }
79
65
  //#endregion
80
- export { AUDIT_SHIP_BACKLOG, AUDIT_SHIP_DEAD_LETTERED, AUDIT_SHIP_DELIVERY, SHIP_DELIVERY_STATES, shipDelivery, shipHealth };
66
+ export { AUDIT_SHIP_BACKLOG, AUDIT_SHIP_DEAD_LETTERED, AUDIT_SHIP_DELIVERY, shipHealth };
package/dist/usage.d.ts CHANGED
@@ -3,25 +3,31 @@
3
3
  import { z } from "zod";
4
4
  import type { AuditDatabase } from "./data/tables";
5
5
  /**
6
- * Which scopes a control-plane connection exercised, and which it was refused — `#812`.
6
+ * Which scopes a control-plane connection exercised, and which it was refused — `#812` — for one connection or every
7
+ * connection at once.
7
8
  *
8
9
  * Every admitted call writes `controlplane/call_allowed`, and every verified call refused a scope writes
9
10
  * `controlplane/call_denied`, both against the connection as `resourceId` and both naming the scope and key in
10
11
  * `metadata`. Answering "granted twelve, used three" from the listing would take one forensic read per event, behind
11
12
  * the scope that also discloses the client IP; this reads the same rows in SQL and returns counts.
12
13
  *
14
+ * **One connection, or every one.** Over-grant — scopes a credential holds and never used — is a question over every
15
+ * connection on the Worker, so leaving the connection out counts them all in the same statement, grouped by connection
16
+ * first. A connection that made no call in the window has no row: the caller joins against the connection listing.
17
+ *
13
18
  * **One statement for the aggregate, never a page walk.** A dashboard connection makes thousands of calls a day, and a
14
19
  * handler that paged them to count would be the largest read on the surface. The `GROUP BY` runs in D1, over rows
15
- * `pithyAuditEventsCallIdx` (`audit_0003_call_index`) finds by action, connection and time.
20
+ * `pithyAuditEventsCallIdx` (`audit_0003_call_index`) finds by action, connection and time — or, across every
21
+ * connection, rows `pithyAuditEventsOccurredAtIdx` finds by the window.
16
22
  *
17
23
  * **Nothing personal leaves this function.** It reads the scope, the key id, and the method and path of the last
18
24
  * allowed call out of `metadata`, and no other key, and never the IP or the user-agent. Those four are the management
19
25
  * client's own footprint.
20
26
  */
21
- /** What to count: one connection, over an inclusive window. */
27
+ /** What to count: one connection, or every connection, over an inclusive window. */
22
28
  export interface ControlPlaneUsageFilter {
23
- /** The connection whose calls are counted — the rows' `resourceId`. */
24
- connectionId: string;
29
+ /** The connection whose calls are counted — the rows' `resourceId`. Absent, every connection's calls are. */
30
+ connectionId?: string;
25
31
  /** Inclusive lower bound on `occurredAt`. */
26
32
  since: Date;
27
33
  /** Inclusive upper bound on `occurredAt`. */
@@ -33,6 +39,7 @@ export interface ControlPlaneUsageFilter {
33
39
  * Internal: the wire shape is `ControlPlaneUsageView` in `http/responses.ts`, and `http/views.ts` projects this into it.
34
40
  */
35
41
  export declare const ControlPlaneUsageRow: z.ZodObject<{
42
+ connectionId: z.ZodString;
36
43
  scope: z.ZodString;
37
44
  keyId: z.ZodNullable<z.ZodString>;
38
45
  allowed: z.ZodNumber;
@@ -45,7 +52,7 @@ export declare const ControlPlaneUsageRow: z.ZodObject<{
45
52
  export type ControlPlaneUsageRow = z.output<typeof ControlPlaneUsageRow>;
46
53
  /** What {@link controlPlaneUsage} answers. */
47
54
  export interface ControlPlaneUsage {
48
- /** One row per `(scope, keyId)` exercised, ordered by scope then key. */
55
+ /** One row per `(connectionId, scope, keyId)` exercised, ordered by connection, then scope, then key. */
49
56
  usage: ControlPlaneUsageRow[];
50
57
  /** The oldest event the trail holds, or null on an empty trail. */
51
58
  oldestEventAt: Date | null;
@@ -55,13 +62,19 @@ export interface ControlPlaneUsage {
55
62
  *
56
63
  * Three steps, in one statement:
57
64
  *
58
- * 1. **`calls`** — the connection's call rows in the window, with the scope, key, method and path lifted out of
59
- * `metadata`. The scope is read from where each writer puts it: an allowed row carries the token's `scope`; a gate
65
+ * 1. **`calls`** — the connection's call rows in the window, or every connection's when none is named, with the
66
+ * connection beside the scope, key, method and path lifted out of `metadata`. The scope is read from where each writer puts it: an allowed row carries the token's `scope`; a gate
60
67
  * refusal names the scope it required as `required`, and a handler's refusal as `scope`, so a denied row reads
61
68
  * `required` first. A row with no scope at all is nobody's usage and is dropped.
62
- * 2. **`ranked`** — each row's recency within its `(scope, keyId, action)`, newest first, `id` breaking a tie. Rank 1
63
- * of the allowed rows is the last allowed call, whose method and path the answer carries.
64
- * 3. **The group** — counts and last instants per `(scope, keyId)`.
69
+ * 2. **`ranked`** — each row's recency within its `(connectionId, scope, keyId, action)`, newest first, `id`
70
+ * breaking a tie. Rank 1 of the allowed rows is the last allowed call, whose method and path the answer carries.
71
+ * 3. **The group** — counts and last instants per `(connectionId, scope, keyId)`.
72
+ *
73
+ * Named, it seeks `pithyAuditEventsCallIdx`: each action, then the connection, then the window as a range. Unnamed,
74
+ * nothing narrows it but the actions and the window, and the window is what is small: an access review reads days of
75
+ * a trail that keeps months. So the planner reads `pithyAuditEventsOccurredAtIdx` over the window and checks the
76
+ * action on each row it finds, and the cost follows the window rather than everything retention holds. A row with no
77
+ * connection — an unverified refusal — is nobody's usage in either.
65
78
  */
66
79
  export declare function controlPlaneUsageStatement(db: AuditDatabase, filter: ControlPlaneUsageFilter): import("kysely").SelectQueryBuilder<import("@pithy-sh/core/src/data/db").DatabaseSchema<{
67
80
  pithyAuditEvents: z.ZodObject<{
@@ -119,6 +132,7 @@ export declare function controlPlaneUsageStatement(db: AuditDatabase, filter: Co
119
132
  }> & {
120
133
  calls: {
121
134
  action: string;
135
+ connectionId: string | null;
122
136
  id: number;
123
137
  keyId: string | null;
124
138
  method: string | null;
@@ -129,6 +143,7 @@ export declare function controlPlaneUsageStatement(db: AuditDatabase, filter: Co
129
143
  } & {
130
144
  ranked: {
131
145
  action: string;
146
+ connectionId: string | null;
132
147
  id: number;
133
148
  keyId: string | null;
134
149
  method: string | null;
@@ -139,6 +154,7 @@ export declare function controlPlaneUsageStatement(db: AuditDatabase, filter: Co
139
154
  };
140
155
  }, "ranked", {
141
156
  allowed: number;
157
+ connectionId: string | null;
142
158
  denied: number;
143
159
  keyId: string | null;
144
160
  lastAllowedAt: number | null;
@@ -148,7 +164,8 @@ export declare function controlPlaneUsageStatement(db: AuditDatabase, filter: Co
148
164
  scope: string | null;
149
165
  }>;
150
166
  /**
151
- * Count one connection's calls by scope and key, over an inclusive window.
167
+ * Count one connection's calls by scope and key, or every connection's by connection, scope and key, over an
168
+ * inclusive window.
152
169
  *
153
170
  * `oldestEventAt` is the oldest event the trail holds at all, for any connection or none. Retention prunes the trail
154
171
  * by time, never per connection, so this is how far back any connection's answer can reach: a window starting before
@@ -1 +1 @@
1
- {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../src/usage.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,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AE,IAAI,CAAC;IACZ,6CAA6C;IAC7C,KAAK,EAAE,IAAI,CAAC;CACb;AAQD;;;;GAIG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;iBAmBkE,CAAC;AACpG,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;AASzE,8CAA8C;AAC9C,MAAM,WAAW,iBAAiB;IAChC,yGAAyG;IACzG,KAAK,EAAE,oBAAoB,EAAE,CAAC;IAC9B,mEAAmE;IACnE,aAAa,EAAE,IAAI,GAAG,IAAI,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,0BAA0B,CAAC,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+D5F;AAED;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,aAAa,EACjB,MAAM,EAAE,uBAAuB,GAC9B,OAAO,CAAC,iBAAiB,CAAC,CAU5B"}
package/dist/usage.js CHANGED
@@ -15,6 +15,7 @@ const CONNECTION_RESOURCE = "controlplane_connection";
15
15
  * Internal: the wire shape is `ControlPlaneUsageView` in `http/responses.ts`, and `http/views.ts` projects this into it.
16
16
  */
17
17
  const ControlPlaneUsageRow = z.object({
18
+ connectionId: z.string().describe("The connection that made the calls — the rows' `resourceId`."),
18
19
  scope: z.string().describe("The scope exercised: what an allowed call's token carried, or what a refused call required — `metadata.required` from the gate, `metadata.scope` from a handler."),
19
20
  keyId: z.string().nullable().describe("The registered key that signed the calls. Null for a row that recorded none."),
20
21
  allowed: z.number().int().describe("How many `controlplane/call_allowed` events in the window."),
@@ -31,13 +32,19 @@ const OldestEvent = z.object({ oldest: SQLiteDate.nullable().describe("The small
31
32
  *
32
33
  * Three steps, in one statement:
33
34
  *
34
- * 1. **`calls`** — the connection's call rows in the window, with the scope, key, method and path lifted out of
35
- * `metadata`. The scope is read from where each writer puts it: an allowed row carries the token's `scope`; a gate
35
+ * 1. **`calls`** — the connection's call rows in the window, or every connection's when none is named, with the
36
+ * connection beside the scope, key, method and path lifted out of `metadata`. The scope is read from where each writer puts it: an allowed row carries the token's `scope`; a gate
36
37
  * refusal names the scope it required as `required`, and a handler's refusal as `scope`, so a denied row reads
37
38
  * `required` first. A row with no scope at all is nobody's usage and is dropped.
38
- * 2. **`ranked`** — each row's recency within its `(scope, keyId, action)`, newest first, `id` breaking a tie. Rank 1
39
- * of the allowed rows is the last allowed call, whose method and path the answer carries.
40
- * 3. **The group** — counts and last instants per `(scope, keyId)`.
39
+ * 2. **`ranked`** — each row's recency within its `(connectionId, scope, keyId, action)`, newest first, `id`
40
+ * breaking a tie. Rank 1 of the allowed rows is the last allowed call, whose method and path the answer carries.
41
+ * 3. **The group** — counts and last instants per `(connectionId, scope, keyId)`.
42
+ *
43
+ * Named, it seeks `pithyAuditEventsCallIdx`: each action, then the connection, then the window as a range. Unnamed,
44
+ * nothing narrows it but the actions and the window, and the window is what is small: an access review reads days of
45
+ * a trail that keeps months. So the planner reads `pithyAuditEventsOccurredAtIdx` over the window and checks the
46
+ * action on each row it finds, and the cost follows the window rather than everything retention holds. A row with no
47
+ * connection — an unverified refusal — is nobody's usage in either.
41
48
  */
42
49
  function controlPlaneUsageStatement(db, filter) {
43
50
  const allowed = ControlPlaneAuditActions.callAllowed;
@@ -46,15 +53,17 @@ function controlPlaneUsageStatement(db, filter) {
46
53
  "id",
47
54
  "action",
48
55
  "occurredAt",
56
+ eb.ref("resourceId").as("connectionId"),
49
57
  sql`case when ${eb.ref("action")} = ${denied}
50
58
  then coalesce(json_extract(${eb.ref("metadata")}, '$.required'), json_extract(${eb.ref("metadata")}, '$.scope'))
51
59
  else json_extract(${eb.ref("metadata")}, '$.scope') end`.as("scope"),
52
60
  sql`json_extract(${eb.ref("metadata")}, '$.keyId')`.as("keyId"),
53
61
  sql`json_extract(${eb.ref("metadata")}, '$.method')`.as("method"),
54
62
  sql`json_extract(${eb.ref("metadata")}, '$.path')`.as("path")
55
- ]).where("action", "in", CALL_ACTIONS).where("resourceId", "=", filter.connectionId).where("occurredAt", ">=", SQLiteDate.encode(filter.since)).where("occurredAt", "<=", SQLiteDate.encode(filter.until)).where("resourceType", "=", CONNECTION_RESOURCE)).with("ranked", (q) => q.selectFrom("calls").selectAll().select(sql`row_number() over (
56
- partition by ${sql.ref("scope")}, ${sql.ref("keyId")}, ${sql.ref("action")}
63
+ ]).where("action", "in", CALL_ACTIONS).where((eb) => filter.connectionId === void 0 ? eb("resourceId", "is not", null) : eb("resourceId", "=", filter.connectionId)).where("occurredAt", ">=", SQLiteDate.encode(filter.since)).where("occurredAt", "<=", SQLiteDate.encode(filter.until)).where("resourceType", "=", CONNECTION_RESOURCE)).with("ranked", (q) => q.selectFrom("calls").selectAll().select(sql`row_number() over (
64
+ partition by ${sql.ref("connectionId")}, ${sql.ref("scope")}, ${sql.ref("keyId")}, ${sql.ref("action")}
57
65
  order by ${sql.ref("occurredAt")} desc, ${sql.ref("id")} desc)`.as("recency")).where("scope", "is not", null)).selectFrom("ranked").select((eb) => [
66
+ "connectionId",
58
67
  "scope",
59
68
  "keyId",
60
69
  sql`sum(case when ${eb.ref("action")} = ${allowed} then 1 else 0 end)`.as("allowed"),
@@ -65,10 +74,15 @@ function controlPlaneUsageStatement(db, filter) {
65
74
  sql`max(case when ${eb.ref("action")} = ${allowed} and ${eb.ref("recency")} = 1
66
75
  then ${eb.ref("path")} end)`.as("lastAllowedPath"),
67
76
  sql`max(case when ${eb.ref("action")} = ${denied} then ${eb.ref("occurredAt")} end)`.as("lastDeniedAt")
68
- ]).groupBy(["scope", "keyId"]).orderBy("scope").orderBy("keyId");
77
+ ]).groupBy([
78
+ "connectionId",
79
+ "scope",
80
+ "keyId"
81
+ ]).orderBy("connectionId").orderBy("scope").orderBy("keyId");
69
82
  }
70
83
  /**
71
- * Count one connection's calls by scope and key, over an inclusive window.
84
+ * Count one connection's calls by scope and key, or every connection's by connection, scope and key, over an
85
+ * inclusive window.
72
86
  *
73
87
  * `oldestEventAt` is the oldest event the trail holds at all, for any connection or none. Retention prunes the trail
74
88
  * by time, never per connection, so this is how far back any connection's answer can reach: a window starting before
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/audit";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.7.1";
6
+ export declare const PACKAGE_VERSION = "0.9.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/audit";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.7.1";
7
+ const PACKAGE_VERSION = "0.9.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/audit",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "license": "FSL-1.1-MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,8 +38,8 @@
38
38
  "@hono/zod-validator": "^0.9.0"
39
39
  },
40
40
  "peerDependencies": {
41
- "@pithy-sh/core": "^0.15.0",
42
- "@pithy-sh/secrets": "^0.6.3",
41
+ "@pithy-sh/core": "^0.17.0",
42
+ "@pithy-sh/secrets": "^0.6.5",
43
43
  "hono": "^4.13.2",
44
44
  "kysely": "^0.29.0",
45
45
  "zod": "^4.4.0"