@wtfalch/keys 0.2.1 → 0.4.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.
package/README.md CHANGED
@@ -27,3 +27,50 @@ Apply the additive `0004_keys_security.sql` migration in every consumer database
27
27
  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
28
 
29
29
  Held keys use active cache expiry (60 seconds by default) and retain at most 256 versions per instance. Set `cacheSeconds: 0` or `maxCacheEntries: 0` to disable caching. Call `dispose()` to zero cached keys, clear timers and refuse further operations. A local forget/revocation invalidates pending opens; other processes remain bounded by their own cache TTL. Plaintext callbacks can copy or return values, so their lifetime cannot be enforced by the SDK.
30
+
31
+ ## Issued-key environments
32
+
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`.
34
+
35
+ ## Issued-key usage tracking
36
+
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`.
38
+
39
+ ## Per-issued-key rate limits
40
+
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.
42
+
43
+ ## Outbound webhooks
44
+
45
+ `@wtfalch/keys/webhooks`'s `createWebhookDispatcher({ url, secret? })` returns a function that POSTs a lifecycle event as JSON — a drop-in for `./issued`'s `audit` option (`credential.minted` / `.rotated` / `.revoked`) or `./held`'s (`key.used`). With `secret`, the body is HMAC-SHA256-signed into an `X-Keys-Signature` header; the receiver checks it with `verifyWebhookSignature(body, signature, secret)`. Delivery is fire-and-forget and best-effort — a subscriber outage never fails the call that produced the event, it only calls `onDeliveryError`.
46
+
47
+ ## Worker transport
48
+
49
+ `createWorkerClient<TGrant>({ url, fetch?, timeoutMs? })` from
50
+ `@wtfalch/keys/worker` implements the shared Worker contract. Pass an HTTPS origin;
51
+ paths, query strings, fragments and URL credentials are refused. It validates
52
+ response shapes and key sizes, refuses redirects, and returns `unreachable` for
53
+ transport/protocol failures. It makes one attempt per call: a request ID is audit
54
+ correlation, not an idempotency guarantee. Host authentication and grant policy
55
+ remain outside the transport. Existing injected clients remain supported.
56
+
57
+ ## Build inputs
58
+
59
+ See [build-time delivery](https://github.com/wtfalch/keys/blob/main/packages/keys/BUILD.md) for delegated build credentials, the host
60
+ endpoint boundary, required BuildKit mounts, explicit bootstrap delivery and
61
+ output/image-layer canary checks. `@wtfalch/keys/build` exports the delivery
62
+ helpers; `keys-build` and `keys-build-scan` are the executable entries.
63
+
64
+ ## Current held values
65
+
66
+ `held.openCurrent({ tenantId, entryId }, use)` selects the highest successfully
67
+ sealed version once, then opens that binding. Pending or failed reservations do
68
+ not hide the preceding value. The existing `held.open(binding, use)` remains the
69
+ version-pinned operation. See the [selection and cache contract](https://github.com/wtfalch/keys/blob/main/packages/keys/src/held/open-current.md).
70
+
71
+ ## Signing generation migration
72
+
73
+ `createSigningGenerationMigrator` from `@wtfalch/keys/issued` provides bounded,
74
+ resumable operator batches that preserve existing bearer secrets. Follow the
75
+ [signing migration runbook](https://github.com/wtfalch/keys/blob/main/packages/keys/src/issued/SIGNING_GENERATION_MIGRATION.md)
76
+ for verification, concurrency and retirement requirements.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises';
3
+ import { scanBuildOutputs } from '../build/scan.js';
4
+ async function main() {
5
+ const [canaryFile, ...paths] = process.argv.slice(2);
6
+ if (!canaryFile)
7
+ throw new Error('missing canary file');
8
+ const values = JSON.parse(await readFile(canaryFile, 'utf8'));
9
+ if (!Array.isArray(values) || values.some((v) => typeof v !== 'string'))
10
+ throw new Error('invalid canaries');
11
+ await scanBuildOutputs(paths, values);
12
+ }
13
+ main().catch(() => {
14
+ process.stderr.write('keys-build-scan: output refused\n');
15
+ process.exitCode = 1;
16
+ });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { fetchBuildValues, readBuildPayload } from '../build/index.js';
5
+ // The spec is trusted build configuration, never a server-supplied command.
6
+ async function main() {
7
+ const [specFile, separator, command, ...args] = process.argv.slice(2);
8
+ if (!specFile || separator !== '--' || !command)
9
+ throw new Error('usage');
10
+ const spec = JSON.parse(await readFile(specFile, 'utf8'));
11
+ let payload;
12
+ if (spec.bootstrapFile) {
13
+ if (spec.url || spec.credentialFile)
14
+ throw new Error('ambiguous delivery mode');
15
+ payload = readBuildPayload(JSON.parse(await readFile(spec.bootstrapFile, 'utf8')), spec.inputs);
16
+ }
17
+ else {
18
+ if (!spec.url)
19
+ throw new Error('url required');
20
+ const credential = (await readFile(spec.credentialFile ?? '/run/secrets/keys_build_credential', 'utf8')).trim();
21
+ payload = await fetchBuildValues({ url: spec.url, credential, inputs: spec.inputs });
22
+ }
23
+ const env = Object.assign(Object.create(null), process.env);
24
+ for (const entry of payload.values)
25
+ env[entry.name] = entry.value;
26
+ const child = spawn(command, args, { env, stdio: 'inherit', shell: false });
27
+ for (const entry of payload.values)
28
+ delete env[entry.name];
29
+ child.once('error', () => {
30
+ process.stderr.write('keys-build: command failed\n');
31
+ process.exitCode = 1;
32
+ });
33
+ child.once('exit', (code) => {
34
+ process.exitCode = code ?? 1;
35
+ });
36
+ }
37
+ main().catch(() => {
38
+ process.stderr.write('keys-build: delivery refused\n');
39
+ process.exitCode = 1;
40
+ });
@@ -0,0 +1,64 @@
1
+ import type { HeldKeys } from '../held/index.js';
2
+ import type { CredentialIssuer, IssueResult } from '../issued/index.js';
3
+ import { type KeyBinding } from '../worker-contract.js';
4
+ export type BuildVisibility = 'public' | 'secret';
5
+ export interface BuildInput {
6
+ readonly name: string;
7
+ readonly binding: KeyBinding;
8
+ /** Secret delivery requires explicit opt-in plus host authorization. */
9
+ readonly visibility?: BuildVisibility;
10
+ }
11
+ export interface BuildValue extends BuildInput {
12
+ readonly visibility: BuildVisibility;
13
+ readonly value: string;
14
+ }
15
+ export interface BuildPayload {
16
+ readonly version: 1;
17
+ readonly expiresAt: number;
18
+ readonly values: readonly BuildValue[];
19
+ }
20
+ export declare class BuildDeliveryError extends Error {
21
+ constructor();
22
+ }
23
+ /**
24
+ * Host-side delegation. The host must authorize attenuation and encode its own
25
+ * grants; this package never interprets application grants. The runtime bearer
26
+ * is verified, used as the parent, and never passed to the image build.
27
+ */
28
+ export declare function issueBuildCredential<TGrant>(options: {
29
+ readonly issuer: Pick<CredentialIssuer<TGrant>, 'check' | 'issue'>;
30
+ readonly runtimeSecret: string;
31
+ readonly inputs: readonly BuildInput[];
32
+ readonly expiresAt: number;
33
+ readonly now?: () => number;
34
+ readonly authorize: (parent: {
35
+ readonly id: string;
36
+ readonly grants: readonly TGrant[];
37
+ }, inputs: readonly BuildInput[], expiresAt: number) => Promise<readonly TGrant[]>;
38
+ }): Promise<IssueResult>;
39
+ /** Host-side normal endpoint AND trusted bootstrap prefetch, sharing one policy. */
40
+ export declare function createBuildDelivery(options: {
41
+ readonly held: Pick<HeldKeys, 'open'>;
42
+ readonly now?: () => number;
43
+ /**
44
+ * Verify the delegated bearer, its parent/revocation and expiry, attenuated
45
+ * authority, and authoritative classification for every exact binding.
46
+ * Return the effective expiry (no later than the parent or child expiry).
47
+ * Throw on any denial. Never trust a caller's claimed public classification.
48
+ */
49
+ readonly authorize: (credential: string, inputs: readonly BuildInput[]) => Promise<{
50
+ readonly expiresAt: number;
51
+ }>;
52
+ }): (credential: string, inputs: readonly BuildInput[]) => Promise<BuildPayload>;
53
+ /** Validate a trusted, mounted bootstrap payload or a normal endpoint response. */
54
+ export declare function readBuildPayload(payload: unknown, inputs: readonly BuildInput[], now?: number): BuildPayload;
55
+ /** Default network path. Errors never silently fall back to a bootstrap payload. */
56
+ export declare function fetchBuildValues(options: {
57
+ readonly url: string;
58
+ readonly credential: string;
59
+ readonly inputs: readonly BuildInput[];
60
+ readonly fetch?: typeof fetch;
61
+ readonly timeoutMs?: number;
62
+ readonly now?: () => number;
63
+ }): Promise<BuildPayload>;
64
+ export { scanBuildOutputs } from './scan.js';
@@ -0,0 +1,156 @@
1
+ import { ID_PATTERN } from '../worker-contract.js';
2
+ export class BuildDeliveryError extends Error {
3
+ constructor() {
4
+ // No response bodies, credentials, values or underlying transport errors.
5
+ super('build key delivery refused');
6
+ this.name = 'BuildDeliveryError';
7
+ }
8
+ }
9
+ function refuse() {
10
+ throw new BuildDeliveryError();
11
+ }
12
+ function validateInputs(inputs) {
13
+ if (!Array.isArray(inputs) || inputs.length === 0 || inputs.length > 100)
14
+ refuse();
15
+ const names = new Set();
16
+ for (const input of inputs) {
17
+ if (!input || !/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(input.name) || names.has(input.name))
18
+ refuse();
19
+ names.add(input.name);
20
+ const b = input.binding;
21
+ if (!b ||
22
+ typeof b.tenantId !== 'string' ||
23
+ typeof b.entryId !== 'string' ||
24
+ !ID_PATTERN.test(b.tenantId) ||
25
+ !ID_PATTERN.test(b.entryId) ||
26
+ !Number.isSafeInteger(b.version) ||
27
+ b.version < 1)
28
+ refuse();
29
+ if (input.visibility !== undefined &&
30
+ input.visibility !== 'public' &&
31
+ input.visibility !== 'secret')
32
+ refuse();
33
+ }
34
+ }
35
+ function sameInput(a, b) {
36
+ return (a.name === b.name &&
37
+ a.binding.tenantId === b.binding.tenantId &&
38
+ a.binding.entryId === b.binding.entryId &&
39
+ a.binding.version === b.binding.version &&
40
+ (a.visibility ?? 'public') === (b.visibility ?? 'public'));
41
+ }
42
+ /**
43
+ * Host-side delegation. The host must authorize attenuation and encode its own
44
+ * grants; this package never interprets application grants. The runtime bearer
45
+ * is verified, used as the parent, and never passed to the image build.
46
+ */
47
+ export async function issueBuildCredential(options) {
48
+ try {
49
+ validateInputs(options.inputs);
50
+ if (!Number.isSafeInteger(options.expiresAt) ||
51
+ options.expiresAt <= (options.now ?? Date.now)())
52
+ refuse();
53
+ const inputs = options.inputs.map((input) => ({
54
+ ...input,
55
+ binding: { ...input.binding },
56
+ visibility: input.visibility ?? 'public',
57
+ }));
58
+ const parent = await options.issuer.check(options.runtimeSecret);
59
+ if (!parent.ok)
60
+ refuse();
61
+ const grants = await options.authorize({ id: parent.id, grants: parent.grants }, inputs, options.expiresAt);
62
+ return options.issuer.issue({ minter: parent.id, grants, expiresAt: options.expiresAt });
63
+ }
64
+ catch {
65
+ return refuse();
66
+ }
67
+ }
68
+ /** Host-side normal endpoint AND trusted bootstrap prefetch, sharing one policy. */
69
+ export function createBuildDelivery(options) {
70
+ return async (credential, inputs) => {
71
+ try {
72
+ validateInputs(inputs);
73
+ if (typeof credential !== 'string' || !credential)
74
+ refuse();
75
+ const selected = inputs.map((input) => ({
76
+ ...input,
77
+ binding: { ...input.binding },
78
+ visibility: input.visibility ?? 'public',
79
+ }));
80
+ const { expiresAt } = await options.authorize(credential, selected);
81
+ const now = options.now ?? Date.now;
82
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= now())
83
+ refuse();
84
+ const values = [];
85
+ for (const input of selected) {
86
+ const value = await options.held.open(input.binding, async (value) => value);
87
+ values.push({ ...input, value });
88
+ }
89
+ if (expiresAt <= now())
90
+ refuse();
91
+ return { version: 1, expiresAt, values };
92
+ }
93
+ catch {
94
+ return refuse();
95
+ }
96
+ };
97
+ }
98
+ /** Validate a trusted, mounted bootstrap payload or a normal endpoint response. */
99
+ export function readBuildPayload(payload, inputs, now = Date.now()) {
100
+ try {
101
+ validateInputs(inputs);
102
+ const p = payload;
103
+ if (!p ||
104
+ p.version !== 1 ||
105
+ !Number.isSafeInteger(p.expiresAt) ||
106
+ p.expiresAt <= now ||
107
+ !Array.isArray(p.values) ||
108
+ p.values.length !== inputs.length)
109
+ refuse();
110
+ validateInputs(p.values);
111
+ for (let i = 0; i < inputs.length; i++) {
112
+ const value = p.values[i];
113
+ const input = inputs[i];
114
+ if (!value || !input || typeof value.value !== 'string' || !sameInput(value, input))
115
+ refuse();
116
+ }
117
+ return p;
118
+ }
119
+ catch {
120
+ return refuse();
121
+ }
122
+ }
123
+ /** Default network path. Errors never silently fall back to a bootstrap payload. */
124
+ export async function fetchBuildValues(options) {
125
+ try {
126
+ validateInputs(options.inputs);
127
+ const url = new URL(options.url);
128
+ if (url.protocol !== 'https:' ||
129
+ url.username ||
130
+ url.password ||
131
+ url.hash ||
132
+ url.search ||
133
+ !options.credential)
134
+ refuse();
135
+ const timeout = options.timeoutMs ?? 10_000;
136
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 2_147_483_647)
137
+ refuse();
138
+ const response = await (options.fetch ?? fetch)(url, {
139
+ method: 'POST',
140
+ redirect: 'error',
141
+ signal: AbortSignal.timeout(timeout),
142
+ headers: {
143
+ authorization: `Bearer ${options.credential}`,
144
+ 'content-type': 'application/json',
145
+ },
146
+ body: JSON.stringify({ inputs: options.inputs }),
147
+ });
148
+ if (response.status !== 200)
149
+ refuse();
150
+ return readBuildPayload(await response.json(), options.inputs, (options.now ?? Date.now)());
151
+ }
152
+ catch {
153
+ return refuse();
154
+ }
155
+ }
156
+ export { scanBuildOutputs } from './scan.js';
@@ -0,0 +1,2 @@
1
+ /** Canary evidence only: transformations and network exfiltration are not detectable. */
2
+ export declare function scanBuildOutputs(paths: readonly string[], forbiddenValues: readonly string[]): Promise<void>;
@@ -0,0 +1,83 @@
1
+ import { lstat, readFile, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { gunzipSync } from 'node:zlib';
4
+ /** Canary evidence only: transformations and network exfiltration are not detectable. */
5
+ export async function scanBuildOutputs(paths, forbiddenValues) {
6
+ if (paths.length === 0 || forbiddenValues.length === 0 || forbiddenValues.some((v) => !v))
7
+ throw new Error('scan requires outputs and nonempty canaries');
8
+ const needles = forbiddenValues
9
+ .flatMap((v) => {
10
+ const hex = Buffer.from(v).toString('hex');
11
+ const spacedHex = hex.replace(/(..)/g, '$1 ').trim();
12
+ return [
13
+ v,
14
+ Buffer.from(v).toString('base64'),
15
+ Buffer.from(v).toString('base64url'),
16
+ hex,
17
+ hex.toUpperCase(),
18
+ spacedHex,
19
+ spacedHex.toUpperCase(),
20
+ JSON.stringify(v).slice(1, -1),
21
+ ];
22
+ })
23
+ .map((v) => Buffer.from(v));
24
+ const maxBytes = 256 * 1024 * 1024;
25
+ function inspect(data, tar, depth = 0) {
26
+ if (depth > 8 || data.length > maxBytes)
27
+ throw new Error('scan input exceeds limits');
28
+ if (needles.some((n) => data.includes(n)))
29
+ throw new Error('build output contains a forbidden value');
30
+ if (['28b52ffd', '425a68', 'fd377a585a00', '504b0304'].some((magic) => data.subarray(0, magic.length / 2).toString('hex') === magic)) {
31
+ throw new Error('unsupported compressed scan input');
32
+ }
33
+ if (data[0] === 0x1f && data[1] === 0x8b) {
34
+ inspect(gunzipSync(data, { maxOutputLength: maxBytes }), tar, depth + 1);
35
+ return;
36
+ }
37
+ if (!tar)
38
+ return;
39
+ let offset = 0;
40
+ while (offset + 512 <= data.length) {
41
+ const header = data.subarray(offset, offset + 512);
42
+ if (header.every((v) => v === 0)) {
43
+ if (data.subarray(offset).some((v) => v !== 0))
44
+ throw new Error('invalid archive trailer');
45
+ return;
46
+ }
47
+ const sizeText = header.subarray(124, 136).toString('ascii').replace(/\0.*$/, '').trim();
48
+ const checksumText = header.subarray(148, 156).toString('ascii').replace(/\0.*$/, '').trim();
49
+ if (!/^[0-7]+$/.test(sizeText) || !/^[0-7]+$/.test(checksumText))
50
+ throw new Error('unsupported tar header');
51
+ let checksum = 0;
52
+ for (let i = 0; i < 512; i++)
53
+ checksum += i >= 148 && i < 156 ? 32 : (header[i] ?? 0);
54
+ if (checksum !== Number.parseInt(checksumText, 8))
55
+ throw new Error('invalid archive checksum');
56
+ const size = Number.parseInt(sizeText, 8);
57
+ if (offset + 512 + size > data.length)
58
+ throw new Error('truncated archive');
59
+ const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
60
+ const member = data.subarray(offset + 512, offset + 512 + size);
61
+ // Docker save contains layer.tar members. Gzip is decoded regardless of name.
62
+ inspect(member, name.endsWith('.tar') || name.endsWith('.tar.gz'), depth + 1);
63
+ offset += 512 + Math.ceil(size / 512) * 512;
64
+ }
65
+ throw new Error('archive has no complete end marker');
66
+ }
67
+ async function visit(path) {
68
+ const stat = await lstat(path);
69
+ if (stat.isSymbolicLink())
70
+ throw new Error('scan refuses symlinks');
71
+ if (stat.isDirectory()) {
72
+ for (const entry of await readdir(path))
73
+ await visit(join(path, entry));
74
+ return;
75
+ }
76
+ if (!stat.isFile() || stat.size > maxBytes)
77
+ throw new Error('unsupported scan input');
78
+ inspect(Buffer.from(path), false);
79
+ inspect(await readFile(path), path.endsWith('.tar') || path.endsWith('.tar.gz'));
80
+ }
81
+ for (const path of paths)
82
+ await visit(path);
83
+ }
@@ -78,6 +78,18 @@ export interface HeldKeys {
78
78
  put(entry: HeldEntryRef, value: string): Promise<{
79
79
  readonly version: number;
80
80
  }>;
81
+ /**
82
+ * Opens the highest version that has actually been sealed for `entry`.
83
+ * `currentVersion` is only a reservation counter, so failed or still-pending
84
+ * puts do not hide the last published version. The selecting statement is
85
+ * the operation's database linearization point; the selected version is
86
+ * never retried or rediscovered, and `use` is invoked at most once.
87
+ *
88
+ * This always reads the database to select a version. Once selected, that
89
+ * exact version may use the same accepted-key cache as `open`, including its
90
+ * no-unwrap/no-audit behavior on a cache hit.
91
+ */
92
+ openCurrent<T>(entry: HeldEntryRef, use: (value: string) => Promise<T>): Promise<T>;
81
93
  /**
82
94
  * Opens one version and hands the plaintext to `use`. The callback can
83
95
  * copy or return the value; this API cannot enforce its lifetime. A
@@ -1,5 +1,5 @@
1
1
  import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'node:crypto';
2
- import { and, eq, sql } from 'drizzle-orm';
2
+ import { and, desc, eq, sql } from 'drizzle-orm';
3
3
  import { ID_PATTERN, } from '../worker-contract.js';
4
4
  import { encodeAad } from './aad.js';
5
5
  import { keysHeldEntries, keysHeldVersions } from './schema.js';
@@ -221,38 +221,7 @@ export function createHeldKeys(options) {
221
221
  forgetEntry(entry);
222
222
  return { version };
223
223
  }
224
- async function open(binding, use) {
225
- requireActive();
226
- const openingEpoch = epoch;
227
- requireId(binding.tenantId, 'tenantId');
228
- requireId(binding.entryId, 'entryId');
229
- requireVersion(binding.version);
230
- const cached = cachedFor(binding);
231
- if (cached) {
232
- const value = gcmOpen(cached.dataKey, cached.iv, cached.ciphertext, encodeAad(binding));
233
- return use(value);
234
- }
235
- const [entryRow] = await db
236
- .select({ revokedAt: keysHeldEntries.revokedAt })
237
- .from(keysHeldEntries)
238
- .where(and(eq(keysHeldEntries.tenantId, binding.tenantId), eq(keysHeldEntries.entryId, binding.entryId)))
239
- .limit(1);
240
- if (!entryRow)
241
- throw new HeldKeysError('not_found', `there is no entry ${binding.entryId}`);
242
- if (entryRow.revokedAt)
243
- throw new HeldKeysError('revoked', `entry ${binding.entryId} is revoked`);
244
- const [versionRow] = await db
245
- .select({
246
- kekId: keysHeldVersions.kekId,
247
- wrappedKey: keysHeldVersions.wrappedKey,
248
- iv: keysHeldVersions.iv,
249
- ciphertext: keysHeldVersions.ciphertext,
250
- })
251
- .from(keysHeldVersions)
252
- .where(and(eq(keysHeldVersions.tenantId, binding.tenantId), eq(keysHeldVersions.entryId, binding.entryId), eq(keysHeldVersions.version, binding.version)))
253
- .limit(1);
254
- if (!versionRow)
255
- throw new HeldKeysError('not_found', `there is no version ${binding.version}`);
224
+ async function openSelected(binding, versionRow, openingEpoch, use) {
256
225
  if (versionRow.wrappedKey === null) {
257
226
  throw new HeldKeysError('not_found', `version ${binding.version} has been shredded`);
258
227
  }
@@ -292,6 +261,92 @@ export function createHeldKeys(options) {
292
261
  dataKey.fill(0);
293
262
  }
294
263
  }
264
+ async function open(binding, use) {
265
+ requireActive();
266
+ const openingEpoch = epoch;
267
+ requireId(binding.tenantId, 'tenantId');
268
+ requireId(binding.entryId, 'entryId');
269
+ requireVersion(binding.version);
270
+ const cached = cachedFor(binding);
271
+ if (cached) {
272
+ const value = gcmOpen(cached.dataKey, cached.iv, cached.ciphertext, encodeAad(binding));
273
+ return use(value);
274
+ }
275
+ const [entryRow] = await db
276
+ .select({ revokedAt: keysHeldEntries.revokedAt })
277
+ .from(keysHeldEntries)
278
+ .where(and(eq(keysHeldEntries.tenantId, binding.tenantId), eq(keysHeldEntries.entryId, binding.entryId)))
279
+ .limit(1);
280
+ if (!entryRow)
281
+ throw new HeldKeysError('not_found', `there is no entry ${binding.entryId}`);
282
+ if (entryRow.revokedAt)
283
+ throw new HeldKeysError('revoked', `entry ${binding.entryId} is revoked`);
284
+ const [versionRow] = await db
285
+ .select({
286
+ kekId: keysHeldVersions.kekId,
287
+ wrappedKey: keysHeldVersions.wrappedKey,
288
+ iv: keysHeldVersions.iv,
289
+ ciphertext: keysHeldVersions.ciphertext,
290
+ })
291
+ .from(keysHeldVersions)
292
+ .where(and(eq(keysHeldVersions.tenantId, binding.tenantId), eq(keysHeldVersions.entryId, binding.entryId), eq(keysHeldVersions.version, binding.version)))
293
+ .limit(1);
294
+ if (!versionRow)
295
+ throw new HeldKeysError('not_found', `there is no version ${binding.version}`);
296
+ return openSelected(binding, versionRow, openingEpoch, use);
297
+ }
298
+ async function openCurrent(entry, use) {
299
+ requireActive();
300
+ const openingEpoch = epoch;
301
+ requireId(entry.tenantId, 'tenantId');
302
+ requireId(entry.entryId, 'entryId');
303
+ // One statement chooses both the entry state and the highest version row
304
+ // visible in its snapshot. In particular, current_version is deliberately
305
+ // absent: put reserves it before the Worker call and may never publish the
306
+ // corresponding version row. When `db` is already a transaction handle,
307
+ // this statement simply participates in that transaction; no nested
308
+ // transaction, commit, or automatic retry is introduced here.
309
+ const [selected] = await db
310
+ .select({
311
+ revokedAt: keysHeldEntries.revokedAt,
312
+ version: keysHeldVersions.version,
313
+ kekId: keysHeldVersions.kekId,
314
+ wrappedKey: keysHeldVersions.wrappedKey,
315
+ iv: keysHeldVersions.iv,
316
+ ciphertext: keysHeldVersions.ciphertext,
317
+ })
318
+ .from(keysHeldEntries)
319
+ .leftJoin(keysHeldVersions, and(eq(keysHeldVersions.tenantId, keysHeldEntries.tenantId), eq(keysHeldVersions.entryId, keysHeldEntries.entryId)))
320
+ .where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
321
+ .orderBy(desc(keysHeldVersions.version))
322
+ .limit(1);
323
+ if (!selected)
324
+ throw new HeldKeysError('not_found', `there is no entry ${entry.entryId}`);
325
+ if (selected.revokedAt)
326
+ throw new HeldKeysError('revoked', `entry ${entry.entryId} is revoked`);
327
+ if (selected.version === null ||
328
+ selected.kekId === null ||
329
+ selected.iv === null ||
330
+ selected.ciphertext === null) {
331
+ throw new HeldKeysError('not_found', `entry ${entry.entryId} has no sealed version`);
332
+ }
333
+ const binding = { ...entry, version: selected.version };
334
+ const versionRow = {
335
+ kekId: selected.kekId,
336
+ wrappedKey: selected.wrappedKey,
337
+ iv: selected.iv,
338
+ ciphertext: selected.ciphertext,
339
+ };
340
+ const cached = cachedFor(binding);
341
+ if (cached) {
342
+ requireActive();
343
+ if (epoch !== openingEpoch)
344
+ throw new HeldKeysError('invalidated');
345
+ const value = gcmOpen(cached.dataKey, cached.iv, cached.ciphertext, encodeAad(binding));
346
+ return use(value);
347
+ }
348
+ return openSelected(binding, versionRow, openingEpoch, use);
349
+ }
295
350
  async function rewrap(rewrapOptions) {
296
351
  requireActive();
297
352
  const { kekIdOld, kekIdNew } = rewrapOptions;
@@ -363,5 +418,5 @@ export function createHeldKeys(options) {
363
418
  evict(key, hit);
364
419
  }
365
420
  }
366
- return { put, open, forget, dispose, rewrap, revokeEntry, archiveTenant };
421
+ return { put, open, openCurrent, forget, dispose, rewrap, revokeEntry, archiveTenant };
367
422
  }
@@ -1,7 +1,17 @@
1
1
  import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
2
2
  import type { SerializedCredential, VerifyKeys, WorkerClient, WorkerErrorCode } from '../worker-contract.js';
3
+ import type { RateLimiter } from './ratelimit.js';
3
4
  export { ID_PATTERN, SIGNED_PREFIX, type RequestMeta, type SerializedCredential, type SignableRow, type SignedKind, type SignedRow, type SignRowRequest, type SignRowResult, type SignRowSuccess, type VerifyKeys, type WorkerClient, type WorkerError, type WorkerErrorCode, type WorkerFailure, } from '../worker-contract.js';
5
+ export { createPostgresRateLimiter, type CreatePostgresRateLimiterOptions, type RateLimiter, type RateLimitResult, } from './ratelimit.js';
6
+ export { createSigningGenerationMigrator, MAX_RESIGN_BATCH_SIZE, type CreateSigningGenerationMigratorOptions, type ResignGenerationBatchRequest, type ResignGenerationBatchResult, type ResignGenerationRefusalReason, type SigningGenerationCursor, type SigningGenerationMigrator, } from './resign.js';
4
7
  export type Db = PgDatabase<PgQueryResultHKT, any, any>;
8
+ /**
9
+ * #47: a built-in sandbox/live split, so a stamped host does not invent its
10
+ * own convention on top of `prefix`. Stored on the row (`environment`,
11
+ * immutable once set) but never signed -- `prefix` alone still decides what
12
+ * a presented secret is, same as before this existed.
13
+ */
14
+ export type KeyEnvironment = 'live' | 'test';
5
15
  export interface AuditEvent {
6
16
  readonly name: 'credential.minted' | 'credential.rotated' | 'credential.revoked';
7
17
  readonly credentialId: string;
@@ -22,6 +32,13 @@ export interface CreateCredentialIssuerOptions<TGrant> {
22
32
  readonly audit?: AuditCallback;
23
33
  /** This host's split-secret prefix, e.g. `ai_live_`. Fixed per issuer; never inferred from a row. */
24
34
  readonly prefix: string;
35
+ /**
36
+ * #45: an abuse limit `check()` consults per credential `id`, spent on
37
+ * every attempt (matched secret or not) once a row is found. Omit it and
38
+ * `check()` behaves exactly as before this existed. `createPostgresRateLimiter`
39
+ * (this module) is a ready-made one backed by the host's own `db`.
40
+ */
41
+ readonly rateLimiter?: RateLimiter;
25
42
  /** Unix milliseconds. Defaults to `Date.now`; a test passes a fake clock. */
26
43
  readonly now?: () => number;
27
44
  }
@@ -32,8 +49,12 @@ export interface IssueRequest<TGrant> {
32
49
  /** Unix milliseconds. Required: refused when missing or already past, never clamped to the minter's own. */
33
50
  readonly expiresAt: number;
34
51
  readonly idempotencyKey?: string;
52
+ /** Default `'live'`. A child must match its minter's environment -- see `IssueRefusalReason`. */
53
+ readonly environment?: KeyEnvironment;
35
54
  }
36
- export type IssueRefusalReason = 'expires_at_required' | 'expires_at_past' | 'minter_not_found' | 'minter_revoked' | 'minter_expired' | WorkerErrorCode;
55
+ export type IssueRefusalReason = 'expires_at_required' | 'expires_at_past' | 'minter_not_found' | 'minter_revoked' | 'minter_expired'
56
+ /** #47: `request.environment` (or its `'live'` default) does not match the minter row's own. */
57
+ | 'environment_mismatch' | WorkerErrorCode;
37
58
  export type IssueResult = {
38
59
  readonly ok: true;
39
60
  readonly id: string;
@@ -44,15 +65,20 @@ export type IssueResult = {
44
65
  readonly ok: false;
45
66
  readonly reason: IssueRefusalReason;
46
67
  };
47
- export type CheckRefusalReason = 'not_found' | 'signature_invalid' | 'revoked' | 'expired' | 'secret_mismatch';
68
+ export type CheckRefusalReason = 'not_found' | 'signature_invalid' | 'revoked' | 'expired' | 'secret_mismatch'
69
+ /** #45: `rateLimiter` refused this credential id for the current window. */
70
+ | 'rate_limited';
48
71
  export type CheckResult<TGrant> = {
49
72
  readonly ok: true;
50
73
  readonly id: string;
51
74
  readonly issuedById: string | null;
52
75
  readonly grants: readonly TGrant[];
76
+ readonly environment: KeyEnvironment;
53
77
  } | {
54
78
  readonly ok: false;
55
79
  readonly reason: CheckRefusalReason;
80
+ /** Only meaningful with `reason: 'rate_limited'`. */
81
+ readonly retryAfterMs?: number;
56
82
  };
57
83
  export type RotateRefusalReason = 'signature_invalid' | 'conflict' | 'not_found' | 'revoked' | 'minter_not_found' | 'minter_revoked' | 'minter_expired' | WorkerErrorCode;
58
84
  export type RotateResult = {
@@ -68,6 +94,7 @@ export interface CredentialLink<TGrant> {
68
94
  readonly grants: readonly TGrant[];
69
95
  readonly expiresAt: number;
70
96
  readonly revokedAt: number | null;
97
+ readonly environment: KeyEnvironment;
71
98
  }
72
99
  export interface CredentialIssuer<TGrant> {
73
100
  /** Calls `worker.signRow`. */