@wtfalch/keys 0.3.0 → 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 +31 -0
- package/dist/bin/build-scan.d.ts +2 -0
- package/dist/bin/build-scan.js +16 -0
- package/dist/bin/build.d.ts +2 -0
- package/dist/bin/build.js +40 -0
- package/dist/build/index.d.ts +64 -0
- package/dist/build/index.js +156 -0
- package/dist/build/scan.d.ts +2 -0
- package/dist/build/scan.js +83 -0
- package/dist/held/index.d.ts +12 -0
- package/dist/held/index.js +89 -34
- package/dist/issued/index.d.ts +1 -0
- package/dist/issued/index.js +1 -0
- package/dist/issued/resign.d.ts +55 -0
- package/dist/issued/resign.js +174 -0
- package/dist/worker.d.ts +13 -0
- package/dist/worker.js +263 -0
- package/package.json +13 -3
package/README.md
CHANGED
|
@@ -43,3 +43,34 @@ Every successful `check()` stamps `lastUsedAt` and increments `useCount` on the
|
|
|
43
43
|
## Outbound webhooks
|
|
44
44
|
|
|
45
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,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,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,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
|
+
}
|
package/dist/held/index.d.ts
CHANGED
|
@@ -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
|
package/dist/held/index.js
CHANGED
|
@@ -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
|
|
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
|
}
|
package/dist/issued/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { SerializedCredential, VerifyKeys, WorkerClient, WorkerErrorCode }
|
|
|
3
3
|
import type { RateLimiter } from './ratelimit.js';
|
|
4
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
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';
|
|
6
7
|
export type Db = PgDatabase<PgQueryResultHKT, any, any>;
|
|
7
8
|
/**
|
|
8
9
|
* #47: a built-in sandbox/live split, so a stamped host does not invent its
|
package/dist/issued/index.js
CHANGED
|
@@ -7,6 +7,7 @@ import { keysIssuedCredentials } from './tables.js';
|
|
|
7
7
|
import { verifyIssuedRowSignature } from './verify.js';
|
|
8
8
|
export { ID_PATTERN, SIGNED_PREFIX, } from '../worker-contract.js';
|
|
9
9
|
export { createPostgresRateLimiter, } from './ratelimit.js';
|
|
10
|
+
export { createSigningGenerationMigrator, MAX_RESIGN_BATCH_SIZE, } from './resign.js';
|
|
10
11
|
function rowsOf(result) {
|
|
11
12
|
if (Array.isArray(result))
|
|
12
13
|
return result;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
2
|
+
import { type SerializedCredential, type WorkerClient, type WorkerErrorCode } from '../worker-contract.js';
|
|
3
|
+
type Db = PgDatabase<PgQueryResultHKT, any, any>;
|
|
4
|
+
/** The hard ceiling keeps one operator call within the Worker's documented request budget. */
|
|
5
|
+
export declare const MAX_RESIGN_BATCH_SIZE = 100;
|
|
6
|
+
export interface CreateSigningGenerationMigratorOptions<TGrant> {
|
|
7
|
+
readonly db: Db;
|
|
8
|
+
/** The Worker endpoint verifies the old signature and its host-scoped mint log before signing. */
|
|
9
|
+
readonly worker: Pick<WorkerClient<TGrant>, 'resign'>;
|
|
10
|
+
/** A valid, non-revoked operator caller credential carrying the `resign` grant. */
|
|
11
|
+
readonly credential: SerializedCredential;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A cursor is deliberately scoped to one source/target pair. Persist the
|
|
15
|
+
* whole value; accepting a bare row id would let an operator accidentally
|
|
16
|
+
* skip rows by reusing it for another migration.
|
|
17
|
+
*/
|
|
18
|
+
export interface SigningGenerationCursor {
|
|
19
|
+
readonly fromGenerationId: string;
|
|
20
|
+
readonly toGenerationId: string;
|
|
21
|
+
readonly afterId: string;
|
|
22
|
+
}
|
|
23
|
+
export interface ResignGenerationBatchRequest {
|
|
24
|
+
readonly fromGenerationId: string;
|
|
25
|
+
readonly toGenerationId: string;
|
|
26
|
+
/** The exact public key for `toGenerationId`; every Worker result is verified locally before publish. */
|
|
27
|
+
readonly targetPublicKey: Uint8Array;
|
|
28
|
+
readonly cursor?: SigningGenerationCursor | null;
|
|
29
|
+
readonly limit: number;
|
|
30
|
+
}
|
|
31
|
+
export type ResignGenerationRefusalReason = WorkerErrorCode | 'conflict' | 'generation_mismatch' | 'target_signature_invalid';
|
|
32
|
+
interface ResignGenerationProgress {
|
|
33
|
+
/** Rows durably published during this call, in cursor order. */
|
|
34
|
+
readonly migratedIds: readonly string[];
|
|
35
|
+
/** Resume with this exact cursor. `null` means restart this source/target pass from the beginning. */
|
|
36
|
+
readonly resumeCursor: SigningGenerationCursor | null;
|
|
37
|
+
}
|
|
38
|
+
export type ResignGenerationBatchResult = (ResignGenerationProgress & {
|
|
39
|
+
readonly ok: true;
|
|
40
|
+
/** True means this cursor pass was exhausted, not that retirement is safe under concurrent writers. */
|
|
41
|
+
readonly complete: boolean;
|
|
42
|
+
}) | (ResignGenerationProgress & {
|
|
43
|
+
readonly ok: false;
|
|
44
|
+
readonly reason: ResignGenerationRefusalReason;
|
|
45
|
+
readonly failedId?: string;
|
|
46
|
+
/** Present when the Worker signed with a generation other than the requested target. */
|
|
47
|
+
readonly actualGenerationId?: string;
|
|
48
|
+
});
|
|
49
|
+
export interface SigningGenerationMigrator {
|
|
50
|
+
resignBatch(request: ResignGenerationBatchRequest): Promise<ResignGenerationBatchResult>;
|
|
51
|
+
/** An observation for rollout checks; it is not, by itself, proof that retirement is safe. */
|
|
52
|
+
countGenerationRows(generationId: string): Promise<number>;
|
|
53
|
+
}
|
|
54
|
+
export declare function createSigningGenerationMigrator<TGrant>(options: CreateSigningGenerationMigratorOptions<TGrant>): SigningGenerationMigrator;
|
|
55
|
+
export {};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { and, asc, eq, gt, sql } from 'drizzle-orm';
|
|
2
|
+
import { ID_PATTERN, } from '../worker-contract.js';
|
|
3
|
+
import { fromBase64Url, toBase64Url } from './codec.js';
|
|
4
|
+
import { canonicalJson } from './encoding.js';
|
|
5
|
+
import { keysIssuedCredentials } from './tables.js';
|
|
6
|
+
import { verifyIssuedRowSignature } from './verify.js';
|
|
7
|
+
/** The hard ceiling keeps one operator call within the Worker's documented request budget. */
|
|
8
|
+
export const MAX_RESIGN_BATCH_SIZE = 100;
|
|
9
|
+
function toSignableRow(row) {
|
|
10
|
+
return {
|
|
11
|
+
id: row.id,
|
|
12
|
+
issuedById: row.issuedById,
|
|
13
|
+
keyPrefix: row.keyPrefix,
|
|
14
|
+
secretHash: row.secretHash,
|
|
15
|
+
previousSecretHash: row.previousSecretHash,
|
|
16
|
+
previousValidUntil: row.previousValidUntil,
|
|
17
|
+
grants: row.grants,
|
|
18
|
+
expiresAt: row.expiresAt,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function sameSignedState(a, b) {
|
|
22
|
+
return (a.signature === b.signature &&
|
|
23
|
+
canonicalJson(toSignableRow(a)) === canonicalJson(toSignableRow(b)));
|
|
24
|
+
}
|
|
25
|
+
function cursorAfter(fromGenerationId, toGenerationId, afterId) {
|
|
26
|
+
return afterId === null ? null : { fromGenerationId, toGenerationId, afterId };
|
|
27
|
+
}
|
|
28
|
+
function validRequest(request) {
|
|
29
|
+
if (!ID_PATTERN.test(request.fromGenerationId) || !ID_PATTERN.test(request.toGenerationId)) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
if (request.fromGenerationId === request.toGenerationId)
|
|
33
|
+
return false;
|
|
34
|
+
if (!Number.isSafeInteger(request.limit) ||
|
|
35
|
+
request.limit < 1 ||
|
|
36
|
+
request.limit > MAX_RESIGN_BATCH_SIZE) {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
if (!(request.targetPublicKey instanceof Uint8Array) ||
|
|
40
|
+
request.targetPublicKey.byteLength !== 32) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (request.cursor) {
|
|
44
|
+
return (request.cursor.fromGenerationId === request.fromGenerationId &&
|
|
45
|
+
request.cursor.toGenerationId === request.toGenerationId &&
|
|
46
|
+
ID_PATTERN.test(request.cursor.afterId));
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
export function createSigningGenerationMigrator(options) {
|
|
51
|
+
const { db, worker, credential } = options;
|
|
52
|
+
const table = keysIssuedCredentials;
|
|
53
|
+
async function resignBatch(request) {
|
|
54
|
+
if (!validRequest(request)) {
|
|
55
|
+
return { ok: false, reason: 'bad_request', migratedIds: [], resumeCursor: null };
|
|
56
|
+
}
|
|
57
|
+
// Own the bytes for the duration of the batch so a caller cannot mutate
|
|
58
|
+
// the supplied view between per-row verification calls.
|
|
59
|
+
const targetPublicKey = new Uint8Array(request.targetPublicKey);
|
|
60
|
+
const afterId = request.cursor?.afterId;
|
|
61
|
+
const condition = afterId
|
|
62
|
+
? and(eq(table.signingGenerationId, request.fromGenerationId), gt(table.id, afterId))
|
|
63
|
+
: eq(table.signingGenerationId, request.fromGenerationId);
|
|
64
|
+
const rows = await db
|
|
65
|
+
.select()
|
|
66
|
+
.from(table)
|
|
67
|
+
.where(condition)
|
|
68
|
+
.orderBy(asc(table.id))
|
|
69
|
+
.limit(request.limit + 1);
|
|
70
|
+
const candidates = rows.slice(0, request.limit);
|
|
71
|
+
const migratedIds = [];
|
|
72
|
+
let lastPublishedId = afterId ?? null;
|
|
73
|
+
for (const row of candidates) {
|
|
74
|
+
const signable = toSignableRow(row);
|
|
75
|
+
const result = await worker.resign({
|
|
76
|
+
requestId: crypto.randomUUID(),
|
|
77
|
+
credential,
|
|
78
|
+
row: signable,
|
|
79
|
+
oldSignature: fromBase64Url(row.signature),
|
|
80
|
+
oldGenerationId: request.fromGenerationId,
|
|
81
|
+
});
|
|
82
|
+
if (!result.ok) {
|
|
83
|
+
return {
|
|
84
|
+
ok: false,
|
|
85
|
+
reason: result.error.code,
|
|
86
|
+
failedId: row.id,
|
|
87
|
+
migratedIds,
|
|
88
|
+
resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (result.generationId !== request.toGenerationId) {
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
reason: 'generation_mismatch',
|
|
95
|
+
failedId: row.id,
|
|
96
|
+
actualGenerationId: result.generationId,
|
|
97
|
+
migratedIds,
|
|
98
|
+
resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const targetSignature = result.signature instanceof Uint8Array ? new Uint8Array(result.signature) : null;
|
|
102
|
+
let targetSignatureValid = false;
|
|
103
|
+
if (targetSignature) {
|
|
104
|
+
try {
|
|
105
|
+
targetSignatureValid = await verifyIssuedRowSignature(signable, targetSignature, [
|
|
106
|
+
targetPublicKey,
|
|
107
|
+
]);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
targetSignatureValid = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (!targetSignature || !targetSignatureValid) {
|
|
114
|
+
return {
|
|
115
|
+
ok: false,
|
|
116
|
+
reason: 'target_signature_invalid',
|
|
117
|
+
failedId: row.id,
|
|
118
|
+
migratedIds,
|
|
119
|
+
resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
const published = await db.transaction(async (tx) => {
|
|
123
|
+
const [current] = await tx.select().from(table).where(eq(table.id, row.id)).for('update');
|
|
124
|
+
if (!current ||
|
|
125
|
+
current.signingGenerationId !== request.fromGenerationId ||
|
|
126
|
+
!sameSignedState(current, row)) {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
await tx
|
|
130
|
+
.update(table)
|
|
131
|
+
.set({
|
|
132
|
+
signature: toBase64Url(targetSignature),
|
|
133
|
+
signingGenerationId: result.generationId,
|
|
134
|
+
})
|
|
135
|
+
.where(and(eq(table.id, row.id), eq(table.signingGenerationId, request.fromGenerationId), eq(table.signature, row.signature)));
|
|
136
|
+
return true;
|
|
137
|
+
});
|
|
138
|
+
if (!published) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
reason: 'conflict',
|
|
142
|
+
failedId: row.id,
|
|
143
|
+
migratedIds,
|
|
144
|
+
resumeCursor: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
migratedIds.push(row.id);
|
|
148
|
+
lastPublishedId = row.id;
|
|
149
|
+
}
|
|
150
|
+
const complete = rows.length <= request.limit;
|
|
151
|
+
return {
|
|
152
|
+
ok: true,
|
|
153
|
+
complete,
|
|
154
|
+
migratedIds,
|
|
155
|
+
resumeCursor: complete
|
|
156
|
+
? null
|
|
157
|
+
: cursorAfter(request.fromGenerationId, request.toGenerationId, lastPublishedId),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
async function countGenerationRows(generationId) {
|
|
161
|
+
if (!ID_PATTERN.test(generationId))
|
|
162
|
+
throw new TypeError('generationId must match ID_PATTERN');
|
|
163
|
+
const result = await db.execute(sql `
|
|
164
|
+
select count(*)::integer as count
|
|
165
|
+
from public.keys_issued_credentials
|
|
166
|
+
where signing_generation_id = ${generationId}
|
|
167
|
+
`);
|
|
168
|
+
const rows = Array.isArray(result)
|
|
169
|
+
? result
|
|
170
|
+
: (result.rows ?? []);
|
|
171
|
+
return Number(rows[0]?.count ?? 0);
|
|
172
|
+
}
|
|
173
|
+
return { resignBatch, countGenerationRows };
|
|
174
|
+
}
|
package/dist/worker.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type WorkerClient } from './worker-contract.js';
|
|
2
|
+
export type * from './worker-contract.js';
|
|
3
|
+
export { WORKER_HTTP } from './worker-contract.js';
|
|
4
|
+
export interface CreateWorkerClientOptions {
|
|
5
|
+
/** Must be an https origin; checked once here, not on every call. */
|
|
6
|
+
readonly url: string;
|
|
7
|
+
/** Defaults to the global `fetch`. A test passes a fake. */
|
|
8
|
+
readonly fetch?: typeof fetch;
|
|
9
|
+
/** Per-call timeout in milliseconds. Default 10s. */
|
|
10
|
+
readonly timeoutMs?: number;
|
|
11
|
+
}
|
|
12
|
+
/** HTTP transport only: no auth policy or automatic retries. */
|
|
13
|
+
export declare function createWorkerClient<TGrant = unknown>(options: CreateWorkerClientOptions): WorkerClient<TGrant>;
|
package/dist/worker.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { ID_PATTERN, WORKER_HTTP, } from './worker-contract.js';
|
|
2
|
+
export { WORKER_HTTP } from './worker-contract.js';
|
|
3
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
4
|
+
/**
|
|
5
|
+
* The 15 codes the Worker itself ever sends (`errors.ts`'s `statusFor`
|
|
6
|
+
* covers exactly these). `unreachable` is deliberately excluded: the
|
|
7
|
+
* contract says the Worker never sends it, so a response body claiming
|
|
8
|
+
* that code is exactly as untrustworthy as one claiming a code that does
|
|
9
|
+
* not exist at all -- both are `unreachable` from here.
|
|
10
|
+
*
|
|
11
|
+
* A value-level mirror, not a type import: `WorkerErrorCode` is a union of
|
|
12
|
+
* string literals, which has no runtime representation to check a decoded
|
|
13
|
+
* body's `error.code` against.
|
|
14
|
+
*/
|
|
15
|
+
const KNOWN_ERROR_CODES = new Set([
|
|
16
|
+
'credential_invalid',
|
|
17
|
+
'credential_expired',
|
|
18
|
+
'credential_revoked',
|
|
19
|
+
'grant_missing',
|
|
20
|
+
'rate_limited',
|
|
21
|
+
'bad_request',
|
|
22
|
+
'aad_mismatch',
|
|
23
|
+
'unknown_generation',
|
|
24
|
+
'bad_minter_signature',
|
|
25
|
+
'minter_expired',
|
|
26
|
+
'minter_revoked',
|
|
27
|
+
'lineage_mismatch',
|
|
28
|
+
'bad_old_signature',
|
|
29
|
+
'unlogged_row',
|
|
30
|
+
'not_in_lineage',
|
|
31
|
+
]);
|
|
32
|
+
/** The only statuses `errors.ts` ever sends for a refusal. Anything else -- 3xx, 5xx, 0 (an opaque redirect) -- is `unreachable`, whatever its body says. */
|
|
33
|
+
const KNOWN_FAILURE_STATUSES = new Set([400, 401, 403, 429]);
|
|
34
|
+
function assertHttpsOrigin(url) {
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = new URL(url);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error('createWorkerClient: url must be an absolute URL');
|
|
41
|
+
}
|
|
42
|
+
if (parsed.protocol !== 'https:' ||
|
|
43
|
+
parsed.username ||
|
|
44
|
+
parsed.password ||
|
|
45
|
+
parsed.pathname !== '/' ||
|
|
46
|
+
parsed.search ||
|
|
47
|
+
parsed.hash) {
|
|
48
|
+
throw new Error('createWorkerClient: url must be an https origin');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
// base64url -- the wire encoding for every Uint8Array field (worker-contract.ts)
|
|
53
|
+
// ---------------------------------------------------------------------------
|
|
54
|
+
function encodeBase64Url(bytes) {
|
|
55
|
+
return Buffer.from(bytes).toString('base64url');
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* `null` on anything that is not exactly one round trip of `encodeBase64Url`
|
|
59
|
+
* -- wrong type, empty, stray characters, or a value `Buffer` would decode
|
|
60
|
+
* leniently but which was never produced by this encoding. A decode failure
|
|
61
|
+
* here is always a shape-invalid body, never a thrown exception: the caller
|
|
62
|
+
* turns it into `unreachable`.
|
|
63
|
+
*/
|
|
64
|
+
function decodeBase64Url(value) {
|
|
65
|
+
if (typeof value !== 'string' || value.length === 0 || !/^[A-Za-z0-9_-]+$/.test(value)) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const bytes = new Uint8Array(Buffer.from(value, 'base64url'));
|
|
69
|
+
return encodeBase64Url(bytes) === value ? bytes : null;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* One request/response round trip. Returns `null` for anything that is not
|
|
73
|
+
* a completed HTTP exchange -- a thrown `fetch` (DNS, TLS, connection
|
|
74
|
+
* refused), an aborted one (the timeout below firing), or any other
|
|
75
|
+
* network failure. Every caller below turns a `null` into `unreachable`.
|
|
76
|
+
*
|
|
77
|
+
* `redirect: 'manual'`: a Worker never redirects, so a 3xx is either a
|
|
78
|
+
* misconfigured `url` or a network intermediary -- never followed, and
|
|
79
|
+
* (per `KNOWN_FAILURE_STATUSES` below) never treated as a real response
|
|
80
|
+
* either. `AbortSignal.timeout` covers both "took too long" and "hung
|
|
81
|
+
* forever" the same way a thrown error does.
|
|
82
|
+
*/
|
|
83
|
+
async function post(fetchImpl, base, path, credential, body, timeoutMs) {
|
|
84
|
+
let response;
|
|
85
|
+
try {
|
|
86
|
+
response = await fetchImpl(new URL(path, base), {
|
|
87
|
+
method: 'POST',
|
|
88
|
+
redirect: 'manual',
|
|
89
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
90
|
+
headers: {
|
|
91
|
+
'content-type': 'application/json',
|
|
92
|
+
authorization: `Bearer ${credential}`,
|
|
93
|
+
},
|
|
94
|
+
body: JSON.stringify(body),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// Never logs `err`: it can carry the request (credential included).
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
let json;
|
|
102
|
+
try {
|
|
103
|
+
json = await response.json();
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
json = undefined;
|
|
107
|
+
}
|
|
108
|
+
return { status: response.status, headers: response.headers, json };
|
|
109
|
+
}
|
|
110
|
+
function unreachable() {
|
|
111
|
+
return { ok: false, error: { code: 'unreachable' } };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Decodes a non-200 body into `WorkerFailure`, or `unreachable` when the
|
|
115
|
+
* status is not one `errors.ts` ever sends, the body is not `{ error: {
|
|
116
|
+
* code } }`, or `code` is not one of `KNOWN_ERROR_CODES`. A malformed or
|
|
117
|
+
* unrecognized refusal is never partially trusted.
|
|
118
|
+
*/
|
|
119
|
+
function decodeFailure(outcome) {
|
|
120
|
+
if (!KNOWN_FAILURE_STATUSES.has(outcome.status))
|
|
121
|
+
return unreachable();
|
|
122
|
+
if (typeof outcome.json !== 'object' || outcome.json === null)
|
|
123
|
+
return unreachable();
|
|
124
|
+
const error = outcome.json.error;
|
|
125
|
+
if (typeof error !== 'object' || error === null)
|
|
126
|
+
return unreachable();
|
|
127
|
+
const e = error;
|
|
128
|
+
if (typeof e.code !== 'string' || !KNOWN_ERROR_CODES.has(e.code))
|
|
129
|
+
return unreachable();
|
|
130
|
+
const expectedStatus = e.code === 'bad_request'
|
|
131
|
+
? 400
|
|
132
|
+
: e.code.startsWith('credential_')
|
|
133
|
+
? 401
|
|
134
|
+
: e.code === 'rate_limited'
|
|
135
|
+
? 429
|
|
136
|
+
: 403;
|
|
137
|
+
if (outcome.status !== expectedStatus)
|
|
138
|
+
return unreachable();
|
|
139
|
+
// Safe: membership in `KNOWN_ERROR_CODES` is exactly the `WorkerErrorCode`
|
|
140
|
+
// union minus `'unreachable'`, which the Worker never sends (checked above).
|
|
141
|
+
const code = e.code;
|
|
142
|
+
// Per WORKER_HTTP's own mapping comment: "429 ... with Retry-After in
|
|
143
|
+
// seconds" -- the header, not the body's own (undocumented-as-public)
|
|
144
|
+
// `retryAfterMs` mirror, is this client's source of truth.
|
|
145
|
+
let retryAfterMs;
|
|
146
|
+
if (outcome.status === 429) {
|
|
147
|
+
const header = outcome.headers.get('retry-after');
|
|
148
|
+
const seconds = header !== null && /^\d+$/.test(header) ? Number(header) : Number.NaN;
|
|
149
|
+
if (Number.isSafeInteger(seconds * 1000))
|
|
150
|
+
retryAfterMs = seconds * 1000;
|
|
151
|
+
}
|
|
152
|
+
const message = typeof e.message === 'string' ? e.message : undefined;
|
|
153
|
+
return {
|
|
154
|
+
ok: false,
|
|
155
|
+
error: {
|
|
156
|
+
code,
|
|
157
|
+
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
|
|
158
|
+
...(message !== undefined ? { message } : {}),
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Everything the six methods below share: POST, map network failure to
|
|
164
|
+
* `unreachable`, hand a non-200 to `decodeFailure`, and otherwise hand the
|
|
165
|
+
* parsed body to `decodeSuccess` -- which itself returns `null` for
|
|
166
|
+
* anything shape-invalid, turned into `unreachable` here rather than in
|
|
167
|
+
* each of the six call sites.
|
|
168
|
+
*/
|
|
169
|
+
async function call(fetchImpl, base, path, credential, body, timeoutMs, decodeSuccess) {
|
|
170
|
+
const outcome = await post(fetchImpl, base, path, credential, body, timeoutMs);
|
|
171
|
+
if (!outcome)
|
|
172
|
+
return unreachable();
|
|
173
|
+
if (outcome.status !== 200)
|
|
174
|
+
return decodeFailure(outcome);
|
|
175
|
+
return decodeSuccess(outcome.json) ?? unreachable();
|
|
176
|
+
}
|
|
177
|
+
function asRecord(json) {
|
|
178
|
+
return typeof json === 'object' && json !== null ? json : null;
|
|
179
|
+
}
|
|
180
|
+
/** HTTP transport only: no auth policy or automatic retries. */
|
|
181
|
+
export function createWorkerClient(options) {
|
|
182
|
+
assertHttpsOrigin(options.url);
|
|
183
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
184
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
185
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) {
|
|
186
|
+
throw new RangeError('timeoutMs must be an integer from 1 to 2147483647');
|
|
187
|
+
}
|
|
188
|
+
const base = options.url;
|
|
189
|
+
const post6 = (path, credential, body, decodeSuccess) => call(fetchImpl, base, path, credential, body, timeoutMs, decodeSuccess);
|
|
190
|
+
return {
|
|
191
|
+
wrap: (req) => post6(WORKER_HTTP.wrap.path, req.credential, { requestId: req.requestId, binding: req.binding }, (json) => {
|
|
192
|
+
const v = asRecord(json);
|
|
193
|
+
if (!v)
|
|
194
|
+
return null;
|
|
195
|
+
const dataKey = decodeBase64Url(v.dataKey);
|
|
196
|
+
const wrappedKey = decodeBase64Url(v.wrappedKey);
|
|
197
|
+
if (!dataKey ||
|
|
198
|
+
!wrappedKey ||
|
|
199
|
+
dataKey.length !== 32 ||
|
|
200
|
+
wrappedKey.length !== 60 ||
|
|
201
|
+
typeof v.kekId !== 'string' ||
|
|
202
|
+
!ID_PATTERN.test(v.kekId))
|
|
203
|
+
return null;
|
|
204
|
+
return { ok: true, dataKey, wrappedKey, kekId: v.kekId };
|
|
205
|
+
}),
|
|
206
|
+
unwrap: (req) => post6(WORKER_HTTP.unwrap.path, req.credential, {
|
|
207
|
+
requestId: req.requestId,
|
|
208
|
+
kekId: req.kekId,
|
|
209
|
+
wrappedKey: encodeBase64Url(req.wrappedKey),
|
|
210
|
+
binding: req.binding,
|
|
211
|
+
}, (json) => {
|
|
212
|
+
const dataKey = decodeBase64Url(asRecord(json)?.dataKey);
|
|
213
|
+
return dataKey?.length === 32 ? { ok: true, dataKey } : null;
|
|
214
|
+
}),
|
|
215
|
+
rewrap: (req) => post6(WORKER_HTTP.rewrap.path, req.credential, {
|
|
216
|
+
requestId: req.requestId,
|
|
217
|
+
kekIdOld: req.kekIdOld,
|
|
218
|
+
kekIdNew: req.kekIdNew,
|
|
219
|
+
wrappedKey: encodeBase64Url(req.wrappedKey),
|
|
220
|
+
binding: req.binding,
|
|
221
|
+
}, (json) => {
|
|
222
|
+
const wrappedKey = decodeBase64Url(asRecord(json)?.wrappedKey);
|
|
223
|
+
return wrappedKey?.length === 60 ? { ok: true, wrappedKey } : null;
|
|
224
|
+
}),
|
|
225
|
+
signRow: (req) => post6(WORKER_HTTP.signRow.path, req.credential, {
|
|
226
|
+
requestId: req.requestId,
|
|
227
|
+
candidate: req.candidate,
|
|
228
|
+
minter: req.minter
|
|
229
|
+
? { row: req.minter.row, signature: encodeBase64Url(req.minter.signature) }
|
|
230
|
+
: null,
|
|
231
|
+
}, (json) => {
|
|
232
|
+
const v = asRecord(json);
|
|
233
|
+
const signature = decodeBase64Url(v?.signature);
|
|
234
|
+
if (signature?.length !== 64 ||
|
|
235
|
+
typeof v?.generationId !== 'string' ||
|
|
236
|
+
!ID_PATTERN.test(v.generationId)) {
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
return { ok: true, signature, generationId: v.generationId };
|
|
240
|
+
}),
|
|
241
|
+
resign: (req) => post6(WORKER_HTTP.resign.path, req.credential, {
|
|
242
|
+
requestId: req.requestId,
|
|
243
|
+
row: req.row,
|
|
244
|
+
oldSignature: encodeBase64Url(req.oldSignature),
|
|
245
|
+
oldGenerationId: req.oldGenerationId,
|
|
246
|
+
}, (json) => {
|
|
247
|
+
const v = asRecord(json);
|
|
248
|
+
const signature = decodeBase64Url(v?.signature);
|
|
249
|
+
if (signature?.length !== 64 ||
|
|
250
|
+
typeof v?.generationId !== 'string' ||
|
|
251
|
+
!ID_PATTERN.test(v.generationId)) {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
return { ok: true, signature, generationId: v.generationId };
|
|
255
|
+
}),
|
|
256
|
+
recordEviction: (req) => post6(WORKER_HTTP.recordEviction.path, req.credential, { requestId: req.requestId, credentialId: req.credentialId, revokedAt: req.revokedAt }, (json) => {
|
|
257
|
+
const receiptId = asRecord(json)?.receiptId;
|
|
258
|
+
return typeof receiptId === 'string' && ID_PATTERN.test(receiptId)
|
|
259
|
+
? { ok: true, receiptId }
|
|
260
|
+
: null;
|
|
261
|
+
}),
|
|
262
|
+
};
|
|
263
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wtfalch/keys",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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",
|
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
"type": "module",
|
|
12
12
|
"files": ["dist"],
|
|
13
13
|
"bin": {
|
|
14
|
-
"keys-migrations": "dist/bin/migrations.js"
|
|
14
|
+
"keys-migrations": "dist/bin/migrations.js",
|
|
15
|
+
"keys-build": "dist/bin/build.js",
|
|
16
|
+
"keys-build-scan": "dist/bin/build-scan.js"
|
|
15
17
|
},
|
|
16
18
|
"exports": {
|
|
17
19
|
"./issued": {
|
|
@@ -27,7 +29,15 @@
|
|
|
27
29
|
"default": "./dist/webhooks.js"
|
|
28
30
|
},
|
|
29
31
|
"./migrations/*.sql": "./dist/migrations/*.sql",
|
|
30
|
-
"./package.json": "./package.json"
|
|
32
|
+
"./package.json": "./package.json",
|
|
33
|
+
"./worker": {
|
|
34
|
+
"types": "./dist/worker.d.ts",
|
|
35
|
+
"default": "./dist/worker.js"
|
|
36
|
+
},
|
|
37
|
+
"./build": {
|
|
38
|
+
"types": "./dist/build/index.d.ts",
|
|
39
|
+
"default": "./dist/build/index.js"
|
|
40
|
+
}
|
|
31
41
|
},
|
|
32
42
|
"sideEffects": false,
|
|
33
43
|
"publishConfig": {
|