Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
# `@suaveplan/api-audit-stdout` — stdout audit sink
**Package**: `@suaveplan/api-audit-stdout`
**Status**: PROPOSED
**Type**: new-package
**Stage**: 8 — see umbrella `openspec/changes/api-plugin-foundation/`
## Why
Per design doc §12.5, every state-changing admin action AND every non-2xx response on an auth-required route produces an audit record with a fixed JSON shape (`ts`, `type`, `principal`, `tenant`, `request_id`, `trace_id`, `subject`, `outcome`, `cause`). The sink is pluggable via the `audit` capability. The default sink writes JSON-per-line to stdout because container runtimes redirect stdout anyway — operators wire it into their existing log pipeline without touching the host.
## What changes
- ADDED: `createStdoutAuditSink({ writer, hmacKey, clock })` — returns an `AuditSink` implementing the `audit` capability. Each `write(record)` emits a single JSON line to the supplied writer (default `process.stdout`). The line is HMAC-signed (HMAC-SHA-256 over canonical bytes) using `hmacKey` so tampering is detectable.
- ADDED: `AuditRecord` Zod schema — locks the wire shape from §12.5. Records that fail validation raise `AUDIT_STDOUT_INVALID_RECORD` and are NOT written.
- ADDED: Backpressure policy — the writer is async; the sink blocks the caller only up to `maxQueueMs` (default 100ms), then drops with `api.audit.dropped_total{sink="stdout"}` increment and a single warning log per minute. Drops are NEVER silent.
- ADDED: Error codes (`AUDIT_STDOUT_*`): `INVALID_RECORD`, `WRITER_FAILED`, `QUEUE_FULL`.
- ADDED: `api.audit.records_total{sink="stdout", type, outcome}` counter — one increment per successful write.
## Out of scope
- File-rotating sink (that's `api-audit-file`).
- Long-term audit storage (separate package).
- HMAC key management — caller supplies the key. Rotating it without losing replay capability is a host-level concern.
## Source mapping
Genesis-original. Source of design intent: `docs/superpowers/specs/2026-05-13-api-plugin-foundation-design.md`.
| Requirement | Design doc section |
|---|---|
| Audit record JSON shape (`ts`, `type`, `principal`, …) | §12.5 |
| Default sink is `api-audit-stdout` | §12.5 |
| HMAC-signed records | §12.5 |
| `audit` capability slot | §12.5 |
## Verification approach
- `src/sink/sink.test.ts` — writes valid records, asserts JSON-per-line output with HMAC suffix; invalid records raise `AUDIT_STDOUT_INVALID_RECORD`.
- `src/sink/sink.spec-conformance.test.ts` — drop policy increments `api.audit.dropped_total{sink="stdout"}` exactly once per dropped record AND emits the warning once per minute (asserted with `FakeClock`).
- `src/schema/schema.test.ts` — every required field present; every optional field accepted; unknown fields rejected (`exactOptionalPropertyTypes` parity).
- `src/hmac/hmac.test.ts` — canonical bytes are deterministic across runs; HMAC verifies with the same key; tampering flips one bit and the verification fails.
- `tests/dep-graph.test.ts` — runtime deps (`api-types`, `crypto-hash`, `error`, `logger`, `zod`).
## Migration impact
None — additive only. `api-host` registers this when `host.audit.sink = "stdout"` (the default).

View File

@@ -0,0 +1,83 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: api-audit-stdout (api-audit-stdout)
**Package**: `@suaveplan/api-audit-stdout`
**Status**: PROPOSED
> Every requirement below carries a `**Verified by:**` line at authoring time.
## ADDED Requirements
### Requirement: JSON-per-line writes with HMAC signature
The package SHALL write each audit record as a single JSON line to the supplied writer (default `process.stdout`). Each line MUST include an HMAC-SHA-256 signature computed over the canonical bytes of the record using the configured `hmacKey`.
#### Scenario: written line is JSON with signature
- WHEN `sink.write({ ts: "...", type: "request.error", ... })` is called
- THEN exactly one line is appended to the writer AND that line parses as JSON AND it contains a `_hmac` field whose value verifies against the canonical bytes
**Verified by:** `src/sink/sink.test.ts::"writes JSON-per-line with HMAC signature"`
---
### Requirement: Record shape validated by Zod
The package SHALL validate each record against `AuditRecord` Zod schema BEFORE writing. Invalid records raise `AUDIT_STDOUT_INVALID_RECORD` and MUST NOT be written.
#### Scenario: missing required field rejected
- WHEN a record is missing `request_id`
- THEN `write()` throws `AUDIT_STDOUT_INVALID_RECORD` AND no line is written
#### Scenario: unknown field rejected
- WHEN a record carries an unknown top-level field
- THEN `write()` throws `AUDIT_STDOUT_INVALID_RECORD`
**Verified by:** `src/schema/schema.test.ts::"missing request_id is rejected"` AND `src/schema/schema.test.ts::"unknown field is rejected"`
---
### Requirement: Backpressure drops are observable
The package SHALL block the caller up to `maxQueueMs` (default 100ms) and then drop the record with `api.audit.dropped_total{sink="stdout"}` increment AND a single warning log per minute. Drops MUST NEVER be silent.
#### Scenario: drop increments dropped_total
- WHEN the writer is paused such that the queue exceeds `maxQueueMs`
- THEN the record is dropped AND `api.audit.dropped_total{sink="stdout"}` increments by 1
#### Scenario: warning log throttled to once per minute
- WHEN 100 records are dropped within 30 seconds (with `FakeClock`)
- THEN at most one warning is logged in that minute window
**Verified by:** `src/sink/sink.spec-conformance.test.ts::"drop increments dropped_total"` AND `src/sink/sink.spec-conformance.test.ts::"warning log throttled to once per minute"`
---
### Requirement: Successful writes counted with labels
The package SHALL increment `api.audit.records_total{sink="stdout", type, outcome}` once per successful write.
#### Scenario: successful write increments counter
- WHEN a valid record is written
- THEN `api.audit.records_total{sink="stdout", type, outcome}` increments by exactly 1 with the record's `type` and `outcome` as labels
**Verified by:** `src/sink/sink.spec-conformance.test.ts::"successful write increments records_total with type and outcome labels"`
---
### Requirement: HMAC verification detects tampering
The package SHALL produce HMAC signatures such that any modification to the record's canonical bytes invalidates the signature on verification with the same key.
#### Scenario: tampering invalidates HMAC
- WHEN a written line's `outcome` is flipped from `success` to `failure` after signing
- THEN HMAC verification with the original key returns `false`
**Verified by:** `src/hmac/hmac.test.ts::"tampering invalidates HMAC"`

View File

@@ -0,0 +1,65 @@
# Tasks — `@suaveplan/api-audit-stdout`
## 0. Pre-flight (non-negotiable)
- [x] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [x] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [x] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Spec authoring
- [x] 1.1 Read design doc (§12.5)
- [x] 1.2 Read `openspec/AGENTS.md` Sections 13 and 14
- [x] 1.3 Draft `proposal.md`
- [x] 1.4 Draft `specs/api-audit-stdout/spec.md`
- [x] 1.5 Every requirement carries `**Verified by:**`
## 2. Implementation
- [x] 2.1 Scaffold `packages/api/api-audit-stdout/`
- [x] 2.2 `src/sink/` — `createStdoutAuditSink`, queue + backpressure
- [x] 2.3 `src/schema/` — `AuditRecord` Zod schema
- [x] 2.4 `src/hmac/` — canonical-bytes + HMAC-SHA-256 wrapper around `@suaveplan/crypto-hash`
- [x] 2.5 `src/error-codes.ts`
- [x] 2.6 `src/instruments/` — `api.audit.records_total`, `api.audit.dropped_total`
- [x] 2.7 `src/index.ts` — explicit named re-exports
## 3. Tests
- [x] 3.1 `src/sink/sink.test.ts`
- [x] 3.2 `src/sink/sink.spec-conformance.test.ts`
- [x] 3.3 `src/schema/schema.test.ts`
- [x] 3.4 `src/hmac/hmac.test.ts`
- [x] 3.5 `tests/dep-graph.test.ts`
- [x] 3.6 Every `it(...)` carries `{ timeout: 5000 }`
## 4. Documentation
- [x] 4.1 Sibling `.md` per implementation `.ts`
- [x] 4.2 `README.md` `## Modules`
- [x] 4.3 Update `CLAUDE.md` package listing
## 5. Pre-archive verification (the 5-gate triple)
- [x] 5.1 `bun run check`
- [x] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/api-audit-stdout`
- [x] 5.3 `bunx turbo test:coverage --filter=@suaveplan/api-audit-stdout` — 100/100/100/100
- [x] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/api-audit-stdout`
- [x] 5.5 `bunx turbo build --filter=@suaveplan/api-audit-stdout`
## 6. Pre-archive 7-row checklist
- [x] 6.1 Generics threaded; `expectTypeOf` on `AuditSink<Caps>`
- [x] 6.2 Zod schemas wired at every record-write boundary
- [x] 6.3 Every `AUDIT_STDOUT_*` code thrown by a production path
- [x] 6.4 Strict-mode: drops are observable, never silent
- [x] 6.5 OTel counters asserted with real `MeterProvider`
- [x] 6.6 Lifecycle dedup — sink `dispose()` is idempotent
- [x] 6.7 No retroactive tick
## 7. Archive
- [x] 7.1 Fold spec delta into `openspec/specs/api-audit-stdout/spec.md`
- [x] 7.2 Move folder to archive
- [x] 7.3 Tick `8.10` in umbrella tasks
- [x] 7.4 Refresh `MANIFEST.md`