@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
@@ -0,0 +1,180 @@
1
+ import { generateKeyPairSync, sign as signWithKey, verify as verifyWithKey, webcrypto, } from 'node:crypto';
2
+ import { encodeAad } from '../held/aad.js';
3
+ import { aesGcmOpen, aesGcmSeal } from '../held/seal.js';
4
+ import { canonicalJson, encodeSigned, pickSignable } from '../issued/encoding.js';
5
+ /**
6
+ * An in-process stand-in for the unwrap Worker (`packages/worker`), for
7
+ * every host test that needs a `WorkerClient<TGrant>` without a live
8
+ * Worker. Implements the full contract -- `wrap`/`unwrap`/`rewrap` for
9
+ * `./held`, `signRow`/`resign`/`recordEviction` for `./issued` -- with the
10
+ * package's own real signing, AAD and sealing code, not a reimplementation:
11
+ * it imports `encodeSigned`/`canonicalJson`/`pickSignable` from `../issued/
12
+ * encoding.js`, `encodeAad` from `../held/aad.js`, and `aesGcmSeal`/
13
+ * `aesGcmOpen` from `../held/seal.js` -- the same module
14
+ * `packages/worker/src/crypto.ts` imports for its own AES-256-GCM layout
15
+ * (#86: before this, the two copies could drift silently) -- rather than
16
+ * duplicating any of them, so a signature or a sealed key this stub
17
+ * produces is verified the same way a real Worker's would be -- proven by
18
+ * `worker-stub.test.ts`, which runs `check()` (`../issued`) and `open()`
19
+ * (`../held`) against rows this stub signed and sealed, and by
20
+ * `../../../worker/src/crypto.test.ts`, which opens a value sealed through
21
+ * this same module with the Worker's own re-exported `aesGcmOpen`, and the
22
+ * reverse.
23
+ *
24
+ * This is what every host's own `tests/keys-worker-stub.ts` re-implemented
25
+ * by hand (issue #83, "checked by hand against dist/issued/index.d.ts") --
26
+ * see the package README's "Adopting ./testing".
27
+ *
28
+ * Signing uses `node:crypto`'s classic, synchronous `generateKeyPairSync`/
29
+ * `sign`/`verify` rather than `webcrypto.subtle`: both produce and check
30
+ * the same RFC 8032 Ed25519 signatures -- `worker-stub.test.ts` proves it
31
+ * by running `../issued/verify.js`'s own `verifyIssuedRowSignature`
32
+ * (which uses `webcrypto.subtle.verify`) against a signature this stub
33
+ * produced -- but being synchronous, it lets `verifyKeys`/`verifyKeysEnv`
34
+ * be plain properties instead of a promise a caller would have to await
35
+ * before building `KEYS_VERIFY_KEYS`.
36
+ */
37
+ // ---------------------------------------------------------------------------
38
+ // The stub
39
+ // ---------------------------------------------------------------------------
40
+ /** Every credential this stub accepts. Anything else is `credential_invalid`, exactly as a real bad bearer token would be. */
41
+ export const TEST_CREDENTIAL = 'stub-test-credential';
42
+ const KEK_ID = 'kek-test';
43
+ const SIGN_GENERATION_ID = 'sign-test';
44
+ function failure(code, retryAfterMs) {
45
+ return {
46
+ ok: false,
47
+ error: retryAfterMs !== undefined ? { code, retryAfterMs } : { code },
48
+ };
49
+ }
50
+ function publicKeyRawOf(key) {
51
+ const jwk = key.export({ format: 'jwk' });
52
+ if (!jwk.x) {
53
+ throw new Error('createKeysWorkerStub: Ed25519 public key export had no JWK x coordinate');
54
+ }
55
+ return new Uint8Array(Buffer.from(jwk.x, 'base64url'));
56
+ }
57
+ /** `canonicalJson`, `encodeSigned` and `pickSignable` are the package's own -- re-exported by `./testing/index.js`, not reimplemented here. */
58
+ export function createKeysWorkerStub(options = {}) {
59
+ const now = options.now ?? (() => Date.now());
60
+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');
61
+ const publicKeyRaw = publicKeyRawOf(publicKey);
62
+ const kek = webcrypto.getRandomValues(new Uint8Array(32));
63
+ const callCounts = {
64
+ wrap: 0,
65
+ unwrap: 0,
66
+ rewrap: 0,
67
+ signRow: 0,
68
+ resign: 0,
69
+ recordEviction: 0,
70
+ };
71
+ let forced = null;
72
+ function record(method) {
73
+ callCounts[method] += 1;
74
+ if (forced && (forced.method === method || forced.method === 'all')) {
75
+ return failure(forced.code, forced.retryAfterMs);
76
+ }
77
+ return null;
78
+ }
79
+ function signRowBytes(row) {
80
+ return new Uint8Array(signWithKey(null, encodeSigned('issued-row', pickSignable(row)), privateKey));
81
+ }
82
+ function verifyRowSignature(row, signature) {
83
+ return verifyWithKey(null, encodeSigned('issued-row', pickSignable(row)), publicKey, signature);
84
+ }
85
+ const client = {
86
+ async wrap(req) {
87
+ const forcedFailure = record('wrap');
88
+ if (forcedFailure)
89
+ return forcedFailure;
90
+ if (req.credential !== TEST_CREDENTIAL)
91
+ return failure('credential_invalid');
92
+ const dataKey = webcrypto.getRandomValues(new Uint8Array(32));
93
+ const wrappedKey = await aesGcmSeal(kek, dataKey, encodeAad(req.binding));
94
+ return { ok: true, dataKey, wrappedKey, kekId: KEK_ID };
95
+ },
96
+ async unwrap(req) {
97
+ const forcedFailure = record('unwrap');
98
+ if (forcedFailure)
99
+ return forcedFailure;
100
+ if (req.credential !== TEST_CREDENTIAL)
101
+ return failure('credential_invalid');
102
+ if (req.kekId !== KEK_ID)
103
+ return failure('unknown_generation');
104
+ const dataKey = await aesGcmOpen(kek, req.wrappedKey, encodeAad(req.binding));
105
+ if (!dataKey)
106
+ return failure('aad_mismatch');
107
+ return { ok: true, dataKey };
108
+ },
109
+ async rewrap(req) {
110
+ const forcedFailure = record('rewrap');
111
+ if (forcedFailure)
112
+ return forcedFailure;
113
+ if (req.credential !== TEST_CREDENTIAL)
114
+ return failure('credential_invalid');
115
+ if (req.kekIdOld !== KEK_ID || req.kekIdNew !== KEK_ID)
116
+ return failure('unknown_generation');
117
+ const aad = encodeAad(req.binding);
118
+ const dataKey = await aesGcmOpen(kek, req.wrappedKey, aad);
119
+ if (!dataKey)
120
+ return failure('aad_mismatch');
121
+ const wrappedKey = await aesGcmSeal(kek, dataKey, aad);
122
+ return { ok: true, wrappedKey };
123
+ },
124
+ async signRow(req) {
125
+ const forcedFailure = record('signRow');
126
+ if (forcedFailure)
127
+ return forcedFailure;
128
+ if (req.credential !== TEST_CREDENTIAL)
129
+ return failure('credential_invalid');
130
+ const { candidate, minter } = req;
131
+ if (minter) {
132
+ if (!verifyRowSignature(minter.row, minter.signature)) {
133
+ return failure('bad_minter_signature');
134
+ }
135
+ if (minter.row.expiresAt <= now())
136
+ return failure('minter_expired');
137
+ }
138
+ // Minimal lineage check -- the mint log and resign/recordEviction
139
+ // sweeps a real Worker keeps are out of this stub's scope.
140
+ const expectedIssuedById = minter ? minter.row.id : null;
141
+ if (candidate.issuedById !== expectedIssuedById)
142
+ return failure('lineage_mismatch');
143
+ return { ok: true, signature: signRowBytes(candidate), generationId: SIGN_GENERATION_ID };
144
+ },
145
+ async resign(req) {
146
+ const forcedFailure = record('resign');
147
+ if (forcedFailure)
148
+ return forcedFailure;
149
+ if (req.credential !== TEST_CREDENTIAL)
150
+ return failure('credential_invalid');
151
+ if (req.oldGenerationId !== SIGN_GENERATION_ID)
152
+ return failure('unknown_generation');
153
+ if (!verifyRowSignature(req.row, req.oldSignature))
154
+ return failure('bad_old_signature');
155
+ return { ok: true, signature: signRowBytes(req.row), generationId: SIGN_GENERATION_ID };
156
+ },
157
+ async recordEviction(req) {
158
+ const forcedFailure = record('recordEviction');
159
+ if (forcedFailure)
160
+ return forcedFailure;
161
+ if (req.credential !== TEST_CREDENTIAL)
162
+ return failure('credential_invalid');
163
+ return { ok: true, receiptId: `receipt-${req.credentialId}-${req.revokedAt}` };
164
+ },
165
+ };
166
+ return Object.assign(client, {
167
+ verifyKeys: [publicKeyRaw],
168
+ verifyKeysEnv: Buffer.from(publicKeyRaw).toString('base64url'),
169
+ callCounts,
170
+ failAs(method, code, retryAfterMs) {
171
+ forced = { method, code, retryAfterMs };
172
+ },
173
+ clearFailure() {
174
+ forced = null;
175
+ },
176
+ });
177
+ }
178
+ // Re-exported by ./testing/index.js so a host's own fixture code can build
179
+ // custom signable bytes without depending on this file's internals.
180
+ export { canonicalJson, encodeSigned, pickSignable };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/keys",
3
- "version": "0.4.2",
3
+ "version": "0.7.0",
4
4
  "description": "The estate's own bearer keys, issued to callers and held on their behalf: two entries, issued and held, nothing stored in common.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -24,10 +24,18 @@
