@pithy-sh/audit 0.1.1 → 0.1.3

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 (56) hide show
  1. package/dist/actions.d.ts +41 -0
  2. package/dist/actions.d.ts.map +1 -0
  3. package/dist/actions.js +55 -0
  4. package/dist/capability.d.ts +40 -0
  5. package/dist/capability.d.ts.map +1 -0
  6. package/dist/capability.js +86 -0
  7. package/dist/cli/emitFromCLI.d.ts +35 -0
  8. package/dist/cli/emitFromCLI.d.ts.map +1 -0
  9. package/dist/cli/emitFromCLI.js +37 -0
  10. package/dist/cli/resolveActor.d.ts +74 -0
  11. package/dist/cli/resolveActor.d.ts.map +1 -0
  12. package/dist/cli/resolveActor.js +83 -0
  13. package/dist/data/auditEvent.d.ts +57 -0
  14. package/dist/data/auditEvent.d.ts.map +1 -0
  15. package/dist/data/auditEvent.js +46 -0
  16. package/dist/data/tables.d.ts +52 -0
  17. package/dist/data/tables.d.ts.map +1 -0
  18. package/dist/data/tables.js +15 -0
  19. package/dist/error/errors.d.ts +41 -0
  20. package/dist/error/errors.d.ts.map +1 -0
  21. package/dist/error/errors.js +30 -0
  22. package/dist/http/guards.d.ts +68 -0
  23. package/dist/http/guards.d.ts.map +1 -0
  24. package/dist/http/guards.js +80 -0
  25. package/dist/http/responses.d.ts +158 -0
  26. package/dist/http/responses.d.ts.map +1 -0
  27. package/dist/http/responses.js +71 -0
  28. package/dist/http/routes.d.ts +59 -0
  29. package/dist/http/routes.d.ts.map +1 -0
  30. package/dist/http/routes.js +125 -0
  31. package/dist/http/schemas.d.ts +45 -0
  32. package/dist/http/schemas.d.ts.map +1 -0
  33. package/dist/http/schemas.js +68 -0
  34. package/dist/http/views.d.ts +53 -0
  35. package/dist/http/views.d.ts.map +1 -0
  36. package/dist/http/views.js +79 -0
  37. package/dist/index.d.ts +16 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +10 -0
  40. package/dist/migrations/0001_init.d.ts +19 -0
  41. package/dist/migrations/0001_init.d.ts.map +1 -0
  42. package/dist/migrations/0001_init.js +45 -0
  43. package/dist/query.d.ts +103 -0
  44. package/dist/query.d.ts.map +1 -0
  45. package/dist/query.js +95 -0
  46. package/dist/recorder.d.ts +80 -0
  47. package/dist/recorder.d.ts.map +1 -0
  48. package/dist/recorder.js +64 -0
  49. package/dist/seeds/example.d.ts +16 -0
  50. package/dist/seeds/example.d.ts.map +1 -0
  51. package/dist/seeds/example.js +194 -0
  52. package/dist/version.generated.d.ts +5 -0
  53. package/dist/version.generated.d.ts.map +1 -0
  54. package/dist/version.generated.js +7 -0
  55. package/package.json +21 -10
  56. package/src/version.generated.ts +1 -1
