@wtfalch/keys 0.7.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +349 -7
  2. package/dist/held/index.d.ts +116 -6
  3. package/dist/held/index.js +247 -25
  4. package/dist/held/schema.d.ts +17 -0
  5. package/dist/held/schema.js +12 -0
  6. package/dist/held/shred.d.ts +6 -0
  7. package/dist/held/shred.js +6 -0
  8. package/dist/held-edge/index.d.ts +17 -2
  9. package/dist/held-edge/index.js +51 -9
  10. package/dist/host/audit-endpoint.js +2 -8
  11. package/dist/host/company-registrar-keys.d.ts +106 -0
  12. package/dist/host/company-registrar-keys.js +211 -0
  13. package/dist/host/events.d.ts +19 -3
  14. package/dist/host/events.js +55 -20
  15. package/dist/host/index.d.ts +15 -1
  16. package/dist/host/index.js +15 -1
  17. package/dist/host/native-build.d.ts +126 -0
  18. package/dist/host/native-build.js +322 -0
  19. package/dist/host/registrar.d.ts +87 -0
  20. package/dist/host/registrar.js +284 -0
  21. package/dist/host/rotation-sweep.d.ts +56 -0
  22. package/dist/host/rotation-sweep.js +89 -0
  23. package/dist/issued/encoding.d.ts +4 -0
  24. package/dist/issued/encoding.js +22 -0
  25. package/dist/issued/index.d.ts +148 -7
  26. package/dist/issued/index.js +320 -34
  27. package/dist/issued/resign.d.ts +16 -0
  28. package/dist/issued/resign.js +55 -2
  29. package/dist/issued/tables.d.ts +38 -0
  30. package/dist/issued/tables.js +6 -0
  31. package/dist/issued/verify.d.ts +14 -3
  32. package/dist/issued/verify.js +10 -3
  33. package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
  34. package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
  35. package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
  36. package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
  37. package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
  38. package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
  39. package/dist/service/body.d.ts +21 -0
  40. package/dist/service/body.js +128 -0
  41. package/dist/service/errors.d.ts +24 -0
  42. package/dist/service/errors.js +89 -0
  43. package/dist/service/handler.d.ts +35 -0
  44. package/dist/service/handler.js +328 -0
  45. package/dist/service/index.d.ts +7 -0
  46. package/dist/service/index.js +7 -0
  47. package/dist/service/policy.d.ts +130 -0
  48. package/dist/service/policy.js +123 -0
  49. package/dist/service/timeout.d.ts +6 -0
  50. package/dist/service/timeout.js +34 -0
  51. package/dist/testing/index.d.ts +3 -0
  52. package/dist/testing/index.js +3 -0
  53. package/dist/webhooks.d.ts +40 -17
  54. package/dist/webhooks.js +70 -26
  55. package/dist/worker-contract.d.ts +43 -6
  56. package/dist/worker-contract.js +37 -0
  57. package/dist/worker.d.ts +1 -1
  58. package/dist/worker.js +7 -28
  59. package/package.json +21 -3
