@pithy-sh/audit 0.1.2 → 0.1.4

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 +43 -0
  2. package/dist/actions.d.ts.map +1 -0
  3. package/dist/actions.js +57 -0
  4. package/dist/capability.d.ts +42 -0
  5. package/dist/capability.d.ts.map +1 -0
  6. package/dist/capability.js +88 -0
  7. package/dist/cli/emitFromCLI.d.ts +37 -0
  8. package/dist/cli/emitFromCLI.d.ts.map +1 -0
  9. package/dist/cli/emitFromCLI.js +39 -0
  10. package/dist/cli/resolveActor.d.ts +76 -0
  11. package/dist/cli/resolveActor.d.ts.map +1 -0
  12. package/dist/cli/resolveActor.js +85 -0
  13. package/dist/data/auditEvent.d.ts +59 -0
  14. package/dist/data/auditEvent.d.ts.map +1 -0
  15. package/dist/data/auditEvent.js +48 -0
  16. package/dist/data/tables.d.ts +54 -0
  17. package/dist/data/tables.d.ts.map +1 -0
  18. package/dist/data/tables.js +17 -0
  19. package/dist/error/errors.d.ts +43 -0
  20. package/dist/error/errors.d.ts.map +1 -0
  21. package/dist/error/errors.js +32 -0
  22. package/dist/http/guards.d.ts +70 -0
  23. package/dist/http/guards.d.ts.map +1 -0
  24. package/dist/http/guards.js +82 -0
  25. package/dist/http/responses.d.ts +160 -0
  26. package/dist/http/responses.d.ts.map +1 -0
  27. package/dist/http/responses.js +73 -0
  28. package/dist/http/routes.d.ts +61 -0
  29. package/dist/http/routes.d.ts.map +1 -0
  30. package/dist/http/routes.js +127 -0
  31. package/dist/http/schemas.d.ts +47 -0
  32. package/dist/http/schemas.d.ts.map +1 -0
  33. package/dist/http/schemas.js +70 -0
  34. package/dist/http/views.d.ts +55 -0
  35. package/dist/http/views.d.ts.map +1 -0
  36. package/dist/http/views.js +81 -0
  37. package/dist/index.d.ts +18 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +12 -0
  40. package/dist/migrations/0001_init.d.ts +21 -0
  41. package/dist/migrations/0001_init.d.ts.map +1 -0
  42. package/dist/migrations/0001_init.js +47 -0
  43. package/dist/query.d.ts +105 -0
  44. package/dist/query.d.ts.map +1 -0
  45. package/dist/query.js +97 -0
  46. package/dist/recorder.d.ts +82 -0
  47. package/dist/recorder.d.ts.map +1 -0
  48. package/dist/recorder.js +66 -0
  49. package/dist/seeds/example.d.ts +18 -0
  50. package/dist/seeds/example.d.ts.map +1 -0
  51. package/dist/seeds/example.js +196 -0
  52. package/dist/version.generated.d.ts +7 -0
  53. package/dist/version.generated.d.ts.map +1 -0
  54. package/dist/version.generated.js +9 -0
  55. package/package.json +21 -10
  56. package/src/version.generated.ts +1 -1
