@wtfalch/keys 0.4.2 → 0.7.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 (44) hide show
  1. package/README.md +160 -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/held-edge/index.d.ts +50 -0
  11. package/dist/held-edge/index.js +175 -0
  12. package/dist/host/audit-endpoint.d.ts +15 -0
  13. package/dist/host/audit-endpoint.js +117 -0
  14. package/dist/host/events.d.ts +26 -0
  15. package/dist/host/events.js +31 -0
  16. package/dist/host/index.d.ts +11 -0
  17. package/dist/host/index.js +11 -0
  18. package/dist/host/schema.d.ts +153 -0
  19. package/dist/host/schema.js +20 -0
  20. package/dist/issued/index.js +2 -2
  21. package/dist/issued/ratelimit.d.ts +1 -1
  22. package/dist/issued/ratelimit.js +1 -1
  23. package/dist/issued/resign.js +1 -1
  24. package/dist/issued/tables.d.ts +4 -4
  25. package/dist/issued/tables.js +4 -4
  26. package/dist/migrations/{0003_keys_shred.sql → held/0002_keys_shred.sql} +26 -31
  27. package/dist/migrations/{0004_keys_security.sql → held/0003_keys_security.sql} +36 -70
  28. package/dist/migrations/host/0001_keys_host_events.sql +73 -0
  29. package/dist/migrations/issued/0002_keys_environment.sql +29 -0
  30. package/dist/migrations/{0006_keys_usage.sql → issued/0003_keys_usage.sql} +3 -2
  31. package/dist/migrations/{0008_keys_environment_default.sql → issued/0005_keys_environment_default.sql} +1 -1
  32. package/dist/migrations/issued/0006_keys_issued_guard.sql +47 -0
  33. package/dist/migrations-dir.d.ts +19 -0
  34. package/dist/migrations-dir.js +20 -0
  35. package/dist/testing/index.d.ts +9 -0
  36. package/dist/testing/index.js +9 -0
  37. package/dist/testing/worker-stub.d.ts +55 -0
  38. package/dist/testing/worker-stub.js +180 -0
  39. package/package.json +21 -4
  40. package/dist/migrations/0005_keys_environment.sql +0 -52
  41. package/dist/migrations/0009_keys_issued_guard.sql +0 -46
  42. /package/dist/migrations/{0002_keys_held.sql → held/0001_keys_held.sql} +0 -0
  43. /package/dist/migrations/{0001_keys_issued.sql → issued/0001_keys_issued.sql} +0 -0
  44. /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,81 @@ 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 `./held-edge`
