@wtfalch/keys 0.7.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 +102 -0
- package/dist/host/company-registrar-keys.d.ts +93 -0
- package/dist/host/company-registrar-keys.js +213 -0
- package/dist/host/index.d.ts +7 -0
- package/dist/host/index.js +7 -0
- package/dist/host/registrar.d.ts +81 -0
- package/dist/host/registrar.js +262 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -189,6 +189,108 @@ pulls from.
|
|
|
189
189
|
no behaviour change and no data migration: the table name, every column
|
|
190
190
|
and the response shape are identical field for field.
|
|
191
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
|
+
|
|
192
294
|
## Adopting `./testing`
|
|
193
295
|
|
|
194
296
|
`@wtfalch/keys/testing` (added in **0.6.0**) is an in-process Worker stub for
|
|
@@ -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);
|
package/dist/host/index.d.ts
CHANGED
|
@@ -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';
|
package/dist/host/index.js
CHANGED
|
@@ -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