@wtfalch/keys 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -141,6 +141,23 @@ transport/protocol failures. It makes one attempt per call: a request ID is audi
141
141
  correlation, not an idempotency guarantee. Host authentication and grant policy
142
142
  remain outside the transport. Existing injected clients remain supported.
143
143
 
144
+ ## Adopting `./held-edge`
145
+
146
+ `@wtfalch/keys/held-edge` is `./held`'s envelope encryption for a Cloudflare Worker: WebCrypto only, no `node:` import, no Postgres. A random AES-256-GCM data key per version encrypts the value, the same custody Worker wraps that data key, and the same AAD (tenant, entry, version; shared with `./held`, never copied) binds both layers. Storage stays with the caller: keep the returned `SealedHeld` as JSON.
147
+
148
+ ```ts
149
+ import { openHeld, sealHeld } from '@wtfalch/keys/held-edge';
150
+
151
+ const sealed = await sealHeld({ worker, credential, tenantId, entryId, version: 1, plaintext });
152
+ const plaintext = await openHeld({ worker, credential, tenantId, entryId, sealed });
153
+ ```
154
+
155
+ - `worker` is any `WorkerClient` (only `wrap` and `unwrap` are used); `credential` is the serialized bearer credential the custody Worker checks. Pass `timeoutMs` (default 10 s) to bound each Worker call.
156
+ - `version` is chosen and incremented by the caller. Opening with the wrong tenant, entry or version fails (`aad_mismatch` from the Worker, `unseal_failed` locally).
157
+ - `tenantId` and `entryId` must match `/^[A-Za-z0-9_-]{1,128}$/`; a bad id throws `HeldEdgeError('bad_request')` before any network call.
158
+ - Errors are `HeldEdgeError` with a `code`: the Worker's own code, `bad_request`, `unseal_failed` or `timeout`. A message never carries the plaintext, a key, or the Worker's free-text message.
159
+ - `createWorkerClient` (`./worker`) uses `Buffer`: on a Worker, enable `nodejs_compat` for it, or inject your own `WorkerClient`. `./held-edge` itself needs neither.
160
+
144
161
  ## Adopting `./host`
145
162
 
146
163
  `@wtfalch/keys/host` (added in **0.6.0**) is the host-side plumbing every
@@ -172,6 +189,108 @@ pulls from.
172
189
  no behaviour change and no data migration: the table name, every column
173
190
  and the response shape are identical field for field.
174
191
 