24
24
  "types": "./dist/held/index.d.ts",
25
25
  "default": "./dist/held/index.js"
26
26
  },
27
+ "./held-edge": {
28
+ "types": "./dist/held-edge/index.d.ts",
29
+ "default": "./dist/held-edge/index.js"
30
+ },
27
31
  "./webhooks": {
28
32
  "types": "./dist/webhooks.d.ts",
29
33
  "default": "./dist/webhooks.js"
30
34
  },
35
+ "./migrations-dir": {
36
+ "types": "./dist/migrations-dir.d.ts",
37
+ "default": "./dist/migrations-dir.js"
38
+ },
31
39
  "./migrations/*.sql": "./dist/migrations/*.sql",
32
40
  "./package.json": "./package.json",
33
41
  "./worker": {
@@ -37,6 +45,14 @@
37
45
  "./build": {
38
46
  "types": "./dist/build/index.d.ts",
39
47
  "default": "./dist/build/index.js"
48
+ },
49
+ "./host": {
50
+ "types": "./dist/host/index.d.ts",
51
+ "default": "./dist/host/index.js"
52
+ },
53
+ "./testing": {
54
+ "types": "./dist/testing/index.d.ts",
55
+ "default": "./dist/testing/index.js"
40
56
  }
41
57
  },