145
+
146
+ `@wtfalch/keys/held-edge` is `./held`'s envelope encryption for a Cloudflare Worker: WebCrypto only, no `node:` import, no Postgres. A random AES-256-GCM data key per version encrypts the value, the same custody Worker wraps that data key, and the same AAD (tenant, entry, version; shared with `./held`, never copied) binds both layers. Storage stays with the caller: keep the returned `SealedHeld` as JSON.
147
+
148
+ ```ts
149
+ import { openHeld, sealHeld } from '@wtfalch/keys/held-edge';
150
+
151
+ const sealed = await sealHeld({ worker, credential, tenantId, entryId, version: 1, plaintext });
152
+ const plaintext = await openHeld({ worker, credential, tenantId, entryId, sealed });
153
+ ```
154
+
155
+ - `worker` is any `WorkerClient` (only `wrap` and `unwrap` are used); `credential` is the serialized bearer credential the custody Worker checks. Pass `timeoutMs` (default 10 s) to bound each Worker call.
156
+ - `version` is chosen and incremented by the caller. Opening with the wrong tenant, entry or version fails (`aad_mismatch` from the Worker, `unseal_failed` locally).
157
+ - `tenantId` and `entryId` must match `/^[A-Za-z0-9_-]{1,128}$/`; a bad id throws `HeldEdgeError('bad_request')` before any network call.
158
+ - Errors are `HeldEdgeError` with a `code`: the Worker's own code, `bad_request`, `unseal_failed` or `timeout`. A message never carries the plaintext, a key, or the Worker's free-text message.
159
+ - `createWorkerClient` (`./worker`) uses `Buffer`: on a Worker, enable `nodejs_compat` for it, or inject your own `WorkerClient`. `./held-edge` itself needs neither.
160
+
161
+ ## Adopting `./host`
162
+
163
+ `@wtfalch/keys/host` (added in **0.6.0**) is the host-side plumbing every
164
+ consumer previously hand-copied: the event table `./issued`'s and `./held`'s
165
+ own `audit` options write to, and the read-only endpoint
166
+ [`packages/reconcile`](https://github.com/wtfalch/keys/tree/main/packages/reconcile)
167
+ pulls from.
168
+
169
+ - Pass `hostMigrationsDir` to `runMigrationSources` (see above) to pick up
170
+ `0001_keys_host_events.sql`. It creates `keys_host_events` with
171
+ `create table if not exists`, so a host that already has this table from its
172
+ own hand-written copy of the same shape applies it as a no-op.
173
+ - `recordEvent(db, event)` inserts one row. Its parameter type is the full
174
+ union `./issued`'s `AuditEvent` and `./held`'s `KeyUsedEvent`, wider than
175
+ either option alone, so `(event) => recordEvent(db, event)` type-checks
176
+ directly as both `CreateCredentialIssuerOptions.audit` and
177
+ `CreateHeldKeysOptions.audit` — no adapter, no cast.
178
+ - `auditEndpoint({ db, token })` returns a fetch-shaped handler
179
+ (`(request: Request) => Promise<Response>`). Wire it directly as a route,
180
+ e.g. in Next.js: `export const GET = auditEndpoint({ db, token:
181
+ process.env.KEYS_AUDIT_TOKEN });`. It implements `packages/reconcile`'s
182
+ `GET /v1/keys/audit` contract exactly — same status codes, same window
183
+ limits, same constant-time token check — and its own test suite runs
184
+ `packages/reconcile`'s `fetchHostRows` client against it directly, so the
185
+ two cannot drift the way the hand-copied endpoints had (issue #83: one
186
+ copy silently dropped the response's target fields).
187
+ - A host already running its own copy of `keys_host_events`,
188
+ `recordKeyEvent`/`handleKeysAudit` can switch to `./host`'s versions with
189
+ no behaviour change and no data migration: the table name, every column
190
+ and the response shape are identical field for field.
191
+
192
+ ## Adopting `./testing`
193
+
194
+ `@wtfalch/keys/testing` (added in **0.6.0**) is an in-process Worker stub for
195
+ a host's own tests, built on the package's own signing and AAD code
196
+ (`encodeSigned`/`canonicalJson`/`pickSignable` from `./issued`, `encodeAad`
197
+ from `./held`) rather than a host-side reimplementation of them — the
198
+ problem issue #83 found: every host's `tests/keys-worker-stub.ts` had
199
+ rebuilt these "checked by hand against `dist/issued/index.d.ts`".
200
+
201
+ `createKeysWorkerStub<TGrant>({ now? })` returns a `WorkerClient<TGrant>`
202
+ implementing the full contract (`wrap`/`unwrap`/`rewrap`/`signRow`/`resign`/
203
+ `recordEviction`), plus `verifyKeys`/`verifyKeysEnv` for
204
+ `createCredentialIssuer`'s `verifyKeys` option, `callCounts` per method, and
205
+ `failAs(method, code, retryAfterMs?)` / `clearFailure()` to force a refusal.
206
+ Every call requires `TEST_CREDENTIAL` as the bearer. `canonicalJson`,
207
+ `encodeSigned` and `pickSignable` are re-exported from this entry too, for a
208
+ host's own fixture code that needs to build signable bytes directly — never
209
+ from `./issued` or the public root, since a host's runtime code has no
210
+ reason to construct signed bytes itself.
211
+
57
212
  ## Build inputs
58
213
 
59
214
  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,50 @@
1
+ /**
2
+ * `./held-edge`: the `./held` envelope model for a Cloudflare Worker.
3
+ *
4
+ * Same model as `../held/index.ts`: a random AES-256-GCM data key per version
5
+ * encrypts the value, the custody Worker wraps that data key, and the AAD
6
+ * (`../held/aad.ts`, shared, not copied) binds tenant, entry and version to
7
+ * both layers. Unlike `./held` there is no Postgres and no `node:crypto`:
8
+ * WebCrypto only. Storage of the `SealedHeld` stays with the caller.
9
+ *
10
+ * This file imports nothing from `node:` and only `../held/aad.ts` and types
11
+ * and constants from `../worker-contract.ts`. The `WorkerClient` is injected
12
+ * (`createWorkerClient` from `../worker` needs `nodejs_compat`).
13
+ */
14
+ import { type SerializedCredential, type WorkerClient, type WorkerErrorCode } from '../worker-contract.js';
15
+ export { encodeAad } from '../held/aad.js';
16
+ export interface SealedHeld {
17
+ v: 1;
18
+ kekId: string;
19
+ /** base64url, the custody Worker's wrapped data key. */
20
+ wrappedKey: string;
21
+ /** base64url, 12 bytes. */
22
+ iv: string;
23
+ /** base64url, ciphertext with the GCM tag appended. */
24
+ ct: string;
25
+ version: number;
26
+ }
27
+ /** Local refusals plus the Worker's own code, verbatim. Never carries a value or a key. */
28
+ export type HeldEdgeErrorCode = WorkerErrorCode | 'bad_request' | 'unseal_failed' | 'timeout';
29
+ export declare class HeldEdgeError extends Error {
30
+ readonly code: HeldEdgeErrorCode;
31
+ constructor(code: HeldEdgeErrorCode, message?: string);
32
+ }
33
+ interface CallOptions {
34
+ readonly worker: Pick<WorkerClient, 'wrap' | 'unwrap'>;
35
+ /** Sent to the custody Worker as the bearer credential. */
36
+ readonly credential: SerializedCredential;
37
+ readonly tenantId: string;
38
+ readonly entryId: string;
39
+ /** Per-call limit on the Worker call. Default 10s. */
40
+ readonly timeoutMs?: number;
41
+ }
42
+ export interface SealHeldOptions extends CallOptions {
43
+ readonly version: number;
44
+ readonly plaintext: string;
45
+ }
46
+ export interface OpenHeldOptions extends CallOptions {
47
+ readonly sealed: SealedHeld;
48
+ }
49
+ export declare function sealHeld(o: SealHeldOptions): Promise<SealedHeld>;
50
+ export declare function openHeld(o: OpenHeldOptions): Promise<string>;
@@ -0,0 +1,175 @@
1
+ import { encodeAad } from '../held/aad.js';
2
+ /**
3
+ * `./held-edge`: the `./held` envelope model for a Cloudflare Worker.
4
+ *
5
+ * Same model as `../held/index.ts`: a random AES-256-GCM data key per version
6
+ * encrypts the value, the custody Worker wraps that data key, and the AAD
7
+ * (`../held/aad.ts`, shared, not copied) binds tenant, entry and version to
8
+ * both layers. Unlike `./held` there is no Postgres and no `node:crypto`:
9
+ * WebCrypto only. Storage of the `SealedHeld` stays with the caller.
10
+ *
11
+ * This file imports nothing from `node:` and only `../held/aad.ts` and types
12
+ * and constants from `../worker-contract.ts`. The `WorkerClient` is injected
13
+ * (`createWorkerClient` from `../worker` needs `nodejs_compat`).
14
+ */
15
+ import { ID_PATTERN, } from '../worker-contract.js';
16
+ export { encodeAad } from '../held/aad.js';
17
+ const DEFAULT_TIMEOUT_MS = 10_000;
18
+ const IV_BYTES = 12;
19
+ const DATA_KEY_BYTES = 32;
20
+ const WRAPPED_KEY_BYTES = 60;
21
+ const TAG_BYTES = 16;
22
+ export class HeldEdgeError extends Error {
23
+ code;
24
+ constructor(code, message) {
25
+ super(message ?? code);
26
+ this.name = 'HeldEdgeError';
27
+ this.code = code;
28
+ }
29
+ }
30
+ function toBase64Url(bytes) {
31
+ let bin = '';
32
+ for (const b of bytes)
33
+ bin += String.fromCharCode(b);
34
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
35
+ }
36
+ /** `null` unless `text` is exactly one round trip of `toBase64Url`. */
37
+ function fromBase64Url(text) {
38
+ if (typeof text !== 'string' || !/^[A-Za-z0-9_-]+$/.test(text))
39
+ return null;
40
+ try {
41
+ const std = text.replace(/-/g, '+').replace(/_/g, '/');
42
+ const bin = atob(std + '='.repeat((4 - (std.length % 4)) % 4));
43
+ const out = new Uint8Array(bin.length);
44
+ for (let i = 0; i < bin.length; i++)
45
+ out[i] = bin.charCodeAt(i);
46
+ return toBase64Url(out) === text ? out : null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ function checkIds(tenantId, entryId) {
53
+ if (typeof tenantId !== 'string' || !ID_PATTERN.test(tenantId)) {
54
+ throw new HeldEdgeError('bad_request', 'tenantId does not match the id pattern');
55
+ }
56
+ if (typeof entryId !== 'string' || !ID_PATTERN.test(entryId)) {
57
+ throw new HeldEdgeError('bad_request', 'entryId does not match the id pattern');
58
+ }
59
+ }
60
+ function checkVersion(version) {
61
+ if (!Number.isSafeInteger(version) || version < 1) {
62
+ throw new HeldEdgeError('bad_request', 'version must be a positive integer');
63
+ }
64
+ }
65
+ function checkTimeout(timeoutMs) {
66
+ const ms = timeoutMs ?? DEFAULT_TIMEOUT_MS;
67
+ if (!Number.isSafeInteger(ms) || ms < 1 || ms > 2_147_483_647) {
68
+ throw new RangeError('timeoutMs must be an integer from 1 to 2147483647');
69
+ }
70
+ return ms;
71
+ }
72
+ /** Races the Worker call against a timer; the timer is always cleared. */
73
+ async function withTimeout(call, ms) {
74
+ let timer;
75
+ const timeout = new Promise((_, reject) => {
76
+ timer = setTimeout(() => reject(new HeldEdgeError('timeout', 'custody Worker timed out')), ms);
77
+ });
78
+ try {
79
+ return await Promise.race([call, timeout]);
80
+ }
81
+ finally {
82
+ clearTimeout(timer);
83
+ }
84
+ }
85
+ /** Surfaces the Worker's code only: its free-text message is never copied. */
86
+ function fromWorker(code) {
87
+ return new HeldEdgeError(code, `custody Worker refused: ${code}`);
88
+ }
89
+ async function importDataKey(dataKey, usage) {
90
+ if (dataKey.length !== DATA_KEY_BYTES)
91
+ throw new HeldEdgeError('unseal_failed');
92
+ return crypto.subtle.importKey('raw', dataKey, { name: 'AES-GCM' }, false, [usage]);
93
+ }
94
+ export async function sealHeld(o) {
95
+ checkIds(o.tenantId, o.entryId);
96
+ checkVersion(o.version);
97
+ if (typeof o.plaintext !== 'string') {
98
+ throw new HeldEdgeError('bad_request', 'plaintext must be a string');
99
+ }
100
+ const ms = checkTimeout(o.timeoutMs);
101
+ const binding = { tenantId: o.tenantId, entryId: o.entryId, version: o.version };
102
+ const aad = encodeAad(binding);
103
+ const result = await withTimeout(o.worker.wrap({ requestId: crypto.randomUUID(), credential: o.credential, binding }), ms);
104
+ if (!result.ok)
105
+ throw fromWorker(result.error.code);
106
+ const dataKey = result.dataKey;
107
+ try {
108
+ // Refuse here what openHeld refuses, or the value would be sealed but never open again.
109
+ if (!ID_PATTERN.test(result.kekId) || result.wrappedKey.length !== WRAPPED_KEY_BYTES) {
110
+ throw new HeldEdgeError('bad_request', 'custody worker returned a malformed wrap');
111
+ }
112
+ const key = await importDataKey(dataKey, 'encrypt');
113
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
114
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, new TextEncoder().encode(o.plaintext)));
115
+ return {
116
+ v: 1,
117
+ kekId: result.kekId,
118
+ wrappedKey: toBase64Url(result.wrappedKey),
119
+ iv: toBase64Url(iv),
120
+ ct: toBase64Url(ct),
121
+ version: o.version,
122
+ };
123
+ }
124
+ finally {
125
+ dataKey.fill(0);
126
+ }
127
+ }
128
+ export async function openHeld(o) {
129
+ checkIds(o.tenantId, o.entryId);
130
+ const s = o.sealed;
131
+ if (typeof s !== 'object' || s === null || s.v !== 1) {
132
+ throw new HeldEdgeError('bad_request', 'sealed is not a v1 SealedHeld');
133
+ }
134
+ checkVersion(s.version);
135
+ if (typeof s.kekId !== 'string' || !ID_PATTERN.test(s.kekId)) {
136
+ throw new HeldEdgeError('bad_request', 'sealed.kekId does not match the id pattern');
137
+ }
138
+ const wrappedKey = fromBase64Url(s.wrappedKey);
139
+ const iv = fromBase64Url(s.iv);
140
+ const ct = fromBase64Url(s.ct);
141
+ if (wrappedKey?.length !== WRAPPED_KEY_BYTES ||
142
+ iv?.length !== IV_BYTES ||
143
+ !ct ||
144
+ ct.length < TAG_BYTES) {
145
+ throw new HeldEdgeError('bad_request', 'sealed has a malformed field');
146
+ }
147
+ const ms = checkTimeout(o.timeoutMs);
148
+ const binding = { tenantId: o.tenantId, entryId: o.entryId, version: s.version };
149
+ const aad = encodeAad(binding);
150
+ const result = await withTimeout(o.worker.unwrap({
151
+ requestId: crypto.randomUUID(),
152
+ credential: o.credential,
153
+ kekId: s.kekId,
154
+ wrappedKey,
155
+ binding,
156
+ }), ms);
157
+ if (!result.ok)
158
+ throw fromWorker(result.error.code);
159
+ const dataKey = result.dataKey;
160
+ try {
161
+ const key = await importDataKey(dataKey, 'decrypt');
162
+ let plain;
163
+ try {
164
+ plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, ct);
165
+ }
166
+ catch {
167
+ // The WebCrypto error is dropped: it says nothing a caller may use.
168
+ throw new HeldEdgeError('unseal_failed', 'that version could not be opened with the given data key');
169
+ }
170
+ return new TextDecoder().decode(plain);
171
+ }
172
+ finally {
173
+ dataKey.fill(0);
174
+ }
175
+ }
@@ -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>;