@@ -0,0 +1,322 @@
1
+ import { createRemoteJWKSet, customFetch, errors, jwtVerify } from 'jose';
2
+ import { HeldKeysError } from '../held/index.js';
3
+ /**
4
+ * S5 of `estate/.plans/2026-10-22-app-shells.md` (decision 5): the one
5
+ * route a `build-app.yml` run may call to trade its own GitHub Actions OIDC
6
+ * token and a `runId` for that run's native build config and the owning
7
+ * company's Apple/Google keys.
8
+ *
9
+ * No table of its own, the same shape `./company-registrar-keys.ts` takes:
10
+ * which company and which `NativeAppConfig` a `runId` names is foundry's
11
+ * row, not this package's, so it arrives through the injected `resolveRun`
12
+ * rather than a query this module writes itself. The four key kinds the
13
+ * plan names each live as one `./held` entry per company (`tenantId` is the
14
+ * organisation id, `entryId` one of `NATIVE_KEY_ENTRY_IDS`); a company that
15
+ * has not entered a kind simply has no entry, read here as "not part of
16
+ * this answer", never a refusal.
17
+ *
18
+ * Authentication is the GitHub Actions OIDC token itself, verified against
19
+ * GitHub's own JWKS -- never a static bearer secret, because the fact that
20
+ * must hold is "this call came from the one workflow file, in the one
21
+ * repo, running on its default branch", which only GitHub's own signed
22
+ * claims can attest to. `repository`, `workflow_ref` and `ref` are each
23
+ * checked by exact match: a token minted for any other repository,
24
+ * workflow file or ref is refused the same as a forged one. The ref is the
25
+ * branch name, not a commit: a run of an older commit of the same file on
26
+ * the default branch carries the same claims and is not told apart.
27
+ *
28
+ * The workflow file is shared by every company, so those checks alone say
29
+ * "some build run", not "this company's run". The token's `run_id` claim is
30
+ * the tie: the exchange answers only when it equals the GitHub run id the
31
+ * `runId` row was bound to (`resolveRun`'s `githubRunId`).
32
+ */
33
+ /** `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. */
34
+ const NATIVE_KEY_ENTRY_IDS = {
35
+ appleAscKey: 'apple-asc-key',
36
+ appleDeveloperId: 'apple-developer-id',
37
+ googlePlayServiceAccount: 'google-play-service-account',
38
+ googleUploadKeystore: 'google-upload-keystore',
39
+ };
40
+ /** The `./held` entry id a native key field is stored and read under, for whatever writes it (Boule, through `held.put`). */
41
+ export function nativeKeyEntryId(field) {
42
+ return NATIVE_KEY_ENTRY_IDS[field];
43
+ }
44
+ /** Every member of `NativeBuildRefusalReason`. Adding one is a major change after 1.0.0. */
45
+ export const NATIVE_BUILD_REFUSAL_REASONS = [
46
+ 'bad_request',
47
+ 'unauthorized',
48
+ 'not_found',
49
+ 'run_mismatch',
50
+ ];
51
+ const GITHUB_OIDC_ISSUER = 'https://token.actions.githubusercontent.com';
52
+ const GITHUB_OIDC_JWKS_URL = 'https://token.actions.githubusercontent.com/.well-known/jwks';
53
+ /** GitHub signs Actions OIDC tokens with RS256 (checked 2026-10-22); no other algorithm is accepted. */
54
+ const ALGORITHMS = ['RS256'];
55
+ /** Generous enough for any id foundry's own build-run table mints; bounded so this field alone cannot grow the request body unreasonably, and excludes whitespace so a run id can never collide with a padded or multi-line value. */
56
+ const RUN_ID_PATTERN = /^\S{1,256}$/;
57
+ /**
58
+ * GitHub's own `workflow_ref` claim is `<owner>/<repo>/.github/workflows/<file>@<ref>`
59
+ * -- the workflow file and the ref it ran at, together. Checking it by exact
60
+ * match is a single check that already covers "the right repo, the right
61
+ * workflow file, and the right ref": a token minted for any other
62
+ * repository, file or ref produces a different string.
63
+ */
64
+ function expectedWorkflowRef(repository, workflowFile, defaultBranch) {
65
+ return `${repository}/.github/workflows/${workflowFile}@refs/heads/${defaultBranch}`;
66
+ }
67
+ function createGithubActionsVerifier(options) {
68
+ const issuer = options.issuer ?? GITHUB_OIDC_ISSUER;
69
+ const jwksUrl = options.jwksUrl ?? GITHUB_OIDC_JWKS_URL;
70
+ const fetchImpl = options.fetchImpl ?? fetch;
71
+ const resolver = createRemoteJWKSet(new URL(jwksUrl), { [customFetch]: fetchImpl });
72
+ const workflowRef = expectedWorkflowRef(options.repository, options.workflowFile, options.defaultBranch);
73
+ const ref = `refs/heads/${options.defaultBranch}`;
74
+ // A key the JWKS does not hold is the token's own fault (`JWKSNoMatchingKey`/
75
+ // `JWKSMultipleMatchingKeys`); any other failure to fetch or parse the key
76
+ // set (the endpoint down, a non-200, a timeout) is GitHub's, not this
77
+ // token's. Thrown as a plain Error so the outer catch below, which treats
78
+ // only a `JOSEError` as "this token is bad", does not mistake an outage
79
+ // for a forged token -- same split `activity`'s `viewer-bearer.ts` makes.
80
+ const getKey = async (header, input) => {
81
+ try {
82
+ return await resolver(header, input);
83
+ }
84
+ catch (error) {
85
+ if (error instanceof errors.JWKSNoMatchingKey ||
86
+ error instanceof errors.JWKSMultipleMatchingKeys) {
87
+ throw error;
88
+ }
89
+ throw new Error('github oidc jwks fetch failed', { cause: error });
90
+ }
91
+ };
92
+ return async function verify(token) {
93
+ if (!options.audience)
94
+ return null;
95
+ let payload;
96
+ try {
97
+ ({ payload } = await jwtVerify(token, getKey, {
98
+ issuer,
99
+ audience: options.audience,
100
+ algorithms: ALGORITHMS,
101
+ requiredClaims: ['exp', 'sub', 'repository', 'workflow_ref', 'ref', 'run_id'],
102
+ clockTolerance: 30,
103
+ }));
104
+ }
105
+ catch (error) {
106
+ if (error instanceof errors.JOSEError)
107
+ return null;
108
+ throw error;
109
+ }
110
+ if (payload.repository !== options.repository)
111
+ return null;
112
+ if (payload.workflow_ref !== workflowRef)
113
+ return null;
114
+ if (payload.ref !== ref)
115
+ return null;
116
+ if (typeof payload.sub !== 'string' || payload.sub.length === 0)
117
+ return null;
118
+ if (typeof payload.run_id !== 'string' || payload.run_id.length === 0)
119
+ return null;
120
+ return { runId: payload.run_id };
121
+ };
122
+ }
123
+ export function createNativeBuildKeyExchange(options) {
124
+ const verify = createGithubActionsVerifier(options);
125
+ const { heldKeys, resolveRun } = options;
126
+ async function readKeys(organisationId) {
127
+ const keys = {};
128
+ for (const field of Object.keys(NATIVE_KEY_ENTRY_IDS)) {
129
+ const entryId = NATIVE_KEY_ENTRY_IDS[field];
130
+ try {
131
+ keys[field] = await heldKeys.openCurrent({ tenantId: organisationId, entryId }, async (raw) => JSON.parse(raw));
132
+ }
133
+ catch (error) {
134
+ // A company simply has not entered this kind: leave it out of the
135
+ // answer rather than refuse the whole exchange over one missing
136
+ // key. Any other code (revoked, disposed, a Worker fault) -- or a
137
+ // stored value that fails to parse -- is a real failure, not "not
138
+ // configured", and propagates to the endpoint's own catch (502).
139
+ if (error instanceof HeldKeysError && error.code === 'not_found')
140
+ continue;
141
+ throw error;
142
+ }
143
+ }
144
+ return keys;
145
+ }
146
+ return {
147
+ authenticate: verify,
148
+ async exchange({ token, runId }) {
149
+ if (typeof runId !== 'string' || !RUN_ID_PATTERN.test(runId)) {
150
+ return { ok: false, reason: 'bad_request' };
151
+ }
152
+ const claims = await verify(token);
153
+ if (claims === null)
154
+ return { ok: false, reason: 'unauthorized' };
155
+ const run = await resolveRun(runId);
156
+ if (run === null)
157
+ return { ok: false, reason: 'not_found' };
158
+ if (run.githubRunId !== claims.runId)
159
+ return { ok: false, reason: 'run_mismatch' };
160
+ const keys = await readKeys(run.organisationId);
161
+ return { ok: true, config: run.config, keys };
162
+ },
163
+ };
164
+ }
165
+ // ---------------------------------------------------------------------------
166
+ // The HTTP route
167
+ // ---------------------------------------------------------------------------
168
+ const EXCHANGE_PATH = '/v1/keys/native-build';
169
+ const BEARER_PATTERN = /^Bearer ([^\s]+)$/;
170
+ const MAX_BODY_BYTES = 4096;
171
+ /** Only these `.code` values are written to the log; any other string could be a driver's text carrying a value. */
172
+ const LOGGABLE_CODES = new Set([
173
+ 'credential_invalid',
174
+ 'credential_expired',
175
+ 'credential_revoked',
176
+ 'grant_missing',
177
+ 'rate_limited',
178
+ 'bad_request',
179
+ 'aad_mismatch',
180
+ 'unknown_generation',
181
+ 'bad_minter_signature',
182
+ 'minter_expired',
183
+ 'minter_revoked',
184
+ 'minter_exceeded',
185
+ 'lineage_mismatch',
186
+ 'bad_old_signature',
187
+ 'unlogged_row',
188
+ 'not_in_lineage',
189
+ 'unreachable',
190
+ 'not_found',
191
+ 'revoked',
192
+ 'unseal_failed',
193
+ 'disposed',
194
+ 'invalidated',
195
+ ]);
196
+ /** The body as text, or `null` when it is over `MAX_BODY_BYTES`; stops reading as soon as the cap is passed. */
197
+ async function readCappedText(request) {
198
+ const declared = Number(request.headers.get('content-length'));
199
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES)
200
+ return null;
201
+ if (!request.body)
202
+ return '';
203
+ const reader = request.body.getReader();
204
+ const chunks = [];
205
+ let total = 0;
206
+ for (;;) {
207
+ const { done, value } = await reader.read();
208
+ if (done)
209
+ break;
210
+ total += value.byteLength;
211
+ if (total > MAX_BODY_BYTES) {
212
+ await reader.cancel();
213
+ return null;
214
+ }
215
+ chunks.push(value);
216
+ }
217
+ const bytes = new Uint8Array(total);
218
+ let offset = 0;
219
+ for (const chunk of chunks) {
220
+ bytes.set(chunk, offset);
221
+ offset += chunk.byteLength;
222
+ }
223
+ return new TextDecoder().decode(bytes);
224
+ }
225
+ function statusForNativeBuild(reason) {
226
+ switch (reason) {
227
+ case 'bad_request':
228
+ return 400;
229
+ case 'unauthorized':
230
+ return 401;
231
+ case 'not_found':
232
+ return 404;
233
+ case 'run_mismatch':
234
+ return 403;
235
+ default: {
236
+ const unreachable = reason;
237
+ void unreachable;
238
+ return 502;
239
+ }
240
+ }
241
+ }
242
+ const MESSAGES = {
243
+ bad_request: 'Send { runId } as JSON, with runId a non-empty string of at most 256 characters.',
244
+ unauthorized: 'The bearer token was not accepted as a build-app.yml run on the configured repository, workflow file and default branch.',
245
+ not_found: 'No build run is known by that id.',
246
+ run_mismatch: 'This token belongs to a different build run than the one asked for, so we did not hand over any keys. Start the build again from the app and it will ask for its own run.',
247
+ };
248
+ const UNAVAILABLE_MESSAGE = 'The key service could not complete this request. Try again in a moment, and contact the operator if it keeps happening.';
249
+ /** Every answer, success or not, may carry a secret or tell about one: never cacheable. */
250
+ function jsonHeaders() {
251
+ return new Headers({ 'content-type': 'application/json', 'cache-control': 'no-store' });
252
+ }
253
+ function errorResponse(reason) {
254
+ return new Response(JSON.stringify({ error: reason, message: MESSAGES[reason] }), {
255
+ status: statusForNativeBuild(reason),
256
+ headers: jsonHeaders(),
257
+ });
258
+ }
259
+ function unavailableResponse() {
260
+ return new Response(JSON.stringify({ error: 'unavailable', message: UNAVAILABLE_MESSAGE }), {
261
+ status: 502,
262
+ headers: jsonHeaders(),
263
+ });
264
+ }
265
+ function okResponse(body) {
266
+ return new Response(JSON.stringify(body), { status: 200, headers: jsonHeaders() });
267
+ }
268
+ function plainResponse(status) {
269
+ return new Response(null, { status, headers: { 'cache-control': 'no-store' } });
270
+ }
271
+ /**
272
+ * `nativeBuildKeysEndpoint({ ... })` returns a fetch-shaped handler -- wire
273
+ * it directly as a route, e.g. `export const POST = nativeBuildKeysEndpoint({ ... });`.
274
+ *
275
+ * `POST /v1/keys/native-build` with `{ runId }` and `Authorization: Bearer
276
+ * <GitHub Actions OIDC token>` answers `200 { config, keys }`. Errors answer
277
+ * `{ error, message }`. A dependency failure that throws (GitHub's JWKS,
278
+ * foundry's run store, the held-key Worker) answers 502 `unavailable`,
279
+ * never a refusal such as `unauthorized` -- the same invariant
280
+ * `registrarEndpoint` keeps.
281
+ */
282
+ export function nativeBuildKeysEndpoint(options) {
283
+ const exchange = createNativeBuildKeyExchange(options);
284
+ return async function handleNativeBuildKeys(request) {
285
+ if (new URL(request.url).pathname !== EXCHANGE_PATH)
286
+ return plainResponse(404);
287
+ if (request.method !== 'POST')
288
+ return plainResponse(405);
289
+ const auth = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
290
+ if (!auth?.[1])
291
+ return errorResponse('unauthorized');
292
+ const token = auth[1];
293
+ try {
294
+ if ((await exchange.authenticate(token)) === null)
295
+ return errorResponse('unauthorized');
296
+ const text = await readCappedText(request);
297
+ if (text === null)
298
+ return errorResponse('bad_request');
299
+ let body;
300
+ try {
301
+ body = JSON.parse(text);
302
+ }
303
+ catch {
304
+ return errorResponse('bad_request');
305
+ }
306
+ const runId = body?.runId;
307
+ const result = await exchange.exchange({ token, runId });
308
+ if (!result.ok)
309
+ return errorResponse(result.reason);
310
+ return okResponse({ config: result.config, keys: result.keys });
311
+ }
312
+ catch (error) {
313
+ // Name and code only: a driver or dependency error's message can
314
+ // quote a secret value -- a held key, or the bearer token itself.
315
+ const name = error instanceof Error ? error.name : typeof error;
316
+ const rawCode = error?.code;
317
+ const code = typeof rawCode === 'string' && LOGGABLE_CODES.has(rawCode) ? ` ${rawCode}` : '';
318
+ console.error(`keys native-build: ${request.method} failed (${name}${code})`);
319
+ return unavailableResponse();
320
+ }
321
+ };
322
+ }
@@ -0,0 +1,87 @@
1
+ import type { CredentialIssuer, Db, IssueRefusalReason } from '../issued/index.js';
2
+ /**
3
+ * A per-company registrar: one company's own credential lets it mint and
4
+ * revoke its own apps' signed-records credentials, without the host that
5
+ * runs this endpoint (or Archon) standing in the middle of every request --
6
+ * the shape keys#119 asks for, modelled on the auth broker's own per-company
7
+ * app registration (`PUT`/`DELETE /apps/:org/:name`, auth#333).
8
+ *
9
+ * There is no new table and no new authentication mechanism here. A
10
+ * "company key" is simply an ordinary credential this same `issuer` already
11
+ * knows how to `check()` -- one whose `grants` the host marks as a
12
+ * registrar's, via `isRegistrarGrant`, when it mints that company's root
13
+ * credential (outside this module, the same way any other credential is
14
+ * minted). Scoping is the existing parent/child lineage: every app this
15
+ * registrar mints is a *child* of the company credential that minted it
16
+ * (`minter`), and every lookup below is filtered by that same parent id, so
17
+ * one company's key can never see or revoke another's app -- enforced by
18
+ * the database query, not by trusting a caller-supplied company id.
19
+ *
20
+ * Re-registering the same `appName` is idempotent (the auth broker's own
21
+ * `PUT` is): the two share one `idempotencyKey`, so a repeat call returns
22
+ * the same credential id with `secret: null` rather than minting a second
23
+ * one. Revoking a name the caller never registered -- or one only a
24
+ * different company registered -- reads as `app_not_found` either way; the
25
+ * caller cannot tell the two apart.
26
+ */
27
+ export interface RegistrarOptions<TGrant> {
28
+ readonly db: Db;
29
+ /** `check()`, `issue()` and `revokeForCompany()` are the only methods this module calls. */
30
+ readonly issuer: Pick<CredentialIssuer<TGrant>, 'check' | 'issue' | 'revokeForCompany'>;
31
+ /** Grants given to every credential minted through this registrar. Fixed by the host; never chosen by a caller. */
32
+ readonly appGrants: readonly TGrant[];
33
+ /** How long a minted app credential lives, in milliseconds from the moment it is registered. */
34
+ readonly appTtlMs: number;
35
+ /** True for a grant that marks a credential as a company's own registrar key, never held by a plain app credential. */
36
+ readonly isRegistrarGrant: (grant: TGrant) => boolean;
37
+ /** Unix milliseconds. Defaults to `Date.now`; a test passes a fake clock. */
38
+ readonly now?: () => number;
39
+ }
40
+ export type RegistrarRefusalReason = 'bad_app_name' | 'company_key_invalid'
41
+ /** Deprecated, removed at 1.0.0: never returned now. It reads as `company_key_invalid`. */
42
+ | 'company_key_not_a_registrar'
43
+ /** Another live company key of this organisation already holds that app name. */
44
+ | 'app_held_by_another_key' | 'rate_limited';
45
+ /** Every member of `RegistrarRefusalReason`. Adding one is a major change after 1.0.0. */
46
+ export declare const REGISTRAR_REFUSAL_REASONS: readonly ["bad_app_name", "company_key_invalid", "company_key_not_a_registrar", "app_held_by_another_key", "rate_limited"];
47
+ export type RegisterAppResult = {
48
+ readonly ok: true;
49
+ readonly id: string;
50
+ readonly secret: string | null;
51
+ } | {
52
+ readonly ok: false;
53
+ readonly reason: RegistrarRefusalReason | IssueRefusalReason;
54
+ /** Only meaningful with `reason: 'rate_limited'`. */
55
+ readonly retryAfterMs?: number;
56
+ };
57
+ export type RevokeAppResult = {
58
+ readonly ok: true;
59
+ readonly revoked: boolean;
60
+ } | {
61
+ readonly ok: false;
62
+ readonly reason: RegistrarRefusalReason | 'app_not_found' | 'protected_credential' | 'purpose_unknown';
63
+ readonly retryAfterMs?: number;
64
+ };
65
+ export interface Registrar {
66
+ /** Calls `issuer.issue()`. Idempotent per `(companySecret, appName)`. */
67
+ registerApp(companySecret: string, appName: string): Promise<RegisterAppResult>;
68
+ /** Calls `issuer.revoke()`. Idempotent: revoking an already-revoked app is `{ ok: true, revoked: false }`. */
69
+ revokeApp(companySecret: string, appName: string): Promise<RevokeAppResult>;
70
+ }
71
+ export declare function createRegistrar<TGrant>(options: RegistrarOptions<TGrant>): Registrar;
72
+ /**
73
+ * `registrarEndpoint({ ... })` returns a fetch-shaped handler -- wire it
74
+ * directly as a route, e.g.
75
+ * `export const PUT = registrarEndpoint({ db, issuer, appGrants, appTtlMs, isRegistrarGrant });`
76
+ * (the same handler again as `export const DELETE`).
77
+ * `PUT /v1/keys/registrar/apps/<appName>` registers (or idempotently
78
+ * re-registers) that app under the caller's company; `DELETE` on the same
79
+ * path revokes it. The caller's company credential is the bearer token,
80
+ * same as every other credential this package already checks -- there is
81
+ * no separate registrar-specific auth scheme to configure.
82
+ *
83
+ * Errors answer `{ error, message }` (the auth broker's shape). A database
84
+ * or issuer failure that throws answers 502 `unavailable`, never a refusal
85
+ * such as `company_key_invalid`.
86
+ */
87
+ export declare function registrarEndpoint<TGrant>(options: RegistrarOptions<TGrant>): (request: Request) => Promise<Response>;