@wtfalch/keys 0.4.2 → 0.6.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 (42) hide show
  1. package/README.md +143 -5
  2. package/dist/bin/copy.d.ts +8 -4
  3. package/dist/bin/copy.js +8 -4
  4. package/dist/bin/migrations.js +21 -7
  5. package/dist/held/schema.js +1 -1
  6. package/dist/held/seal.d.ts +22 -0
  7. package/dist/held/seal.js +48 -0
  8. package/dist/held/shred.d.ts +1 -1
  9. package/dist/held/shred.js +1 -1
  10. package/dist/host/audit-endpoint.d.ts +15 -0
  11. package/dist/host/audit-endpoint.js +117 -0
  12. package/dist/host/events.d.ts +26 -0
  13. package/dist/host/events.js +31 -0
  14. package/dist/host/index.d.ts +11 -0
  15. package/dist/host/index.js +11 -0
  16. package/dist/host/schema.d.ts +153 -0
  17. package/dist/host/schema.js +20 -0
  18. package/dist/issued/index.js +2 -2
  19. package/dist/issued/ratelimit.d.ts +1 -1
  20. package/dist/issued/ratelimit.js +1 -1
  21. package/dist/issued/resign.js +1 -1
  22. package/dist/issued/tables.d.ts +4 -4
  23. package/dist/issued/tables.js +4 -4
  24. package/dist/migrations/{0003_keys_shred.sql → held/0002_keys_shred.sql} +26 -31
  25. package/dist/migrations/{0004_keys_security.sql → held/0003_keys_security.sql} +36 -70
  26. package/dist/migrations/host/0001_keys_host_events.sql +73 -0
  27. package/dist/migrations/issued/0002_keys_environment.sql +29 -0
  28. package/dist/migrations/{0006_keys_usage.sql → issued/0003_keys_usage.sql} +3 -2
  29. package/dist/migrations/{0008_keys_environment_default.sql → issued/0005_keys_environment_default.sql} +1 -1
  30. package/dist/migrations/issued/0006_keys_issued_guard.sql +47 -0
  31. package/dist/migrations-dir.d.ts +19 -0
  32. package/dist/migrations-dir.js +20 -0
  33. package/dist/testing/index.d.ts +9 -0
  34. package/dist/testing/index.js +9 -0
  35. package/dist/testing/worker-stub.d.ts +55 -0
  36. package/dist/testing/worker-stub.js +180 -0
  37. package/package.json +17 -4
  38. package/dist/migrations/0005_keys_environment.sql +0 -52
  39. package/dist/migrations/0009_keys_issued_guard.sql +0 -46
  40. /package/dist/migrations/{0002_keys_held.sql → held/0001_keys_held.sql} +0 -0
  41. /package/dist/migrations/{0001_keys_issued.sql → issued/0001_keys_issued.sql} +0 -0
  42. /package/dist/migrations/{0007_keys_rate_limit.sql → issued/0004_keys_rate_limit.sql} +0 -0
package/README.md CHANGED
@@ -10,8 +10,95 @@ authentication or authorisation of its own — every check runs through
10
10
 
11
11
  ```sh
12
12
  pnpm add @wtfalch/keys drizzle-orm@^0.45.2
13
+ pnpm add @wtfalch/db # the host applies the migrations and makes the runtime role with it
13
14
  ```
14
15
 