@@ -0,0 +1,43 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ /**
4
+ * Author a capability's action constants. The taxonomy is **federated**: each capability owns and
5
+ * exports its own `domain/reason` action codes (`auth/login`, `entitlement/granted`) and adds them
6
+ * without touching core — the way migrations and table prefixes already federate per-capability.
7
+ *
8
+ * This validates every code against the shared {@link AuditAction} shape at author time, so a typo
9
+ * (a missing slash, an uppercase letter) fails loudly where the constant is declared rather than
10
+ * silently when an event is emitted. Returns the same object, typed, so call sites read
11
+ * `AuthAuditActions.login`:
12
+ *
13
+ * ```ts
14
+ * export const AuthAuditActions = defineAuditActions({
15
+ * login: "auth/login",
16
+ * tokenRefreshed: "auth/token_refreshed",
17
+ * });
18
+ * ```
19
+ */
20
+ export declare function defineAuditActions<const T extends Record<string, string>>(actions: T): T;
21
+ /**
22
+ * This capability's own action codes — the trail recording the reads of itself.
23
+ *
24
+ * **Reading an audit trail is a security-relevant action.** It is the record of who did what across
25
+ * every other capability, so a management client paging through it is doing something that has to be
26
+ * answerable later; a trail that records every write and no read cannot answer "who looked".
27
+ *
28
+ * They are separate codes rather than one, because the two reads disclose different things and a
29
+ * reviewer filtering the trail should not have to inspect metadata to tell them apart:
30
+ * `audit/trail_read` is a filtered page of structural fields, while `audit/event_read` is the full
31
+ * record of one event — the IP, the user-agent, and the capability metadata included.
32
+ *
33
+ * Yes, this appends to the table it just read. That is a loop by design, not by accident: the row it
34
+ * writes is one row, it is the only durable evidence the read happened, and the alternative is a
35
+ * surface that quietly exempts itself from the guarantee it exists to provide.
36
+ */
37
+ export declare const AuditTrailActions: {
38
+ /** A filtered page of the trail was read. */
39
+ readonly trailRead: "audit/trail_read";
40
+ /** One event was read in full, network identifiers and metadata included. */
41
+ readonly eventRead: "audit/event_read";
42
+ };
43
+ //# sourceMappingURL=actions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,CAYxF;AAED;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB;IAC5B,6CAA6C;;IAE7C,6EAA6E;;CAE7E,CAAC"}
@@ -0,0 +1,57 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { AuditInvalidEventError } from "./error/errors.js";
4
+ import { AuditAction } from "@pithy-sh/core/src/audit/auditEvent";
5
+ //#region src/actions.ts
6
+ /**
7
+ * Author a capability's action constants. The taxonomy is **federated**: each capability owns and
8
+ * exports its own `domain/reason` action codes (`auth/login`, `entitlement/granted`) and adds them
9
+ * without touching core — the way migrations and table prefixes already federate per-capability.
10
+ *
11
+ * This validates every code against the shared {@link AuditAction} shape at author time, so a typo
12
+ * (a missing slash, an uppercase letter) fails loudly where the constant is declared rather than
13
+ * silently when an event is emitted. Returns the same object, typed, so call sites read
14
+ * `AuthAuditActions.login`:
15
+ *
16
+ * ```ts
17
+ * export const AuthAuditActions = defineAuditActions({
18
+ * login: "auth/login",
19
+ * tokenRefreshed: "auth/token_refreshed",
20
+ * });
21
+ * ```
22
+ */
23
+ function defineAuditActions(actions) {
24
+ for (const [name, code] of Object.entries(actions)) {
25
+ const parsed = AuditAction.safeParse(code);
26
+ if (!parsed.success) throw new AuditInvalidEventError({
27
+ message: `Invalid audit action code for "${name}": ${code}`,
28
+ action: "Use a lowercase namespaced `domain/reason` code, e.g. `auth/login`.",
29
+ detail: parsed.error.message
30
+ });
31
+ }
32
+ return actions;
33
+ }
34
+ /**
35
+ * This capability's own action codes — the trail recording the reads of itself.
36
+ *
37
+ * **Reading an audit trail is a security-relevant action.** It is the record of who did what across
38
+ * every other capability, so a management client paging through it is doing something that has to be
39
+ * answerable later; a trail that records every write and no read cannot answer "who looked".
40
+ *
41
+ * They are separate codes rather than one, because the two reads disclose different things and a
42
+ * reviewer filtering the trail should not have to inspect metadata to tell them apart:
43
+ * `audit/trail_read` is a filtered page of structural fields, while `audit/event_read` is the full
44
+ * record of one event — the IP, the user-agent, and the capability metadata included.
45
+ *
46
+ * Yes, this appends to the table it just read. That is a loop by design, not by accident: the row it
47
+ * writes is one row, it is the only durable evidence the read happened, and the alternative is a
48
+ * surface that quietly exempts itself from the guarantee it exists to provide.
49
+ */
50
+ const AuditTrailActions = defineAuditActions({
51
+ /** A filtered page of the trail was read. */
52
+ trailRead: "audit/trail_read",
53
+ /** One event was read in full, network identifiers and metadata included. */
54
+ eventRead: "audit/event_read"
55
+ });
56
+ //#endregion
57
+ export { AuditTrailActions, defineAuditActions };
@@ -0,0 +1,42 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { type Capability } from "@pithy-sh/core/src/capability/capability";
4
+ import { z } from "zod";
5
+ /**
6
+ * Sort order of the audit migration within the audit database, relative to other capabilities
7
+ * (core low, app high). Unique per database; the migration registry composes the key
8
+ * `0250_audit_0001_init`.
9
+ */
10
+ export declare const AUDIT_MIGRATION_ORDER = 250;
11
+ /**
12
+ * Configuration for the audit capability, passed in `pithy.config.ts`. `database` names the D1
13
+ * **binding** the audit table lives in and writes go to, defaulting to `DB` (the shared app
14
+ * database). KV is deliberately not an option: an audit log is a query workload (by actor, action,
15
+ * time range, resource, outcome) and KV is get-by-key only.
16
+ *
17
+ * `basePath` is where the read-only control-plane routes mount. It is config rather than a constant
18
+ * for the reason every capability's is: an adopter may already own `/audit`, and the admin manifest
19
+ * reports whatever they chose, so a management client follows the move without either side
20
+ * coordinating.
21
+ */
22
+ export declare const AuditConfig: z.ZodObject<{
23
+ database: z.ZodDefault<z.ZodString>;
24
+ basePath: z.ZodDefault<z.ZodString>;
25
+ }, z.core.$strip>;
26
+ export type AuditConfig = z.output<typeof AuditConfig>;
27
+ export type AuditConfigInput = z.input<typeof AuditConfig>;
28
+ /** The audit capability, with its resolved binding attached for discovery. */
29
+ export interface AuditCapability extends Capability {
30
+ /** The D1 binding the audit table lives in (the resolved `database` config). */
31
+ auditDatabase: string;
32
+ }
33
+ /**
34
+ * The audit capability. It contributes the `pithy_audit_events` table to the configured D1 binding
35
+ * (default `DB`) and installs the request-context `emit()` recorder via middleware — replacing core's
36
+ * no-op with a synchronous, non-fatal D1 writer. Any capability then records a security-relevant
37
+ * action with `c.var.emit(...)` without importing this package (principle 4).
38
+ */
39
+ export declare function audit(config?: AuditConfigInput): AuditCapability;
40
+ /** Whether a capability is the audit capability — carries its resolved binding. */
41
+ export declare function isAuditCapability(capability: Capability): capability is AuditCapability;
42
+ //# sourceMappingURL=capability.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,UAAU,EAAoB,MAAM,0CAA0C,CAAC;AAE7F,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAUxB;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAWzC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW;;;iBAc8B,CAAC;AACvD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AACvD,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC;AAE3D,8EAA8E;AAC9E,MAAM,WAAW,eAAgB,SAAQ,UAAU;IACjD,gFAAgF;IAChF,aAAa,EAAE,MAAM,CAAC;CACvB;AAED;;;;;GAKG;AACH,wBAAgB,KAAK,CAAC,MAAM,GAAE,gBAAqB,GAAG,eAAe,CAyDpE;AAED,mFAAmF;AACnF,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,eAAe,CAEvF"}
@@ -0,0 +1,88 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { auditTables } from "./data/tables.js";
4
+ import { auditAdminRoutes } from "./http/guards.js";
5
+ import { registerAuditRoutes } from "./http/routes.js";
6
+ import { audit_0001_init } from "./migrations/0001_init.js";
7
+ import { recordAuditEvent } from "./recorder.js";
8
+ import { auditExampleSeed } from "./seeds/example.js";
9
+ import { PACKAGE_VERSION } from "./version.generated.js";
10
+ import { defineCapability } from "@pithy-sh/core/src/capability/capability";
11
+ import { workerIdentity } from "@pithy-sh/core/src/worker/identity";
12
+ import { z } from "zod";
13
+ //#region src/capability.ts
14
+ /**
15
+ * Sort order of the audit migration within the audit database, relative to other capabilities
16
+ * (core low, app high). Unique per database; the migration registry composes the key
17
+ * `0250_audit_0001_init`.
18
+ */
19
+ const AUDIT_MIGRATION_ORDER = 250;
20
+ /**
21
+ * The registry name the audit table joins. The store of record is D1, shared with the primary app
22
+ * database (`app`, the `DB` binding) by default — so the audit migration tracks alongside the app's
23
+ * in one `pithy_migrations` table rather than fighting it on a second provider over the same binding.
24
+ * The physical binding is config-selectable; this registry key is the coordination point capabilities
25
+ * use to share one database (CLAUDE.md §Data layer; isolating audit into its own D1 is a later issue).
26
+ */
27
+ const AUDIT_DATABASE_NAME = "app";
28
+ /**
29
+ * Configuration for the audit capability, passed in `pithy.config.ts`. `database` names the D1
30
+ * **binding** the audit table lives in and writes go to, defaulting to `DB` (the shared app
31
+ * database). KV is deliberately not an option: an audit log is a query workload (by actor, action,
32
+ * time range, resource, outcome) and KV is get-by-key only.
33
+ *
34
+ * `basePath` is where the read-only control-plane routes mount. It is config rather than a constant
35
+ * for the reason every capability's is: an adopter may already own `/audit`, and the admin manifest
36
+ * reports whatever they chose, so a management client follows the move without either side
37
+ * coordinating.
38
+ */
39
+ const AuditConfig = z.object({
40
+ database: z.string().default("DB").describe("The D1 binding the audit table and its migrations target. Defaults to `DB`, the shared app database."),
41
+ basePath: z.string().startsWith("/").default("/audit").describe("Where the control-plane routes that read the trail mount. Reads only — the trail is append-only and this surface never writes.")
42
+ }).describe("Configuration for the audit capability.");
43
+ /**
44
+ * The audit capability. It contributes the `pithy_audit_events` table to the configured D1 binding
45
+ * (default `DB`) and installs the request-context `emit()` recorder via middleware — replacing core's
46
+ * no-op with a synchronous, non-fatal D1 writer. Any capability then records a security-relevant
47
+ * action with `c.var.emit(...)` without importing this package (principle 4).
48
+ */
49
+ function audit(config = {}) {
50
+ const resolved = AuditConfig.parse(config);
51
+ const capability = defineCapability({
52
+ name: "audit",
53
+ version: PACKAGE_VERSION,
54
+ config: AuditConfig,
55
+ requiredBindings: [{
56
+ type: "d1",
57
+ name: resolved.database
58
+ }],
59
+ databases: { [AUDIT_DATABASE_NAME]: {
60
+ binding: resolved.database,
61
+ tables: auditTables,
62
+ migrationOrder: 250,
63
+ migrations: { "0001_init": audit_0001_init }
64
+ } },
65
+ seeds: [auditExampleSeed],
66
+ adminRoutes: auditAdminRoutes(resolved.basePath),
67
+ routes: registerAuditRoutes({
68
+ basePath: resolved.basePath,
69
+ database: (c) => c.var.db[AUDIT_DATABASE_NAME]
70
+ }),
71
+ middleware: [(app) => {
72
+ app.use("*", async (c, next) => {
73
+ c.set("emit", (event) => recordAuditEvent(c.var.db[AUDIT_DATABASE_NAME], event, {
74
+ origin: workerIdentity(c.env),
75
+ onError: (error) => c.var.log.child("audit").error("audit event dropped", { error })
76
+ }));
77
+ await next();
78
+ });
79
+ }]
80
+ });
81
+ return Object.assign(capability, { auditDatabase: resolved.database });
82
+ }
83
+ /** Whether a capability is the audit capability — carries its resolved binding. */
84
+ function isAuditCapability(capability) {
85
+ return capability.name === "audit" && "auditDatabase" in capability;
86
+ }
87
+ //#endregion
88
+ export { AUDIT_MIGRATION_ORDER, AuditConfig, audit, isAuditCapability };
@@ -0,0 +1,37 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
5
+ import { type AuditRecorderOptions } from "../recorder";
6
+ import type { ResolvedActor } from "./resolveActor";
7
+ /**
8
+ * The event an `emitFromCLI` caller supplies — every audit field except the actor, which comes from
9
+ * {@link ResolvedActor} (resolved from the CF token, not the caller). The CLI describes *what*
10
+ * happened; the resolver decides *who*.
11
+ *
12
+ * Plus `environment`, which the CLI alone may state per event. In a Worker the origin is read from
13
+ * `env` and an emitter can never touch it — there the emitter is a request handler and the whole point
14
+ * is that it cannot lie. A CLI command is not that: it *is* the trusted process, there is no untrusted
15
+ * caller in it, and one invocation legitimately acts on several environments — `pithy storage provision`
16
+ * loops every managed environment in a single run. Nothing else knows which one a given event belongs
17
+ * to, so the event carries it.
18
+ */
19
+ export type CliAuditEvent = Omit<AuditEventInput, "actorType" | "actorId"> & {
20
+ /**
21
+ * The environment this one event acted on. Overrides the emitter's configured origin environment;
22
+ * omitted, the configured one stands.
23
+ */
24
+ environment?: string | null;
25
+ };
26
+ /**
27
+ * Record an audit event from a Node/Bun context — the second emit path, for CLI-originated actions
28
+ * (`pithy migrate`, `pithy deploy`, `pithy secrets set`). The CLI can't use a D1 binding, so it
29
+ * writes over the REST API: `d1` is a `CloudflareD1Manager` from `@pithy-sh/cloudflare` (which
30
+ * implements `D1Database`), and the same Kysely/codec path the in-Worker recorder uses runs against
31
+ * it. The {@link ResolvedActor} is merged in, with its correlation metadata under the caller's own.
32
+ *
33
+ * Like the in-Worker recorder, this is **non-fatal**: a write failure is logged, never thrown, so an
34
+ * audit write never breaks the command it records.
35
+ */
36
+ export declare function emitFromCLI(d1: D1Database, event: CliAuditEvent, actor: ResolvedActor, options?: AuditRecorderOptions): Promise<void>;
37
+ //# sourceMappingURL=emitFromCLI.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emitFromCLI.d.ts","sourceRoot":"","sources":["../../src/cli/emitFromCLI.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAE3E,OAAO,EAAE,KAAK,oBAAoB,EAAoB,MAAM,aAAa,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,EAAE,WAAW,GAAG,SAAS,CAAC,GAAG;IAC3E;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,WAAW,CAC/B,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,aAAa,EACpB,KAAK,EAAE,aAAa,EACpB,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAqBf"}
@@ -0,0 +1,39 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { auditDatabase } from "../data/tables.js";
4
+ import { recordAuditEvent } from "../recorder.js";
5
+ //#region src/cli/emitFromCLI.ts
6
+ /**
7
+ * Record an audit event from a Node/Bun context — the second emit path, for CLI-originated actions
8
+ * (`pithy migrate`, `pithy deploy`, `pithy secrets set`). The CLI can't use a D1 binding, so it
9
+ * writes over the REST API: `d1` is a `CloudflareD1Manager` from `@pithy-sh/cloudflare` (which
10
+ * implements `D1Database`), and the same Kysely/codec path the in-Worker recorder uses runs against
11
+ * it. The {@link ResolvedActor} is merged in, with its correlation metadata under the caller's own.
12
+ *
13
+ * Like the in-Worker recorder, this is **non-fatal**: a write failure is logged, never thrown, so an
14
+ * audit write never breaks the command it records.
15
+ */
16
+ async function emitFromCLI(d1, event, actor, options) {
17
+ const { environment, ...rest } = event;
18
+ const merged = {
19
+ ...rest,
20
+ actorType: actor.actorType,
21
+ actorId: actor.actorId,
22
+ metadata: {
23
+ ...actor.metadata,
24
+ ...event.metadata ?? {}
25
+ }
26
+ };
27
+ const origin = environment === void 0 ? options?.origin : {
28
+ project: options?.origin?.project ?? null,
29
+ environment,
30
+ worker: options?.origin?.worker ?? null,
31
+ version: options?.origin?.version ?? null
32
+ };
33
+ await recordAuditEvent(auditDatabase(d1), merged, {
34
+ ...options,
35
+ ...origin ? { origin } : {}
36
+ });
37
+ }
38
+ //#endregion
39
+ export { emitFromCLI };
@@ -0,0 +1,76 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import type { AuditActorType, AuditMetadata } from "@pithy-sh/core/src/audit/auditEvent";
4
+ /** The user-scoped slice: who is behind a `cfut_*` token. `clients.user()` satisfies it. */
5
+ export interface CfUserActorSource {
6
+ /** The Cloudflare user behind a user token (`GET /user`). */
7
+ getUser(): Promise<{
8
+ id?: string;
9
+ email?: string;
10
+ }>;
11
+ }
12
+ /** The account-scoped slice: which credential a `cfat_*` token is. `clients.accountTokens()` satisfies it. */
13
+ export interface CfAccountTokenActorSource {
14
+ /** Verify the calling token against the account, returning its id + status (`GET /accounts/{id}/tokens/verify`). */
15
+ verifyToken(): Promise<{
16
+ id: string;
17
+ status: string;
18
+ }>;
19
+ /** The token's name by id, or `null` when the caller may not read it (`GET /accounts/{id}/tokens/{id}`). */
20
+ getTokenName(tokenId: string): Promise<string | null>;
21
+ }
22
+ /**
23
+ * The slices of `@pithy-sh/cloudflare` actor resolution needs — declared structurally so the resolver
24
+ * is unit-testable with a fake and the audit package never hard-depends on the concrete managers.
25
+ * `{ user: clients.user(), accountTokens: clients.accountTokens() }` satisfies it.
26
+ *
27
+ * **Two scopes, not one, because a token is valid in exactly one of them.** An account-owned
28
+ * (`cfat_*`) token — the kind CLAUDE.md prefers and `pithy token mint` produces — answers
29
+ * `Invalid API Token` at every `/user/*` endpoint. A single flat source made the wrong scope
30
+ * reachable from the account path, and since resolution failure is never fatal, the whole preferred
31
+ * setup silently attributed to `system`. Split, the account path cannot reach a user endpoint at all.
32
+ */
33
+ export interface CfActorSource {
34
+ /** User-scoped reads, for a `cfut_*` token. */
35
+ user: CfUserActorSource;
36
+ /** Account-scoped reads, for a `cfat_*` token. */
37
+ accountTokens: CfAccountTokenActorSource;
38
+ }
39
+ /** A resolved CLI actor: who to attribute a control-plane audit event to, plus correlation metadata. */
40
+ export interface ResolvedActor {
41
+ /** The kind of principal. */
42
+ actorType: AuditActorType;
43
+ /** The principal's id (a user email, a token name), or null when unresolved. */
44
+ actorId: string | null;
45
+ /** Correlation detail for the event's `metadata` — never the raw token value. */
46
+ metadata: AuditMetadata;
47
+ }
48
+ /**
49
+ * Resolve the actor behind a CF API token from its **prefix** — the only part read, never the value:
50
+ *
51
+ * - `cfut_*` (user token) → a human developer. Resolve the user's email via `GET /user`; the CF user
52
+ * id rides in `metadata` for stable cross-reference. `actorType: "user"`, `actorId: <email>`.
53
+ * - `cfat_*` (account token) → a service account or CI pipeline. Verify the token **against the
54
+ * account**, then read its name; `actorType: "service"`, `actorId: <token-name>` (the token id is
55
+ * the fallback and rides in `metadata`).
56
+ *
57
+ * The name is best-effort by design. Reading a token record needs `API Tokens Read`, which the
58
+ * least-privilege tokens `pithy token mint` produces deliberately do not carry, so the account source
59
+ * answers `null` there and `actorId` falls back to the token id — which verify always yields, for any
60
+ * account token, with no permission at all. Attribution stays on the credential either way — once
61
+ * verify has named it, nothing about a decorative label may take that back — so a name read that
62
+ * *fails* rather than declining takes the same fallback, and records why in `metadata.cfTokenNameError`
63
+ * instead of vanishing. Widening the mint permission set to make the name readable would trade least
64
+ * privilege for a label.
65
+ *
66
+ * Resolution failure — a bad token, a network error, an unrecognized prefix — is **never fatal**: it
67
+ * returns a `system` actor with a `metadata` note, so the event is still written, just unattributed.
68
+ */
69
+ export declare function resolveActor(apiToken: string, source: CfActorSource): Promise<ResolvedActor>;
70
+ /**
71
+ * A resolver that runs {@link resolveActor} **once** and caches the result for the lifetime of a CLI
72
+ * command — actor identity is resolved at session start, not per event. Memoizes the in-flight
73
+ * promise so concurrent emits share the single resolution.
74
+ */
75
+ export declare function createCachedActorResolver(apiToken: string, source: CfActorSource): () => Promise<ResolvedActor>;
76
+ //# sourceMappingURL=resolveActor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveActor.d.ts","sourceRoot":"","sources":["../../src/cli/resolveActor.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAGzF,4FAA4F;AAC5F,MAAM,WAAW,iBAAiB;IAChC,6DAA6D;IAC7D,OAAO,IAAI,OAAO,CAAC;QAAE,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACrD;AAED,8GAA8G;AAC9G,MAAM,WAAW,yBAAyB;IACxC,oHAAoH;IACpH,WAAW,IAAI,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACvD,4GAA4G;IAC5G,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;CACvD;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,aAAa;IAC5B,+CAA+C;IAC/C,IAAI,EAAE,iBAAiB,CAAC;IACxB,kDAAkD;IAClD,aAAa,EAAE,yBAAyB,CAAC;CAC1C;AAED,wGAAwG;AACxG,MAAM,WAAW,aAAa;IAC5B,6BAA6B;IAC7B,SAAS,EAAE,cAAc,CAAC;IAC1B,gFAAgF;IAChF,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,iFAAiF;IACjF,QAAQ,EAAE,aAAa,CAAC;CACzB;AAOD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAsClG;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,GAAG,MAAM,OAAO,CAAC,aAAa,CAAC,CAM/G"}
@@ -0,0 +1,85 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { messageOf } from "@pithy-sh/core/src/error/pithyError";
4
+ //#region src/cli/resolveActor.ts
5
+ /** The fallback actor when resolution can't attribute the action: `system`, with a note (never fatal). */
6
+ function systemActor(note) {
7
+ return {
8
+ actorType: "system",
9
+ actorId: null,
10
+ metadata: {
11
+ actorResolutionFailed: true,
12
+ note
13
+ }
14
+ };
15
+ }
16
+ /**
17
+ * Resolve the actor behind a CF API token from its **prefix** — the only part read, never the value:
18
+ *
19
+ * - `cfut_*` (user token) → a human developer. Resolve the user's email via `GET /user`; the CF user
20
+ * id rides in `metadata` for stable cross-reference. `actorType: "user"`, `actorId: <email>`.
21
+ * - `cfat_*` (account token) → a service account or CI pipeline. Verify the token **against the
22
+ * account**, then read its name; `actorType: "service"`, `actorId: <token-name>` (the token id is
23
+ * the fallback and rides in `metadata`).
24
+ *
25
+ * The name is best-effort by design. Reading a token record needs `API Tokens Read`, which the
26
+ * least-privilege tokens `pithy token mint` produces deliberately do not carry, so the account source
27
+ * answers `null` there and `actorId` falls back to the token id — which verify always yields, for any
28
+ * account token, with no permission at all. Attribution stays on the credential either way — once
29
+ * verify has named it, nothing about a decorative label may take that back — so a name read that
30
+ * *fails* rather than declining takes the same fallback, and records why in `metadata.cfTokenNameError`
31
+ * instead of vanishing. Widening the mint permission set to make the name readable would trade least
32
+ * privilege for a label.
33
+ *
34
+ * Resolution failure — a bad token, a network error, an unrecognized prefix — is **never fatal**: it
35
+ * returns a `system` actor with a `metadata` note, so the event is still written, just unattributed.
36
+ */
37
+ async function resolveActor(apiToken, source) {
38
+ try {
39
+ if (apiToken.startsWith("cfut_")) {
40
+ const user = await source.user.getUser();
41
+ return {
42
+ actorType: "user",
43
+ actorId: user.email ?? user.id ?? null,
44
+ metadata: {
45
+ cfTokenType: "user",
46
+ cfUserId: user.id ?? null
47
+ }
48
+ };
49
+ }
50
+ if (apiToken.startsWith("cfat_")) {
51
+ const verification = await source.accountTokens.verifyToken();
52
+ let nameError;
53
+ return {
54
+ actorType: "service",
55
+ actorId: await source.accountTokens.getTokenName(verification.id).catch((error) => {
56
+ nameError = messageOf(error);
57
+ return null;
58
+ }) ?? verification.id,
59
+ metadata: {
60
+ cfTokenType: "account",
61
+ cfTokenId: verification.id,
62
+ cfTokenStatus: verification.status,
63
+ ...nameError === void 0 ? {} : { cfTokenNameError: nameError }
64
+ }
65
+ };
66
+ }
67
+ return systemActor("Unrecognized Cloudflare API token prefix; expected `cfut_` or `cfat_`.");
68
+ } catch (error) {
69
+ return systemActor(`Cloudflare actor resolution failed: ${messageOf(error)}`);
70
+ }
71
+ }
72
+ /**
73
+ * A resolver that runs {@link resolveActor} **once** and caches the result for the lifetime of a CLI
74
+ * command — actor identity is resolved at session start, not per event. Memoizes the in-flight
75
+ * promise so concurrent emits share the single resolution.
76
+ */
77
+ function createCachedActorResolver(apiToken, source) {
78
+ let cached;
79
+ return () => {
80
+ cached ??= resolveActor(apiToken, source);
81
+ return cached;
82
+ };
83
+ }
84
+ //#endregion
85
+ export { createCachedActorResolver, resolveActor };
@@ -0,0 +1,59 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * The `pithy_audit_events` table — one row per recorded security-relevant action. One Zod object is
6
+ * the whole table definition: `z.output` is the app shape (a `Date` for `occurredAt`, a decoded
7
+ * object for `metadata`), `z.input` is the SQLite row shape (ms-epoch numbers, JSON strings), and
8
+ * every JS↔SQLite conversion goes through a codec. The taxonomy enums and the `action` validator are
9
+ * core's (`@pithy-sh/core/src/audit/auditEvent`) — the seam every emitter writes to; this table is
10
+ * how `@pithy-sh/audit` persists it.
11
+ *
12
+ * The `pithy_audit_` prefix (CamelCasePlugin snake-cases `pithyAuditEvents` → `pithy_audit_events`)
13
+ * keeps the table from clashing with an adopter's own (principle 1). `id` is an autoincrement
14
+ * surrogate giving natural event ordering; it is internal and never exposed over HTTP.
15
+ */
16
+ /**
17
+ * The `metadata` column codec — the JSON ↔ object conversion, Zod-validated against {@link AuditMetadata}
18
+ * on both sides. Exported so the recorder encodes the column through the same codec it is read back
19
+ * with, rather than hand-rolling `JSON.stringify` (CLAUDE.md §Data layer).
20
+ */
21
+ export declare const AuditMetadataColumn: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>, z.ZodRecord<z.ZodString, z.ZodUnknown>>;
22
+ export declare const AuditEventRow: z.ZodObject<{
23
+ id: z.ZodNumber;
24
+ eventId: z.ZodString;
25
+ occurredAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
26
+ action: z.ZodString;
27
+ outcome: z.ZodEnum<{
28
+ denied: "denied";
29
+ failure: "failure";
30
+ success: "success";
31
+ }>;
32
+ severity: z.ZodEnum<{
33
+ critical: "critical";
34
+ info: "info";
35
+ warning: "warning";
36
+ }>;
37
+ actorType: z.ZodEnum<{
38
+ anonymous: "anonymous";
39
+ "control-plane": "control-plane";
40
+ service: "service";
41
+ system: "system";
42
+ user: "user";
43
+ }>;
44
+ actorId: z.ZodNullable<z.ZodString>;
45
+ sessionId: z.ZodNullable<z.ZodString>;
46
+ resourceType: z.ZodNullable<z.ZodString>;
47
+ resourceId: z.ZodNullable<z.ZodString>;
48
+ ip: z.ZodNullable<z.ZodString>;
49
+ userAgent: z.ZodNullable<z.ZodString>;
50
+ requestId: z.ZodNullable<z.ZodString>;
51
+ metadata: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodUnknown>]>, z.ZodRecord<z.ZodString, z.ZodUnknown>>>;
52
+ project: z.ZodNullable<z.ZodString>;
53
+ environment: z.ZodNullable<z.ZodString>;
54
+ worker: z.ZodNullable<z.ZodString>;
55
+ version: z.ZodNullable<z.ZodString>;
56
+ tenant: z.ZodNullable<z.ZodString>;
57
+ }, z.core.$strip>;
58
+ export type AuditEventRow = z.output<typeof AuditEventRow>;
59
+ //# sourceMappingURL=auditEvent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auditEvent.d.ts","sourceRoot":"","sources":["../../src/data/auditEvent.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;GAWG;AACH;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,gIAA4B,CAAC;AAE7D,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkF2F,CAAC;AACtH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC"}
@@ -0,0 +1,48 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: FSL-1.1-MIT
3
+ import { AuditAction, AuditActorType, AuditMetadata, AuditOutcome, AuditSeverity } from "@pithy-sh/core/src/audit/auditEvent";
4
+ import { z } from "zod";
5
+ import { SQLiteDate, sqliteJson } from "@pithy-sh/core/src/data/codecs";
6
+ //#region src/data/auditEvent.ts
7
+ /**
8
+ * The `pithy_audit_events` table — one row per recorded security-relevant action. One Zod object is
9
+ * the whole table definition: `z.output` is the app shape (a `Date` for `occurredAt`, a decoded
10
+ * object for `metadata`), `z.input` is the SQLite row shape (ms-epoch numbers, JSON strings), and
11
+ * every JS↔SQLite conversion goes through a codec. The taxonomy enums and the `action` validator are
12
+ * core's (`@pithy-sh/core/src/audit/auditEvent`) — the seam every emitter writes to; this table is
13
+ * how `@pithy-sh/audit` persists it.
14
+ *
15
+ * The `pithy_audit_` prefix (CamelCasePlugin snake-cases `pithyAuditEvents` → `pithy_audit_events`)
16
+ * keeps the table from clashing with an adopter's own (principle 1). `id` is an autoincrement
17
+ * surrogate giving natural event ordering; it is internal and never exposed over HTTP.
18
+ */
19
+ /**
20
+ * The `metadata` column codec — the JSON ↔ object conversion, Zod-validated against {@link AuditMetadata}
21
+ * on both sides. Exported so the recorder encodes the column through the same codec it is read back
22
+ * with, rather than hand-rolling `JSON.stringify` (CLAUDE.md §Data layer).
23
+ */
24
+ const AuditMetadataColumn = sqliteJson(AuditMetadata);
25
+ const AuditEventRow = z.object({
26
+ id: z.number().int().describe("Autoincrement surrogate primary key. Monotonic, so it gives natural event ordering; internal, never exposed."),
27
+ eventId: z.string().describe("Client-generated unique idempotency key (a UUID), set by the recorder before the insert and held stable across `withD1Retry` attempts. The unique index turns a retry after a post-commit transport hiccup into a no-op (the guard fires) instead of a duplicate row."),
28
+ occurredAt: SQLiteDate.describe("When the action occurred. Ms-epoch in SQLite, a `Date` in app code; indexed for time-range queries."),
29
+ action: AuditAction.describe("What happened, as a namespaced `domain/reason` action code; indexed for per-action queries."),
30
+ outcome: AuditOutcome.describe("Whether the action succeeded, failed, or was denied."),
31
+ severity: AuditSeverity.describe("How serious the event is, orthogonal to outcome; drives dashboard filtering and alerting."),
32
+ actorType: AuditActorType.describe("The kind of principal that acted."),
33
+ actorId: z.string().nullable().describe("The acting principal's stable id (user id, service/token name); null for `system`/`anonymous`. Indexed."),
34
+ sessionId: z.string().nullable().describe("The session this action belongs to, tying a chain of actions together; null when none."),
35
+ resourceType: z.string().nullable().describe("The type of resource the action targeted (e.g. `user`, `secret`); null when not resource-scoped."),
36
+ resourceId: z.string().nullable().describe("The id of the resource the action targeted; null when not resource-scoped."),
37
+ ip: z.string().nullable().describe("The client IP the request came from, for correlation; null when unknown."),
38
+ userAgent: z.string().nullable().describe("The client user-agent string, for correlation; null when unknown."),
39
+ requestId: z.string().nullable().describe("The request correlation id, tying this event to one request/trace; null when unknown."),
40
+ metadata: AuditMetadataColumn.nullable().describe("Capability-specific structured detail as a JSON column, Zod-validated on write and read; null when there is none."),
41
+ project: z.string().nullable().describe("The project this event was recorded in, stamped by the recorder from the Worker's `PROJECT` var — never by the emitter, so it cannot be forged or omitted. Null on rows written before this column existed, and on a Worker carrying no `PROJECT` var."),
42
+ environment: z.string().nullable().describe("The environment the recording Worker serves (`dev` | `staging` | `prod`), stamped by the recorder from the `ENVIRONMENT` var. Null on rows written before this column existed. Recorded on the row rather than inferred from the database, because an exported or aggregated trail no longer knows which database it came from."),
43
+ worker: z.string().nullable().describe("The `apps/<name>` directory name of the Worker that recorded the event, stamped from the `WORKER` var; null for a CLI-originated action, which came from no Worker. Two Workers in one project share a database when they declare the same binding, so this is the only column that separates their events."),
44
+ version: z.string().nullable().describe("The Cloudflare version id of the build that recorded the event, stamped by the recorder from the `CF_VERSION_METADATA` binding. Null for a CLI-originated action, for a Worker that does not declare the binding, and on rows written before this column existed. It is what turns \"this was revoked\" into \"this was revoked, by this subject, against this exact build\"."),
45
+ tenant: z.string().nullable().describe("Whose action it was — the id of the tenant it was taken *for*, indexed with `occurredAt` for the (tenant, time) read this column exists to serve. **Supplied by the emitter, not stamped by the recorder** — the opposite of the four columns above it, and deliberately: `project`, `environment` and `worker` are properties of the writer, constant across every row a multi-tenant Worker writes, and no Worker var can know which customer an action belonged to. So this one is exactly as trustworthy as the call site that sets it, and it cannot be defaulted or verified here. Null means *not tenant-scoped* — a single-tenant app, a CLI-originated action, a fleet-wide operator action — and on rows written before this column existed. Never derived from a membership table afterwards: the tenant of an action is a fact at the time of the action, membership is a fact now.")
46
+ }).describe("One audit event in `pithy_audit_events` — the durable, queryable record of a security-relevant action.");
47
+ //#endregion
48
+ export { AuditEventRow, AuditMetadataColumn };