@@ -0,0 +1,125 @@
1
+ import { AuditTrailActions } from "../actions.js";
2
+ import { AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE } from "./guards.js";
3
+ import { pageAuditEvents, readAuditEvent } from "../query.js";
4
+ import { AuditEventIdParam, ListAuditEventsQuery } from "./schemas.js";
5
+ import { auditEventDetailView, auditEventView } from "./views.js";
6
+ import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
7
+ import { zValidator } from "@hono/zod-validator";
8
+ import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
9
+ import { validationHook } from "@pithy-sh/core/src/http/validation";
10
+ //#region src/http/routes.ts
11
+ /** Every route, and how it is gated. */
12
+ const AUDIT_ROUTES = [{
13
+ method: "GET",
14
+ path: "/events",
15
+ strategy: "control-plane",
16
+ scope: AUDIT_TRAIL_READ_SCOPE
17
+ }, {
18
+ method: "GET",
19
+ path: "/events/:eventId",
20
+ strategy: "control-plane",
21
+ scope: AUDIT_EVENT_DETAIL_READ_SCOPE
22
+ }];
23
+ /**
24
+ * The verified management client behind a control-plane call.
25
+ *
26
+ * `requireControlPlane()` has run on every route in this file, so `c.var.controlPlane` is populated by
27
+ * the time a handler reads it. The throw is a programming-error guard, not a runtime path: reaching it
28
+ * would mean a route was mounted without its gate, which is the one mistake this file is arranged to
29
+ * make impossible.
30
+ */
31
+ function caller(c) {
32
+ const context = c.var.controlPlane;
33
+ if (!context) throw new InternalError({
34
+ message: "Audit could not identify the management caller.",
35
+ detail: "requireControlPlane() must run before an audit handler reads the caller."
36
+ });
37
+ return context;
38
+ }
39
+ /**
40
+ * The filter, as the audit trail should record that it was asked.
41
+ *
42
+ * Built here rather than inline in the `metadata:` literal for two reasons. It keeps dates as ISO
43
+ * strings — a `Date` would round-trip out of the JSON column as a string anyway, so writing one is a
44
+ * silent type change. And `metadata` may not carry top-level keys that name a column (`project`,
45
+ * `environment`, `worker`, `tenant`); nesting the filter under one key keeps the record of *what was
46
+ * asked for* distinct from the record of *where the reading happened* and *whose events these were*,
47
+ * which is what those columns mean. A `tenant` here is a filter the caller typed, not the tenant this
48
+ * read belonged to — collapsing the two would make the trail lie about its own reads.
49
+ */
50
+ function askedFor(query) {
51
+ const { from, to, cursor, ...rest } = query;
52
+ return {
53
+ ...rest,
54
+ ...from ? { from: from.toISOString() } : {},
55
+ ...to ? { to: to.toISOString() } : {},
56
+ resumed: cursor !== void 0
57
+ };
58
+ }
59
+ /** Register the audit sub-router. Returned as the capability's `routes` hook. */
60
+ function registerAuditRoutes(options) {
61
+ const base = options.basePath;
62
+ const database = options.database;
63
+ return (app) => {
64
+ /**
65
+ * CONTROL-PLANE READ. A filtered, resumable page of the trail — keyset, never offset, because the
66
+ * table is appended to while it is being read and an offset page silently skips records.
67
+ */
68
+ app.get(`${base}/events`, requireControlPlane(AUDIT_TRAIL_READ_SCOPE), zValidator("query", ListAuditEventsQuery, validationHook), async (c) => {
69
+ const operator = caller(c);
70
+ const query = c.req.valid("query");
71
+ const page = await pageAuditEvents(database(c), query);
72
+ await c.var.emit({
73
+ action: AuditTrailActions.trailRead,
74
+ outcome: "success",
75
+ actorType: "control-plane",
76
+ actorId: operator.subject,
77
+ resourceType: "audit_trail",
78
+ requestId: c.req.header("cf-ray"),
79
+ ip: c.req.header("cf-connecting-ip"),
80
+ userAgent: c.req.header("user-agent"),
81
+ metadata: {
82
+ connectionId: operator.connectionId,
83
+ query: askedFor(query),
84
+ returned: page.events.length,
85
+ more: page.nextCursor !== null
86
+ }
87
+ });
88
+ return c.json({
89
+ events: page.events.map(auditEventView),
90
+ nextCursor: page.nextCursor
91
+ }, 200);
92
+ });
93
+ /**
94
+ * CONTROL-PLANE READ, the forensic one. Returns the client IP, the user-agent, and the capability's
95
+ * metadata bag, which is why it sits behind its own scope rather than the listing's.
96
+ */
97
+ app.get(`${base}/events/:eventId`, requireControlPlane(AUDIT_EVENT_DETAIL_READ_SCOPE), zValidator("param", AuditEventIdParam, validationHook), async (c) => {
98
+ const operator = caller(c);
99
+ const { eventId } = c.req.valid("param");
100
+ const row = await readAuditEvent(database(c), eventId);
101
+ await c.var.emit({
102
+ action: AuditTrailActions.eventRead,
103
+ outcome: row ? "success" : "failure",
104
+ actorType: "control-plane",
105
+ actorId: operator.subject,
106
+ resourceType: "audit_event",
107
+ resourceId: eventId,
108
+ requestId: c.req.header("cf-ray"),
109
+ ip: c.req.header("cf-connecting-ip"),
110
+ userAgent: c.req.header("user-agent"),
111
+ metadata: {
112
+ connectionId: operator.connectionId,
113
+ found: row !== null
114
+ }
115
+ });
116
+ if (!row) throw new NotFoundError({
117
+ message: "No audit event with that id.",
118
+ action: "Check the eventId against a page from GET /events."
119
+ });
120
+ return c.json({ event: auditEventDetailView(row) }, 200);
121
+ });
122
+ };
123
+ }
124
+ //#endregion
125
+ export { AUDIT_ROUTES, registerAuditRoutes };
@@ -0,0 +1,45 @@
1
+ import { z } from "zod";
2
+ /** One event's id in the path. */
3
+ export declare const AuditEventIdParam: z.ZodObject<{
4
+ eventId: z.ZodString;
5
+ }, z.core.$strip>;
6
+ export type AuditEventIdParam = z.infer<typeof AuditEventIdParam>;
7
+ /**
8
+ * The trail query: what to filter by, and where to resume.
9
+ *
10
+ * Field names match {@link AuditQuery} exactly, so the validated object is the filter — there is no
11
+ * hand-written mapping in the handler for a rename to fall out of sync with.
12
+ */
13
+ export declare const ListAuditEventsQuery: z.ZodObject<{
14
+ actorType: z.ZodOptional<z.ZodEnum<{
15
+ anonymous: "anonymous";
16
+ "control-plane": "control-plane";
17
+ service: "service";
18
+ system: "system";
19
+ user: "user";
20
+ }>>;
21
+ actorId: z.ZodOptional<z.ZodString>;
22
+ action: z.ZodOptional<z.ZodString>;
23
+ outcome: z.ZodOptional<z.ZodEnum<{
24
+ denied: "denied";
25
+ failure: "failure";
26
+ success: "success";
27
+ }>>;
28
+ severity: z.ZodOptional<z.ZodEnum<{
29
+ critical: "critical";
30
+ info: "info";
31
+ warning: "warning";
32
+ }>>;
33
+ resourceType: z.ZodOptional<z.ZodString>;
34
+ resourceId: z.ZodOptional<z.ZodString>;
35
+ project: z.ZodOptional<z.ZodString>;
36
+ environment: z.ZodOptional<z.ZodString>;
37
+ worker: z.ZodOptional<z.ZodString>;
38
+ tenant: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodPipe<z.ZodLiteral<"">, z.ZodTransform<null, "">>]>>;
39
+ from: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<Date, string>>>;
40
+ to: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<Date, string>>>;
41
+ cursor: z.ZodOptional<z.ZodString>;
42
+ limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
43
+ }, z.core.$strip>;
44
+ export type ListAuditEventsQuery = z.infer<typeof ListAuditEventsQuery>;
45
+ //# sourceMappingURL=schemas.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/http/schemas.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA+CxB,kCAAkC;AAClC,eAAO,MAAM,iBAAiB;;iBAS+B,CAAC;AAC9D,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAElE;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsCiE,CAAC;AACnG,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC"}
@@ -0,0 +1,68 @@
1
+ import { AuditAction, AuditActorType, AuditOutcome, AuditSeverity } from "@pithy-sh/core/src/audit/auditEvent";
2
+ import { z } from "zod";
3
+ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
4
+ //#region src/http/schemas.ts
5
+ /**
6
+ * The request contracts audit's two routes declare (CLAUDE.md §HTTP).
7
+ *
8
+ * Every one of these is a **bound on something a caller chose**, which is the whole job here: a
9
+ * control-plane credential is verified, but verified is not trusted, and a management client with a
10
+ * bug can ask for a million rows off the largest table in the project as easily as a hostile one can.
11
+ *
12
+ * The free-text filters are bounded strings rather than enums, deliberately. `action` is a federated
13
+ * taxonomy — every capability declares its own codes and core holds no closed union — so the valid
14
+ * set is not knowable here, and the same is true of `resourceType`, `project`, and `worker`. Each is
15
+ * only ever compared, never interpreted, so a filter naming something this deployment has never
16
+ * recorded is an empty page rather than a 400. That is the better answer to the same question: a
17
+ * dashboard filtering by a capability the adopter removed should show nothing, not fail.
18
+ */
19
+ /** How long any single filter value may be. Generous for a name, far short of a payload. */
20
+ const MAX_FILTER_LENGTH = 256;
21
+ /** A bounded free-text filter value — compared against a column, never interpreted. */
22
+ const FilterValue = z.string().min(1).max(MAX_FILTER_LENGTH);
23
+ /**
24
+ * The tenant filter, where **an empty value is the null filter**: `?tenant=acme` is one tenant's trail,
25
+ * `?tenant=` is the events that belong to no tenant, and omitting it entirely filters nothing.
26
+ *
27
+ * Three states over a query string that natively has two, so the third needs an encoding. The empty
28
+ * string is the one value that cannot collide: `FilterValue` is `min(1)`, so no tenant id is ever
29
+ * empty, and no adopter can be locked out of filtering for a tenant whose id happens to be the sentinel
30
+ * — which is what `?tenant=none` or `?tenant=null` would have risked. It is decoded here rather than in
31
+ * the handler, so `AuditQuery`'s `string | null` is what reaches the query builder.
32
+ */
33
+ const TenantFilter = z.union([FilterValue, z.literal("").transform(() => null)]);
34
+ /**
35
+ * An inclusive time bound, as ISO-8601, decoded to a `Date` by the schema rather than by the handler.
36
+ *
37
+ * The conversion belongs here because a handler takes typed values: the route signature carries the
38
+ * contract, so `from` reaches the query as the `Date` the filter wants and no handler ever parses a
39
+ * caller's string.
40
+ */
41
+ const TimeBound = z.string().datetime({ offset: true }).transform((value) => new Date(value));
42
+ /** One event's id in the path. */
43
+ const AuditEventIdParam = z.object({ eventId: z.string().uuid().describe("The event's `eventId` — the recorder's UUID idempotency key, not the internal autoincrement `id`. A param schema constrains the string; the handler still does the lookup.") }).describe("The path parameters of the single-event route.");
44
+ /**
45
+ * The trail query: what to filter by, and where to resume.
46
+ *
47
+ * Field names match {@link AuditQuery} exactly, so the validated object is the filter — there is no
48
+ * hand-written mapping in the handler for a rename to fall out of sync with.
49
+ */
50
+ const ListAuditEventsQuery = z.object({
51
+ 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'."),
52
+ actorId: FilterValue.optional().describe("Filter to one principal — a user id, a service name, a token subject."),
53
+ action: AuditAction.max(MAX_FILTER_LENGTH).optional().describe("Filter to one exact `domain/reason` action code. Exact, never a prefix — the taxonomy is federated."),
54
+ 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."),
55
+ severity: AuditSeverity.optional().describe("Filter to one severity."),
56
+ resourceType: FilterValue.optional().describe("Filter to the kind of thing acted on (`user`, `secret`)."),
57
+ resourceId: FilterValue.optional().describe("Filter to one target — everything that happened to this thing."),
58
+ project: FilterValue.optional().describe("Filter to one project, as the recorder stamped it."),
59
+ environment: FilterValue.optional().describe("Filter to one environment (`dev` | `staging` | `prod`)."),
60
+ worker: FilterValue.optional().describe("Filter to one `apps/<name>` Worker. Two Workers sharing a database share this table, so this is the only column that tells their events apart."),
61
+ tenant: TenantFilter.optional().describe("Filter to one tenant — whose actions these were, as the emitter recorded them. Send it empty (`?tenant=`) for the events that belong to no tenant: a CLI-originated action, a fleet-wide one, or a row recorded before the column existed. Omit it to filter nothing."),
62
+ from: TimeBound.optional().describe("Inclusive lower bound on when the event occurred, ISO-8601."),
63
+ to: TimeBound.optional().describe("Inclusive upper bound on when the event occurred, ISO-8601."),
64
+ cursor: z.string().max(512).optional().describe("Where to resume, from the previous page's `nextCursor`. Opaque; a malformed one is a first page."),
65
+ limit: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).optional().describe("How many events to return. Bounded, because a verified client can still have a bug.")
66
+ }).describe("The audit trail query: what to filter the trail by, and where to resume reading it.");
67
+ //#endregion
68
+ export { AuditEventIdParam, ListAuditEventsQuery };
@@ -0,0 +1,53 @@
1
+ import type { AuditEventRow } from "../data/auditEvent";
2
+ import type { AuditEventDetailView, AuditEventView } from "./responses";
3
+ /**
4
+ * What a management client is shown of an audit event — decided here, once, rather than by whichever
5
+ * columns a query happened to select.
6
+ *
7
+ * **No route returns a raw row.** The trail is the most sensitive table Pithy ships: it is the record
8
+ * of every security-relevant action across every capability, and it carries personal data the adopter
9
+ * collected from their own users. Handing a `SELECT *` to a client means every column the schema ever
10
+ * gains is disclosed by default, which is exactly backwards.
11
+ *
12
+ * ## What is deliberately absent from both views
13
+ *
14
+ * `id`, the autoincrement surrogate. Its own schema says internal, never exposed, and that is right:
15
+ * it is monotonic, so publishing it tells a client how many events the project has recorded and lets
16
+ * it address rows by counting. Events are addressed by `eventId`, a UUID. The keyset cursor does
17
+ * carry `id` as a position, and that is a different thing — it is opaque, it is not a field a client
18
+ * can filter or address by, and it names only the row that client was just handed.
19
+ *
20
+ * ## What is in the detail view only, and why
21
+ *
22
+ * `ip`, `userAgent`, and `metadata`. These are the trail's personal data, and they are the reason
23
+ * {@link AUDIT_EVENT_DETAIL_READ_SCOPE} exists as a separate grant.
24
+ *
25
+ * - **`ip`** is a personal identifier under GDPR, and it is also the field a forensic read genuinely
26
+ * needs — "was this login from where this person usually is". So it is exposed, not dropped;
27
+ * dropping it would make the column pointless and the incident unanswerable. It is exposed one
28
+ * event at a time, behind its own scope, so reading it is a decision rather than a side effect of
29
+ * opening a dashboard.
30
+ * - **`userAgent`** is a device fingerprint. Same reasoning, same place.
31
+ * - **`metadata`** is a capability-specific bag whose contents nothing here can predict. `@pithy-sh/testers`
32
+ * writes an invited tester's email address into it, on purpose, and other capabilities write resource
33
+ * names and denial reasons. A page of a hundred events would therefore leak an arbitrary amount of
34
+ * whatever every capability decided to record — so it is not in the listing at any page size.
35
+ *
36
+ * `sessionId` **is** in the list view, and it is not the exception it looks like. Better Auth's session
37
+ * row id is not its session token: the credential is `session.token`, which the trail never holds. The
38
+ * id is a correlation key, and correlating a chain of actions to one sign-in is most of what an audit
39
+ * trail is read for.
40
+ */
41
+ /**
42
+ * ## The field list lives in `responses.ts`
43
+ *
44
+ * Both view types are `z.output` of the Zod objects there, so there is one declaration of what a
45
+ * client receives rather than an interface here and a mirror of it in every management client. A
46
+ * field added to one and not the other does not compile.
47
+ *
48
+ * Project one row for the listing.
49
+ */
50
+ export declare function auditEventView(row: AuditEventRow): AuditEventView;
51
+ /** Project one row for the single-event read, network identifiers and metadata included. */
52
+ export declare function auditEventDetailView(row: AuditEventRow): AuditEventDetailView;
53
+ //# sourceMappingURL=views.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"views.d.ts","sourceRoot":"","sources":["../../src/http/views.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,aAAa,GAAG,cAAc,CAwBjE;AAED,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,aAAa,GAAG,oBAAoB,CAE7E"}
@@ -0,0 +1,79 @@
1
+ //#region src/http/views.ts
2
+ /**
3
+ * What a management client is shown of an audit event — decided here, once, rather than by whichever
4
+ * columns a query happened to select.
5
+ *
6
+ * **No route returns a raw row.** The trail is the most sensitive table Pithy ships: it is the record
7
+ * of every security-relevant action across every capability, and it carries personal data the adopter
8
+ * collected from their own users. Handing a `SELECT *` to a client means every column the schema ever
9
+ * gains is disclosed by default, which is exactly backwards.
10
+ *
11
+ * ## What is deliberately absent from both views
12
+ *
13
+ * `id`, the autoincrement surrogate. Its own schema says internal, never exposed, and that is right:
14
+ * it is monotonic, so publishing it tells a client how many events the project has recorded and lets
15
+ * it address rows by counting. Events are addressed by `eventId`, a UUID. The keyset cursor does
16
+ * carry `id` as a position, and that is a different thing — it is opaque, it is not a field a client
17
+ * can filter or address by, and it names only the row that client was just handed.
18
+ *
19
+ * ## What is in the detail view only, and why
20
+ *
21
+ * `ip`, `userAgent`, and `metadata`. These are the trail's personal data, and they are the reason
22
+ * {@link AUDIT_EVENT_DETAIL_READ_SCOPE} exists as a separate grant.
23
+ *
24
+ * - **`ip`** is a personal identifier under GDPR, and it is also the field a forensic read genuinely
25
+ * needs — "was this login from where this person usually is". So it is exposed, not dropped;
26
+ * dropping it would make the column pointless and the incident unanswerable. It is exposed one
27
+ * event at a time, behind its own scope, so reading it is a decision rather than a side effect of
28
+ * opening a dashboard.
29
+ * - **`userAgent`** is a device fingerprint. Same reasoning, same place.
30
+ * - **`metadata`** is a capability-specific bag whose contents nothing here can predict. `@pithy-sh/testers`
31
+ * writes an invited tester's email address into it, on purpose, and other capabilities write resource
32
+ * names and denial reasons. A page of a hundred events would therefore leak an arbitrary amount of
33
+ * whatever every capability decided to record — so it is not in the listing at any page size.
34
+ *
35
+ * `sessionId` **is** in the list view, and it is not the exception it looks like. Better Auth's session
36
+ * row id is not its session token: the credential is `session.token`, which the trail never holds. The
37
+ * id is a correlation key, and correlating a chain of actions to one sign-in is most of what an audit
38
+ * trail is read for.
39
+ */
40
+ /**
41
+ * ## The field list lives in `responses.ts`
42
+ *
43
+ * Both view types are `z.output` of the Zod objects there, so there is one declaration of what a
44
+ * client receives rather than an interface here and a mirror of it in every management client. A
45
+ * field added to one and not the other does not compile.
46
+ *
47
+ * Project one row for the listing.
48
+ */
49
+ function auditEventView(row) {
50
+ return {
51
+ eventId: row.eventId,
52
+ occurredAt: row.occurredAt.toISOString(),
53
+ action: row.action,
54
+ outcome: row.outcome,
55
+ severity: row.severity,
56
+ actorType: row.actorType,
57
+ actorId: row.actorId,
58
+ sessionId: row.sessionId,
59
+ resourceType: row.resourceType,
60
+ resourceId: row.resourceId,
61
+ requestId: row.requestId,
62
+ project: row.project,
63
+ environment: row.environment,
64
+ worker: row.worker,
65
+ version: row.version,
66
+ tenant: row.tenant
67
+ };
68
+ }
69
+ /** Project one row for the single-event read, network identifiers and metadata included. */
70
+ function auditEventDetailView(row) {
71
+ return {
72
+ ...auditEventView(row),
73
+ ip: row.ip,
74
+ userAgent: row.userAgent,
75
+ metadata: row.metadata
76
+ };
77
+ }
78
+ //#endregion
79
+ export { auditEventDetailView, auditEventView };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The package entrypoint — the surface `pithy add audit` wires into `pithy.config.ts`. Deliberately
3
+ * narrow: the capability factory, the recorder/query seams an app reads the trail with, the federated
4
+ * action-constant helper, and the CLI emitter + actor resolver. Every other module is imported by
5
+ * deep path (`@pithy-sh/audit/src/...`); this is the documented contract, not a barrel.
6
+ */
7
+ export { AuditTrailActions, defineAuditActions } from "./actions";
8
+ export { type AuditCapability, type AuditConfigInput, audit, isAuditCapability } from "./capability";
9
+ export { type CliAuditEvent, emitFromCLI } from "./cli/emitFromCLI";
10
+ export { type CfAccountTokenActorSource, type CfActorSource, type CfUserActorSource, createCachedActorResolver, type ResolvedActor, resolveActor, } from "./cli/resolveActor";
11
+ export { AuditEventRow } from "./data/auditEvent";
12
+ export { type AuditDatabase, auditDatabase } from "./data/tables";
13
+ export { AUDIT_CONTROL_PLANE_SCOPES, AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE, auditAdminRoutes, } from "./http/guards";
14
+ export { type AuditEventPage, type AuditQuery, pageAuditEvents, queryAuditEvents, readAuditEvent } from "./query";
15
+ export { type AuditRecorderOptions, createAuditEmit, recordAuditEvent } from "./recorder";
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AAEH,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,gBAAgB,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACrG,OAAO,EAAE,KAAK,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EACL,KAAK,yBAAyB,EAC9B,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,yBAAyB,EACzB,KAAK,aAAa,EAClB,YAAY,GACb,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,KAAK,aAAa,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,EACL,0BAA0B,EAC1B,6BAA6B,EAC7B,sBAAsB,EACtB,gBAAgB,GACjB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,UAAU,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClH,OAAO,EAAE,KAAK,oBAAoB,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import { AuditTrailActions, defineAuditActions } from "./actions.js";
2
+ import { AuditEventRow } from "./data/auditEvent.js";
3
+ import { auditDatabase } from "./data/tables.js";
4
+ import { AUDIT_CONTROL_PLANE_SCOPES, AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE, auditAdminRoutes } from "./http/guards.js";
5
+ import { pageAuditEvents, queryAuditEvents, readAuditEvent } from "./query.js";
6
+ import { createAuditEmit, recordAuditEvent } from "./recorder.js";
7
+ import { audit, isAuditCapability } from "./capability.js";
8
+ import { emitFromCLI } from "./cli/emitFromCLI.js";
9
+ import { createCachedActorResolver, resolveActor } from "./cli/resolveActor.js";
10
+ export { AUDIT_CONTROL_PLANE_SCOPES, AUDIT_EVENT_DETAIL_READ_SCOPE, AUDIT_TRAIL_READ_SCOPE, AuditEventRow, AuditTrailActions, audit, auditAdminRoutes, auditDatabase, createAuditEmit, createCachedActorResolver, defineAuditActions, emitFromCLI, isAuditCapability, pageAuditEvents, queryAuditEvents, readAuditEvent, recordAuditEvent, resolveActor };
@@ -0,0 +1,19 @@
1
+ import type { Migration } from "kysely/migration";
2
+ /**
3
+ * Create the `pithy_audit_events` table in the configured audit database (the `DB` binding by
4
+ * default). The `pithy_audit_` prefix keeps it from clashing with an adopter's own tables.
5
+ *
6
+ * Identifiers are declared in **camelCase**: the runner installs `CamelCasePlugin`, which snake-cases
7
+ * every identifier in the emitted DDL (CLAUDE.md §Data layer). `pithyAuditEvents` becomes the SQL
8
+ * table `pithy_audit_events`; the column names match the Zod schema.
9
+ *
10
+ * The indexes serve the query shapes the trail is read by — time range (`occurredAt`), per-action
11
+ * (`action`), per-actor (`actorType`, `actorId`), per-resource (`resourceType`, `resourceId`), and
12
+ * per-tenant over a window (`tenant`, `occurredAt`).
13
+ * `down` is the tested inverse: drop the indexes, then the table (D1 has no transactional DDL).
14
+ *
15
+ * This is the whole audit schema, in one migration — see `CONTRIBUTING.md` §Migrations for why that is
16
+ * the shape while nothing is published, and what changes the day something is.
17
+ */
18
+ export declare const audit_0001_init: Migration;
19
+ //# sourceMappingURL=0001_init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"0001_init.d.ts","sourceRoot":"","sources":["../../src/migrations/0001_init.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,eAAe,EAAE,SA8F7B,CAAC"}
@@ -0,0 +1,45 @@
1
+ //#region src/migrations/0001_init.ts
2
+ /**
3
+ * Create the `pithy_audit_events` table in the configured audit database (the `DB` binding by
4
+ * default). The `pithy_audit_` prefix keeps it from clashing with an adopter's own tables.
5
+ *
6
+ * Identifiers are declared in **camelCase**: the runner installs `CamelCasePlugin`, which snake-cases
7
+ * every identifier in the emitted DDL (CLAUDE.md §Data layer). `pithyAuditEvents` becomes the SQL
8
+ * table `pithy_audit_events`; the column names match the Zod schema.
9
+ *
10
+ * The indexes serve the query shapes the trail is read by — time range (`occurredAt`), per-action
11
+ * (`action`), per-actor (`actorType`, `actorId`), per-resource (`resourceType`, `resourceId`), and
12
+ * per-tenant over a window (`tenant`, `occurredAt`).
13
+ * `down` is the tested inverse: drop the indexes, then the table (D1 has no transactional DDL).
14
+ *
15
+ * This is the whole audit schema, in one migration — see `CONTRIBUTING.md` §Migrations for why that is
16
+ * the shape while nothing is published, and what changes the day something is.
17
+ */
18
+ const audit_0001_init = {
19
+ up: async (db) => {
20
+ await db.schema.createTable("pithyAuditEvents").addColumn("id", "integer", (c) => c.primaryKey().autoIncrement()).addColumn("eventId", "text", (c) => c.notNull()).addColumn("occurredAt", "integer", (c) => c.notNull()).addColumn("action", "text", (c) => c.notNull()).addColumn("outcome", "text", (c) => c.notNull()).addColumn("severity", "text", (c) => c.notNull().defaultTo("info")).addColumn("actorType", "text", (c) => c.notNull()).addColumn("actorId", "text").addColumn("sessionId", "text").addColumn("resourceType", "text").addColumn("resourceId", "text").addColumn("ip", "text").addColumn("userAgent", "text").addColumn("requestId", "text").addColumn("metadata", "text").addColumn("project", "text").addColumn("environment", "text").addColumn("worker", "text").addColumn("version", "text").addColumn("tenant", "text").execute();
21
+ await db.schema.createIndex("pithyAuditEventsEventIdIdx").on("pithyAuditEvents").column("eventId").unique().execute();
22
+ await db.schema.createIndex("pithyAuditEventsOccurredAtIdx").on("pithyAuditEvents").column("occurredAt").execute();
23
+ await db.schema.createIndex("pithyAuditEventsActionIdx").on("pithyAuditEvents").column("action").execute();
24
+ await db.schema.createIndex("pithyAuditEventsActorIdx").on("pithyAuditEvents").columns(["actorType", "actorId"]).execute();
25
+ await db.schema.createIndex("pithyAuditEventsResourceIdx").on("pithyAuditEvents").columns(["resourceType", "resourceId"]).execute();
26
+ await db.schema.createIndex("pithyAuditEventsOriginIdx").on("pithyAuditEvents").columns([
27
+ "project",
28
+ "environment",
29
+ "worker"
30
+ ]).execute();
31
+ await db.schema.createIndex("pithyAuditEventsTenantIdx").on("pithyAuditEvents").columns(["tenant", "occurredAt"]).execute();
32
+ },
33
+ down: async (db) => {
34
+ await db.schema.dropIndex("pithyAuditEventsTenantIdx").execute();
35
+ await db.schema.dropIndex("pithyAuditEventsOriginIdx").execute();
36
+ await db.schema.dropIndex("pithyAuditEventsResourceIdx").execute();
37
+ await db.schema.dropIndex("pithyAuditEventsActorIdx").execute();
38
+ await db.schema.dropIndex("pithyAuditEventsActionIdx").execute();
39
+ await db.schema.dropIndex("pithyAuditEventsOccurredAtIdx").execute();
40
+ await db.schema.dropIndex("pithyAuditEventsEventIdIdx").execute();
41
+ await db.schema.dropTable("pithyAuditEvents").execute();
42
+ }
43
+ };
44
+ //#endregion
45
+ export { audit_0001_init };
@@ -0,0 +1,103 @@
1
+ import type { AuditActorType, AuditOutcome, AuditSeverity } from "@pithy-sh/core/src/audit/auditEvent";
2
+ import { AuditEventRow } from "./data/auditEvent";
3
+ import type { AuditDatabase } from "./data/tables";
4
+ /**
5
+ * A filter over the audit trail. Every field is optional and ANDed together; an empty filter returns
6
+ * the whole trail (newest first). This is the typed read seam consumers use to read events by actor,
7
+ * action, time range, resource, outcome, severity, origin, and tenant.
8
+ *
9
+ * `tenant` is the only field where `null` is a value rather than an absence — see its own doc. Every
10
+ * other field is "match this or don't filter".
11
+ *
12
+ * It is a Kysely query first: `src/http/routes.ts` is the control-plane surface over it, and it is
13
+ * this package's own contribution behind `requireControlPlane(scope)` rather than something core
14
+ * reaches in and adds. `actorType: "control-plane"` is what separates a management client's actions
15
+ * from the adopter's own users', which is the question that surface is actually asked.
16
+ */
17
+ export interface AuditQuery {
18
+ /** Match the acting principal's kind. */
19
+ actorType?: AuditActorType;
20
+ /** Match the acting principal's id. */
21
+ actorId?: string;
22
+ /** Match an exact `domain/reason` action code. */
23
+ action?: string;
24
+ /** Match the outcome (`success` | `failure` | `denied`). */
25
+ outcome?: AuditOutcome;
26
+ /** Match the severity (`info` | `warning` | `critical`). */
27
+ severity?: AuditSeverity;
28
+ /** Match the targeted resource's type. */
29
+ resourceType?: string;
30
+ /** Match the targeted resource's id. */
31
+ resourceId?: string;
32
+ /** Match the project the event was recorded in. */
33
+ project?: string;
34
+ /** Match the environment the recording Worker served. */
35
+ environment?: string;
36
+ /** Match the recording Worker's `apps/<name>` directory name. */
37
+ worker?: string;
38
+ /**
39
+ * Match the tenant the action was taken for — the read this column exists to serve, usually with a
40
+ * time range.
41
+ *
42
+ * **`null` is a filter, not an absence.** Omitted (`undefined`) means "do not filter by tenant";
43
+ * `null` means "the events that belong to no tenant" — a CLI-originated action, a fleet-wide operator
44
+ * action, a row recorded before the column existed. Both are questions an adopter genuinely asks, and
45
+ * the second one is why this is `string | null` rather than `string`: without it, asking it means
46
+ * writing SQL against this capability's own table.
47
+ */
48
+ tenant?: string | null;
49
+ /** Inclusive lower bound on `occurredAt`. */
50
+ from?: Date;
51
+ /** Inclusive upper bound on `occurredAt`. */
52
+ to?: Date;
53
+ /**
54
+ * Cap the number of rows returned. {@link queryAuditEvents} uses it verbatim; {@link pageAuditEvents}
55
+ * clamps it into `[1, MAX_PAGE_SIZE]`, because that one answers a caller over HTTP.
56
+ */
57
+ limit?: number;
58
+ /**
59
+ * Where to resume, from the previous page's `nextCursor`. Read only by {@link pageAuditEvents}, and
60
+ * opaque — a malformed one is a first page, never an error (see `@pithy-sh/core/src/data/cursor`).
61
+ */
62
+ cursor?: string;
63
+ }
64
+ /**
65
+ * One page of the trail, and where the next one starts.
66
+ *
67
+ * `nextCursor` is null at the end of the list, and knowing that costs no `COUNT` — the query
68
+ * over-fetches by one row and {@link toPage} drops it. On the largest table in most projects, a count
69
+ * query per page is the difference between a page load and a table scan.
70
+ */
71
+ export interface AuditEventPage {
72
+ /** The page, newest first. */
73
+ events: AuditEventRow[];
74
+ /** Where the next page starts, or null at the end of the trail. */
75
+ nextCursor: string | null;
76
+ }
77
+ /**
78
+ * Read audit events matching `filter`, newest first (`occurredAt` then `id`, both descending). Each
79
+ * row is decoded back through {@link AuditEventRow} — dates become `Date`s, `metadata` a parsed and
80
+ * validated object — so callers get the app shape, never raw SQLite columns.
81
+ */
82
+ export declare function queryAuditEvents(db: AuditDatabase, filter?: AuditQuery): Promise<AuditEventRow[]>;
83
+ /**
84
+ * One page of the trail, resumable — the read the control-plane route serves.
85
+ *
86
+ * **Keyset, never offset.** The audit table is appended to constantly while somebody is reading it, so
87
+ * with `OFFSET` every event recorded during a read pushes one row from the page a client already has
88
+ * onto the page it is about to fetch: it sees that row twice, and any row that fell off the far end it
89
+ * never sees at all. On a security trail, "you may silently miss a record while paging" is not a
90
+ * usability defect. The cursor names the last row's exact position instead, so the next page starts
91
+ * where the previous ended whatever was written in between.
92
+ */
93
+ export declare function pageAuditEvents(db: AuditDatabase, filter?: AuditQuery): Promise<AuditEventPage>;
94
+ /**
95
+ * Read one event by its `eventId`, or null when there is none.
96
+ *
97
+ * Addressed by `eventId` — the recorder's UUID idempotency key, uniquely indexed — and never by the
98
+ * autoincrement `id`. `id` is a surrogate that leaks how many events a project has recorded and is
99
+ * guessable by counting; `eventId` is neither, and it is the value the trail's own idempotency
100
+ * guarantee is written against.
101
+ */
102
+ export declare function readAuditEvent(db: AuditDatabase, eventId: string): Promise<AuditEventRow | null>;
103
+ //# sourceMappingURL=query.d.ts.map
@@ -0,0 +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;AAGvG,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,kDAAkD;IAClD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,4DAA4D;IAC5D,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,aAAa,CAAC;IACzB,0CAA0C;IAC1C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,wCAAwC;IACxC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yDAAyD;IACzD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iEAAiE;IACjE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;;;;;OASG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,6CAA6C;IAC7C,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,6CAA6C;IAC7C,EAAE,CAAC,EAAE,IAAI,CAAC;IACV;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B,8BAA8B;IAC9B,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,mEAAmE;IACnE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAwDD;;;;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"}