@wtfalch/keys 0.8.0 → 0.13.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 +244 -27
- package/dist/held/index.d.ts +116 -6
- package/dist/held/index.js +259 -37
- package/dist/held/schema.d.ts +17 -0
- package/dist/held/schema.js +12 -0
- package/dist/held/seal.d.ts +1 -1
- package/dist/held/seal.js +1 -1
- package/dist/held/shred.d.ts +6 -0
- package/dist/held/shred.js +6 -0
- package/dist/held/tenant.d.ts +2 -0
- package/dist/held/tenant.js +46 -0
- package/dist/held-edge/index.d.ts +17 -2
- package/dist/held-edge/index.js +51 -9
- package/dist/host/audit-endpoint.js +2 -8
- package/dist/host/company-registrar-keys.d.ts +13 -0
- package/dist/host/company-registrar-keys.js +6 -8
- package/dist/host/events.d.ts +19 -3
- package/dist/host/events.js +56 -20
- package/dist/host/index.d.ts +9 -2
- package/dist/host/index.js +9 -2
- package/dist/host/native-build.d.ts +126 -0
- package/dist/host/native-build.js +322 -0
- package/dist/host/registrar.d.ts +10 -4
- package/dist/host/registrar.js +64 -42
- package/dist/host/rotation-sweep.d.ts +56 -0
- package/dist/host/rotation-sweep.js +89 -0
- package/dist/issued/encoding.d.ts +4 -0
- package/dist/issued/encoding.js +22 -0
- package/dist/issued/index.d.ts +148 -7
- package/dist/issued/index.js +320 -34
- package/dist/issued/resign.d.ts +16 -0
- package/dist/issued/resign.js +55 -2
- package/dist/issued/tables.d.ts +38 -0
- package/dist/issued/tables.js +6 -0
- package/dist/issued/verify.d.ts +14 -3
- package/dist/issued/verify.js +10 -3
- package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
- package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
- package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
- package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
- package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
- package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
- package/dist/migrations/tenant-rows/0001_keys_tenant_rows.sql +63 -0
- package/dist/migrations-dir.d.ts +9 -0
- package/dist/migrations-dir.js +9 -0
- package/dist/service/body.d.ts +21 -0
- package/dist/service/body.js +128 -0
- package/dist/service/errors.d.ts +24 -0
- package/dist/service/errors.js +89 -0
- package/dist/service/handler.d.ts +35 -0
- package/dist/service/handler.js +328 -0
- package/dist/service/index.d.ts +7 -0
- package/dist/service/index.js +7 -0
- package/dist/service/policy.d.ts +130 -0
- package/dist/service/policy.js +123 -0
- package/dist/service/timeout.d.ts +6 -0
- package/dist/service/timeout.js +34 -0
- package/dist/webhooks.d.ts +40 -17
- package/dist/webhooks.js +70 -26
- package/dist/worker-contract.d.ts +43 -6
- package/dist/worker-contract.js +37 -0
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +7 -28
- package/package.json +21 -7
- package/dist/testing/index.d.ts +0 -9
- package/dist/testing/index.js +0 -9
- package/dist/testing/worker-stub.d.ts +0 -55
- package/dist/testing/worker-stub.js +0 -180
package/dist/held-edge/index.js
CHANGED
|
@@ -12,13 +12,22 @@ import { encodeAad } from '../held/aad.js';
|
|
|
12
12
|
* and constants from `../worker-contract.ts`. The `WorkerClient` is injected
|
|
13
13
|
* (`createWorkerClient` from `../worker` needs `nodejs_compat`).
|
|
14
14
|
*/
|
|
15
|
-
import { ID_PATTERN, } from '../worker-contract.js';
|
|
15
|
+
import { ID_PATTERN, WORKER_ERROR_CODES, } from '../worker-contract.js';
|
|
16
16
|
export { encodeAad } from '../held/aad.js';
|
|
17
17
|
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
18
18
|
const IV_BYTES = 12;
|
|
19
19
|
const DATA_KEY_BYTES = 32;
|
|
20
20
|
const WRAPPED_KEY_BYTES = 60;
|
|
21
21
|
const TAG_BYTES = 16;
|
|
22
|
+
/** Every member of `HeldEdgeErrorCode`. Adding one is a major change after 1.0.0. */
|
|
23
|
+
export const HELD_EDGE_ERROR_CODES = [
|
|
24
|
+
...WORKER_ERROR_CODES,
|
|
25
|
+
'bad_request',
|
|
26
|
+
'unseal_failed',
|
|
27
|
+
'timeout',
|
|
28
|
+
'transport',
|
|
29
|
+
'version_mismatch',
|
|
30
|
+
];
|
|
22
31
|
export class HeldEdgeError extends Error {
|
|
23
32
|
code;
|
|
24
33
|
constructor(code, message) {
|
|
@@ -69,14 +78,34 @@ function checkTimeout(timeoutMs) {
|
|
|
69
78
|
}
|
|
70
79
|
return ms;
|
|
71
80
|
}
|
|
72
|
-
|
|
81
|
+
function zeroKey(result) {
|
|
82
|
+
if (result?.ok && result.dataKey instanceof Uint8Array)
|
|
83
|
+
result.dataKey.fill(0);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Races the Worker call against a timer; the timer is always cleared. A call that
|
|
87
|
+
* settles after the timeout has its data key zeroed. A throw or rejection from the
|
|
88
|
+
* Worker call becomes `transport`; the cause is dropped, as it can carry the request.
|
|
89
|
+
*/
|
|
73
90
|
async function withTimeout(call, ms) {
|
|
74
91
|
let timer;
|
|
75
|
-
const
|
|
76
|
-
|
|
92
|
+
const timedOut = Symbol('timeout');
|
|
93
|
+
const timeout = new Promise((resolve) => {
|
|
94
|
+
timer = setTimeout(() => resolve(timedOut), ms);
|
|
77
95
|
});
|
|
96
|
+
const started = (async () => call())();
|
|
78
97
|
try {
|
|
79
|
-
|
|
98
|
+
const winner = await Promise.race([started, timeout]);
|
|
99
|
+
if (winner === timedOut) {
|
|
100
|
+
started.then(zeroKey, () => undefined);
|
|
101
|
+
throw new HeldEdgeError('timeout', 'custody Worker timed out');
|
|
102
|
+
}
|
|
103
|
+
return winner;
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
if (e instanceof HeldEdgeError)
|
|
107
|
+
throw e;
|
|
108
|
+
throw new HeldEdgeError('transport', 'custody Worker call failed');
|
|
80
109
|
}
|
|
81
110
|
finally {
|
|
82
111
|
clearTimeout(timer);
|
|
@@ -87,8 +116,11 @@ function fromWorker(code) {
|
|
|
87
116
|
return new HeldEdgeError(code, `custody Worker refused: ${code}`);
|
|
88
117
|
}
|
|
89
118
|
async function importDataKey(dataKey, usage) {
|
|
90
|
-
if (dataKey.length !== DATA_KEY_BYTES)
|
|
91
|
-
throw
|
|
119
|
+
if (dataKey.length !== DATA_KEY_BYTES) {
|
|
120
|
+
throw usage === 'encrypt'
|
|
121
|
+
? new HeldEdgeError('bad_request', 'custody worker returned a data key of the wrong length')
|
|
122
|
+
: new HeldEdgeError('unseal_failed');
|
|
123
|
+
}
|
|
92
124
|
return crypto.subtle.importKey('raw', dataKey, { name: 'AES-GCM' }, false, [usage]);
|
|
93
125
|
}
|
|
94
126
|
export async function sealHeld(o) {
|
|
@@ -97,10 +129,14 @@ export async function sealHeld(o) {
|
|
|
97
129
|
if (typeof o.plaintext !== 'string') {
|
|
98
130
|
throw new HeldEdgeError('bad_request', 'plaintext must be a string');
|
|
99
131
|
}
|
|
132
|
+
// TextEncoder turns a lone surrogate into U+FFFD, so the value would open as a different string.
|
|
133
|
+
if (!o.plaintext.isWellFormed()) {
|
|
134
|
+
throw new HeldEdgeError('bad_request', 'plaintext is not well-formed UTF-16');
|
|
135
|
+
}
|
|
100
136
|
const ms = checkTimeout(o.timeoutMs);
|
|
101
137
|
const binding = { tenantId: o.tenantId, entryId: o.entryId, version: o.version };
|
|
102
138
|
const aad = encodeAad(binding);
|
|
103
|
-
const result = await withTimeout(o.worker.wrap({ requestId: crypto.randomUUID(), credential: o.credential, binding }), ms);
|
|
139
|
+
const result = await withTimeout(() => o.worker.wrap({ requestId: crypto.randomUUID(), credential: o.credential, binding }), ms);
|
|
104
140
|
if (!result.ok)
|
|
105
141
|
throw fromWorker(result.error.code);
|
|
106
142
|
const dataKey = result.dataKey;
|
|
@@ -132,6 +168,12 @@ export async function openHeld(o) {
|
|
|
132
168
|
throw new HeldEdgeError('bad_request', 'sealed is not a v1 SealedHeld');
|
|
133
169
|
}
|
|
134
170
|
checkVersion(s.version);
|
|
171
|
+
if (o.expectedVersion !== undefined) {
|
|
172
|
+
checkVersion(o.expectedVersion);
|
|
173
|
+
if (s.version !== o.expectedVersion) {
|
|
174
|
+
throw new HeldEdgeError('version_mismatch', 'sealed.version is not the expected version');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
135
177
|
if (typeof s.kekId !== 'string' || !ID_PATTERN.test(s.kekId)) {
|
|
136
178
|
throw new HeldEdgeError('bad_request', 'sealed.kekId does not match the id pattern');
|
|
137
179
|
}
|
|
@@ -147,7 +189,7 @@ export async function openHeld(o) {
|
|
|
147
189
|
const ms = checkTimeout(o.timeoutMs);
|
|
148
190
|
const binding = { tenantId: o.tenantId, entryId: o.entryId, version: s.version };
|
|
149
191
|
const aad = encodeAad(binding);
|
|
150
|
-
const result = await withTimeout(o.worker.unwrap({
|
|
192
|
+
const result = await withTimeout(() => o.worker.unwrap({
|
|
151
193
|
requestId: crypto.randomUUID(),
|
|
152
194
|
credential: o.credential,
|
|
153
195
|
kekId: s.kekId,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { safeEqual } from '@wtfalch/utils/crypto';
|
|
2
2
|
import { and, asc, gte, inArray, isNotNull, lt } from 'drizzle-orm';
|
|
3
3
|
import { keysHostEvents } from './schema.js';
|
|
4
4
|
/**
|
|
@@ -37,12 +37,6 @@ const unauthorized = () => jsonResponse({ error: { code: 'unauthorized' } }, 401
|
|
|
37
37
|
const badRequest = () => jsonResponse({ error: { code: 'bad_request' } }, 400);
|
|
38
38
|
const windowTooLarge = () => jsonResponse({ error: { code: 'window_too_large' } }, 413);
|
|
39
39
|
const methodNotAllowed = () => jsonResponse({ error: { code: 'method_not_allowed' } }, 405);
|
|
40
|
-
/** Constant-time regardless of length: both sides are always a 32-byte SHA-256 digest, so `timingSafeEqual` never throws on a length mismatch here. */
|
|
41
|
-
function tokensMatch(presented, configured) {
|
|
42
|
-
const a = createHash('sha256').update(presented, 'utf8').digest();
|
|
43
|
-
const b = createHash('sha256').update(configured, 'utf8').digest();
|
|
44
|
-
return timingSafeEqual(a, b);
|
|
45
|
-
}
|
|
46
40
|
/** `Number(bigint)` past this silently rounds, which would let `since`/`until` collapse together after conversion even though the `bigint` comparison above said they didn't. 16 digits alone doesn't rule that out, so bound it explicitly too. */
|
|
47
41
|
const MAX_SAFE_WINDOW_PARAM = BigInt(Number.MAX_SAFE_INTEGER);
|
|
48
42
|
/** A decimal-integer query param, or `null` for anything else -- absent, empty, signed, fractional, exponential, over 16 digits, or past `Number.MAX_SAFE_INTEGER`. */
|
|
@@ -68,7 +62,7 @@ export function auditEndpoint(options) {
|
|
|
68
62
|
if (!token || token.length < 32)
|
|
69
63
|
return unavailable();
|
|
70
64
|
const match = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
|
|
71
|
-
if (!match?.[1] || !
|
|
65
|
+
if (!match?.[1] || !safeEqual(match[1], token))
|
|
72
66
|
return unauthorized();
|
|
73
67
|
const url = new URL(request.url);
|
|
74
68
|
const since = parseWindowParam(url.searchParams.get('since'));
|
|
@@ -18,6 +18,10 @@ import type { CredentialIssuer, Db, IssueRefusalReason, KeyEnvironment } from '.
|
|
|
18
18
|
* is never an idempotent replay with `secret: null`, which a platform that
|
|
19
19
|
* lost the first answer could not use).
|
|
20
20
|
*
|
|
21
|
+
* The key is minted as `company_root` with its `organisationId`, so company
|
|
22
|
+
* key management (`revokeForCompany`) cannot remove it; this platform route
|
|
23
|
+
* revokes it with `revoke()`, the trusted path.
|
|
24
|
+
*
|
|
21
25
|
* The org binding through `idempotencyKey` is advisory: the key is a label the
|
|
22
26
|
* minter chose, not proof about the caller. It is only safe because only the
|
|
23
27
|
* holder of the platform token can mint a key carrying that prefix; revoke
|
|
@@ -32,6 +36,15 @@ export interface CompanyRegistrarKeysOptions<TGrant> {
|
|
|
32
36
|
readonly issuer: Pick<CredentialIssuer<TGrant>, 'issue' | 'revoke'>;
|
|
33
37
|
/** The grant that marks a credential as a company's registrar key (the host's `isRegistrarGrant` accepts it). */
|
|
34
38
|
readonly registrarGrant: TGrant;
|
|
39
|
+
/**
|
|
40
|
+
* Grants the company key also holds, after `registrarGrant`. The Worker refuses a child
|
|
41
|
+
* row with a grant its minter lacks, so the apps a registrar registers can only hold
|
|
42
|
+
* grants listed here (or, for an object grant with a string `tenantId`, a grant of the
|
|
43
|
+
* same tenant). Only `registrarGrant` marks a registrar. A company key minted before
|
|
44
|
+
* this option existed holds only the registrar grant, so its apps fail at the Worker
|
|
45
|
+
* until the company's key is rolled: mint a new one, then revoke the old one.
|
|
46
|
+
*/
|
|
47
|
+
readonly appGrants?: readonly TGrant[];
|
|
35
48
|
/** Longest lifetime a mint may ask for, in days. Defaults to 365. */
|
|
36
49
|
readonly maxExpiresDays?: number;
|
|
37
50
|
/** Environment of the minted key. Defaults to `'live'`; app credentials inherit it. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { safeEqual } from '@wtfalch/utils/crypto';
|
|
2
2
|
import { and, eq, isNull, like } from 'drizzle-orm';
|
|
3
3
|
import { keysIssuedCredentials } from '../issued/tables.js';
|
|
4
4
|
import { ID_PATTERN } from '../worker-contract.js';
|
|
@@ -7,6 +7,7 @@ const DEFAULT_MAX_DAYS = 365;
|
|
|
7
7
|
const prefixFor = (organisationId) => `company-registrar:${organisationId}:`;
|
|
8
8
|
export function createCompanyRegistrarKeys(options) {
|
|
9
9
|
const { db, issuer, registrarGrant } = options;
|
|
10
|
+
const appGrants = options.appGrants ?? [];
|
|
10
11
|
const maxDays = options.maxExpiresDays ?? DEFAULT_MAX_DAYS;
|
|
11
12
|
const environment = options.environment ?? 'live';
|
|
12
13
|
const now = options.now ?? (() => Date.now());
|
|
@@ -26,10 +27,12 @@ export function createCompanyRegistrarKeys(options) {
|
|
|
26
27
|
return { ok: false, reason: 'bad_request' };
|
|
27
28
|
}
|
|
28
29
|
const result = await issuer.issue({
|
|
29
|
-
grants: [registrarGrant],
|
|
30
|
+
grants: [registrarGrant, ...appGrants],
|
|
30
31
|
minter: null,
|
|
31
32
|
expiresAt: now() + expiresDays * DAY_MS,
|
|
32
33
|
environment,
|
|
34
|
+
purpose: 'company_root',
|
|
35
|
+
organisationId,
|
|
33
36
|
idempotencyKey: `${prefixFor(organisationId)}${name}:${crypto.randomUUID()}`,
|
|
34
37
|
});
|
|
35
38
|
if (!result.ok)
|
|
@@ -102,11 +105,6 @@ function respond(body, status) {
|
|
|
102
105
|
});
|
|
103
106
|
}
|
|
104
107
|
const fail = (status, error, message) => respond({ error, message }, status);
|
|
105
|
-
function tokensMatch(presented, configured) {
|
|
106
|
-
const a = createHash('sha256').update(presented, 'utf8').digest();
|
|
107
|
-
const b = createHash('sha256').update(configured, 'utf8').digest();
|
|
108
|
-
return timingSafeEqual(a, b);
|
|
109
|
-
}
|
|
110
108
|
const UNAVAILABLE = 'The key service could not complete this request. Try again in a moment, and contact the operator if it keeps happening.';
|
|
111
109
|
const MINT_FAILED = "The key service could not complete this request. A key may have been made anyway, and its secret is lost. Revoke all of this organisation's registrar keys (DELETE /v1/keys/platform/registrars/<organisationId>), then try again; contact the operator if it keeps happening.";
|
|
112
110
|
const REVOKE_BAD = 'The request was not valid. The organisation id and key id in the address must be letters, digits, dashes or underscores. Fix the address and try again.';
|
|
@@ -138,7 +136,7 @@ export function platformRegistrarEndpoint(options) {
|
|
|
138
136
|
return fail(503, 'unavailable', 'The platform route is not configured on this key service.');
|
|
139
137
|
}
|
|
140
138
|
const auth = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
|
|
141
|
-
if (!auth?.[1] || !
|
|
139
|
+
if (!auth?.[1] || !safeEqual(auth[1], token)) {
|
|
142
140
|
return fail(401, 'unauthorized', 'The platform token was not accepted.');
|
|
143
141
|
}
|
|
144
142
|
try {
|
package/dist/host/events.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { KeyUsedEvent } from '../held/index.js';
|
|
1
|
+
import type { HeldMutationEvent, KeyUsedEvent } from '../held/index.js';
|
|
2
2
|
import type { Db } from '../issued/index.js';
|
|
3
3
|
import type { AuditEvent } from '../issued/index.js';
|
|
4
4
|
/**
|
|
@@ -6,7 +6,11 @@ import type { AuditEvent } from '../issued/index.js';
|
|
|
6
6
|
* hand `recordEvent` -- the exact union `CreateCredentialIssuerOptions.audit`
|
|
7
7
|
* (`AuditEvent`, discriminated by `name`: `'credential.minted' |
|
|
8
8
|
* 'credential.rotated' | 'credential.revoked'`) and `CreateHeldKeysOptions.audit`
|
|
9
|
-
* (`KeyUsedEvent`, `name: 'key.used'`) can ever produce, between them
|
|
9
|
+
* (`KeyUsedEvent`, `name: 'key.used'`) can ever produce, between them, plus the
|
|
10
|
+
* three held mutations `./service` records: `CreateHeldKeysOptions.auditInTransaction`
|
|
11
|
+
* (`HeldMutationEvent`: `held.put`, `held.revoked`) and the shred sweep (`held.shredded`).
|
|
12
|
+
* `host/0002` adds those three kinds to the table's check, and `auditEndpoint`
|
|
13
|
+
* never returns them.
|
|
10
14
|
*
|
|
11
15
|
* `recordEvent`'s own parameter is this union, wider than either option
|
|
12
16
|
* alone expects, so `(event) => recordEvent(db, event)` type-checks as both
|
|
@@ -15,7 +19,12 @@ import type { AuditEvent } from '../issued/index.js';
|
|
|
15
19
|
* for (TypeScript's ordinary parameter contravariance), with no cast on
|
|
16
20
|
* either side.
|
|
17
21
|
*/
|
|
18
|
-
export type HostEvent = AuditEvent | KeyUsedEvent;
|
|
22
|
+
export type HostEvent = AuditEvent | KeyUsedEvent | HeldMutationEvent | HeldShredEvent;
|
|
23
|
+
/** The shred sweep ran. It names no tenant: the sweep decides eligibility on its own. */
|
|
24
|
+
export interface HeldShredEvent {
|
|
25
|
+
readonly name: 'held.shredded';
|
|
26
|
+
readonly at: number;
|
|
27
|
+
}
|
|
19
28
|
/**
|
|
20
29
|
* Inserts one `keys_host_events` row: this host's own append-only record of
|
|
21
30
|
* what `@wtfalch/keys` did on its behalf. Takes a drizzle handle rather than
|
|
@@ -24,3 +33,10 @@ export type HostEvent = AuditEvent | KeyUsedEvent;
|
|
|
24
33
|
* a disposable one.
|
|
25
34
|
*/
|
|
26
35
|
export declare function recordEvent(db: Db, event: HostEvent): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* `recordEvent` for `CreateCredentialIssuerOptions.auditInTransaction`:
|
|
38
|
+
* `auditInTransaction: recordEventInTransaction`. The event row is written in
|
|
39
|
+
* the same transaction as the change, so both commit or neither does. A failed
|
|
40
|
+
* insert aborts the change.
|
|
41
|
+
*/
|
|
42
|
+
export declare function recordEventInTransaction(tx: Db, event: AuditEvent): Promise<void>;
|
package/dist/host/events.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { inTenant } from '../held/tenant.js';
|
|
1
2
|
import { keysHostEvents } from './schema.js';
|
|
2
3
|
/**
|
|
3
4
|
* Inserts one `keys_host_events` row: this host's own append-only record of
|
|
@@ -7,25 +8,60 @@ import { keysHostEvents } from './schema.js';
|
|
|
7
8
|
* a disposable one.
|
|
8
9
|
*/
|
|
9
10
|
export async function recordEvent(db, event) {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
11
|
+
const at = new Date(event.at);
|
|
12
|
+
switch (event.name) {
|
|
13
|
+
case 'key.used':
|
|
14
|
+
await inTenant(db, event.tenantId, (tx) => tx.insert(keysHostEvents).values({
|
|
15
|
+
kind: event.name,
|
|
16
|
+
requestId: event.requestId,
|
|
17
|
+
credentialId: null,
|
|
18
|
+
tenantId: event.tenantId,
|
|
19
|
+
entryId: event.entryId,
|
|
20
|
+
version: event.version,
|
|
21
|
+
at,
|
|
22
|
+
}));
|
|
23
|
+
return;
|
|
24
|
+
case 'held.put':
|
|
25
|
+
case 'held.revoked':
|
|
26
|
+
await inTenant(db, event.tenantId, (tx) => tx.insert(keysHostEvents).values({
|
|
27
|
+
kind: event.name,
|
|
28
|
+
requestId: null,
|
|
29
|
+
credentialId: null,
|
|
30
|
+
tenantId: event.tenantId,
|
|
31
|
+
entryId: event.entryId,
|
|
32
|
+
version: event.name === 'held.put' ? event.version : null,
|
|
33
|
+
at,
|
|
34
|
+
}));
|
|
35
|
+
return;
|
|
36
|
+
case 'held.shredded':
|
|
37
|
+
await db.insert(keysHostEvents).values({
|
|
38
|
+
kind: event.name,
|
|
39
|
+
requestId: null,
|
|
40
|
+
credentialId: null,
|
|
41
|
+
tenantId: null,
|
|
42
|
+
entryId: null,
|
|
43
|
+
version: null,
|
|
44
|
+
at,
|
|
45
|
+
});
|
|
46
|
+
return;
|
|
47
|
+
default:
|
|
48
|
+
await db.insert(keysHostEvents).values({
|
|
49
|
+
kind: event.name,
|
|
50
|
+
requestId: event.requestId ?? null,
|
|
51
|
+
credentialId: event.credentialId,
|
|
52
|
+
tenantId: null,
|
|
53
|
+
entryId: null,
|
|
54
|
+
version: null,
|
|
55
|
+
at,
|
|
56
|
+
});
|
|
21
57
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* `recordEvent` for `CreateCredentialIssuerOptions.auditInTransaction`:
|
|
61
|
+
* `auditInTransaction: recordEventInTransaction`. The event row is written in
|
|
62
|
+
* the same transaction as the change, so both commit or neither does. A failed
|
|
63
|
+
* insert aborts the change.
|
|
64
|
+
*/
|
|
65
|
+
export async function recordEventInTransaction(tx, event) {
|
|
66
|
+
await recordEvent(tx, event);
|
|
31
67
|
}
|
package/dist/host/index.d.ts
CHANGED
|
@@ -10,9 +10,16 @@
|
|
|
10
10
|
* that lets a company's own credential mint and revoke its own apps'
|
|
11
11
|
* signed-records credentials, built entirely on `./issued`'s existing
|
|
12
12
|
* `check()`/`issue()`/`revoke()` -- see `registrar.ts`'s own header.
|
|
13
|
+
*
|
|
14
|
+
* `createNativeBuildKeyExchange`/`nativeBuildKeysEndpoint` (#126) is the
|
|
15
|
+
* route a native-shell `build-app.yml` run trades its own GitHub Actions
|
|
16
|
+
* OIDC token and a `runId` through, for that run's config and the owning
|
|
17
|
+
* company's Apple/Google keys -- see `native-build.ts`'s own header.
|
|
13
18
|
*/
|
|
14
19
|
export { auditEndpoint, type AuditEndpointOptions } from './audit-endpoint.js';
|
|
15
|
-
export { recordEvent, type HostEvent } from './events.js';
|
|
16
|
-
export { createRegistrar, registrarEndpoint, type RegisterAppResult, type Registrar, type RegistrarOptions, type RegistrarRefusalReason, type RevokeAppResult, } from './registrar.js';
|
|
20
|
+
export { recordEvent, recordEventInTransaction, type HeldShredEvent, type HostEvent, } from './events.js';
|
|
21
|
+
export { createRegistrar, REGISTRAR_REFUSAL_REASONS, registrarEndpoint, type RegisterAppResult, type Registrar, type RegistrarOptions, type RegistrarRefusalReason, type RevokeAppResult, } from './registrar.js';
|
|
17
22
|
export { createCompanyRegistrarKeys, platformRegistrarEndpoint, type CompanyRegistrarKeys, type CompanyRegistrarKeysOptions, type MintCompanyKeyResult, type PlatformRegistrarEndpointOptions, } from './company-registrar-keys.js';
|
|
23
|
+
export { createNativeBuildKeyExchange, NATIVE_BUILD_REFUSAL_REASONS, nativeBuildKeysEndpoint, nativeKeyEntryId, type NativeBuildClaims, type NativeBuildExchangeResult, type NativeBuildKeyExchange, type NativeBuildKeyExchangeOptions, type NativeBuildKeys, type NativeBuildKeysEndpointOptions, type NativeBuildRefusalReason, type NativeBuildRun, type NativeKeyField, } from './native-build.js';
|
|
24
|
+
export { runRotationSweep, type RotationSweepOptions, type RotationSweepReport, type RotationSweepResult, } from './rotation-sweep.js';
|
|
18
25
|
export { keysHostEvents, type KeysHostEventRow } from './schema.js';
|
package/dist/host/index.js
CHANGED
|
@@ -10,9 +10,16 @@
|
|
|
10
10
|
* that lets a company's own credential mint and revoke its own apps'
|
|
11
11
|
* signed-records credentials, built entirely on `./issued`'s existing
|
|
12
12
|
* `check()`/`issue()`/`revoke()` -- see `registrar.ts`'s own header.
|
|
13
|
+
*
|
|
14
|
+
* `createNativeBuildKeyExchange`/`nativeBuildKeysEndpoint` (#126) is the
|
|
15
|
+
* route a native-shell `build-app.yml` run trades its own GitHub Actions
|
|
16
|
+
* OIDC token and a `runId` through, for that run's config and the owning
|
|
17
|
+
* company's Apple/Google keys -- see `native-build.ts`'s own header.
|
|
13
18
|
*/
|
|
14
19
|
export { auditEndpoint } from './audit-endpoint.js';
|
|
15
|
-
export { recordEvent } from './events.js';
|
|
16
|
-
export { createRegistrar, registrarEndpoint, } from './registrar.js';
|
|
20
|
+
export { recordEvent, recordEventInTransaction, } from './events.js';
|
|
21
|
+
export { createRegistrar, REGISTRAR_REFUSAL_REASONS, registrarEndpoint, } from './registrar.js';
|
|
17
22
|
export { createCompanyRegistrarKeys, platformRegistrarEndpoint, } from './company-registrar-keys.js';
|
|
23
|
+
export { createNativeBuildKeyExchange, NATIVE_BUILD_REFUSAL_REASONS, nativeBuildKeysEndpoint, nativeKeyEntryId, } from './native-build.js';
|
|
24
|
+
export { runRotationSweep, } from './rotation-sweep.js';
|
|
18
25
|
export { keysHostEvents } from './schema.js';
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { type HeldKeys } from '../held/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* S5 of `estate/.plans/2026-10-22-app-shells.md` (decision 5): the one
|
|
4
|
+
* route a `build-app.yml` run may call to trade its own GitHub Actions OIDC
|
|
5
|
+
* token and a `runId` for that run's native build config and the owning
|
|
6
|
+
* company's Apple/Google keys.
|
|
7
|
+
*
|
|
8
|
+
* No table of its own, the same shape `./company-registrar-keys.ts` takes:
|
|
9
|
+
* which company and which `NativeAppConfig` a `runId` names is foundry's
|
|
10
|
+
* row, not this package's, so it arrives through the injected `resolveRun`
|
|
11
|
+
* rather than a query this module writes itself. The four key kinds the
|
|
12
|
+
* plan names each live as one `./held` entry per company (`tenantId` is the
|
|
13
|
+
* organisation id, `entryId` one of `NATIVE_KEY_ENTRY_IDS`); a company that
|
|
14
|
+
* has not entered a kind simply has no entry, read here as "not part of
|
|
15
|
+
* this answer", never a refusal.
|
|
16
|
+
*
|
|
17
|
+
* Authentication is the GitHub Actions OIDC token itself, verified against
|
|
18
|
+
* GitHub's own JWKS -- never a static bearer secret, because the fact that
|
|
19
|
+
* must hold is "this call came from the one workflow file, in the one
|
|
20
|
+
* repo, running on its default branch", which only GitHub's own signed
|
|
21
|
+
* claims can attest to. `repository`, `workflow_ref` and `ref` are each
|
|
22
|
+
* checked by exact match: a token minted for any other repository,
|
|
23
|
+
* workflow file or ref is refused the same as a forged one. The ref is the
|
|
24
|
+
* branch name, not a commit: a run of an older commit of the same file on
|
|
25
|
+
* the default branch carries the same claims and is not told apart.
|
|
26
|
+
*
|
|
27
|
+
* The workflow file is shared by every company, so those checks alone say
|
|
28
|
+
* "some build run", not "this company's run". The token's `run_id` claim is
|
|
29
|
+
* the tie: the exchange answers only when it equals the GitHub run id the
|
|
30
|
+
* `runId` row was bound to (`resolveRun`'s `githubRunId`).
|
|
31
|
+
*/
|
|
32
|
+
/** `ID_PATTERN`-safe entry id per key kind; `held/index.ts`'s `requireId` refuses a dot, so these are not the dotted names the plan uses in prose. */
|
|
33
|
+
declare const NATIVE_KEY_ENTRY_IDS: {
|
|
34
|
+
readonly appleAscKey: "apple-asc-key";
|
|
35
|
+
readonly appleDeveloperId: "apple-developer-id";
|
|
36
|
+
readonly googlePlayServiceAccount: "google-play-service-account";
|
|
37
|
+
readonly googleUploadKeystore: "google-upload-keystore";
|
|
38
|
+
};
|
|
39
|
+
export type NativeKeyField = keyof typeof NATIVE_KEY_ENTRY_IDS;
|
|
40
|
+
/** The `./held` entry id a native key field is stored and read under, for whatever writes it (Boule, through `held.put`). */
|
|
41
|
+
export declare function nativeKeyEntryId(field: NativeKeyField): string;
|
|
42
|
+
/** Only the kinds a company has actually entered; a missing field is "not configured", not an error. Each value is the parsed JSON a `put` stored. */
|
|
43
|
+
export type NativeBuildKeys = Partial<Record<NativeKeyField, unknown>>;
|
|
44
|
+
export interface NativeBuildRun<TConfig> {
|
|
45
|
+
readonly organisationId: string;
|
|
46
|
+
readonly config: TConfig;
|
|
47
|
+
readonly githubRunId: string;
|
|
48
|
+
}
|
|
49
|
+
/** The claims of a GitHub Actions token that passed every check. */
|
|
50
|
+
export interface NativeBuildClaims {
|
|
51
|
+
/** GitHub's `run_id` claim: the Actions run that minted the token. */
|
|
52
|
+
readonly runId: string;
|
|
53
|
+
}
|
|
54
|
+
export interface NativeBuildKeyExchangeOptions<TConfig> {
|
|
55
|
+
/** `openCurrent` is the only call this module makes; it never writes a held key. */
|
|
56
|
+
readonly heldKeys: Pick<HeldKeys, 'openCurrent'>;
|
|
57
|
+
/**
|
|
58
|
+
* Foundry's own build-run row: the company and config a `runId` names, and
|
|
59
|
+
* `githubRunId`, the GitHub Actions run id (a decimal string) of the one
|
|
60
|
+
* job allowed to read it. Returns `null` for a `runId` this run does not
|
|
61
|
+
* recognise -- including one that belongs to another company -- and for a
|
|
62
|
+
* row that does not yet know its GitHub run id (so the answer is 404).
|
|
63
|
+
* There is deliberately no bind on first use: the first token to ask would
|
|
64
|
+
* claim the row, and since every company's runs pass the same workflow
|
|
65
|
+
* checks, company A could claim company B's unclaimed run. The row is
|
|
66
|
+
* bound by whoever dispatched the run, before the run can ask. `null` is
|
|
67
|
+
* the ordinary answer for "unknown run", never thrown; throwing is
|
|
68
|
+
* reserved for an actual dependency failure (foundry's store unreachable),
|
|
69
|
+
* which this module reports the same way it reports any other outage:
|
|
70
|
+
* 502, logged without the runId.
|
|
71
|
+
*/
|
|
72
|
+
readonly resolveRun: (runId: string) => Promise<NativeBuildRun<TConfig> | null>;
|
|
73
|
+
/**
|
|
74
|
+
* The audience `build-app.yml` asks GitHub for with its own `id-token`
|
|
75
|
+
* request (`core.getIDToken(audience)`). Unset or empty refuses every
|
|
76
|
+
* token -- fails closed, the same rule `activity`'s `viewer-bearer.ts`
|
|
77
|
+
* applies to its own audience.
|
|
78
|
+
*/
|
|
79
|
+
readonly audience: string | undefined;
|
|
80
|
+
/** `owner/repo` of the one repository whose `build-app.yml` may call this endpoint, e.g. `'wtfalch/shell'`. */
|
|
81
|
+
readonly repository: string;
|
|
82
|
+
/** The workflow file's name, e.g. `'build-app.yml'`. */
|
|
83
|
+
readonly workflowFile: string;
|
|
84
|
+
/** That repository's default branch, e.g. `'main'`. The run must have executed the workflow file as committed there -- `workflow_ref` carries both the file and the ref together. */
|
|
85
|
+
readonly defaultBranch: string;
|
|
86
|
+
/** GitHub's OIDC issuer. Overridden only by tests. */
|
|
87
|
+
readonly issuer?: string;
|
|
88
|
+
/** GitHub's OIDC JWKS endpoint. Overridden only by tests. */
|
|
89
|
+
readonly jwksUrl?: string;
|
|
90
|
+
/** Test seam; defaults to the platform's global `fetch`. Used for every JWKS fetch `createRemoteJWKSet` makes. */
|
|
91
|
+
readonly fetchImpl?: typeof fetch;
|
|
92
|
+
}
|
|
93
|
+
export type NativeBuildRefusalReason = 'bad_request' | 'unauthorized' | 'not_found' | 'run_mismatch';
|
|
94
|
+
/** Every member of `NativeBuildRefusalReason`. Adding one is a major change after 1.0.0. */
|
|
95
|
+
export declare const NATIVE_BUILD_REFUSAL_REASONS: readonly ["bad_request", "unauthorized", "not_found", "run_mismatch"];
|
|
96
|
+
export type NativeBuildExchangeResult<TConfig> = {
|
|
97
|
+
readonly ok: true;
|
|
98
|
+
readonly config: TConfig;
|
|
99
|
+
readonly keys: NativeBuildKeys;
|
|
100
|
+
} | {
|
|
101
|
+
readonly ok: false;
|
|
102
|
+
readonly reason: NativeBuildRefusalReason;
|
|
103
|
+
};
|
|
104
|
+
export interface NativeBuildKeyExchange<TConfig> {
|
|
105
|
+
/** The checked claims of a token, or `null` when it is refused. Reads no run and no key. */
|
|
106
|
+
authenticate(token: string): Promise<NativeBuildClaims | null>;
|
|
107
|
+
exchange(input: {
|
|
108
|
+
readonly token: string;
|
|
109
|
+
readonly runId: unknown;
|
|
110
|
+
}): Promise<NativeBuildExchangeResult<TConfig>>;
|
|
111
|
+
}
|
|
112
|
+
export declare function createNativeBuildKeyExchange<TConfig>(options: NativeBuildKeyExchangeOptions<TConfig>): NativeBuildKeyExchange<TConfig>;
|
|
113
|
+
export type NativeBuildKeysEndpointOptions<TConfig> = NativeBuildKeyExchangeOptions<TConfig>;
|
|
114
|
+
/**
|
|
115
|
+
* `nativeBuildKeysEndpoint({ ... })` returns a fetch-shaped handler -- wire
|
|
116
|
+
* it directly as a route, e.g. `export const POST = nativeBuildKeysEndpoint({ ... });`.
|
|
117
|
+
*
|
|
118
|
+
* `POST /v1/keys/native-build` with `{ runId }` and `Authorization: Bearer
|
|
119
|
+
* <GitHub Actions OIDC token>` answers `200 { config, keys }`. Errors answer
|
|
120
|
+
* `{ error, message }`. A dependency failure that throws (GitHub's JWKS,
|
|
121
|
+
* foundry's run store, the held-key Worker) answers 502 `unavailable`,
|
|
122
|
+
* never a refusal such as `unauthorized` -- the same invariant
|
|
123
|
+
* `registrarEndpoint` keeps.
|
|
124
|
+
*/
|
|
125
|
+
export declare function nativeBuildKeysEndpoint<TConfig>(options: NativeBuildKeysEndpointOptions<TConfig>): (request: Request) => Promise<Response>;
|
|
126
|
+
export {};
|