16
+ ## Migrations and roles
17
+
18
+ This package ships SQL and takes a handle. It never connects and never
19
+ migrates: the host applies the SQL with `runMigrationSources` from
20
+ [`@wtfalch/db`](https://github.com/wtfalch/db) and makes the runtime role with
21
+ `ensureRuntimeRole`. The SQL names no schema; the host's `schema` decides where
22
+ it lands. Pass a `withDrizzle(...).orm` (or `tx.orm`) as `db`.
23
+
24
+ There is one chain per part, each complete and ordered on its own, from the
25
+ dependency-free subpath `@wtfalch/keys/migrations-dir`. Pass only the parts
26
+ the host uses; an issued-only host passes one source and gets no held tables.
27
+
28
+ | Export | Source name | Creates |
29
+ | --- | --- | --- |
30
+ | `issuedMigrationsDir` | `keys-issued` | `keys_issued_credentials`, `keys_issued_rate_limit_windows`, the revocation guard (`./issued`) |
31
+ | `heldMigrationsDir` | `keys-held` | `keys_held_entries`, `keys_held_versions`, `keys_shred_expired()` and its guards (`./held`) |
32
+ | `hostMigrationsDir` | `keys-host` | `keys_host_events` (`./host`) |
33
+
34
+ ```ts
35
+ import { runMigrationSources } from '@wtfalch/db/migrate';
36
+ import { ensureRuntimeRole } from '@wtfalch/db/runtime-role';
37
+ import {
38
+ heldMigrationsDir,
39
+ hostMigrationsDir,
40
+ issuedMigrationsDir,
41
+ } from '@wtfalch/keys/migrations-dir';
42
+
43
+ await runMigrationSources({
44
+ url: process.env.DATABASE_URL_OWNER, // the owner credential, never the runtime one
45
+ schema: 'svc',
46
+ sources: [
47
+ { name: 'keys-issued', dir: issuedMigrationsDir },
48
+ { name: 'keys-held', dir: heldMigrationsDir },
49
+ { name: 'keys-host', dir: hostMigrationsDir },
50
+ ],
51
+ });
52
+
53
+ await ensureRuntimeRole({
54
+ ownerUrl: process.env.DATABASE_URL_OWNER,
55
+ runtimeUrl: process.env.DATABASE_URL,
56
+ schemas: ['svc'],
57
+ appendOnly: ['keys_held_versions', 'keys_host_events'],
58
+ noDelete: ['keys_issued_credentials'], // needs @wtfalch/db >= 0.5.2
59
+ grants: ['svc.keys_shred_expired()'],
60
+ });
61
+ ```
62
+
63
+ The runtime connection's `searchPath` must cover the schema
64
+ (`createDatabase({ searchPath: ['svc'] })`), and `schemas` above must list it.
65
+ Each function the SQL creates pins the schema it was created in, with
66
+ `pg_catalog` after it and `pg_temp` last, so a caller-owned temporary table
67
+ cannot shadow a protected one. This holds when each file is applied in one
68
+ transaction, which `runMigrationSources` and `psql -1 -f` do; plain `psql -f`
69
+ freezes the session path instead. Hosts migrate with `@wtfalch/db` 0.5.2 or
70
+ later: 0.5.0 and 0.5.1 let a temporary table shadow tables inside `SECURITY
71
+ DEFINER` functions.
72
+
73
+ Why each list is what it is, read from the triggers in the SQL:
74
+
75
+ | Table | Role may | List | Why |
76
+ | --- | --- | --- | --- |
77
+ | `keys_issued_credentials` | select, insert, update | `noDelete` | Revoke, rotate and usage stamps are updates; `keys_issued_guard` refuses delete and truncate whatever the role holds |
78
+ | `keys_issued_rate_limit_windows` | select, insert, update, delete | none | An upsert counter; no guard, nothing to protect |
79
+ | `keys_held_entries` | select, insert, update, delete | none | Revoke and archive stamp clocks the guard fixes once set. The code never deletes, but nothing in the SQL refuses it either (unchanged from 0.4) |
80
+ | `keys_held_versions` | select, insert | `appendOnly` | Retire and shred run in `SECURITY DEFINER` code. The guard would allow a rewrap from an `UPDATE`, but a runtime role that can update can write garbage as a rewrap, so rewrap needs an operator handle |
81
+ | `keys_host_events` | select, insert | `appendOnly` | Every update, delete and truncate is refused by its guard |
82
+ | `keys_shred_expired()` | execute | `grants` | The only way the runtime role shreds; it takes no target |
83
+
84
+ Call `assertRuntimeRole(db, { appendOnly: ['svc.keys_held_versions',
85
+ 'svc.keys_host_events'], noDelete: ['svc.keys_issued_credentials'] })` at boot.
86
+
87
+ A host that cannot call `runMigrationSources` can copy the files instead:
88
+ `keys-migrations <dir> issued held host` (name only the chains it uses). It
89
+ copies each chain's files into `<dir>` as the next numbers; the host applies
90
+ them as its own and still makes the runtime role as above.
91
+
92
+ Apply each file in one transaction. The three files that create `SECURITY
93
+ DEFINER` functions start with
94
+ `select set_config('search_path', ..., true)`, which sets the path for the
95
+ transaction only. Outside a transaction (`psql -f` without `-1`, or a runner
96
+ that sends one statement at a time) it does nothing, and each function then
97
+ freezes the session's `search_path` instead of `<schema>, pg_catalog, pg_temp`,
98
+ so a temporary table can shadow a protected one. With `psql`, use
99
+ `psql -1 -f <file>`. `runMigrationSources` already runs each file in one
100
+ transaction.
101
+
15
102
  ## Dev
16
103
 
17
104
  ```sh
@@ -22,7 +109,7 @@ pnpm test
22
109
 
23
110
  ## Security upgrade
24
111
 
25
- Apply the additive `0004_keys_security.sql` migration in every consumer database before relying on the updated guards. A host that uses only the issued module (no `0002`/`0003` held tables) cannot apply `0004`; it applies `0009_keys_issued_guard.sql` instead, which carries `0004`'s issued-credential guard alone and is a no-op where `0004` already ran. All issuer processes must upgrade together for issuance/cascade serialization. See [the remediation and rollout notes](../../security/REMEDIATION.md).
112
+ Apply the held chain's `0003_keys_security.sql` (and the issued chain's `0006_keys_issued_guard.sql`) in every consumer database before relying on the updated guards: passing the chains to `runMigrationSources` does it. An issued-only host applies the issued chain alone and gets the revocation guard without any held table. All issuer processes must upgrade together for issuance/cascade serialization. See [the remediation and rollout notes](../../security/REMEDIATION.md).
26
113
 
27
114
  New bearer secrets have a 32-character base32 tail (160 random bits). Existing 20-character tails remain accepted. Rotation refuses invalid stored signatures and returns `conflict` if the row changes during signing.
28
115
 
@@ -30,15 +117,15 @@ Held keys use active cache expiry (60 seconds by default) and retain at most 256
30
117
 
31
118
  ## Issued-key environments
32
119
 
33
- Every issued credential carries a built-in `environment`, `'live'` or `'test'` (default `'live'`), passed on `issue()` and reported by `check()` and `lineageOf()`. A credential can only mint a child in its own environment — `issue()` returns `{ ok: false, reason: 'environment_mismatch' }` otherwise. Apply `0005_keys_environment.sql` alongside `0004_keys_security.sql`, and `0008_keys_environment_default.sql` in the same run: without it, containers still on 0.2.1 or older cannot issue keys between the migration and their redeploy.
120
+ Every issued credential carries a built-in `environment`, `'live'` or `'test'` (default `'live'`), passed on `issue()` and reported by `check()` and `lineageOf()`. A credential can only mint a child in its own environment — `issue()` returns `{ ok: false, reason: 'environment_mismatch' }` otherwise. The issued chain's `0002_keys_environment.sql` and `0005_keys_environment_default.sql` apply in the same run: without it, containers still on 0.2.1 or older cannot issue keys between the migration and their redeploy.
34
121
 
35
122
  ## Issued-key usage tracking
36
123
 
37
- Every successful `check()` stamps `lastUsedAt` and increments `useCount` on the credential's row — read them off `KeysIssuedCredentialRow` directly (an admin UI's own query, not a new `check()` return field). The write is best-effort: it never turns a genuine secret into a refusal, and a revoked, expired, tampered or wrong-secret check never bumps it. Apply `0006_keys_usage.sql` alongside `0004_keys_security.sql` and `0005_keys_environment.sql`.
124
+ Every successful `check()` stamps `lastUsedAt` and increments `useCount` on the credential's row — read them off `KeysIssuedCredentialRow` directly (an admin UI's own query, not a new `check()` return field). The write is best-effort: it never turns a genuine secret into a refusal, and a revoked, expired, tampered or wrong-secret check never bumps it. It comes from the issued chain's `0003_keys_usage.sql`.
38
125
 
39
126
  ## Per-issued-key rate limits
40
127
 
41
- `CreateCredentialIssuerOptions.rateLimiter` (optional) is consulted on every `check()`, keyed by the credential's own `id` — spent on every attempt against a known credential, matched secret or not, so an unlimited number of wrong guesses can't get around it. Refused as `{ ok: false, reason: 'rate_limited', retryAfterMs }`. `createPostgresRateLimiter({ db, limitPerWindow, windowMs? })` is a ready-made fixed-window limiter backed by the host's own Postgres (`0007_keys_rate_limit.sql`, applied alongside `0004`–`0006`); bring your own `RateLimiter` for anything else (Redis, D1, …). Omit it and `check()` behaves exactly as before this existed — this was previously only enforced on the host's own service credential (`packages/worker/src/ratelimit.ts`), never on an individual end-user issued key.
128
+ `CreateCredentialIssuerOptions.rateLimiter` (optional) is consulted on every `check()`, keyed by the credential's own `id` — spent on every attempt against a known credential, matched secret or not, so an unlimited number of wrong guesses can't get around it. Refused as `{ ok: false, reason: 'rate_limited', retryAfterMs }`. `createPostgresRateLimiter({ db, limitPerWindow, windowMs? })` is a ready-made fixed-window limiter backed by the host's own Postgres (the issued chain's `0004_keys_rate_limit.sql`); bring your own `RateLimiter` for anything else (Redis, D1, …). Omit it and `check()` behaves exactly as before this existed — this was previously only enforced on the host's own service credential (`packages/worker/src/ratelimit.ts`), never on an individual end-user issued key.
42
129
 
43
130
  ## Outbound webhooks
44
131
 
@@ -47,13 +134,64 @@ Every successful `check()` stamps `lastUsedAt` and increments `useCount` on the
47
134
  ## Worker transport
48
135
 
49
136
  `createWorkerClient<TGrant>({ url, fetch?, timeoutMs? })` from
50
- `@wtfalch/keys/worker` implements the shared Worker contract. Pass an HTTPS origin;
137
+ `@wtfalch/keys/worker` (added in **0.4.0**) implements the shared Worker contract. Pass an HTTPS origin;
51
138
  paths, query strings, fragments and URL credentials are refused. It validates
52
139
  response shapes and key sizes, refuses redirects, and returns `unreachable` for
53
140
  transport/protocol failures. It makes one attempt per call: a request ID is audit
54
141
  correlation, not an idempotency guarantee. Host authentication and grant policy
55
142
  remain outside the transport. Existing injected clients remain supported.
56
143
 
144
+ ## Adopting `./host`
145
+
146
+ `@wtfalch/keys/host` (added in **0.6.0**) is the host-side plumbing every
147
+ consumer previously hand-copied: the event table `./issued`'s and `./held`'s
148
+ own `audit` options write to, and the read-only endpoint
149
+ [`packages/reconcile`](https://github.com/wtfalch/keys/tree/main/packages/reconcile)
150
+ pulls from.
151
+
152
+ - Pass `hostMigrationsDir` to `runMigrationSources` (see above) to pick up
153
+ `0001_keys_host_events.sql`. It creates `keys_host_events` with
154
+ `create table if not exists`, so a host that already has this table from its
155
+ own hand-written copy of the same shape applies it as a no-op.
156
+ - `recordEvent(db, event)` inserts one row. Its parameter type is the full
157
+ union `./issued`'s `AuditEvent` and `./held`'s `KeyUsedEvent`, wider than
158
+ either option alone, so `(event) => recordEvent(db, event)` type-checks
159
+ directly as both `CreateCredentialIssuerOptions.audit` and
160
+ `CreateHeldKeysOptions.audit` — no adapter, no cast.
161
+ - `auditEndpoint({ db, token })` returns a fetch-shaped handler
162
+ (`(request: Request) => Promise<Response>`). Wire it directly as a route,
163
+ e.g. in Next.js: `export const GET = auditEndpoint({ db, token:
164
+ process.env.KEYS_AUDIT_TOKEN });`. It implements `packages/reconcile`'s
165
+ `GET /v1/keys/audit` contract exactly — same status codes, same window
166
+ limits, same constant-time token check — and its own test suite runs
167
+ `packages/reconcile`'s `fetchHostRows` client against it directly, so the
168
+ two cannot drift the way the hand-copied endpoints had (issue #83: one
169
+ copy silently dropped the response's target fields).
170
+ - A host already running its own copy of `keys_host_events`,
171
+ `recordKeyEvent`/`handleKeysAudit` can switch to `./host`'s versions with
172
+ no behaviour change and no data migration: the table name, every column
173
+ and the response shape are identical field for field.
174
+
175
+ ## Adopting `./testing`
176
+
177
+ `@wtfalch/keys/testing` (added in **0.6.0**) is an in-process Worker stub for
178
+ a host's own tests, built on the package's own signing and AAD code
179
+ (`encodeSigned`/`canonicalJson`/`pickSignable` from `./issued`, `encodeAad`
180
+ from `./held`) rather than a host-side reimplementation of them — the
181
+ problem issue #83 found: every host's `tests/keys-worker-stub.ts` had
182
+ rebuilt these "checked by hand against `dist/issued/index.d.ts`".
183
+
184
+ `createKeysWorkerStub<TGrant>({ now? })` returns a `WorkerClient<TGrant>`
185
+ implementing the full contract (`wrap`/`unwrap`/`rewrap`/`signRow`/`resign`/
186
+ `recordEviction`), plus `verifyKeys`/`verifyKeysEnv` for
187
+ `createCredentialIssuer`'s `verifyKeys` option, `callCounts` per method, and
188
+ `failAs(method, code, retryAfterMs?)` / `clearFailure()` to force a refusal.
189
+ Every call requires `TEST_CREDENTIAL` as the bearer. `canonicalJson`,
190
+ `encodeSigned` and `pickSignable` are re-exported from this entry too, for a
191
+ host's own fixture code that needs to build signable bytes directly — never
192
+ from `./issued` or the public root, since a host's runtime code has no
193
+ reason to construct signed bytes itself.
194
+
57
195
  ## Build inputs
58
196
 
59
197
  See [build-time delivery](https://github.com/wtfalch/keys/blob/main/packages/keys/BUILD.md) for delegated build credentials, the host
@@ -6,10 +6,14 @@
6
6
  * same mechanism `@wtfalch/audit`, `@wtfalch/threads` and `@wtfalch/reporting`
7
7
  * use; the manifest name differs.
8
8
  *
9
- * `./held` and `./issued` each ship their own numbered migration
10
- * (`0001_keys_issued.sql`, `0002_keys_held.sql`) into this package's shared
11
- * `src/migrations/`, whichever lands first -- so this copies every `.sql`
12
- * file present, not one hardcoded name.
9
+ * The app must apply each copied file in one transaction (`psql -1 -f`). The
10
+ * files that create `SECURITY DEFINER` functions set `search_path` with
11
+ * `set_config(..., true)`, which lasts one transaction. Outside one it does
12
+ * nothing, and the function freezes the session path, which can lack
13
+ * `pg_temp` last.
14
+ *
15
+ * Each chain (`issued`, `held`, `host`) is copied from its own directory;
16
+ * every file name is unique across chains, so one manifest tracks all three.
13
17
  */
14
18
  export declare const MANIFEST = ".keys-migrations.json";
15
19
  export interface Manifest {
package/dist/bin/copy.js CHANGED
@@ -8,10 +8,14 @@ import { basename, join } from 'node:path';
8
8
  * same mechanism `@wtfalch/audit`, `@wtfalch/threads` and `@wtfalch/reporting`
9
9
  * use; the manifest name differs.
10
10
  *
11
- * `./held` and `./issued` each ship their own numbered migration
12
- * (`0001_keys_issued.sql`, `0002_keys_held.sql`) into this package's shared
13
- * `src/migrations/`, whichever lands first -- so this copies every `.sql`
14
- * file present, not one hardcoded name.
11
+ * The app must apply each copied file in one transaction (`psql -1 -f`). The
12
+ * files that create `SECURITY DEFINER` functions set `search_path` with
13
+ * `set_config(..., true)`, which lasts one transaction. Outside one it does
14
+ * nothing, and the function freezes the session path, which can lack
15
+ * `pg_temp` last.
16
+ *
17
+ * Each chain (`issued`, `held`, `host`) is copied from its own directory;
18
+ * every file name is unique across chains, so one manifest tracks all three.
15
19
  */
16
20
  export const MANIFEST = '.keys-migrations.json';
17
21
  const NUMBERED = /^(\d{4})_(.+\.sql)$/;
@@ -4,15 +4,29 @@ import { dirname, join, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { copyMigrations, describeCopy } from './copy.js';
6
6
  /**
7
- * `keys-migrations [dir]`: copy this package's migrations the app has not
8
- * yet copied into `dir` (default `drizzle`) as the next numbers. Idempotent;
7
+ * `keys-migrations <dir> <chain>...`: copy the named chains' migrations the
8
+ * app has not yet copied into `dir` as the next numbers. A chain is `issued`,
9
+ * `held` or `host`; name only the parts the app uses, in that order. Idempotent;
9
10
  * run it after every upgrade of @wtfalch/keys, then commit what it wrote.
10
11
  *
11
- * Ships every `.sql` file under `dist/migrations/` -- both `./held`'s and
12
- * `./issued`'s, whichever this package version carries.
12
+ * Apply each copied file in one transaction (`psql -1 -f`): the files that
13
+ * create `SECURITY DEFINER` functions pin `search_path` with a
14
+ * transaction-local `set_config`, which does nothing outside one.
15
+ *
16
+ * The fallback for a host that cannot pass `runMigrationSources` the
17
+ * directories from `@wtfalch/keys/migrations-dir`.
13
18
  */
19
+ const CHAINS = ['issued', 'held', 'host'];
14
20
  const here = dirname(fileURLToPath(import.meta.url));
15
- const from = join(here, '..', 'migrations');
16
- const to = resolve(process.cwd(), process.argv[2] ?? 'drizzle');
21
+ const [dirArg, ...chains] = process.argv.slice(2);
22
+ if (!dirArg || chains.length === 0 || chains.some((c) => !CHAINS.includes(c))) {
23
+ console.error(`usage: keys-migrations <dir> <${CHAINS.join('|')}>...`);
24
+ console.error('Apply each copied file in one transaction (psql -1 -f); outside one the\nsearch_path pin on SECURITY DEFINER functions does nothing.');
25
+ process.exit(2);
26
+ }
27
+ const to = resolve(process.cwd(), dirArg);
17
28
  const { version } = JSON.parse(readFileSync(join(here, '..', '..', 'package.json'), 'utf8'));
18
- console.log(describeCopy(copyMigrations({ from, to, version })));
29
+ for (const chain of chains) {
30
+ const from = join(here, '..', 'migrations', chain);
31
+ console.log(describeCopy(copyMigrations({ from, to, version })));
32
+ }
@@ -1,6 +1,6 @@
1
1
  import { customType, index, integer, pgTable, primaryKey, text, timestamp, } from 'drizzle-orm/pg-core';
2
2
  /**
3
- * Mirrors `migrations/0002_keys_held.sql`, which is the source of truth: the
3
+ * Mirrors `migrations/held/0001_keys_held.sql`, which is the source of truth: the
4
4
  * SQL carries the CHECKs and the foreign key that drizzle-kit does not
5
5
  * generate. Unlike `@wtfalch/audit`'s tables, a host never declares its own
6
6
  * columns alongside these -- `./held` owns the whole row, so the tables stay
@@ -0,0 +1,22 @@
1
+ /**
2
+ * AES-256-GCM seal/open for one 32-byte key under another: `iv (12 bytes) ||
3
+ * ciphertext-with-tag`, WebCrypto's tag appended to the ciphertext itself.
4
+ *
5
+ * The one module both the unwrap Worker (`packages/worker/src/crypto.ts`)
6
+ * and the in-process test stub (`../testing/worker-stub.ts`) import for this
7
+ * layout, rather than each carrying its own copy. Before #86 the stub
8
+ * reimplemented it by hand: a real risk, since a host's tests would keep
9
+ * passing against a stub whose layout had silently drifted from what the
10
+ * Worker actually does. `crypto.test.ts` (`packages/worker/src`) proves a
11
+ * value sealed through the Worker's own `aesGcmSeal` opens with this
12
+ * module's `aesGcmOpen`, and the reverse.
13
+ *
14
+ * WebCrypto only (`crypto.subtle`), via the global `crypto` rather than
15
+ * `node:crypto`: this file runs in workerd, which has no `node:crypto`, and
16
+ * in Node >=22, whose global `crypto` is the same WebCrypto API. Same
17
+ * constraint as `./aad.ts`.
18
+ */
19
+ /** `iv (12 bytes) || ciphertext-with-tag`. WebCrypto's AES-GCM appends the 16-byte tag to the ciphertext itself. */
20
+ export declare function aesGcmSeal(kekBytes: Uint8Array, plaintext: Uint8Array, aad: Uint8Array): Promise<Uint8Array>;
21
+ /** Inverse of `aesGcmSeal`. Returns `null` on a bad tag or malformed input -- never the underlying WebCrypto error. */
22
+ export declare function aesGcmOpen(kekBytes: Uint8Array, sealed: Uint8Array, aad: Uint8Array): Promise<Uint8Array | null>;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * AES-256-GCM seal/open for one 32-byte key under another: `iv (12 bytes) ||
3
+ * ciphertext-with-tag`, WebCrypto's tag appended to the ciphertext itself.
4
+ *
5
+ * The one module both the unwrap Worker (`packages/worker/src/crypto.ts`)
6
+ * and the in-process test stub (`../testing/worker-stub.ts`) import for this
7
+ * layout, rather than each carrying its own copy. Before #86 the stub
8
+ * reimplemented it by hand: a real risk, since a host's tests would keep
9
+ * passing against a stub whose layout had silently drifted from what the
10
+ * Worker actually does. `crypto.test.ts` (`packages/worker/src`) proves a
11
+ * value sealed through the Worker's own `aesGcmSeal` opens with this
12
+ * module's `aesGcmOpen`, and the reverse.
13
+ *
14
+ * WebCrypto only (`crypto.subtle`), via the global `crypto` rather than
15
+ * `node:crypto`: this file runs in workerd, which has no `node:crypto`, and
16
+ * in Node >=22, whose global `crypto` is the same WebCrypto API. Same
17
+ * constraint as `./aad.ts`.
18
+ */
19
+ const GCM_IV_BYTES = 12;
20
+ /** `iv (12 bytes) || ciphertext-with-tag`. WebCrypto's AES-GCM appends the 16-byte tag to the ciphertext itself. */
21
+ export async function aesGcmSeal(kekBytes, plaintext, aad) {
22
+ const key = await crypto.subtle.importKey('raw', kekBytes, { name: 'AES-GCM' }, false, [
23
+ 'encrypt',
24
+ ]);
25
+ const iv = crypto.getRandomValues(new Uint8Array(GCM_IV_BYTES));
26
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, plaintext));
27
+ const out = new Uint8Array(iv.length + ciphertext.length);
28
+ out.set(iv, 0);
29
+ out.set(ciphertext, iv.length);
30
+ return out;
31
+ }
32
+ /** Inverse of `aesGcmSeal`. Returns `null` on a bad tag or malformed input -- never the underlying WebCrypto error. */
33
+ export async function aesGcmOpen(kekBytes, sealed, aad) {
34
+ if (sealed.length <= GCM_IV_BYTES)
35
+ return null;
36
+ const iv = sealed.subarray(0, GCM_IV_BYTES);
37
+ const ciphertext = sealed.subarray(GCM_IV_BYTES);
38
+ try {
39
+ const key = await crypto.subtle.importKey('raw', kekBytes, { name: 'AES-GCM' }, false, [
40
+ 'decrypt',
41
+ ]);
42
+ const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, ciphertext);
43
+ return new Uint8Array(plaintext);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
@@ -1,6 +1,6 @@
1
1
  import type { HeldKeysDb } from './index.js';
2
2
  /**
3
- * Calls `keys_shred_expired()` -- 0003_keys_shred.sql's `SECURITY DEFINER`
3
+ * Calls `keys_shred_expired()` -- `migrations/held/0002_keys_shred.sql`'s `SECURITY DEFINER`
4
4
  * sweep -- and returns how many `keys_held_versions` rows it shredded. Takes
5
5
  * no row-targeting argument itself, matching the function: the function
6
6
  * decides eligibility on its own from `retired_at`, `revoked_at` and
@@ -1,7 +1,7 @@
1
1
  import { and, eq, sql } from 'drizzle-orm';
2
2
  import { keysHeldEntries, keysHeldVersions } from './schema.js';
3
3
  /**
4
- * Calls `keys_shred_expired()` -- 0003_keys_shred.sql's `SECURITY DEFINER`
4
+ * Calls `keys_shred_expired()` -- `migrations/held/0002_keys_shred.sql`'s `SECURITY DEFINER`
5
5
  * sweep -- and returns how many `keys_held_versions` rows it shredded. Takes
6
6
  * no row-targeting argument itself, matching the function: the function
7
7
  * decides eligibility on its own from `retired_at`, `revoked_at` and
@@ -0,0 +1,15 @@
1
+ import type { Db } from '../issued/index.js';
2
+ export interface AuditEndpointOptions {
3
+ readonly db: Db;
4
+ readonly token: string | undefined;
5
+ /** Unix milliseconds. Defaults to `Date.now`; accepted for parity with this module's siblings even though no check below currently needs "now". */
6
+ readonly now?: () => number;
7
+ }
8
+ /**
9
+ * `auditEndpoint({ db, token })` returns a fetch-shaped handler
10
+ * (`(request: Request) => Promise<Response>`) -- wire it directly as a
11
+ * route: `export const GET = auditEndpoint({ db, token:
12
+ * process.env.KEYS_AUDIT_TOKEN });`. Deps are read once, at handler
13
+ * construction; nothing here is re-read per request.
14
+ */
15
+ export declare function auditEndpoint(options: AuditEndpointOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,117 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { and, asc, gte, inArray, isNotNull, lt } from 'drizzle-orm';
3
+ import { keysHostEvents } from './schema.js';
4
+ /**
5
+ * `GET /v1/keys/audit` -- the per-host read-only endpoint
6
+ * `packages/reconcile` pulls from (`../../reconcile/README.md`'s "Host
7
+ * audit contract", and that package's `hosts.ts`/`types.ts` for the exact
8
+ * wire shape this must return). Every host that adopts `./host` ships the
9
+ * same response shape, so `packages/reconcile` never has to special-case
10
+ * one host's endpoint against another's -- this is exactly the copy that
11
+ * issue #83 found drifting between `files`, `ai`, `integrations` and
12
+ * `boule` (one of the four copies dropped the target fields the contract
13
+ * requires; the drift is silent until reconciliation starts flagging false
14
+ * `host_row_unmatched` findings).
15
+ *
16
+ * Fails closed throughout: a misconfigured token refuses to serve at all
17
+ * (503) rather than falling back to "accept anything", an unrecognised or
18
+ * malformed request is refused before it ever reaches the database (400),
19
+ * and a window matching more rows than this endpoint will ever return is
20
+ * refused outright (413) rather than silently truncated -- a dropped row
21
+ * here would look identical to a real reconciliation finding on the other
22
+ * side (`packages/reconcile/README.md`'s own fails-closed rule for the
23
+ * client half of this contract).
24
+ */
25
+ const REQUEST_BEARING_KINDS = ['key.used', 'credential.minted', 'credential.rotated'];
26
+ /** No signs, no exponents, at most 16 digits -- deliberately narrower than "whatever `Number()` accepts". */
27
+ const INTEGER_PATTERN = /^\d{1,16}$/;
28
+ const THIRTY_ONE_DAYS_MS = 31 * 24 * 60 * 60 * 1000;
29
+ /** A dropped row would look like a real reconciliation finding; refuse the whole window instead of truncating it. */
30
+ const MAX_ROWS = 50_000;
31
+ const BEARER_PATTERN = /^Bearer ([^\s]+)$/;
32
+ function jsonResponse(body, status) {
33
+ return Response.json(body, { status, headers: { 'cache-control': 'no-store' } });
34
+ }
35
+ const unavailable = () => jsonResponse({ error: { code: 'unavailable' } }, 503);
36
+ const unauthorized = () => jsonResponse({ error: { code: 'unauthorized' } }, 401);
37
+ const badRequest = () => jsonResponse({ error: { code: 'bad_request' } }, 400);
38
+ const windowTooLarge = () => jsonResponse({ error: { code: 'window_too_large' } }, 413);
39
+ const methodNotAllowed = () => jsonResponse({ error: { code: 'method_not_allowed' } }, 405);
40
+ /** Constant-time regardless of length: both sides are always a 32-byte SHA-256 digest, so `timingSafeEqual` never throws on a length mismatch here. */
41
+ function tokensMatch(presented, configured) {
42
+ const a = createHash('sha256').update(presented, 'utf8').digest();
43
+ const b = createHash('sha256').update(configured, 'utf8').digest();
44
+ return timingSafeEqual(a, b);
45
+ }
46
+ /** `Number(bigint)` past this silently rounds, which would let `since`/`until` collapse together after conversion even though the `bigint` comparison above said they didn't. 16 digits alone doesn't rule that out, so bound it explicitly too. */
47
+ const MAX_SAFE_WINDOW_PARAM = BigInt(Number.MAX_SAFE_INTEGER);
48
+ /** A decimal-integer query param, or `null` for anything else -- absent, empty, signed, fractional, exponential, over 16 digits, or past `Number.MAX_SAFE_INTEGER`. */
49
+ function parseWindowParam(raw) {
50
+ if (raw === null || !INTEGER_PATTERN.test(raw))
51
+ return null;
52
+ const value = BigInt(raw);
53
+ return value <= MAX_SAFE_WINDOW_PARAM ? value : null;
54
+ }
55
+ /**
56
+ * `auditEndpoint({ db, token })` returns a fetch-shaped handler
57
+ * (`(request: Request) => Promise<Response>`) -- wire it directly as a
58
+ * route: `export const GET = auditEndpoint({ db, token:
59
+ * process.env.KEYS_AUDIT_TOKEN });`. Deps are read once, at handler
60
+ * construction; nothing here is re-read per request.
61
+ */
62
+ export function auditEndpoint(options) {
63
+ const { db, token } = options;
64
+ return async function handleKeysAudit(request) {
65
+ if (request.method !== 'GET')
66
+ return methodNotAllowed();
67
+ // A misconfigured host must not serve, regardless of what the caller presents.
68
+ if (!token || token.length < 32)
69
+ return unavailable();
70
+ const match = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
71
+ if (!match?.[1] || !tokensMatch(match[1], token))
72
+ return unauthorized();
73
+ const url = new URL(request.url);
74
+ const since = parseWindowParam(url.searchParams.get('since'));
75
+ const until = parseWindowParam(url.searchParams.get('until'));
76
+ if (since === null ||
77
+ until === null ||
78
+ since >= until ||
79
+ until - since > BigInt(THIRTY_ONE_DAYS_MS)) {
80
+ return badRequest();
81
+ }
82
+ const sinceMs = Number(since);
83
+ const untilMs = Number(until);
84
+ const rows = await db
85
+ .select({
86
+ kind: keysHostEvents.kind,
87
+ requestId: keysHostEvents.requestId,
88
+ credentialId: keysHostEvents.credentialId,
89
+ tenantId: keysHostEvents.tenantId,
90
+ entryId: keysHostEvents.entryId,
91
+ version: keysHostEvents.version,
92
+ at: keysHostEvents.at,
93
+ })
94
+ .from(keysHostEvents)
95
+ .where(and(inArray(keysHostEvents.kind, [...REQUEST_BEARING_KINDS]), isNotNull(keysHostEvents.requestId), gte(keysHostEvents.at, new Date(sinceMs)), lt(keysHostEvents.at, new Date(untilMs))))
96
+ .orderBy(asc(keysHostEvents.at), asc(keysHostEvents.id))
97
+ .limit(MAX_ROWS + 1);
98
+ if (rows.length > MAX_ROWS)
99
+ return windowTooLarge();
100
+ const body = rows.map((row) => {
101
+ // `at` is timestamptz (microsecond storage); every row here was
102
+ // written from a unix-ms `Date`, so its fraction is already an exact
103
+ // multiple of one millisecond -- floor explicitly anyway rather than
104
+ // trust that.
105
+ const common = {
106
+ kind: row.kind,
107
+ requestId: row.requestId,
108
+ at: Math.floor(row.at.getTime()),
109
+ };
110
+ if (row.kind === 'key.used') {
111
+ return { ...common, tenantId: row.tenantId, entryId: row.entryId, version: row.version };
112
+ }
113
+ return { ...common, credentialId: row.credentialId };
114
+ });
115
+ return jsonResponse(body, 200);
116
+ };
117
+ }
@@ -0,0 +1,26 @@
1
+ import type { KeyUsedEvent } from '../held/index.js';
2
+ import type { Db } from '../issued/index.js';
3
+ import type { AuditEvent } from '../issued/index.js';
4
+ /**
5
+ * Every event `./issued`'s `AuditCallback` or `./held`'s `audit` option can
6
+ * hand `recordEvent` -- the exact union `CreateCredentialIssuerOptions.audit`
7
+ * (`AuditEvent`, discriminated by `name`: `'credential.minted' |
8
+ * 'credential.rotated' | 'credential.revoked'`) and `CreateHeldKeysOptions.audit`
9
+ * (`KeyUsedEvent`, `name: 'key.used'`) can ever produce, between them.
10
+ *
11
+ * `recordEvent`'s own parameter is this union, wider than either option
12
+ * alone expects, so `(event) => recordEvent(db, event)` type-checks as both
13
+ * an `AuditCallback` and a held `audit` callback -- a function that accepts
14
+ * more than an option asks for is assignable wherever that option is asked
15
+ * for (TypeScript's ordinary parameter contravariance), with no cast on
16
+ * either side.
17
+ */
18
+ export type HostEvent = AuditEvent | KeyUsedEvent;
19
+ /**
20
+ * Inserts one `keys_host_events` row: this host's own append-only record of
21
+ * what `@wtfalch/keys` did on its behalf. Takes a drizzle handle rather than
22
+ * assuming a module-level `db`, so a script built on its own handle can call
23
+ * it without pulling in a host's database module, and a test can point it at
24
+ * a disposable one.
25
+ */
26
+ export declare function recordEvent(db: Db, event: HostEvent): Promise<void>;
@@ -0,0 +1,31 @@
1
+ import { keysHostEvents } from './schema.js';
2
+ /**
3
+ * Inserts one `keys_host_events` row: this host's own append-only record of
4
+ * what `@wtfalch/keys` did on its behalf. Takes a drizzle handle rather than
5
+ * assuming a module-level `db`, so a script built on its own handle can call
6
+ * it without pulling in a host's database module, and a test can point it at
7
+ * a disposable one.
8
+ */
9
+ export async function recordEvent(db, event) {
10
+ if (event.name === 'key.used') {
11
+ await db.insert(keysHostEvents).values({
12
+ kind: event.name,
13
+ requestId: event.requestId,
14
+ credentialId: null,
15
+ tenantId: event.tenantId,
16
+ entryId: event.entryId,
17
+ version: event.version,
18
+ at: new Date(event.at),
19
+ });
20
+ return;
21
+ }
22
+ await db.insert(keysHostEvents).values({
23
+ kind: event.name,
24
+ requestId: event.requestId ?? null,
25
+ credentialId: event.credentialId,
26
+ tenantId: null,
27
+ entryId: null,
28
+ version: null,
29
+ at: new Date(event.at),
30
+ });
31
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `./host`: the pieces of a keys host that #83 found hand-copied into
3
+ * every consumer (`files`, `ai`, `integrations`, `boule`) -- the event
4
+ * table `./issued` and `./held`'s `audit` options write to, and the
5
+ * read-only endpoint `packages/reconcile` pulls from. See the package
6
+ * README's "Adopting ./host" for how an existing host swaps its own copy
7
+ * for this one with no behaviour change.
8
+ */
9
+ export { auditEndpoint, type AuditEndpointOptions } from './audit-endpoint.js';
10
+ export { recordEvent, type HostEvent } from './events.js';
11
+ export { keysHostEvents, type KeysHostEventRow } from './schema.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `./host`: the pieces of a keys host that #83 found hand-copied into
3
+ * every consumer (`files`, `ai`, `integrations`, `boule`) -- the event
4
+ * table `./issued` and `./held`'s `audit` options write to, and the
5
+ * read-only endpoint `packages/reconcile` pulls from. See the package
6
+ * README's "Adopting ./host" for how an existing host swaps its own copy
7
+ * for this one with no behaviour change.
8
+ */
9
+ export { auditEndpoint } from './audit-endpoint.js';
10
+ export { recordEvent } from './events.js';
11
+ export { keysHostEvents } from './schema.js';