@wtfalch/keys 0.7.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +349 -7
- package/dist/held/index.d.ts +116 -6
- package/dist/held/index.js +247 -25
- package/dist/held/schema.d.ts +17 -0
- package/dist/held/schema.js +12 -0
- package/dist/held/shred.d.ts +6 -0
- package/dist/held/shred.js +6 -0
- package/dist/held-edge/index.d.ts +17 -2
- package/dist/held-edge/index.js +51 -9
- package/dist/host/audit-endpoint.js +2 -8
- package/dist/host/company-registrar-keys.d.ts +106 -0
- package/dist/host/company-registrar-keys.js +211 -0
- package/dist/host/events.d.ts +19 -3
- package/dist/host/events.js +55 -20
- package/dist/host/index.d.ts +15 -1
- package/dist/host/index.js +15 -1
- package/dist/host/native-build.d.ts +126 -0
- package/dist/host/native-build.js +322 -0
- package/dist/host/registrar.d.ts +87 -0
- package/dist/host/registrar.js +284 -0
- package/dist/host/rotation-sweep.d.ts +56 -0
- package/dist/host/rotation-sweep.js +89 -0
- package/dist/issued/encoding.d.ts +4 -0
- package/dist/issued/encoding.js +22 -0
- package/dist/issued/index.d.ts +148 -7
- package/dist/issued/index.js +320 -34
- package/dist/issued/resign.d.ts +16 -0
- package/dist/issued/resign.js +55 -2
- package/dist/issued/tables.d.ts +38 -0
- package/dist/issued/tables.js +6 -0
- package/dist/issued/verify.d.ts +14 -3
- package/dist/issued/verify.js +10 -3
- package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
- package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
- package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
- package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
- package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
- package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
- package/dist/service/body.d.ts +21 -0
- package/dist/service/body.js +128 -0
- package/dist/service/errors.d.ts +24 -0
- package/dist/service/errors.js +89 -0
- package/dist/service/handler.d.ts +35 -0
- package/dist/service/handler.js +328 -0
- package/dist/service/index.d.ts +7 -0
- package/dist/service/index.js +7 -0
- package/dist/service/policy.d.ts +130 -0
- package/dist/service/policy.js +123 -0
- package/dist/service/timeout.d.ts +6 -0
- package/dist/service/timeout.js +34 -0
- package/dist/testing/index.d.ts +3 -0
- package/dist/testing/index.js +3 -0
- package/dist/webhooks.d.ts +40 -17
- package/dist/webhooks.js +70 -26
- package/dist/worker-contract.d.ts +43 -6
- package/dist/worker-contract.js +37 -0
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +7 -28
- package/package.json +21 -3
|
@@ -0,0 +1,106 @@
|
|
|
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 key is minted as `company_root` with its `organisationId`, so company
|
|
22
|
+
* key management (`revokeForCompany`) cannot remove it; this platform route
|
|
23
|
+
* revokes it with `revoke()`, the trusted path.
|
|
24
|
+
*
|
|
25
|
+
* The org binding through `idempotencyKey` is advisory: the key is a label the
|
|
26
|
+
* minter chose, not proof about the caller. It is only safe because only the
|
|
27
|
+
* holder of the platform token can mint a key carrying that prefix; revoke
|
|
28
|
+
* therefore also requires a root row (no minter) with the host's registrar
|
|
29
|
+
* grant, so a look-alike key never qualifies.
|
|
30
|
+
*
|
|
31
|
+
* Revoke cascades: every app credential the company registered is a child of
|
|
32
|
+
* the registrar key, so they all go with it.
|
|
33
|
+
*/
|
|
34
|
+
export interface CompanyRegistrarKeysOptions<TGrant> {
|
|
35
|
+
readonly db: Db;
|
|
36
|
+
readonly issuer: Pick<CredentialIssuer<TGrant>, 'issue' | 'revoke'>;
|
|
37
|
+
/** The grant that marks a credential as a company's registrar key (the host's `isRegistrarGrant` accepts it). */
|
|
38
|
+
readonly registrarGrant: TGrant;
|
|
39
|
+
/**
|
|
40
|
+
* Grants the company key also holds, after `registrarGrant`. The Worker refuses a child
|
|
41
|
+
* row with a grant its minter lacks, so the apps a registrar registers can only hold
|
|
42
|
+
* grants listed here (or, for an object grant with a string `tenantId`, a grant of the
|
|
43
|
+
* same tenant). Only `registrarGrant` marks a registrar. A company key minted before
|
|
44
|
+
* this option existed holds only the registrar grant, so its apps fail at the Worker
|
|
45
|
+
* until the company's key is rolled: mint a new one, then revoke the old one.
|
|
46
|
+
*/
|
|
47
|
+
readonly appGrants?: readonly TGrant[];
|
|
48
|
+
/** Longest lifetime a mint may ask for, in days. Defaults to 365. */
|
|
49
|
+
readonly maxExpiresDays?: number;
|
|
50
|
+
/** Environment of the minted key. Defaults to `'live'`; app credentials inherit it. */
|
|
51
|
+
readonly environment?: KeyEnvironment;
|
|
52
|
+
/** Unix milliseconds. Defaults to `Date.now`. */
|
|
53
|
+
readonly now?: () => number;
|
|
54
|
+
}
|
|
55
|
+
export type MintCompanyKeyResult = {
|
|
56
|
+
readonly ok: true;
|
|
57
|
+
readonly id: string;
|
|
58
|
+
readonly secret: string;
|
|
59
|
+
} | {
|
|
60
|
+
readonly ok: false;
|
|
61
|
+
readonly reason: 'bad_request' | IssueRefusalReason;
|
|
62
|
+
};
|
|
63
|
+
export interface CompanyRegistrarKeys {
|
|
64
|
+
mint(input: {
|
|
65
|
+
readonly organisationId: string;
|
|
66
|
+
readonly name: string;
|
|
67
|
+
readonly expiresDays: number;
|
|
68
|
+
}): Promise<MintCompanyKeyResult>;
|
|
69
|
+
/** `revoked: false` when nothing was revoked (unknown id, another company's id, already revoked, not a registrar key). */
|
|
70
|
+
revoke(organisationId: string, id: string): Promise<{
|
|
71
|
+
readonly ok: true;
|
|
72
|
+
readonly revoked: boolean;
|
|
73
|
+
} | {
|
|
74
|
+
readonly ok: false;
|
|
75
|
+
readonly reason: 'bad_request';
|
|
76
|
+
}>;
|
|
77
|
+
/** Revokes (cascade) every live registrar key of the company; `revoked` is how many keys. */
|
|
78
|
+
revokeAll(organisationId: string): Promise<{
|
|
79
|
+
readonly ok: true;
|
|
80
|
+
readonly revoked: number;
|
|
81
|
+
} | {
|
|
82
|
+
readonly ok: false;
|
|
83
|
+
readonly reason: 'bad_request';
|
|
84
|
+
}>;
|
|
85
|
+
}
|
|
86
|
+
export declare function createCompanyRegistrarKeys<TGrant>(options: CompanyRegistrarKeysOptions<TGrant>): CompanyRegistrarKeys;
|
|
87
|
+
export interface PlatformRegistrarEndpointOptions<TGrant> extends CompanyRegistrarKeysOptions<TGrant> {
|
|
88
|
+
/** The platform's bearer token. Missing or under 32 characters: the route answers 503 and serves nothing. */
|
|
89
|
+
readonly token: string | undefined;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* `platformRegistrarEndpoint({ ... })` returns a fetch-shaped handler for all
|
|
93
|
+
* routes; wire it as `POST` and `DELETE` the way `registrarEndpoint` is wired.
|
|
94
|
+
*
|
|
95
|
+
* - `POST /v1/keys/platform/registrars` with `{ organisationId, name, expiresDays }`
|
|
96
|
+
* answers `200 { id, secret }`. The secret is shown once.
|
|
97
|
+
* - `DELETE /v1/keys/platform/registrars/<organisationId>/<id>` answers
|
|
98
|
+
* `200 { revoked }` (`false` when nothing live matched: idempotent), and
|
|
99
|
+
* revokes every app the company registered with it.
|
|
100
|
+
*
|
|
101
|
+
* - `DELETE /v1/keys/platform/registrars/<organisationId>` revokes (cascade)
|
|
102
|
+
* every live registrar key of that company and answers `200 { revoked: <count> }`.
|
|
103
|
+
*
|
|
104
|
+
* All need `Authorization: Bearer <platform token>`.
|
|
105
|
+
*/
|
|
106
|
+
export declare function platformRegistrarEndpoint<TGrant>(options: PlatformRegistrarEndpointOptions<TGrant>): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { safeEqual } from '@wtfalch/utils/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 appGrants = options.appGrants ?? [];
|
|
11
|
+
const maxDays = options.maxExpiresDays ?? DEFAULT_MAX_DAYS;
|
|
12
|
+
const environment = options.environment ?? 'live';
|
|
13
|
+
const now = options.now ?? (() => Date.now());
|
|
14
|
+
const grantKey = JSON.stringify(registrarGrant);
|
|
15
|
+
// A company registrar key: root credential, this company's prefix, carrying the registrar grant.
|
|
16
|
+
const isCompanyKey = (row, organisationId) => row.issuedById === null &&
|
|
17
|
+
row.idempotencyKey?.startsWith(prefixFor(organisationId)) === true &&
|
|
18
|
+
Array.isArray(row.grants) &&
|
|
19
|
+
row.grants.some((g) => JSON.stringify(g) === grantKey);
|
|
20
|
+
return {
|
|
21
|
+
async mint({ organisationId, name, expiresDays }) {
|
|
22
|
+
if (!ID_PATTERN.test(organisationId) ||
|
|
23
|
+
!ID_PATTERN.test(name) ||
|
|
24
|
+
!Number.isInteger(expiresDays) ||
|
|
25
|
+
expiresDays < 1 ||
|
|
26
|
+
expiresDays > maxDays) {
|
|
27
|
+
return { ok: false, reason: 'bad_request' };
|
|
28
|
+
}
|
|
29
|
+
const result = await issuer.issue({
|
|
30
|
+
grants: [registrarGrant, ...appGrants],
|
|
31
|
+
minter: null,
|
|
32
|
+
expiresAt: now() + expiresDays * DAY_MS,
|
|
33
|
+
environment,
|
|
34
|
+
purpose: 'company_root',
|
|
35
|
+
organisationId,
|
|
36
|
+
idempotencyKey: `${prefixFor(organisationId)}${name}:${crypto.randomUUID()}`,
|
|
37
|
+
});
|
|
38
|
+
if (!result.ok)
|
|
39
|
+
return result;
|
|
40
|
+
// A fresh nonce means this is never a replay; a null secret would be unusable, so refuse it.
|
|
41
|
+
if (result.secret === null)
|
|
42
|
+
return { ok: false, reason: 'unreachable' };
|
|
43
|
+
return { ok: true, id: result.id, secret: result.secret };
|
|
44
|
+
},
|
|
45
|
+
async revoke(organisationId, id) {
|
|
46
|
+
if (!ID_PATTERN.test(organisationId) || !ID_PATTERN.test(id)) {
|
|
47
|
+
return { ok: false, reason: 'bad_request' };
|
|
48
|
+
}
|
|
49
|
+
const [row] = await db
|
|
50
|
+
.select({
|
|
51
|
+
idempotencyKey: keysIssuedCredentials.idempotencyKey,
|
|
52
|
+
issuedById: keysIssuedCredentials.issuedById,
|
|
53
|
+
grants: keysIssuedCredentials.grants,
|
|
54
|
+
revokedAt: keysIssuedCredentials.revokedAt,
|
|
55
|
+
})
|
|
56
|
+
.from(keysIssuedCredentials)
|
|
57
|
+
.where(eq(keysIssuedCredentials.id, id))
|
|
58
|
+
.limit(1);
|
|
59
|
+
// Only a registrar key minted for this company: this route can never
|
|
60
|
+
// reach an app credential, a credential of another company or an
|
|
61
|
+
// unrelated host credential.
|
|
62
|
+
if (!row || !isCompanyKey(row, organisationId) || row.revokedAt !== null) {
|
|
63
|
+
return { ok: true, revoked: false };
|
|
64
|
+
}
|
|
65
|
+
const done = await issuer.revoke(id, { cascade: true });
|
|
66
|
+
return { ok: true, revoked: Array.isArray(done) && done.includes(id) };
|
|
67
|
+
},
|
|
68
|
+
async revokeAll(organisationId) {
|
|
69
|
+
if (!ID_PATTERN.test(organisationId))
|
|
70
|
+
return { ok: false, reason: 'bad_request' };
|
|
71
|
+
const prefix = prefixFor(organisationId).replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
72
|
+
const rows = await db
|
|
73
|
+
.select({
|
|
74
|
+
id: keysIssuedCredentials.id,
|
|
75
|
+
idempotencyKey: keysIssuedCredentials.idempotencyKey,
|
|
76
|
+
issuedById: keysIssuedCredentials.issuedById,
|
|
77
|
+
grants: keysIssuedCredentials.grants,
|
|
78
|
+
})
|
|
79
|
+
.from(keysIssuedCredentials)
|
|
80
|
+
.where(and(like(keysIssuedCredentials.idempotencyKey, `${prefix}%`), isNull(keysIssuedCredentials.revokedAt)));
|
|
81
|
+
let revoked = 0;
|
|
82
|
+
for (const row of rows) {
|
|
83
|
+
if (!isCompanyKey(row, organisationId))
|
|
84
|
+
continue;
|
|
85
|
+
const done = await issuer.revoke(row.id, { cascade: true });
|
|
86
|
+
if (Array.isArray(done) && done.includes(row.id))
|
|
87
|
+
revoked += 1;
|
|
88
|
+
}
|
|
89
|
+
return { ok: true, revoked };
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
// The HTTP route
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
const MINT_PATH = '/v1/keys/platform/registrars';
|
|
97
|
+
const REVOKE_PATH = /^\/v1\/keys\/platform\/registrars\/([^/]+)\/([^/]+)$/;
|
|
98
|
+
const BEARER_PATTERN = /^Bearer ([^\s]+)$/;
|
|
99
|
+
const MAX_BODY_BYTES = 4096;
|
|
100
|
+
const ORG_REVOKE_PATH = /^\/v1\/keys\/platform\/registrars\/([^/]+)$/;
|
|
101
|
+
function respond(body, status) {
|
|
102
|
+
return new Response(JSON.stringify(body), {
|
|
103
|
+
status,
|
|
104
|
+
headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const fail = (status, error, message) => respond({ error, message }, status);
|
|
108
|
+
const UNAVAILABLE = 'The key service could not complete this request. Try again in a moment, and contact the operator if it keeps happening.';
|
|
109
|
+
const MINT_FAILED = "The key service could not complete this request. A key may have been made anyway, and its secret is lost. Revoke all of this organisation's registrar keys (DELETE /v1/keys/platform/registrars/<organisationId>), then try again; contact the operator if it keeps happening.";
|
|
110
|
+
const REVOKE_BAD = 'The request was not valid. The organisation id and key id in the address must be letters, digits, dashes or underscores. Fix the address and try again.';
|
|
111
|
+
/**
|
|
112
|
+
* `platformRegistrarEndpoint({ ... })` returns a fetch-shaped handler for all
|
|
113
|
+
* routes; wire it as `POST` and `DELETE` the way `registrarEndpoint` is wired.
|
|
114
|
+
*
|
|
115
|
+
* - `POST /v1/keys/platform/registrars` with `{ organisationId, name, expiresDays }`
|
|
116
|
+
* answers `200 { id, secret }`. The secret is shown once.
|
|
117
|
+
* - `DELETE /v1/keys/platform/registrars/<organisationId>/<id>` answers
|
|
118
|
+
* `200 { revoked }` (`false` when nothing live matched: idempotent), and
|
|
119
|
+
* revokes every app the company registered with it.
|
|
120
|
+
*
|
|
121
|
+
* - `DELETE /v1/keys/platform/registrars/<organisationId>` revokes (cascade)
|
|
122
|
+
* every live registrar key of that company and answers `200 { revoked: <count> }`.
|
|
123
|
+
*
|
|
124
|
+
* All need `Authorization: Bearer <platform token>`.
|
|
125
|
+
*/
|
|
126
|
+
export function platformRegistrarEndpoint(options) {
|
|
127
|
+
const keys = createCompanyRegistrarKeys(options);
|
|
128
|
+
const { token } = options;
|
|
129
|
+
return async function handlePlatformRegistrar(request) {
|
|
130
|
+
const path = new URL(request.url).pathname;
|
|
131
|
+
const revokeMatch = REVOKE_PATH.exec(path);
|
|
132
|
+
const orgMatch = ORG_REVOKE_PATH.exec(path);
|
|
133
|
+
if (path !== MINT_PATH && !revokeMatch && !orgMatch)
|
|
134
|
+
return new Response(null, { status: 404, headers: { 'cache-control': 'no-store' } });
|
|
135
|
+
if (!token || token.length < 32) {
|
|
136
|
+
return fail(503, 'unavailable', 'The platform route is not configured on this key service.');
|
|
137
|
+
}
|
|
138
|
+
const auth = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
|
|
139
|
+
if (!auth?.[1] || !safeEqual(auth[1], token)) {
|
|
140
|
+
return fail(401, 'unauthorized', 'The platform token was not accepted.');
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
if (request.method === 'POST' && path === MINT_PATH) {
|
|
144
|
+
const text = await request.text();
|
|
145
|
+
if (new TextEncoder().encode(text).length > MAX_BODY_BYTES)
|
|
146
|
+
return badRequest();
|
|
147
|
+
let body;
|
|
148
|
+
try {
|
|
149
|
+
body = JSON.parse(text);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return badRequest();
|
|
153
|
+
}
|
|
154
|
+
const b = body;
|
|
155
|
+
if (!b ||
|
|
156
|
+
typeof b.organisationId !== 'string' ||
|
|
157
|
+
typeof b.name !== 'string' ||
|
|
158
|
+
typeof b.expiresDays !== 'number') {
|
|
159
|
+
return badRequest();
|
|
160
|
+
}
|
|
161
|
+
const result = await keys.mint({
|
|
162
|
+
organisationId: b.organisationId,
|
|
163
|
+
name: b.name,
|
|
164
|
+
expiresDays: b.expiresDays,
|
|
165
|
+
});
|
|
166
|
+
if (!result.ok) {
|
|
167
|
+
return result.reason === 'bad_request' ? badRequest() : unavailable(MINT_FAILED);
|
|
168
|
+
}
|
|
169
|
+
return respond({ id: result.id, secret: result.secret }, 200);
|
|
170
|
+
}
|
|
171
|
+
if (request.method === 'DELETE' && revokeMatch) {
|
|
172
|
+
let organisationId;
|
|
173
|
+
let id;
|
|
174
|
+
try {
|
|
175
|
+
organisationId = decodeURIComponent(revokeMatch[1]);
|
|
176
|
+
id = decodeURIComponent(revokeMatch[2]);
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return badRequest(REVOKE_BAD);
|
|
180
|
+
}
|
|
181
|
+
const result = await keys.revoke(organisationId, id);
|
|
182
|
+
if (!result.ok)
|
|
183
|
+
return badRequest(REVOKE_BAD);
|
|
184
|
+
return respond({ revoked: result.revoked }, 200);
|
|
185
|
+
}
|
|
186
|
+
if (request.method === 'DELETE' && orgMatch) {
|
|
187
|
+
let organisationId;
|
|
188
|
+
try {
|
|
189
|
+
organisationId = decodeURIComponent(orgMatch[1]);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return badRequest(REVOKE_BAD);
|
|
193
|
+
}
|
|
194
|
+
const result = await keys.revokeAll(organisationId);
|
|
195
|
+
if (!result.ok)
|
|
196
|
+
return badRequest(REVOKE_BAD);
|
|
197
|
+
return respond({ revoked: result.revoked }, 200);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
const name = error instanceof Error ? error.name : typeof error;
|
|
202
|
+
const code = error?.code;
|
|
203
|
+
console.error(`keys platform registrar: ${request.method} failed (${name}${typeof code === 'string' ? ` ${code}` : ''})`);
|
|
204
|
+
// A mint that threw may still have created a key.
|
|
205
|
+
return request.method === 'POST' ? unavailable(MINT_FAILED) : unavailable();
|
|
206
|
+
}
|
|
207
|
+
return new Response(null, { status: 405, headers: { 'cache-control': 'no-store' } });
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
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);
|
|
211
|
+
const unavailable = (message = UNAVAILABLE) => fail(502, 'unavailable', message);
|
package/dist/host/events.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { KeyUsedEvent } from '../held/index.js';
|
|
1
|
+
import type { HeldMutationEvent, KeyUsedEvent } from '../held/index.js';
|
|
2
2
|
import type { Db } from '../issued/index.js';
|
|
3
3
|
import type { AuditEvent } from '../issued/index.js';
|
|
4
4
|
/**
|
|
@@ -6,7 +6,11 @@ import type { AuditEvent } from '../issued/index.js';
|
|
|
6
6
|
* hand `recordEvent` -- the exact union `CreateCredentialIssuerOptions.audit`
|
|
7
7
|
* (`AuditEvent`, discriminated by `name`: `'credential.minted' |
|
|
8
8
|
* 'credential.rotated' | 'credential.revoked'`) and `CreateHeldKeysOptions.audit`
|
|
9
|
-
* (`KeyUsedEvent`, `name: 'key.used'`) can ever produce, between them
|
|
9
|
+
* (`KeyUsedEvent`, `name: 'key.used'`) can ever produce, between them, plus the
|
|
10
|
+
* three held mutations `./service` records: `CreateHeldKeysOptions.auditInTransaction`
|
|
11
|
+
* (`HeldMutationEvent`: `held.put`, `held.revoked`) and the shred sweep (`held.shredded`).
|
|
12
|
+
* `host/0002` adds those three kinds to the table's check, and `auditEndpoint`
|
|
13
|
+
* never returns them.
|
|
10
14
|
*
|
|
11
15
|
* `recordEvent`'s own parameter is this union, wider than either option
|
|
12
16
|
* alone expects, so `(event) => recordEvent(db, event)` type-checks as both
|
|
@@ -15,7 +19,12 @@ import type { AuditEvent } from '../issued/index.js';
|
|
|
15
19
|
* for (TypeScript's ordinary parameter contravariance), with no cast on
|
|
16
20
|
* either side.
|
|
17
21
|
*/
|
|
18
|
-
export type HostEvent = AuditEvent | KeyUsedEvent;
|
|
22
|
+
export type HostEvent = AuditEvent | KeyUsedEvent | HeldMutationEvent | HeldShredEvent;
|
|
23
|
+
/** The shred sweep ran. It names no tenant: the sweep decides eligibility on its own. */
|
|
24
|
+
export interface HeldShredEvent {
|
|
25
|
+
readonly name: 'held.shredded';
|
|
26
|
+
readonly at: number;
|
|
27
|
+
}
|
|
19
28
|
/**
|
|
20
29
|
* Inserts one `keys_host_events` row: this host's own append-only record of
|
|
21
30
|
* what `@wtfalch/keys` did on its behalf. Takes a drizzle handle rather than
|
|
@@ -24,3 +33,10 @@ export type HostEvent = AuditEvent | KeyUsedEvent;
|
|
|
24
33
|
* a disposable one.
|
|
25
34
|
*/
|
|
26
35
|
export declare function recordEvent(db: Db, event: HostEvent): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* `recordEvent` for `CreateCredentialIssuerOptions.auditInTransaction`:
|
|
38
|
+
* `auditInTransaction: recordEventInTransaction`. The event row is written in
|
|
39
|
+
* the same transaction as the change, so both commit or neither does. A failed
|
|
40
|
+
* insert aborts the change.
|
|
41
|
+
*/
|
|
42
|
+
export declare function recordEventInTransaction(tx: Db, event: AuditEvent): Promise<void>;
|
package/dist/host/events.js
CHANGED
|
@@ -7,25 +7,60 @@ import { keysHostEvents } from './schema.js';
|
|
|
7
7
|
* a disposable one.
|
|
8
8
|
*/
|
|
9
9
|
export async function recordEvent(db, event) {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
10
|
+
const at = new Date(event.at);
|
|
11
|
+
switch (event.name) {
|
|
12
|
+
case 'key.used':
|
|
13
|
+
await db.insert(keysHostEvents).values({
|
|
14
|
+
kind: event.name,
|
|
15
|
+
requestId: event.requestId,
|
|
16
|
+
credentialId: null,
|
|
17
|
+
tenantId: event.tenantId,
|
|
18
|
+
entryId: event.entryId,
|
|
19
|
+
version: event.version,
|
|
20
|
+
at,
|
|
21
|
+
});
|
|
22
|
+
return;
|
|
23
|
+
case 'held.put':
|
|
24
|
+
case 'held.revoked':
|
|
25
|
+
await db.insert(keysHostEvents).values({
|
|
26
|
+
kind: event.name,
|
|
27
|
+
requestId: null,
|
|
28
|
+
credentialId: null,
|
|
29
|
+
tenantId: event.tenantId,
|
|
30
|
+
entryId: event.entryId,
|
|
31
|
+
version: event.name === 'held.put' ? event.version : null,
|
|
32
|
+
at,
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
case 'held.shredded':
|
|
36
|
+
await db.insert(keysHostEvents).values({
|
|
37
|
+
kind: event.name,
|
|
38
|
+
requestId: null,
|
|
39
|
+
credentialId: null,
|
|
40
|
+
tenantId: null,
|
|
41
|
+
entryId: null,
|
|
42
|
+
version: null,
|
|
43
|
+
at,
|
|
44
|
+
});
|
|
45
|
+
return;
|
|
46
|
+
default:
|
|
47
|
+
await db.insert(keysHostEvents).values({
|
|
48
|
+
kind: event.name,
|
|
49
|
+
requestId: event.requestId ?? null,
|
|
50
|
+
credentialId: event.credentialId,
|
|
51
|
+
tenantId: null,
|
|
52
|
+
entryId: null,
|
|
53
|
+
version: null,
|
|
54
|
+
at,
|
|
55
|
+
});
|
|
21
56
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* `recordEvent` for `CreateCredentialIssuerOptions.auditInTransaction`:
|
|
60
|
+
* `auditInTransaction: recordEventInTransaction`. The event row is written in
|
|
61
|
+
* the same transaction as the change, so both commit or neither does. A failed
|
|
62
|
+
* insert aborts the change.
|
|
63
|
+
*/
|
|
64
|
+
export async function recordEventInTransaction(tx, event) {
|
|
65
|
+
await recordEvent(tx, event);
|
|
31
66
|
}
|
package/dist/host/index.d.ts
CHANGED
|
@@ -5,7 +5,21 @@
|
|
|
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.
|
|
13
|
+
*
|
|
14
|
+
* `createNativeBuildKeyExchange`/`nativeBuildKeysEndpoint` (#126) is the
|
|
15
|
+
* route a native-shell `build-app.yml` run trades its own GitHub Actions
|
|
16
|
+
* OIDC token and a `runId` through, for that run's config and the owning
|
|
17
|
+
* company's Apple/Google keys -- see `native-build.ts`'s own header.
|
|
8
18
|
*/
|
|
9
19
|
export { auditEndpoint, type AuditEndpointOptions } from './audit-endpoint.js';
|
|
10
|
-
export { recordEvent, type HostEvent } from './events.js';
|
|
20
|
+
export { recordEvent, recordEventInTransaction, type HeldShredEvent, type HostEvent, } from './events.js';
|
|
21
|
+
export { createRegistrar, REGISTRAR_REFUSAL_REASONS, registrarEndpoint, type RegisterAppResult, type Registrar, type RegistrarOptions, type RegistrarRefusalReason, type RevokeAppResult, } from './registrar.js';
|
|
22
|
+
export { createCompanyRegistrarKeys, platformRegistrarEndpoint, type CompanyRegistrarKeys, type CompanyRegistrarKeysOptions, type MintCompanyKeyResult, type PlatformRegistrarEndpointOptions, } from './company-registrar-keys.js';
|
|
23
|
+
export { createNativeBuildKeyExchange, NATIVE_BUILD_REFUSAL_REASONS, nativeBuildKeysEndpoint, nativeKeyEntryId, type NativeBuildClaims, type NativeBuildExchangeResult, type NativeBuildKeyExchange, type NativeBuildKeyExchangeOptions, type NativeBuildKeys, type NativeBuildKeysEndpointOptions, type NativeBuildRefusalReason, type NativeBuildRun, type NativeKeyField, } from './native-build.js';
|
|
24
|
+
export { runRotationSweep, type RotationSweepOptions, type RotationSweepReport, type RotationSweepResult, } from './rotation-sweep.js';
|
|
11
25
|
export { keysHostEvents, type KeysHostEventRow } from './schema.js';
|
package/dist/host/index.js
CHANGED
|
@@ -5,7 +5,21 @@
|
|
|
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.
|
|
13
|
+
*
|
|
14
|
+
* `createNativeBuildKeyExchange`/`nativeBuildKeysEndpoint` (#126) is the
|
|
15
|
+
* route a native-shell `build-app.yml` run trades its own GitHub Actions
|
|
16
|
+
* OIDC token and a `runId` through, for that run's config and the owning
|
|
17
|
+
* company's Apple/Google keys -- see `native-build.ts`'s own header.
|
|
8
18
|
*/
|
|
9
19
|
export { auditEndpoint } from './audit-endpoint.js';
|
|
10
|
-
export { recordEvent } from './events.js';
|
|
20
|
+
export { recordEvent, recordEventInTransaction, } from './events.js';
|
|
21
|
+
export { createRegistrar, REGISTRAR_REFUSAL_REASONS, registrarEndpoint, } from './registrar.js';
|
|
22
|
+
export { createCompanyRegistrarKeys, platformRegistrarEndpoint, } from './company-registrar-keys.js';
|
|
23
|
+
export { createNativeBuildKeyExchange, NATIVE_BUILD_REFUSAL_REASONS, nativeBuildKeysEndpoint, nativeKeyEntryId, } from './native-build.js';
|
|
24
|
+
export { runRotationSweep, } from './rotation-sweep.js';
|
|
11
25
|
export { keysHostEvents } from './schema.js';
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { type HeldKeys } from '../held/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* S5 of `estate/.plans/2026-10-22-app-shells.md` (decision 5): the one
|
|
4
|
+
* route a `build-app.yml` run may call to trade its own GitHub Actions OIDC
|
|
5
|
+
* token and a `runId` for that run's native build config and the owning
|
|
6
|
+
* company's Apple/Google keys.
|
|
7
|
+
*
|
|
8
|
+
* No table of its own, the same shape `./company-registrar-keys.ts` takes:
|
|
9
|
+
* which company and which `NativeAppConfig` a `runId` names is foundry's
|
|
10
|
+
* row, not this package's, so it arrives through the injected `resolveRun`
|
|
11
|
+
* rather than a query this module writes itself. The four key kinds the
|
|
12
|
+
* plan names each live as one `./held` entry per company (`tenantId` is the
|
|
13
|
+
* organisation id, `entryId` one of `NATIVE_KEY_ENTRY_IDS`); a company that
|
|
14
|
+
* has not entered a kind simply has no entry, read here as "not part of
|
|
15
|
+
* this answer", never a refusal.
|
|
16
|
+
*
|
|
17
|
+
* Authentication is the GitHub Actions OIDC token itself, verified against
|
|
18
|
+
* GitHub's own JWKS -- never a static bearer secret, because the fact that
|
|
19
|
+
* must hold is "this call came from the one workflow file, in the one
|
|
20
|
+
* repo, running on its default branch", which only GitHub's own signed
|
|
21
|
+
* claims can attest to. `repository`, `workflow_ref` and `ref` are each
|
|
22
|
+
* checked by exact match: a token minted for any other repository,
|
|
23
|
+
* workflow file or ref is refused the same as a forged one. The ref is the
|
|
24
|
+
* branch name, not a commit: a run of an older commit of the same file on
|
|
25
|
+
* the default branch carries the same claims and is not told apart.
|
|
26
|
+
*
|
|
27
|
+
* The workflow file is shared by every company, so those checks alone say
|
|
28
|
+
* "some build run", not "this company's run". The token's `run_id` claim is
|
|
29
|
+
* the tie: the exchange answers only when it equals the GitHub run id the
|
|
30
|
+
* `runId` row was bound to (`resolveRun`'s `githubRunId`).
|
|
31
|
+
*/
|
|
32
|
+
/** `ID_PATTERN`-safe entry id per key kind; `held/index.ts`'s `requireId` refuses a dot, so these are not the dotted names the plan uses in prose. */
|
|
33
|
+
declare const NATIVE_KEY_ENTRY_IDS: {
|
|
34
|
+
readonly appleAscKey: "apple-asc-key";
|
|
35
|
+
readonly appleDeveloperId: "apple-developer-id";
|
|
36
|
+
readonly googlePlayServiceAccount: "google-play-service-account";
|
|
37
|
+
readonly googleUploadKeystore: "google-upload-keystore";
|
|
38
|
+
};
|
|
39
|
+
export type NativeKeyField = keyof typeof NATIVE_KEY_ENTRY_IDS;
|
|
40
|
+
/** The `./held` entry id a native key field is stored and read under, for whatever writes it (Boule, through `held.put`). */
|
|
41
|
+
export declare function nativeKeyEntryId(field: NativeKeyField): string;
|
|
42
|
+
/** Only the kinds a company has actually entered; a missing field is "not configured", not an error. Each value is the parsed JSON a `put` stored. */
|
|
43
|
+
export type NativeBuildKeys = Partial<Record<NativeKeyField, unknown>>;
|
|
44
|
+
export interface NativeBuildRun<TConfig> {
|
|
45
|
+
readonly organisationId: string;
|
|
46
|
+
readonly config: TConfig;
|
|
47
|
+
readonly githubRunId: string;
|
|
48
|
+
}
|
|
49
|
+
/** The claims of a GitHub Actions token that passed every check. */
|
|
50
|
+
export interface NativeBuildClaims {
|
|
51
|
+
/** GitHub's `run_id` claim: the Actions run that minted the token. */
|
|
52
|
+
readonly runId: string;
|
|
53
|
+
}
|
|
54
|
+
export interface NativeBuildKeyExchangeOptions<TConfig> {
|
|
55
|
+
/** `openCurrent` is the only call this module makes; it never writes a held key. */
|
|
56
|
+
readonly heldKeys: Pick<HeldKeys, 'openCurrent'>;
|
|
57
|
+
/**
|
|
58
|
+
* Foundry's own build-run row: the company and config a `runId` names, and
|
|
59
|
+
* `githubRunId`, the GitHub Actions run id (a decimal string) of the one
|
|
60
|
+
* job allowed to read it. Returns `null` for a `runId` this run does not
|
|
61
|
+
* recognise -- including one that belongs to another company -- and for a
|
|
62
|
+
* row that does not yet know its GitHub run id (so the answer is 404).
|
|
63
|
+
* There is deliberately no bind on first use: the first token to ask would
|
|
64
|
+
* claim the row, and since every company's runs pass the same workflow
|
|
65
|
+
* checks, company A could claim company B's unclaimed run. The row is
|
|
66
|
+
* bound by whoever dispatched the run, before the run can ask. `null` is
|
|
67
|
+
* the ordinary answer for "unknown run", never thrown; throwing is
|
|
68
|
+
* reserved for an actual dependency failure (foundry's store unreachable),
|
|
69
|
+
* which this module reports the same way it reports any other outage:
|
|
70
|
+
* 502, logged without the runId.
|
|
71
|
+
*/
|
|
72
|
+
readonly resolveRun: (runId: string) => Promise<NativeBuildRun<TConfig> | null>;
|
|
73
|
+
/**
|
|
74
|
+
* The audience `build-app.yml` asks GitHub for with its own `id-token`
|
|
75
|
+
* request (`core.getIDToken(audience)`). Unset or empty refuses every
|
|
76
|
+
* token -- fails closed, the same rule `activity`'s `viewer-bearer.ts`
|
|
77
|
+
* applies to its own audience.
|
|
78
|
+
*/
|
|
79
|
+
readonly audience: string | undefined;
|
|
80
|
+
/** `owner/repo` of the one repository whose `build-app.yml` may call this endpoint, e.g. `'wtfalch/shell'`. */
|
|
81
|
+
readonly repository: string;
|
|
82
|
+
/** The workflow file's name, e.g. `'build-app.yml'`. */
|
|
83
|
+
readonly workflowFile: string;
|
|
84
|
+
/** That repository's default branch, e.g. `'main'`. The run must have executed the workflow file as committed there -- `workflow_ref` carries both the file and the ref together. */
|
|
85
|
+
readonly defaultBranch: string;
|
|
86
|
+
/** GitHub's OIDC issuer. Overridden only by tests. */
|
|
87
|
+
readonly issuer?: string;
|
|
88
|
+
/** GitHub's OIDC JWKS endpoint. Overridden only by tests. */
|
|
89
|
+
readonly jwksUrl?: string;
|
|
90
|
+
/** Test seam; defaults to the platform's global `fetch`. Used for every JWKS fetch `createRemoteJWKSet` makes. */
|
|
91
|
+
readonly fetchImpl?: typeof fetch;
|
|
92
|
+
}
|
|
93
|
+
export type NativeBuildRefusalReason = 'bad_request' | 'unauthorized' | 'not_found' | 'run_mismatch';
|
|
94
|
+
/** Every member of `NativeBuildRefusalReason`. Adding one is a major change after 1.0.0. */
|
|
95
|
+
export declare const NATIVE_BUILD_REFUSAL_REASONS: readonly ["bad_request", "unauthorized", "not_found", "run_mismatch"];
|
|
96
|
+
export type NativeBuildExchangeResult<TConfig> = {
|
|
97
|
+
readonly ok: true;
|
|
98
|
+
readonly config: TConfig;
|
|
99
|
+
readonly keys: NativeBuildKeys;
|
|
100
|
+
} | {
|
|
101
|
+
readonly ok: false;
|
|
102
|
+
readonly reason: NativeBuildRefusalReason;
|
|
103
|
+
};
|
|
104
|
+
export interface NativeBuildKeyExchange<TConfig> {
|
|
105
|
+
/** The checked claims of a token, or `null` when it is refused. Reads no run and no key. */
|
|
106
|
+
authenticate(token: string): Promise<NativeBuildClaims | null>;
|
|
107
|
+
exchange(input: {
|
|
108
|
+
readonly token: string;
|
|
109
|
+
readonly runId: unknown;
|
|
110
|
+
}): Promise<NativeBuildExchangeResult<TConfig>>;
|
|
111
|
+
}
|
|
112
|
+
export declare function createNativeBuildKeyExchange<TConfig>(options: NativeBuildKeyExchangeOptions<TConfig>): NativeBuildKeyExchange<TConfig>;
|
|
113
|
+
export type NativeBuildKeysEndpointOptions<TConfig> = NativeBuildKeyExchangeOptions<TConfig>;
|
|
114
|
+
/**
|
|
115
|
+
* `nativeBuildKeysEndpoint({ ... })` returns a fetch-shaped handler -- wire
|
|
116
|
+
* it directly as a route, e.g. `export const POST = nativeBuildKeysEndpoint({ ... });`.
|
|
117
|
+
*
|
|
118
|
+
* `POST /v1/keys/native-build` with `{ runId }` and `Authorization: Bearer
|
|
119
|
+
* <GitHub Actions OIDC token>` answers `200 { config, keys }`. Errors answer
|
|
120
|
+
* `{ error, message }`. A dependency failure that throws (GitHub's JWKS,
|
|
121
|
+
* foundry's run store, the held-key Worker) answers 502 `unavailable`,
|
|
122
|
+
* never a refusal such as `unauthorized` -- the same invariant
|
|
123
|
+
* `registrarEndpoint` keeps.
|
|
124
|
+
*/
|
|
125
|
+
export declare function nativeBuildKeysEndpoint<TConfig>(options: NativeBuildKeysEndpointOptions<TConfig>): (request: Request) => Promise<Response>;
|
|
126
|
+
export {};
|