42
58
  "sideEffects": false,
@@ -47,18 +63,19 @@
47
63
  "node": ">=22.0.0"
48
64
  },
49
65
  "scripts": {
50
- "build": "rm -rf dist && tsc -p tsconfig.build.json && mkdir -p dist/migrations && find src/migrations -maxdepth 1 -name '*.sql' -exec cp {} dist/migrations/ \\;",
66
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && mkdir -p dist/migrations && cp -R src/migrations/issued src/migrations/held src/migrations/host dist/migrations/",
51
67
  "prepack": "pnpm build",
52
68
  "typecheck": "tsc --noEmit",
53
69
  "test": "vitest run"
54
70
  },
55
71
  "peerDependencies": {
56
- "drizzle-orm": ">=0.45.2"
72
+ "drizzle-orm": ">=0.45.2 <1.0.0"
57
73
  },
58
74
  "devDependencies": {
59
75
  "@electric-sql/pglite": "^0.5.8",
60
76
  "@types/node": "^22",
61
- "drizzle-orm": "^0.45.2",
77
+ "@wtfalch/db": "0.5.2",
78
+ "drizzle-orm": "0.45.2",
62
79
  "postgres": "^3.4.5",
63
80
  "typescript": "^5.9.0",
64
81
  "vitest": "^4.1.6"
@@ -1,52 +0,0 @@
1
- -- #47: a built-in `environment` on every issued credential, so a host's
2
- -- sandbox/live split is a structured field rather than a convention the host
3
- -- invents on top of `key_prefix`. Additive; do not edit copied migrations.
4
- --
5
- -- Not part of SignableRow (worker-contract.ts): the Worker's signature never
6
- -- covers it, same footing as idempotency_key and created_at. What keeps it
7
- -- trustworthy despite that is keys_issued_guard() below, extended to refuse
8
- -- any UPDATE that changes it -- set once at issue(), for that row's life.
9
- --
10
- -- Backfilled 'live' on existing rows: every row minted before this migration
11
- -- was minted under a single, unqualified prefix, which today's default
12
- -- environment ('live') matches.
13
- alter table keys_issued_credentials
14
- add column if not exists environment text not null default 'live';
15
- alter table keys_issued_credentials alter column environment drop default;
16
-
17
- do $$
18
- begin
19
- if not exists (
20
- select 1 from pg_constraint
21
- where conname = 'keys_issued_credentials_environment_check'
22
- ) then
23
- alter table keys_issued_credentials
24
- add constraint keys_issued_credentials_environment_check
25
- check (environment in ('live', 'test'));
26
- end if;
27
- end
28
- $$;
29
-
30
- -- Extends 0004's keys_issued_guard(): identity, lineage AND environment are
31
- -- immutable once a row is inserted.
32
- create or replace function public.keys_issued_guard() returns trigger
33
- language plpgsql
34
- set search_path = pg_catalog, public, pg_temp
35
- as $$
36
- begin
37
- if tg_op in ('DELETE', 'TRUNCATE') then
38
- raise exception 'keys_issued_credentials: delete and truncate refused';
39
- end if;
40
- if tg_op = 'UPDATE' then
41
- if new.id is distinct from old.id or new.issued_by_id is distinct from old.issued_by_id
42
- or new.key_prefix is distinct from old.key_prefix
43
- or new.environment is distinct from old.environment then
44
- raise exception 'keys_issued_credentials: identity, lineage and environment are immutable';
45
- end if;
46
- if old.revoked_at is not null and new.revoked_at is distinct from old.revoked_at then
47
- raise exception 'keys_issued_credentials: revocation is permanent';
48
- end if;
49
- end if;
50
- return new;
51
- end
52
- $$;
@@ -1,46 +0,0 @@
1
- -- The issued-credential guard from 0004_keys_security.sql (K03), on its own.
2
- -- Additive; do not edit copied migrations.
3
- --
4
- -- 0004 also changes triggers on keys_held_versions, so a host that uses only
5
- -- the issued module (0001, 0005-0008, no 0002/0003) cannot apply it. Without
6
- -- this file such a host has no guard: a revoked credential could be
7
- -- un-revoked, or deleted and inserted again. The function body is 0005's, the
8
- -- newest (it also freezes environment), so this needs 0005 first. The
9
- -- triggers and the revoke are 0004's. Running it after 0004 and 0005 changes
10
- -- nothing.
11
- create or replace function public.keys_issued_guard() returns trigger
12
- language plpgsql
13
- set search_path = pg_catalog, public, pg_temp
14
- as $$
15
- begin
16
- if tg_op in ('DELETE', 'TRUNCATE') then
17
- raise exception 'keys_issued_credentials: delete and truncate refused';
18
- end if;
19
- if tg_op = 'UPDATE' then
20
- if new.id is distinct from old.id or new.issued_by_id is distinct from old.issued_by_id
21
- or new.key_prefix is distinct from old.key_prefix
22
- or new.environment is distinct from old.environment then
23
- raise exception 'keys_issued_credentials: identity, lineage and environment are immutable';
24
- end if;
25
- if old.revoked_at is not null and new.revoked_at is distinct from old.revoked_at then
26
- raise exception 'keys_issued_credentials: revocation is permanent';
27
- end if;
28
- end if;
29
- return new;
30
- end
31
- $$;
32
- drop trigger if exists keys_issued_guard_update on public.keys_issued_credentials;
33
- create trigger keys_issued_guard_update before update or delete on public.keys_issued_credentials
34
- for each row execute function public.keys_issued_guard();
35
- drop trigger if exists keys_issued_guard_truncate on public.keys_issued_credentials;
36
- create trigger keys_issued_guard_truncate before truncate on public.keys_issued_credentials
37
- for each statement execute function public.keys_issued_guard();
38
-
39
- do $$
40
- declare rt text := current_database() || '_rt';
41
- begin
42
- if exists (select 1 from pg_roles where rolname = rt) then
43
- execute format('revoke delete, truncate on public.keys_issued_credentials from %I', rt);
44
- end if;
45
- end
46
- $$;