192
+ ## Per-company registrar
193
+
194
+ `createRegistrar`/`registrarEndpoint` from `./host` (added for #119) let a
195
+ company's own credential mint and revoke its own apps' signed-records
196
+ credentials directly, the way the auth broker lets a company register its
197
+ own apps (`PUT`/`DELETE /apps/:org/:name`) — without the operator standing in
198
+ the middle of every request, and without any new table or authentication
199
+ mechanism: a "company key" is just an ordinary credential this same
200
+ `issuer` already knows how to `check()`, marked by whichever grant the host
201
+ decides means "this one may register apps" (`isRegistrarGrant`).
202
+
203
+ ```ts
204
+ import { createRegistrar, registrarEndpoint } from '@wtfalch/keys/host';
205
+
206
+ const options = {
207
+ db,
208
+ issuer, // from createCredentialIssuer
209
+ appGrants: ['sign'],
210
+ appTtlMs: 365 * 24 * 60 * 60 * 1000,
211
+ isRegistrarGrant: (grant) => grant === 'registrar',
212
+ };
213
+
214
+ export const PUT = registrarEndpoint(options);
215
+ export const DELETE = registrarEndpoint(options);
216
+ ```
217
+
218
+ - `PUT /v1/keys/registrar/apps/<appName>` registers that app under the
219
+ caller's own company credential (the bearer) and returns its `id` and
220
+ `secret`. Re-registering the same name is idempotent: a repeat call
221
+ returns the same `id` with `secret: null`, never a second credential.
222
+ - `DELETE` on the same path revokes it. Revoking a name the caller never
223
+ registered — or one only a different company registered — is
224
+ `app_not_found` either way; the caller cannot tell the two apart.
225
+ - Scoping is the existing parent/child lineage, not a lookup a caller's
226
+ input could widen: every app this registrar mints is a child of the
227
+ company credential that minted it, and every lookup is filtered by that
228
+ same parent id, so one company's key can never see or revoke another's
229
+ app. `createRegistrar` alone (no HTTP) is there for a host that wants the
230
+ same guarantee behind its own transport.
231
+ - Every answer is `cache-control: no-store`. Errors are `{ error, message }`
232
+ (the auth broker's shape): `error` is a stable code, `message` says in
233
+ plain words what happened and what to do. A database or issuer failure is
234
+ 502 `{ error: "unavailable" }`, never a refusal like `company_key_invalid`.
235
+ `createRegistrar` throws if `appGrants` holds a grant `isRegistrarGrant`
236
+ accepts.
237
+ - A lost app secret: the secret is shown once, so `DELETE` the app and then
238
+ `PUT` it again for a new one (a repeat `PUT` on a live app returns
239
+ `secret: null`). A rotated company key: revoke the old key (the cascade
240
+ revokes the apps it minted), then register the apps again under the new key.
241
+ - Deliberate differences from the broker's `PUT /apps/:org/:name`: a repeat
242
+ `PUT` returns `secret: null` rather than a fresh key, and the registrar has
243
+ no bad-key limiter of its own; it relies on the issuer's per-credential
244
+ `rateLimiter` (a failed `check()` on an unknown key is not counted by it),
245
+ so put edge rate limiting in front of the route.
246
+
247
+ ### Platform route: minting a company's registrar key
248
+
249
+ `platformRegistrarEndpoint` (from `./host`) is the platform's side: it mints
250
+ and revokes the company key that `registrarEndpoint` then accepts. Wire it
251
+ next to the registrar, with the host's registrar grant and a platform token
252
+ (a static bearer, checked like `auditEndpoint`'s; under 32 characters or
253
+ unset, the route answers 503 and serves nothing):
254
+
255
+ ```ts
256
+ const platform = platformRegistrarEndpoint({
257
+ db,
258
+ issuer,
259
+ registrarGrant: 'registrar', // the grant `isRegistrarGrant` accepts
260
+ token: process.env.KEYS_PLATFORM_TOKEN,
261
+ });
262
+ export const POST = platform;
263
+ export const DELETE = platform;
264
+ ```
265
+
266
+ - `POST /v1/keys/platform/registrars` with `{ organisationId, name, expiresDays }`
267
+ (`expiresDays` a whole number, 1 to 365) answers `200 { id, secret }`. The
268
+ secret is shown once. Every call mints a new key.
269
+ - `DELETE /v1/keys/platform/registrars/<organisationId>/<id>` answers
270
+ `200 { revoked }` and revokes the key together with every app credential
271
+ registered under it. `revoked` is true only when the issuer revoked that key.
272
+ Idempotent: `false` when nothing live matches (unknown id, already revoked,
273
+ another company's id, or any credential that is not a root registrar key
274
+ minted for that company).
275
+ - `DELETE /v1/keys/platform/registrars/<organisationId>` revokes (cascade)
276
+ every live registrar key of that organisation and answers
277
+ `200 { revoked: <count> }` (0 when there are none). Use it when a mint's
278
+ answer was lost: the response carried the only copy of the secret, so a key
279
+ may exist that nobody holds, and a failed mint (502) may have created one.
280
+ Revoke all of the organisation's keys, then mint again. It is also the
281
+ cleanup when the organisation is destroyed.
282
+ - Every call needs `Authorization: Bearer <platform token>`. The platform token
283
+ must be its own secret, never the audit token or any other token. Errors are
284
+ `{ error, message }`:
285
+ - 200 success
286
+ - 400 `bad_request` (invalid body, organisation id or key id)
287
+ - 401 `unauthorized` (missing or wrong token)
288
+ - 404 (path not under this route)
289
+ - 405 (method not allowed for the path)
290
+ - 502 `unavailable` (the issuer or database failed; after a mint, a key may
291
+ have been made, so revoke all of the organisation's keys before retrying)
292
+ - 503 `unavailable` (no platform token configured, or under 32 characters)
293
+
175
294
  ## Adopting `./testing`
176
295
 
177
296
  `@wtfalch/keys/testing` (added in **0.6.0**) is an in-process Worker stub for
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `./held-edge`: the `./held` envelope model for a Cloudflare Worker.
3
+ *
4
+ * Same model as `../held/index.ts`: a random AES-256-GCM data key per version
5
+ * encrypts the value, the custody Worker wraps that data key, and the AAD
6
+ * (`../held/aad.ts`, shared, not copied) binds tenant, entry and version to
7
+ * both layers. Unlike `./held` there is no Postgres and no `node:crypto`:
8
+ * WebCrypto only. Storage of the `SealedHeld` stays with the caller.
9
+ *
10
+ * This file imports nothing from `node:` and only `../held/aad.ts` and types
11
+ * and constants from `../worker-contract.ts`. The `WorkerClient` is injected
12
+ * (`createWorkerClient` from `../worker` needs `nodejs_compat`).
13
+ */
14
+ import { type SerializedCredential, type WorkerClient, type WorkerErrorCode } from '../worker-contract.js';
15
+ export { encodeAad } from '../held/aad.js';
16
+ export interface SealedHeld {
17
+ v: 1;
18
+ kekId: string;
19
+ /** base64url, the custody Worker's wrapped data key. */
20
+ wrappedKey: string;
21
+ /** base64url, 12 bytes. */
22
+ iv: string;
23
+ /** base64url, ciphertext with the GCM tag appended. */
24
+ ct: string;
25
+ version: number;
26
+ }
27
+ /** Local refusals plus the Worker's own code, verbatim. Never carries a value or a key. */
28
+ export type HeldEdgeErrorCode = WorkerErrorCode | 'bad_request' | 'unseal_failed' | 'timeout';
29
+ export declare class HeldEdgeError extends Error {
30
+ readonly code: HeldEdgeErrorCode;
31
+ constructor(code: HeldEdgeErrorCode, message?: string);
32
+ }
33
+ interface CallOptions {
34
+ readonly worker: Pick<WorkerClient, 'wrap' | 'unwrap'>;
35
+ /** Sent to the custody Worker as the bearer credential. */
36
+ readonly credential: SerializedCredential;
37
+ readonly tenantId: string;
38
+ readonly entryId: string;
39
+ /** Per-call limit on the Worker call. Default 10s. */
40
+ readonly timeoutMs?: number;
41
+ }
42
+ export interface SealHeldOptions extends CallOptions {
43
+ readonly version: number;
44
+ readonly plaintext: string;
45
+ }
46
+ export interface OpenHeldOptions extends CallOptions {
47
+ readonly sealed: SealedHeld;
48
+ }
49
+ export declare function sealHeld(o: SealHeldOptions): Promise<SealedHeld>;
50
+ export declare function openHeld(o: OpenHeldOptions): Promise<string>;
@@ -0,0 +1,175 @@
1
+ import { encodeAad } from '../held/aad.js';
2
+ /**
3
+ * `./held-edge`: the `./held` envelope model for a Cloudflare Worker.
4
+ *
5
+ * Same model as `../held/index.ts`: a random AES-256-GCM data key per version
6
+ * encrypts the value, the custody Worker wraps that data key, and the AAD
7
+ * (`../held/aad.ts`, shared, not copied) binds tenant, entry and version to
8
+ * both layers. Unlike `./held` there is no Postgres and no `node:crypto`:
9
+ * WebCrypto only. Storage of the `SealedHeld` stays with the caller.
10
+ *
11
+ * This file imports nothing from `node:` and only `../held/aad.ts` and types
12
+ * and constants from `../worker-contract.ts`. The `WorkerClient` is injected
13
+ * (`createWorkerClient` from `../worker` needs `nodejs_compat`).
14
+ */
15
+ import { ID_PATTERN, } from '../worker-contract.js';
16
+ export { encodeAad } from '../held/aad.js';
17
+ const DEFAULT_TIMEOUT_MS = 10_000;
18
+ const IV_BYTES = 12;
19
+ const DATA_KEY_BYTES = 32;
20
+ const WRAPPED_KEY_BYTES = 60;
21
+ const TAG_BYTES = 16;
22
+ export class HeldEdgeError extends Error {
23
+ code;
24
+ constructor(code, message) {
25
+ super(message ?? code);
26
+ this.name = 'HeldEdgeError';
27
+ this.code = code;
28
+ }
29
+ }
30
+ function toBase64Url(bytes) {
31
+ let bin = '';
32
+ for (const b of bytes)
33
+ bin += String.fromCharCode(b);
34
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
35
+ }
36
+ /** `null` unless `text` is exactly one round trip of `toBase64Url`. */
37
+ function fromBase64Url(text) {
38
+ if (typeof text !== 'string' || !/^[A-Za-z0-9_-]+$/.test(text))
39
+ return null;
40
+ try {
41
+ const std = text.replace(/-/g, '+').replace(/_/g, '/');
42
+ const bin = atob(std + '='.repeat((4 - (std.length % 4)) % 4));
43
+ const out = new Uint8Array(bin.length);
44
+ for (let i = 0; i < bin.length; i++)
45
+ out[i] = bin.charCodeAt(i);
46
+ return toBase64Url(out) === text ? out : null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ function checkIds(tenantId, entryId) {
53
+ if (typeof tenantId !== 'string' || !ID_PATTERN.test(tenantId)) {
54
+ throw new HeldEdgeError('bad_request', 'tenantId does not match the id pattern');
55
+ }
56
+ if (typeof entryId !== 'string' || !ID_PATTERN.test(entryId)) {
57
+ throw new HeldEdgeError('bad_request', 'entryId does not match the id pattern');
58
+ }
59
+ }
60
+ function checkVersion(version) {
61
+ if (!Number.isSafeInteger(version) || version < 1) {
62
+ throw new HeldEdgeError('bad_request', 'version must be a positive integer');
63
+ }
64
+ }
65
+ function checkTimeout(timeoutMs) {
66
+ const ms = timeoutMs ?? DEFAULT_TIMEOUT_MS;
67
+ if (!Number.isSafeInteger(ms) || ms < 1 || ms > 2_147_483_647) {
68
+ throw new RangeError('timeoutMs must be an integer from 1 to 2147483647');
69
+ }
70
+ return ms;
71
+ }
72
+ /** Races the Worker call against a timer; the timer is always cleared. */
73
+ async function withTimeout(call, ms) {
74
+ let timer;
75
+ const timeout = new Promise((_, reject) => {
76
+ timer = setTimeout(() => reject(new HeldEdgeError('timeout', 'custody Worker timed out')), ms);
77
+ });
78
+ try {
79
+ return await Promise.race([call, timeout]);
80
+ }
81
+ finally {
82
+ clearTimeout(timer);
83
+ }
84
+ }
85
+ /** Surfaces the Worker's code only: its free-text message is never copied. */
86
+ function fromWorker(code) {
87
+ return new HeldEdgeError(code, `custody Worker refused: ${code}`);
88
+ }
89
+ async function importDataKey(dataKey, usage) {
90
+ if (dataKey.length !== DATA_KEY_BYTES)
91
+ throw new HeldEdgeError('unseal_failed');
92
+ return crypto.subtle.importKey('raw', dataKey, { name: 'AES-GCM' }, false, [usage]);
93
+ }
94
+ export async function sealHeld(o) {
95
+ checkIds(o.tenantId, o.entryId);
96
+ checkVersion(o.version);
97
+ if (typeof o.plaintext !== 'string') {
98
+ throw new HeldEdgeError('bad_request', 'plaintext must be a string');
99
+ }
100
+ const ms = checkTimeout(o.timeoutMs);
101
+ const binding = { tenantId: o.tenantId, entryId: o.entryId, version: o.version };
102
+ const aad = encodeAad(binding);
103
+ const result = await withTimeout(o.worker.wrap({ requestId: crypto.randomUUID(), credential: o.credential, binding }), ms);
104
+ if (!result.ok)
105
+ throw fromWorker(result.error.code);
106
+ const dataKey = result.dataKey;
107
+ try {
108
+ // Refuse here what openHeld refuses, or the value would be sealed but never open again.
109
+ if (!ID_PATTERN.test(result.kekId) || result.wrappedKey.length !== WRAPPED_KEY_BYTES) {
110
+ throw new HeldEdgeError('bad_request', 'custody worker returned a malformed wrap');
111
+ }
112
+ const key = await importDataKey(dataKey, 'encrypt');
113
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
114
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, new TextEncoder().encode(o.plaintext)));
115
+ return {
116
+ v: 1,
117
+ kekId: result.kekId,
118
+ wrappedKey: toBase64Url(result.wrappedKey),
119
+ iv: toBase64Url(iv),
120
+ ct: toBase64Url(ct),
121
+ version: o.version,
122
+ };
123
+ }
124
+ finally {
125
+ dataKey.fill(0);
126
+ }
127
+ }
128
+ export async function openHeld(o) {
129
+ checkIds(o.tenantId, o.entryId);
130
+ const s = o.sealed;
131
+ if (typeof s !== 'object' || s === null || s.v !== 1) {
132
+ throw new HeldEdgeError('bad_request', 'sealed is not a v1 SealedHeld');
133
+ }
134
+ checkVersion(s.version);
135
+ if (typeof s.kekId !== 'string' || !ID_PATTERN.test(s.kekId)) {
136
+ throw new HeldEdgeError('bad_request', 'sealed.kekId does not match the id pattern');
137
+ }
138
+ const wrappedKey = fromBase64Url(s.wrappedKey);
139
+ const iv = fromBase64Url(s.iv);
140
+ const ct = fromBase64Url(s.ct);
141
+ if (wrappedKey?.length !== WRAPPED_KEY_BYTES ||
142
+ iv?.length !== IV_BYTES ||
143
+ !ct ||
144
+ ct.length < TAG_BYTES) {
145
+ throw new HeldEdgeError('bad_request', 'sealed has a malformed field');
146
+ }
147
+ const ms = checkTimeout(o.timeoutMs);
148
+ const binding = { tenantId: o.tenantId, entryId: o.entryId, version: s.version };
149
+ const aad = encodeAad(binding);
150
+ const result = await withTimeout(o.worker.unwrap({
151
+ requestId: crypto.randomUUID(),
152
+ credential: o.credential,
153
+ kekId: s.kekId,
154
+ wrappedKey,
155
+ binding,
156
+ }), ms);
157
+ if (!result.ok)
158
+ throw fromWorker(result.error.code);
159
+ const dataKey = result.dataKey;
160
+ try {
161
+ const key = await importDataKey(dataKey, 'decrypt');
162
+ let plain;
163
+ try {
164
+ plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, ct);
165
+ }
166
+ catch {
167
+ // The WebCrypto error is dropped: it says nothing a caller may use.
168
+ throw new HeldEdgeError('unseal_failed', 'that version could not be opened with the given data key');
169
+ }
170
+ return new TextDecoder().decode(plain);
171
+ }
172
+ finally {
173
+ dataKey.fill(0);
174
+ }
175
+ }
@@ -0,0 +1,93 @@
1
+ import type { CredentialIssuer, Db, IssueRefusalReason, KeyEnvironment } from '../issued/index.js';
2
+ /**
3
+ * The platform's half of the per-company registrar (`./registrar.ts`): the
4
+ * route through which the platform (foundry) mints a company's registrar
5
+ * credential and revokes it. The company's Boule then presents that
6
+ * credential to `registrarEndpoint` to register its own apps.
7
+ *
8
+ * Authentication is the host's static platform bearer token, checked the way
9
+ * `auditEndpoint` checks its own: constant-time, and a missing or short token
10
+ * means the route refuses to serve at all (503), never "accept anything".
11
+ *
12
+ * No table of its own. A company registrar key is an ordinary root
13
+ * credential (`minter: null`) of the host's issuer carrying the host's
14
+ * registrar grant. It is tied to its company by its `idempotencyKey`,
15
+ * `company-registrar:<organisationId>:<name>:<nonce>`, so revoke is scoped by
16
+ * the database row, not by trusting the caller to pass the right company.
17
+ * The nonce makes every mint a fresh credential with a secret (a repeat call
18
+ * is never an idempotent replay with `secret: null`, which a platform that
19
+ * lost the first answer could not use).
20
+ *
21
+ * The org binding through `idempotencyKey` is advisory: the key is a label the
22
+ * minter chose, not proof about the caller. It is only safe because only the
23
+ * holder of the platform token can mint a key carrying that prefix; revoke
24
+ * therefore also requires a root row (no minter) with the host's registrar
25
+ * grant, so a look-alike key never qualifies.
26
+ *
27
+ * Revoke cascades: every app credential the company registered is a child of
28
+ * the registrar key, so they all go with it.
29
+ */
30
+ export interface CompanyRegistrarKeysOptions<TGrant> {
31
+ readonly db: Db;
32
+ readonly issuer: Pick<CredentialIssuer<TGrant>, 'issue' | 'revoke'>;
33
+ /** The grant that marks a credential as a company's registrar key (the host's `isRegistrarGrant` accepts it). */
34
+ readonly registrarGrant: TGrant;
35
+ /** Longest lifetime a mint may ask for, in days. Defaults to 365. */
36
+ readonly maxExpiresDays?: number;
37
+ /** Environment of the minted key. Defaults to `'live'`; app credentials inherit it. */
38
+ readonly environment?: KeyEnvironment;
39
+ /** Unix milliseconds. Defaults to `Date.now`. */
40
+ readonly now?: () => number;
41
+ }
42
+ export type MintCompanyKeyResult = {
43
+ readonly ok: true;
44
+ readonly id: string;
45
+ readonly secret: string;
46
+ } | {
47
+ readonly ok: false;
48
+ readonly reason: 'bad_request' | IssueRefusalReason;
49
+ };
50
+ export interface CompanyRegistrarKeys {
51
+ mint(input: {
52
+ readonly organisationId: string;
53
+ readonly name: string;
54
+ readonly expiresDays: number;
55
+ }): Promise<MintCompanyKeyResult>;
56
+ /** `revoked: false` when nothing was revoked (unknown id, another company's id, already revoked, not a registrar key). */
57
+ revoke(organisationId: string, id: string): Promise<{
58
+ readonly ok: true;
59
+ readonly revoked: boolean;
60
+ } | {
61
+ readonly ok: false;
62
+ readonly reason: 'bad_request';
63
+ }>;
64
+ /** Revokes (cascade) every live registrar key of the company; `revoked` is how many keys. */
65
+ revokeAll(organisationId: string): Promise<{
66
+ readonly ok: true;
67
+ readonly revoked: number;
68
+ } | {
69
+ readonly ok: false;
70
+ readonly reason: 'bad_request';
71
+ }>;
72
+ }
73
+ export declare function createCompanyRegistrarKeys<TGrant>(options: CompanyRegistrarKeysOptions<TGrant>): CompanyRegistrarKeys;
74
+ export interface PlatformRegistrarEndpointOptions<TGrant> extends CompanyRegistrarKeysOptions<TGrant> {
75
+ /** The platform's bearer token. Missing or under 32 characters: the route answers 503 and serves nothing. */
76
+ readonly token: string | undefined;
77
+ }
78
+ /**
79
+ * `platformRegistrarEndpoint({ ... })` returns a fetch-shaped handler for all
80
+ * routes; wire it as `POST` and `DELETE` the way `registrarEndpoint` is wired.
81
+ *
82
+ * - `POST /v1/keys/platform/registrars` with `{ organisationId, name, expiresDays }`
83
+ * answers `200 { id, secret }`. The secret is shown once.
84
+ * - `DELETE /v1/keys/platform/registrars/<organisationId>/<id>` answers
85
+ * `200 { revoked }` (`false` when nothing live matched: idempotent), and
86
+ * revokes every app the company registered with it.
87
+ *
88
+ * - `DELETE /v1/keys/platform/registrars/<organisationId>` revokes (cascade)
89
+ * every live registrar key of that company and answers `200 { revoked: <count> }`.
90
+ *
91
+ * All need `Authorization: Bearer <platform token>`.
92
+ */
93
+ export declare function platformRegistrarEndpoint<TGrant>(options: PlatformRegistrarEndpointOptions<TGrant>): (request: Request) => Promise<Response>;
@@ -0,0 +1,213 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { and, eq, isNull, like } from 'drizzle-orm';
3
+ import { keysIssuedCredentials } from '../issued/tables.js';
4
+ import { ID_PATTERN } from '../worker-contract.js';
5
+ const DAY_MS = 24 * 60 * 60 * 1000;
6
+ const DEFAULT_MAX_DAYS = 365;
7
+ const prefixFor = (organisationId) => `company-registrar:${organisationId}:`;
8
+ export function createCompanyRegistrarKeys(options) {
9
+ const { db, issuer, registrarGrant } = options;
10
+ const maxDays = options.maxExpiresDays ?? DEFAULT_MAX_DAYS;
11
+ const environment = options.environment ?? 'live';
12
+ const now = options.now ?? (() => Date.now());
13
+ const grantKey = JSON.stringify(registrarGrant);
14
+ // A company registrar key: root credential, this company's prefix, carrying the registrar grant.
15
+ const isCompanyKey = (row, organisationId) => row.issuedById === null &&
16
+ row.idempotencyKey?.startsWith(prefixFor(organisationId)) === true &&
17
+ Array.isArray(row.grants) &&
18
+ row.grants.some((g) => JSON.stringify(g) === grantKey);
19
+ return {
20
+ async mint({ organisationId, name, expiresDays }) {
21
+ if (!ID_PATTERN.test(organisationId) ||
22
+ !ID_PATTERN.test(name) ||
23
+ !Number.isInteger(expiresDays) ||
24
+ expiresDays < 1 ||
25
+ expiresDays > maxDays) {
26
+ return { ok: false, reason: 'bad_request' };
27
+ }
28
+ const result = await issuer.issue({
29
+ grants: [registrarGrant],
30
+ minter: null,
31
+ expiresAt: now() + expiresDays * DAY_MS,
32
+ environment,
33
+ idempotencyKey: `${prefixFor(organisationId)}${name}:${crypto.randomUUID()}`,
34
+ });
35
+ if (!result.ok)
36
+ return result;
37
+ // A fresh nonce means this is never a replay; a null secret would be unusable, so refuse it.
38
+ if (result.secret === null)
39
+ return { ok: false, reason: 'unreachable' };
40
+ return { ok: true, id: result.id, secret: result.secret };
41
+ },
42
+ async revoke(organisationId, id) {
43
+ if (!ID_PATTERN.test(organisationId) || !ID_PATTERN.test(id)) {
44
+ return { ok: false, reason: 'bad_request' };
45
+ }
46
+ const [row] = await db
47
+ .select({
48
+ idempotencyKey: keysIssuedCredentials.idempotencyKey,
49
+ issuedById: keysIssuedCredentials.issuedById,
50
+ grants: keysIssuedCredentials.grants,
51
+ revokedAt: keysIssuedCredentials.revokedAt,
52
+ })
53
+ .from(keysIssuedCredentials)
54
+ .where(eq(keysIssuedCredentials.id, id))
55
+ .limit(1);
56
+ // Only a registrar key minted for this company: this route can never
57
+ // reach an app credential, a credential of another company or an
58
+ // unrelated host credential.
59
+ if (!row || !isCompanyKey(row, organisationId) || row.revokedAt !== null) {
60
+ return { ok: true, revoked: false };
61
+ }
62
+ const done = await issuer.revoke(id, { cascade: true });
63
+ return { ok: true, revoked: Array.isArray(done) && done.includes(id) };
64
+ },
65
+ async revokeAll(organisationId) {
66
+ if (!ID_PATTERN.test(organisationId))
67
+ return { ok: false, reason: 'bad_request' };
68
+ const prefix = prefixFor(organisationId).replace(/[\\%_]/g, (c) => `\\${c}`);
69
+ const rows = await db
70
+ .select({
71
+ id: keysIssuedCredentials.id,
72
+ idempotencyKey: keysIssuedCredentials.idempotencyKey,
73
+ issuedById: keysIssuedCredentials.issuedById,
74
+ grants: keysIssuedCredentials.grants,
75
+ })
76
+ .from(keysIssuedCredentials)
77
+ .where(and(like(keysIssuedCredentials.idempotencyKey, `${prefix}%`), isNull(keysIssuedCredentials.revokedAt)));
78
+ let revoked = 0;
79
+ for (const row of rows) {
80
+ if (!isCompanyKey(row, organisationId))
81
+ continue;
82
+ const done = await issuer.revoke(row.id, { cascade: true });
83
+ if (Array.isArray(done) && done.includes(row.id))
84
+ revoked += 1;
85
+ }
86
+ return { ok: true, revoked };
87
+ },
88
+ };
89
+ }
90
+ // ---------------------------------------------------------------------------
91
+ // The HTTP route
92
+ // ---------------------------------------------------------------------------
93
+ const MINT_PATH = '/v1/keys/platform/registrars';
94
+ const REVOKE_PATH = /^\/v1\/keys\/platform\/registrars\/([^/]+)\/([^/]+)$/;
95
+ const BEARER_PATTERN = /^Bearer ([^\s]+)$/;
96
+ const MAX_BODY_BYTES = 4096;
97
+ const ORG_REVOKE_PATH = /^\/v1\/keys\/platform\/registrars\/([^/]+)$/;
98
+ function respond(body, status) {
99
+ return new Response(JSON.stringify(body), {
100
+ status,
101
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
102
+ });
103
+ }
104
+ 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
+ const UNAVAILABLE = 'The key service could not complete this request. Try again in a moment, and contact the operator if it keeps happening.';
111
+ 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
+ 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.';
113
+ /**
114
+ * `platformRegistrarEndpoint({ ... })` returns a fetch-shaped handler for all
115
+ * routes; wire it as `POST` and `DELETE` the way `registrarEndpoint` is wired.
116
+ *
117
+ * - `POST /v1/keys/platform/registrars` with `{ organisationId, name, expiresDays }`
118
+ * answers `200 { id, secret }`. The secret is shown once.
119
+ * - `DELETE /v1/keys/platform/registrars/<organisationId>/<id>` answers
120
+ * `200 { revoked }` (`false` when nothing live matched: idempotent), and
121
+ * revokes every app the company registered with it.
122
+ *
123
+ * - `DELETE /v1/keys/platform/registrars/<organisationId>` revokes (cascade)
124
+ * every live registrar key of that company and answers `200 { revoked: <count> }`.
125
+ *
126
+ * All need `Authorization: Bearer <platform token>`.
127
+ */
128
+ export function platformRegistrarEndpoint(options) {
129
+ const keys = createCompanyRegistrarKeys(options);
130
+ const { token } = options;
131
+ return async function handlePlatformRegistrar(request) {
132
+ const path = new URL(request.url).pathname;
133
+ const revokeMatch = REVOKE_PATH.exec(path);
134
+ const orgMatch = ORG_REVOKE_PATH.exec(path);
135
+ if (path !== MINT_PATH && !revokeMatch && !orgMatch)
136
+ return new Response(null, { status: 404, headers: { 'cache-control': 'no-store' } });
137
+ if (!token || token.length < 32) {
138
+ return fail(503, 'unavailable', 'The platform route is not configured on this key service.');
139
+ }
140
+ const auth = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
141
+ if (!auth?.[1] || !tokensMatch(auth[1], token)) {
142
+ return fail(401, 'unauthorized', 'The platform token was not accepted.');
143
+ }
144
+ try {
145
+ if (request.method === 'POST' && path === MINT_PATH) {
146
+ const text = await request.text();
147
+ if (new TextEncoder().encode(text).length > MAX_BODY_BYTES)
148
+ return badRequest();
149
+ let body;
150
+ try {
151
+ body = JSON.parse(text);
152
+ }
153
+ catch {
154
+ return badRequest();
155
+ }
156
+ const b = body;
157
+ if (!b ||
158
+ typeof b.organisationId !== 'string' ||
159
+ typeof b.name !== 'string' ||
160
+ typeof b.expiresDays !== 'number') {
161
+ return badRequest();
162
+ }
163
+ const result = await keys.mint({
164
+ organisationId: b.organisationId,
165
+ name: b.name,
166
+ expiresDays: b.expiresDays,
167
+ });
168
+ if (!result.ok) {
169
+ return result.reason === 'bad_request' ? badRequest() : unavailable(MINT_FAILED);
170
+ }
171
+ return respond({ id: result.id, secret: result.secret }, 200);
172
+ }
173
+ if (request.method === 'DELETE' && revokeMatch) {
174
+ let organisationId;
175
+ let id;
176
+ try {
177
+ organisationId = decodeURIComponent(revokeMatch[1]);
178
+ id = decodeURIComponent(revokeMatch[2]);
179
+ }
180
+ catch {
181
+ return badRequest(REVOKE_BAD);
182
+ }
183
+ const result = await keys.revoke(organisationId, id);
184
+ if (!result.ok)
185
+ return badRequest(REVOKE_BAD);
186
+ return respond({ revoked: result.revoked }, 200);
187
+ }
188
+ if (request.method === 'DELETE' && orgMatch) {
189
+ let organisationId;
190
+ try {
191
+ organisationId = decodeURIComponent(orgMatch[1]);
192
+ }
193
+ catch {
194
+ return badRequest(REVOKE_BAD);
195
+ }
196
+ const result = await keys.revokeAll(organisationId);
197
+ if (!result.ok)
198
+ return badRequest(REVOKE_BAD);
199
+ return respond({ revoked: result.revoked }, 200);
200
+ }
201
+ }
202
+ catch (error) {
203
+ const name = error instanceof Error ? error.name : typeof error;
204
+ const code = error?.code;
205
+ console.error(`keys platform registrar: ${request.method} failed (${name}${typeof code === 'string' ? ` ${code}` : ''})`);
206
+ // A mint that threw may still have created a key.
207
+ return request.method === 'POST' ? unavailable(MINT_FAILED) : unavailable();
208
+ }
209
+ return new Response(null, { status: 405, headers: { 'cache-control': 'no-store' } });
210
+ };
211
+ }
212
+ const badRequest = (message = 'The request was not valid. Send organisationId and name (letters, digits, dashes or underscores) and expiresDays (a whole number from 1 to 365), then try again.') => fail(400, 'bad_request', message);
213
+ const unavailable = (message = UNAVAILABLE) => fail(502, 'unavailable', message);
@@ -5,7 +5,14 @@
5
5
  * read-only endpoint `packages/reconcile` pulls from. See the package
6
6
  * README's "Adopting ./host" for how an existing host swaps its own copy
7
7
  * for this one with no behaviour change.
8
+ *
9
+ * `createRegistrar`/`registrarEndpoint` (#119) are the per-company route
10
+ * that lets a company's own credential mint and revoke its own apps'
11
+ * signed-records credentials, built entirely on `./issued`'s existing
12
+ * `check()`/`issue()`/`revoke()` -- see `registrar.ts`'s own header.
8
13
  */
9
14
  export { auditEndpoint, type AuditEndpointOptions } from './audit-endpoint.js';
10
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';
17
+ export { createCompanyRegistrarKeys, platformRegistrarEndpoint, type CompanyRegistrarKeys, type CompanyRegistrarKeysOptions, type MintCompanyKeyResult, type PlatformRegistrarEndpointOptions, } from './company-registrar-keys.js';
11
18
  export { keysHostEvents, type KeysHostEventRow } from './schema.js';
@@ -5,7 +5,14 @@
5
5
  * read-only endpoint `packages/reconcile` pulls from. See the package
6
6
  * README's "Adopting ./host" for how an existing host swaps its own copy
7
7
  * for this one with no behaviour change.
8
+ *
9
+ * `createRegistrar`/`registrarEndpoint` (#119) are the per-company route
10
+ * that lets a company's own credential mint and revoke its own apps'
11
+ * signed-records credentials, built entirely on `./issued`'s existing
12
+ * `check()`/`issue()`/`revoke()` -- see `registrar.ts`'s own header.
8
13
  */
9
14
  export { auditEndpoint } from './audit-endpoint.js';
10
15
  export { recordEvent } from './events.js';
16
+ export { createRegistrar, registrarEndpoint, } from './registrar.js';
17
+ export { createCompanyRegistrarKeys, platformRegistrarEndpoint, } from './company-registrar-keys.js';
11
18
  export { keysHostEvents } from './schema.js';
@@ -0,0 +1,81 @@
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 `revoke()` are the only methods this module calls. */
30
+ readonly issuer: Pick<CredentialIssuer<TGrant>, 'check' | 'issue' | 'revoke'>;
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' | 'company_key_not_a_registrar' | 'rate_limited';
41
+ export type RegisterAppResult = {
42
+ readonly ok: true;
43
+ readonly id: string;
44
+ readonly secret: string | null;
45
+ } | {
46
+ readonly ok: false;
47
+ readonly reason: RegistrarRefusalReason | IssueRefusalReason;
48
+ /** Only meaningful with `reason: 'rate_limited'`. */
49
+ readonly retryAfterMs?: number;
50
+ };
51
+ export type RevokeAppResult = {
52
+ readonly ok: true;
53
+ readonly revoked: boolean;
54
+ } | {
55
+ readonly ok: false;
56
+ readonly reason: RegistrarRefusalReason | 'app_not_found';
57
+ readonly retryAfterMs?: number;
58
+ };
59
+ export interface Registrar {
60
+ /** Calls `issuer.issue()`. Idempotent per `(companySecret, appName)`. */
61
+ registerApp(companySecret: string, appName: string): Promise<RegisterAppResult>;
62
+ /** Calls `issuer.revoke()`. Idempotent: revoking an already-revoked app is `{ ok: true, revoked: false }`. */
63
+ revokeApp(companySecret: string, appName: string): Promise<RevokeAppResult>;
64
+ }
65
+ export declare function createRegistrar<TGrant>(options: RegistrarOptions<TGrant>): Registrar;
66
+ /**
67
+ * `registrarEndpoint({ ... })` returns a fetch-shaped handler -- wire it
68
+ * directly as a route, e.g.
69
+ * `export const PUT = registrarEndpoint({ db, issuer, appGrants, appTtlMs, isRegistrarGrant });`
70
+ * (the same handler again as `export const DELETE`).
71
+ * `PUT /v1/keys/registrar/apps/<appName>` registers (or idempotently
72
+ * re-registers) that app under the caller's company; `DELETE` on the same
73
+ * path revokes it. The caller's company credential is the bearer token,
74
+ * same as every other credential this package already checks -- there is
75
+ * no separate registrar-specific auth scheme to configure.
76
+ *
77
+ * Errors answer `{ error, message }` (the auth broker's shape). A database
78
+ * or issuer failure that throws answers 502 `unavailable`, never a refusal
79
+ * such as `company_key_invalid`.
80
+ */
81
+ export declare function registrarEndpoint<TGrant>(options: RegistrarOptions<TGrant>): (request: Request) => Promise<Response>;
@@ -0,0 +1,262 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import { keysIssuedCredentials } from '../issued/tables.js';
3
+ import { ID_PATTERN } from '../worker-contract.js';
4
+ /**
5
+ * `registrar:<companyCredentialId>:<appName>` -- deterministic, so a repeat
6
+ * `registerApp` call is the same `issue()` idempotency key, and `revokeApp`
7
+ * can find the row without a table of its own. Both components are
8
+ * `ID_PATTERN`-checked before this is built, so neither can smuggle a colon
9
+ * in and reach across the boundary between them.
10
+ */
11
+ function scopeKey(companyCredentialId, appName) {
12
+ return `registrar:${companyCredentialId}:${appName}`;
13
+ }
14
+ export function createRegistrar(options) {
15
+ const { db, issuer, appGrants, appTtlMs, isRegistrarGrant } = options;
16
+ // A registrar that hands out registrar-capable credentials would let a
17
+ // company key mint further company keys, which the lineage scoping below
18
+ // is not built to contain. Refuse at construction, not on first use.
19
+ if (appGrants.some(isRegistrarGrant)) {
20
+ throw new Error('createRegistrar: appGrants contains a grant isRegistrarGrant accepts; an app credential must never be able to act as a registrar');
21
+ }
22
+ const now = options.now ?? (() => Date.now());
23
+ async function checkCompanyKey(companySecret) {
24
+ const checked = await issuer.check(companySecret);
25
+ if (!checked.ok) {
26
+ // Never surfaces *why* a presented secret failed (not found, bad
27
+ // signature, revoked, expired, wrong secret) -- the Worker's own
28
+ // boundary collapses the same way (`credential_invalid` covers
29
+ // several underlying reasons) so a caller gains nothing by probing.
30
+ if (checked.reason === 'rate_limited') {
31
+ return { ok: false, reason: 'rate_limited', retryAfterMs: checked.retryAfterMs };
32
+ }
33
+ return { ok: false, reason: 'company_key_invalid' };
34
+ }
35
+ if (!checked.grants.some(isRegistrarGrant)) {
36
+ return { ok: false, reason: 'company_key_not_a_registrar' };
37
+ }
38
+ return { ok: true, companyCredentialId: checked.id, environment: checked.environment };
39
+ }
40
+ /**
41
+ * `issue()`'s own idempotency replay matches on `idempotencyKey` alone --
42
+ * it does not look at `revokedAt`/`expiresAt` (`../issued/index.ts`), so
43
+ * a revoked or expired app would otherwise keep answering every future
44
+ * `registerApp` with its own dead id and `secret: null` forever, and the
45
+ * company could never get a working credential for that name again.
46
+ * Renaming a stale row's `idempotencyKey` away (an ordinary column,
47
+ * unlike the four `keys_issued_guard` freezes) frees the live key for
48
+ * `issue()` to mint a genuinely new credential under, while leaving the
49
+ * old row itself untouched and still in its lineage.
50
+ */
51
+ async function freeStaleSlot(companyCredentialId, appName) {
52
+ const key = scopeKey(companyCredentialId, appName);
53
+ const [row] = await db
54
+ .select({
55
+ id: keysIssuedCredentials.id,
56
+ revokedAt: keysIssuedCredentials.revokedAt,
57
+ expiresAt: keysIssuedCredentials.expiresAt,
58
+ })
59
+ .from(keysIssuedCredentials)
60
+ .where(eq(keysIssuedCredentials.idempotencyKey, key))
61
+ .limit(1);
62
+ if (!row)
63
+ return;
64
+ if (row.revokedAt === null && row.expiresAt > now())
65
+ return;
66
+ await db
67
+ .update(keysIssuedCredentials)
68
+ .set({ idempotencyKey: `${key}:superseded:${row.id}` })
69
+ .where(eq(keysIssuedCredentials.id, row.id));
70
+ }
71
+ async function registerApp(companySecret, appName) {
72
+ if (!ID_PATTERN.test(appName))
73
+ return { ok: false, reason: 'bad_app_name' };
74
+ const scoped = await checkCompanyKey(companySecret);
75
+ if (!scoped.ok)
76
+ return scoped;
77
+ await freeStaleSlot(scoped.companyCredentialId, appName);
78
+ const result = await issuer.issue({
79
+ grants: appGrants,
80
+ minter: scoped.companyCredentialId,
81
+ expiresAt: now() + appTtlMs,
82
+ environment: scoped.environment,
83
+ idempotencyKey: scopeKey(scoped.companyCredentialId, appName),
84
+ });
85
+ if (!result.ok)
86
+ return result;
87
+ return { ok: true, id: result.id, secret: result.secret };
88
+ }
89
+ async function revokeApp(companySecret, appName) {
90
+ if (!ID_PATTERN.test(appName))
91
+ return { ok: false, reason: 'bad_app_name' };
92
+ const scoped = await checkCompanyKey(companySecret);
93
+ if (!scoped.ok)
94
+ return scoped;
95
+ const [row] = await db
96
+ .select({
97
+ id: keysIssuedCredentials.id,
98
+ issuedById: keysIssuedCredentials.issuedById,
99
+ revokedAt: keysIssuedCredentials.revokedAt,
100
+ })
101
+ .from(keysIssuedCredentials)
102
+ .where(eq(keysIssuedCredentials.idempotencyKey, scopeKey(scoped.companyCredentialId, appName)))
103
+ .limit(1);
104
+ // Scoped twice: by the idempotency key (unique per company+app already)
105
+ // and, belt and suspenders, by `issuedById` -- so a lookup can never
106
+ // reach a row this company's key did not itself mint.
107
+ if (!row || row.issuedById !== scoped.companyCredentialId) {
108
+ return { ok: false, reason: 'app_not_found' };
109
+ }
110
+ if (row.revokedAt !== null)
111
+ return { ok: true, revoked: false };
112
+ // No app credential this registrar mints is ever a minter of its own --
113
+ // it is always a leaf under the company credential -- so cascading has
114
+ // nothing to reach beyond the row itself.
115
+ await issuer.revoke(row.id, { cascade: false });
116
+ return { ok: true, revoked: true };
117
+ }
118
+ return { registerApp, revokeApp };
119
+ }
120
+ // ---------------------------------------------------------------------------
121
+ // The HTTP route
122
+ // ---------------------------------------------------------------------------
123
+ const PATH_PATTERN = /^\/v1\/keys\/registrar\/apps\/([^/]+)$/;
124
+ const BEARER_PATTERN = /^Bearer (.+)$/;
125
+ function statusForRegistrar(reason) {
126
+ switch (reason) {
127
+ case 'bad_app_name':
128
+ case 'expires_at_required':
129
+ case 'expires_at_past':
130
+ case 'environment_mismatch':
131
+ return 400;
132
+ case 'company_key_invalid':
133
+ return 401;
134
+ case 'company_key_not_a_registrar':
135
+ case 'minter_not_found':
136
+ case 'minter_revoked':
137
+ case 'minter_expired':
138
+ return 403;
139
+ case 'rate_limited':
140
+ return 429;
141
+ case 'app_not_found':
142
+ return 404;
143
+ // Raw Worker codes surfaced by `issue()`: none of them is something the
144
+ // caller can fix by changing the request. They are a fault between this
145
+ // host and its signing Worker, so they answer 502, not a refusal.
146
+ case 'credential_invalid':
147
+ case 'credential_expired':
148
+ case 'credential_revoked':
149
+ case 'grant_missing':
150
+ case 'bad_request':
151
+ case 'aad_mismatch':
152
+ case 'unknown_generation':
153
+ case 'bad_minter_signature':
154
+ case 'lineage_mismatch':
155
+ case 'bad_old_signature':
156
+ case 'unlogged_row':
157
+ case 'not_in_lineage':
158
+ case 'unreachable':
159
+ return 502;
160
+ default: {
161
+ const unreachable = reason;
162
+ void unreachable;
163
+ // A reason this build does not know (a newer issuer): not a refusal.
164
+ return 502;
165
+ }
166
+ }
167
+ }
168
+ const MESSAGES = {
169
+ bad_app_name: 'The app name is not valid. Use letters, digits, dashes, dots or underscores, then try again.',
170
+ company_key_invalid: 'The company key was not accepted. Check that you are sending the current key as a Bearer token; if it was rotated or revoked, ask for a new one.',
171
+ company_key_not_a_registrar: 'This key belongs to an app, not to a company, so it cannot register apps. Use the company key.',
172
+ rate_limited: 'Too many attempts. Please wait a little and try again.',
173
+ app_not_found: 'No app with that name is registered under this company key.',
174
+ expires_at_required: 'The app credential could not be given an expiry. Contact the operator.',
175
+ expires_at_past: 'The app credential could not be given an expiry. Contact the operator.',
176
+ environment_mismatch: 'The company key and the app credential are for different environments.',
177
+ minter_not_found: 'The company key is no longer known. Ask for a new company key and register again.',
178
+ minter_revoked: 'The company key has been revoked. Ask for a new company key and register again.',
179
+ minter_expired: 'The company key has expired. Ask for a new company key and register again.',
180
+ };
181
+ const UNAVAILABLE_MESSAGE = 'The key service could not complete this request. Nothing was changed that you need to undo; try again in a moment, and contact the operator if it keeps happening.';
182
+ function messageFor(reason) {
183
+ return MESSAGES[reason] ?? UNAVAILABLE_MESSAGE;
184
+ }
185
+ /** Every answer, success or not, may carry a secret or tell about one: never cacheable. */
186
+ function jsonHeaders() {
187
+ return new Headers({ 'content-type': 'application/json', 'cache-control': 'no-store' });
188
+ }
189
+ function errorResponse(reason, retryAfterMs) {
190
+ const headers = jsonHeaders();
191
+ if (retryAfterMs !== undefined) {
192
+ headers.set('retry-after', String(Math.ceil(retryAfterMs / 1000)));
193
+ }
194
+ const status = statusForRegistrar(reason);
195
+ return new Response(JSON.stringify({ error: reason, message: messageFor(reason) }), {
196
+ status,
197
+ headers,
198
+ });
199
+ }
200
+ function unavailableResponse() {
201
+ return new Response(JSON.stringify({ error: 'unavailable', message: UNAVAILABLE_MESSAGE }), {
202
+ status: 502,
203
+ headers: jsonHeaders(),
204
+ });
205
+ }
206
+ function okResponse(body) {
207
+ return new Response(JSON.stringify(body), { status: 200, headers: jsonHeaders() });
208
+ }
209
+ function plainResponse(status) {
210
+ return new Response(null, { status, headers: { 'cache-control': 'no-store' } });
211
+ }
212
+ /**
213
+ * `registrarEndpoint({ ... })` returns a fetch-shaped handler -- wire it
214
+ * directly as a route, e.g.
215
+ * `export const PUT = registrarEndpoint({ db, issuer, appGrants, appTtlMs, isRegistrarGrant });`
216
+ * (the same handler again as `export const DELETE`).
217
+ * `PUT /v1/keys/registrar/apps/<appName>` registers (or idempotently
218
+ * re-registers) that app under the caller's company; `DELETE` on the same
219
+ * path revokes it. The caller's company credential is the bearer token,
220
+ * same as every other credential this package already checks -- there is
221
+ * no separate registrar-specific auth scheme to configure.
222
+ *
223
+ * Errors answer `{ error, message }` (the auth broker's shape). A database
224
+ * or issuer failure that throws answers 502 `unavailable`, never a refusal
225
+ * such as `company_key_invalid`.
226
+ */
227
+ export function registrarEndpoint(options) {
228
+ const registrar = createRegistrar(options);
229
+ return async function handleKeysRegistrar(request) {
230
+ const match = PATH_PATTERN.exec(new URL(request.url).pathname);
231
+ if (!match)
232
+ return plainResponse(404);
233
+ const appName = match[1];
234
+ const auth = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
235
+ if (!auth)
236
+ return errorResponse('company_key_invalid');
237
+ const companySecret = auth[1];
238
+ try {
239
+ if (request.method === 'PUT') {
240
+ const result = await registrar.registerApp(companySecret, appName);
241
+ if (!result.ok)
242
+ return errorResponse(result.reason, result.retryAfterMs);
243
+ return okResponse({ id: result.id, secret: result.secret });
244
+ }
245
+ if (request.method === 'DELETE') {
246
+ const result = await registrar.revokeApp(companySecret, appName);
247
+ if (!result.ok)
248
+ return errorResponse(result.reason, result.retryAfterMs);
249
+ return okResponse({ revoked: result.revoked });
250
+ }
251
+ }
252
+ catch (error) {
253
+ // Name and code only: a driver error's message can quote the query and
254
+ // its parameters, and a parameter may be (a hash of) a secret.
255
+ const name = error instanceof Error ? error.name : typeof error;
256
+ const code = error?.code;
257
+ console.error(`keys registrar: ${request.method} failed (${name}${typeof code === 'string' ? ` ${code}` : ''})`);
258
+ return unavailableResponse();
259
+ }
260
+ return plainResponse(405);
261
+ };
262
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/keys",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "The estate's own bearer keys, issued to callers and held on their behalf: two entries, issued and held, nothing stored in common.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -24,6 +24,10 @@
24
24
  "types": "./dist/held/index.d.ts",
25
25
  "default": "./dist/held/index.js"
26
26
  },
27
+ "./held-edge": {
28
+ "types": "./dist/held-edge/index.d.ts",
29
+ "default": "./dist/held-edge/index.js"
30
+ },
27
31
  "./webhooks": {
28
32
  "types": "./dist/webhooks.d.ts",
29
33
  "default": "./dist/webhooks.js"