@wtfalch/keys 0.8.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +244 -27
- package/dist/held/index.d.ts +116 -6
- package/dist/held/index.js +259 -37
- package/dist/held/schema.d.ts +17 -0
- package/dist/held/schema.js +12 -0
- package/dist/held/seal.d.ts +1 -1
- package/dist/held/seal.js +1 -1
- package/dist/held/shred.d.ts +6 -0
- package/dist/held/shred.js +6 -0
- package/dist/held/tenant.d.ts +2 -0
- package/dist/held/tenant.js +46 -0
- package/dist/held-edge/index.d.ts +17 -2
- package/dist/held-edge/index.js +51 -9
- package/dist/host/audit-endpoint.js +2 -8
- package/dist/host/company-registrar-keys.d.ts +13 -0
- package/dist/host/company-registrar-keys.js +6 -8
- package/dist/host/events.d.ts +19 -3
- package/dist/host/events.js +56 -20
- package/dist/host/index.d.ts +9 -2
- package/dist/host/index.js +9 -2
- package/dist/host/native-build.d.ts +126 -0
- package/dist/host/native-build.js +322 -0
- package/dist/host/registrar.d.ts +10 -4
- package/dist/host/registrar.js +64 -42
- package/dist/host/rotation-sweep.d.ts +56 -0
- package/dist/host/rotation-sweep.js +89 -0
- package/dist/issued/encoding.d.ts +4 -0
- package/dist/issued/encoding.js +22 -0
- package/dist/issued/index.d.ts +148 -7
- package/dist/issued/index.js +320 -34
- package/dist/issued/resign.d.ts +16 -0
- package/dist/issued/resign.js +55 -2
- package/dist/issued/tables.d.ts +38 -0
- package/dist/issued/tables.js +6 -0
- package/dist/issued/verify.d.ts +14 -3
- package/dist/issued/verify.js +10 -3
- package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
- package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
- package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
- package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
- package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
- package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
- package/dist/migrations/tenant-rows/0001_keys_tenant_rows.sql +63 -0
- package/dist/migrations-dir.d.ts +9 -0
- package/dist/migrations-dir.js +9 -0
- package/dist/service/body.d.ts +21 -0
- package/dist/service/body.js +128 -0
- package/dist/service/errors.d.ts +24 -0
- package/dist/service/errors.js +89 -0
- package/dist/service/handler.d.ts +35 -0
- package/dist/service/handler.js +328 -0
- package/dist/service/index.d.ts +7 -0
- package/dist/service/index.js +7 -0
- package/dist/service/policy.d.ts +130 -0
- package/dist/service/policy.js +123 -0
- package/dist/service/timeout.d.ts +6 -0
- package/dist/service/timeout.js +34 -0
- package/dist/webhooks.d.ts +40 -17
- package/dist/webhooks.js +70 -26
- package/dist/worker-contract.d.ts +43 -6
- package/dist/worker-contract.js +37 -0
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +7 -28
- package/package.json +21 -7
- package/dist/testing/index.d.ts +0 -9
- package/dist/testing/index.js +0 -9
- package/dist/testing/worker-stub.d.ts +0 -55
- package/dist/testing/worker-stub.js +0 -180
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { ServiceError } from '@wtfalch/contracts';
|
|
2
|
+
import { ID_PATTERN } from '../worker-contract.js';
|
|
3
|
+
export const MAX_BODY_BYTES = 64 * 1024;
|
|
4
|
+
export const MAX_GRANTS = 64;
|
|
5
|
+
export const MAX_GRANT_BYTES = 4 * 1024;
|
|
6
|
+
const MAX_SECRET_LENGTH = 512;
|
|
7
|
+
const MAX_KEY_LENGTH = 200;
|
|
8
|
+
const invalid = () => new ServiceError('invalid_request', 'invalid_request');
|
|
9
|
+
/** The body of a request, read up to `MAX_BODY_BYTES` and no further. Anything but a JSON object is `invalid_request`. */
|
|
10
|
+
export async function readObjectBody(request) {
|
|
11
|
+
const declared = request.headers.get('content-length');
|
|
12
|
+
if (declared !== null && Number(declared) > MAX_BODY_BYTES)
|
|
13
|
+
throw invalid();
|
|
14
|
+
if (!request.body)
|
|
15
|
+
throw invalid();
|
|
16
|
+
const reader = request.body.getReader();
|
|
17
|
+
const chunks = [];
|
|
18
|
+
let size = 0;
|
|
19
|
+
for (;;) {
|
|
20
|
+
const { done, value } = await reader.read();
|
|
21
|
+
if (done)
|
|
22
|
+
break;
|
|
23
|
+
size += value.byteLength;
|
|
24
|
+
if (size > MAX_BODY_BYTES) {
|
|
25
|
+
await reader.cancel();
|
|
26
|
+
throw invalid();
|
|
27
|
+
}
|
|
28
|
+
chunks.push(value);
|
|
29
|
+
}
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// The parser's message can quote the body; the caller gets the refusal's name only.
|
|
36
|
+
throw invalid();
|
|
37
|
+
}
|
|
38
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
|
|
39
|
+
throw invalid();
|
|
40
|
+
return parsed;
|
|
41
|
+
}
|
|
42
|
+
/** The query string as fields. A repeated name is `invalid_request`. */
|
|
43
|
+
export function queryFields(url) {
|
|
44
|
+
const fields = {};
|
|
45
|
+
for (const [name, value] of url.searchParams) {
|
|
46
|
+
if (Object.hasOwn(fields, name))
|
|
47
|
+
throw invalid();
|
|
48
|
+
fields[name] = value;
|
|
49
|
+
}
|
|
50
|
+
return fields;
|
|
51
|
+
}
|
|
52
|
+
/** Refuses a field outside `allowed`: a caller cannot send `purpose`, and a typo is not silently dropped. */
|
|
53
|
+
export function onlyFields(fields, allowed) {
|
|
54
|
+
for (const name of Object.keys(fields))
|
|
55
|
+
if (!allowed.includes(name))
|
|
56
|
+
throw invalid();
|
|
57
|
+
}
|
|
58
|
+
export function idField(fields, name) {
|
|
59
|
+
const value = fields[name];
|
|
60
|
+
if (typeof value !== 'string' || !ID_PATTERN.test(value))
|
|
61
|
+
throw invalid();
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
export function optionalIdField(fields, name) {
|
|
65
|
+
const value = fields[name];
|
|
66
|
+
return value === undefined || value === null ? null : idField(fields, name);
|
|
67
|
+
}
|
|
68
|
+
export function secretField(fields, name) {
|
|
69
|
+
const value = fields[name];
|
|
70
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_SECRET_LENGTH) {
|
|
71
|
+
throw invalid();
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
export function textField(fields, name) {
|
|
76
|
+
const value = fields[name];
|
|
77
|
+
if (typeof value !== 'string')
|
|
78
|
+
throw invalid();
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
export function optionalKeyField(fields, name) {
|
|
82
|
+
const value = fields[name];
|
|
83
|
+
if (value === undefined)
|
|
84
|
+
return undefined;
|
|
85
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_KEY_LENGTH) {
|
|
86
|
+
throw invalid();
|
|
87
|
+
}
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
export function numberField(fields, name) {
|
|
91
|
+
const value = fields[name];
|
|
92
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value))
|
|
93
|
+
throw invalid();
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
export function graceField(fields, name) {
|
|
97
|
+
const value = fields[name];
|
|
98
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
|
|
99
|
+
throw invalid();
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
export function optionalBooleanField(fields, name) {
|
|
103
|
+
const value = fields[name];
|
|
104
|
+
if (value === undefined)
|
|
105
|
+
return undefined;
|
|
106
|
+
if (typeof value !== 'boolean')
|
|
107
|
+
throw invalid();
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
export function optionalEnvironmentField(fields, name) {
|
|
111
|
+
const value = fields[name];
|
|
112
|
+
if (value === undefined)
|
|
113
|
+
return undefined;
|
|
114
|
+
if (value !== 'live' && value !== 'test')
|
|
115
|
+
throw invalid();
|
|
116
|
+
return value;
|
|
117
|
+
}
|
|
118
|
+
/** At most `MAX_GRANTS` entries, each at most `MAX_GRANT_BYTES` of JSON. What a grant means is the host's. */
|
|
119
|
+
export function grantsField(fields, name) {
|
|
120
|
+
const value = fields[name];
|
|
121
|
+
if (!Array.isArray(value) || value.length > MAX_GRANTS)
|
|
122
|
+
throw invalid();
|
|
123
|
+
for (const grant of value) {
|
|
124
|
+
if (Buffer.byteLength(JSON.stringify(grant) ?? '', 'utf8') > MAX_GRANT_BYTES)
|
|
125
|
+
throw invalid();
|
|
126
|
+
}
|
|
127
|
+
return value;
|
|
128
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { ServiceError, type ServiceErrorCode } from '@wtfalch/contracts';
|
|
2
|
+
import { type HeldKeysErrorCode } from '../held/index.js';
|
|
3
|
+
import type { IssueRefusalReason, RevokeForCompanyResult, RotateRefusalReason } from '../issued/index.js';
|
|
4
|
+
type RevokeRefusal = Extract<RevokeForCompanyResult, {
|
|
5
|
+
ok: false;
|
|
6
|
+
}>['reason'];
|
|
7
|
+
/** Every refusal name the library can hand `toServiceError`. */
|
|
8
|
+
export type Refusal = IssueRefusalReason | RotateRefusalReason | RevokeRefusal | HeldKeysErrorCode;
|
|
9
|
+
/**
|
|
10
|
+
* The closed table. A new member in any refusal union is a type error here until it has a row,
|
|
11
|
+
* and `service.test.ts` fails the same way at run time. The refusals that stay with the caller are
|
|
12
|
+
* `invalid_request`, `not_found`, `conflict`, `forbidden` and `rate_limited`. Everything the
|
|
13
|
+
* caller cannot fix, and anything about the Worker, is `unavailable`.
|
|
14
|
+
*/
|
|
15
|
+
export declare const REFUSAL_CODES: Readonly<Record<Refusal, ServiceErrorCode>>;
|
|
16
|
+
/**
|
|
17
|
+
* The one place a library refusal or a thrown value becomes a `ServiceError`. `message` is the
|
|
18
|
+
* refusal's name and nothing else, and `reason` repeats it where the refusal has one, so the
|
|
19
|
+
* caller can tell two `conflict`s apart. An unknown refusal, or any throw that is not a
|
|
20
|
+
* `ServiceError` or a `HeldKeysError`, is `unavailable` with one fixed log line that names the
|
|
21
|
+
* class and never the message.
|
|
22
|
+
*/
|
|
23
|
+
export declare function toServiceError(failure: unknown, retryAfterMs?: number): ServiceError;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { ServiceError } from '@wtfalch/contracts';
|
|
2
|
+
import { HeldKeysError } from '../held/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* The closed table. A new member in any refusal union is a type error here until it has a row,
|
|
5
|
+
* and `service.test.ts` fails the same way at run time. The refusals that stay with the caller are
|
|
6
|
+
* `invalid_request`, `not_found`, `conflict`, `forbidden` and `rate_limited`. Everything the
|
|
7
|
+
* caller cannot fix, and anything about the Worker, is `unavailable`.
|
|
8
|
+
*/
|
|
9
|
+
export const REFUSAL_CODES = {
|
|
10
|
+
// issue
|
|
11
|
+
expires_at_required: 'invalid_request',
|
|
12
|
+
expires_at_past: 'invalid_request',
|
|
13
|
+
minter_not_found: 'not_found',
|
|
14
|
+
minter_revoked: 'forbidden',
|
|
15
|
+
minter_expired: 'forbidden',
|
|
16
|
+
expires_after_minter: 'invalid_request',
|
|
17
|
+
purpose_not_allowed: 'invalid_request',
|
|
18
|
+
organisation_mismatch: 'invalid_request',
|
|
19
|
+
idempotency_conflict: 'conflict',
|
|
20
|
+
idempotent_row_revoked: 'conflict',
|
|
21
|
+
idempotent_row_expired: 'conflict',
|
|
22
|
+
environment_mismatch: 'invalid_request',
|
|
23
|
+
bad_worker_signature: 'unavailable',
|
|
24
|
+
// rotate
|
|
25
|
+
signature_invalid: 'unavailable',
|
|
26
|
+
conflict: 'conflict',
|
|
27
|
+
not_found: 'not_found',
|
|
28
|
+
revoked: 'conflict',
|
|
29
|
+
// revoke
|
|
30
|
+
protected_credential: 'conflict',
|
|
31
|
+
purpose_unknown: 'conflict',
|
|
32
|
+
// held
|
|
33
|
+
unseal_failed: 'unavailable',
|
|
34
|
+
disposed: 'unavailable',
|
|
35
|
+
invalidated: 'unavailable',
|
|
36
|
+
forbidden: 'forbidden',
|
|
37
|
+
// the Worker
|
|
38
|
+
credential_invalid: 'unavailable',
|
|
39
|
+
credential_expired: 'unavailable',
|
|
40
|
+
credential_revoked: 'unavailable',
|
|
41
|
+
grant_missing: 'unavailable',
|
|
42
|
+
rate_limited: 'rate_limited',
|
|
43
|
+
bad_request: 'invalid_request',
|
|
44
|
+
aad_mismatch: 'unavailable',
|
|
45
|
+
unknown_generation: 'unavailable',
|
|
46
|
+
bad_minter_signature: 'unavailable',
|
|
47
|
+
minter_exceeded: 'forbidden',
|
|
48
|
+
lineage_mismatch: 'unavailable',
|
|
49
|
+
bad_old_signature: 'unavailable',
|
|
50
|
+
unlogged_row: 'unavailable',
|
|
51
|
+
not_in_lineage: 'unavailable',
|
|
52
|
+
unreachable: 'unavailable',
|
|
53
|
+
};
|
|
54
|
+
const CLASS_NAME = /^[A-Za-z][A-Za-z0-9_$]{0,63}$/;
|
|
55
|
+
/** The class of a thrown value, never its message or any field of it. */
|
|
56
|
+
function className(error) {
|
|
57
|
+
const name = error?.constructor?.name;
|
|
58
|
+
return typeof name === 'string' && CLASS_NAME.test(name) ? name : 'non-error';
|
|
59
|
+
}
|
|
60
|
+
function unavailable(detail) {
|
|
61
|
+
console.error(`keys-service: unavailable (${detail})`);
|
|
62
|
+
return new ServiceError('unavailable', 'unavailable');
|
|
63
|
+
}
|
|
64
|
+
function isRefusal(value) {
|
|
65
|
+
return typeof value === 'string' && Object.hasOwn(REFUSAL_CODES, value);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The one place a library refusal or a thrown value becomes a `ServiceError`. `message` is the
|
|
69
|
+
* refusal's name and nothing else, and `reason` repeats it where the refusal has one, so the
|
|
70
|
+
* caller can tell two `conflict`s apart. An unknown refusal, or any throw that is not a
|
|
71
|
+
* `ServiceError` or a `HeldKeysError`, is `unavailable` with one fixed log line that names the
|
|
72
|
+
* class and never the message.
|
|
73
|
+
*/
|
|
74
|
+
export function toServiceError(failure, retryAfterMs) {
|
|
75
|
+
if (failure instanceof ServiceError)
|
|
76
|
+
return failure;
|
|
77
|
+
if (failure instanceof HeldKeysError)
|
|
78
|
+
return toServiceError(failure.code, failure.retryAfterMs);
|
|
79
|
+
if (isRefusal(failure)) {
|
|
80
|
+
const code = REFUSAL_CODES[failure];
|
|
81
|
+
if (code === 'unavailable')
|
|
82
|
+
return unavailable(failure);
|
|
83
|
+
const seconds = code === 'rate_limited' && retryAfterMs !== undefined && Number.isFinite(retryAfterMs)
|
|
84
|
+
? Math.max(1, Math.ceil(retryAfterMs / 1000))
|
|
85
|
+
: undefined;
|
|
86
|
+
return new ServiceError(code, failure, seconds, failure === code ? undefined : failure);
|
|
87
|
+
}
|
|
88
|
+
return unavailable(className(failure));
|
|
89
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ResourceAccess } from '@wtfalch/authz';
|
|
2
|
+
import { type Db, type RateLimiter, type SerializedCredential, type VerifyKeys, type WorkerClient } from '../issued/index.js';
|
|
3
|
+
export declare const DEFAULT_WORKER_TIMEOUT_MS = 5000;
|
|
4
|
+
/** What the host's token check yields. The handler never reads a token. */
|
|
5
|
+
export interface Principal {
|
|
6
|
+
readonly applicationId: string;
|
|
7
|
+
readonly platformId: string;
|
|
8
|
+
readonly access: Pick<ResourceAccess, 'allows'>;
|
|
9
|
+
}
|
|
10
|
+
export interface CreateKeysHandlerOptions<TGrant> {
|
|
11
|
+
/** The runtime role's connection. */
|
|
12
|
+
readonly db: Db;
|
|
13
|
+
/** The caller, or `null` for 401. A throw is `unavailable`. */
|
|
14
|
+
readonly principal: (request: Request) => Promise<Principal | null> | Principal | null;
|
|
15
|
+
readonly worker: Pick<WorkerClient<TGrant>, 'wrap' | 'unwrap' | 'rewrap' | 'signRow'>;
|
|
16
|
+
readonly credential: SerializedCredential;
|
|
17
|
+
readonly verifyKeys: VerifyKeys;
|
|
18
|
+
/** This host's split-secret prefix, e.g. `ai_live_`. */
|
|
19
|
+
readonly prefix: string;
|
|
20
|
+
/** Bearer token for `GET /v1/keys/audit`. Unset or short, the route answers 503. */
|
|
21
|
+
readonly auditToken: string | undefined;
|
|
22
|
+
/** The mount path, e.g. `/keys`. Default empty. */
|
|
23
|
+
readonly basePath?: string;
|
|
24
|
+
readonly rateLimiter?: RateLimiter;
|
|
25
|
+
readonly now?: () => number;
|
|
26
|
+
/** Bound on every Worker call. Default 5 seconds. */
|
|
27
|
+
readonly workerTimeoutMs?: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* `createKeysHandler(...)` returns `(request) => Promise<Response>` for the keys routes of C7
|
|
31
|
+
* (docs/contracts.md). Every route runs in one order: principal, a bounded body, authorization on
|
|
32
|
+
* the scoping id alone, the other fields, then the library. A refusal at any step is the error
|
|
33
|
+
* envelope of `@wtfalch/contracts`. Nothing escapes as a raw 500.
|
|
34
|
+
*/
|
|
35
|
+
export declare function createKeysHandler<TGrant = unknown>(options: CreateKeysHandlerOptions<TGrant>): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { ServiceError, serviceErrorResponse } from '@wtfalch/contracts';
|
|
2
|
+
import { createHeldKeys, shredExpired } from '../held/index.js';
|
|
3
|
+
import { auditEndpoint, recordEvent, recordEventInTransaction } from '../host/index.js';
|
|
4
|
+
import { createCredentialIssuer, } from '../issued/index.js';
|
|
5
|
+
import { graceField, grantsField, idField, numberField, onlyFields, optionalBooleanField, optionalEnvironmentField, optionalIdField, optionalKeyField, queryFields, readObjectBody, secretField, textField, } from './body.js';
|
|
6
|
+
import { toServiceError } from './errors.js';
|
|
7
|
+
import { withWorkerTimeout } from './timeout.js';
|
|
8
|
+
export const DEFAULT_WORKER_TIMEOUT_MS = 5_000;
|
|
9
|
+
function json(data, status = 200) {
|
|
10
|
+
return Response.json(data, { status, headers: { 'cache-control': 'no-store' } });
|
|
11
|
+
}
|
|
12
|
+
/** A route states its parse and its run once each; the table keeps one shape. */
|
|
13
|
+
function defineRoute(route) {
|
|
14
|
+
return {
|
|
15
|
+
...route,
|
|
16
|
+
run: (ctx, scopeId, input, id) => {
|
|
17
|
+
onlyFields(input, route.fields);
|
|
18
|
+
return route.run(ctx, scopeId, route.parse(input, id), id);
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** The `:id` of a path, held to the same shape as every other id. */
|
|
23
|
+
function pathIdOf(id) {
|
|
24
|
+
return idField({ id }, 'id');
|
|
25
|
+
}
|
|
26
|
+
function routeTable() {
|
|
27
|
+
return [
|
|
28
|
+
defineRoute({
|
|
29
|
+
method: 'POST',
|
|
30
|
+
path: '/v1/issued/issue',
|
|
31
|
+
permission: 'keys:issue',
|
|
32
|
+
resource: 'keys.credential',
|
|
33
|
+
scope: 'organisationId',
|
|
34
|
+
input: 'body',
|
|
35
|
+
fields: ['organisationId', 'grants', 'minter', 'expiresAt', 'idempotencyKey', 'environment'],
|
|
36
|
+
parse: (input) => ({
|
|
37
|
+
grants: grantsField(input, 'grants'),
|
|
38
|
+
minter: optionalIdField(input, 'minter'),
|
|
39
|
+
expiresAt: numberField(input, 'expiresAt'),
|
|
40
|
+
idempotencyKey: optionalKeyField(input, 'idempotencyKey'),
|
|
41
|
+
environment: optionalEnvironmentField(input, 'environment'),
|
|
42
|
+
}),
|
|
43
|
+
async run(ctx, organisationId, p) {
|
|
44
|
+
// A minter of another organisation is a missing minter.
|
|
45
|
+
if (p.minter !== null && !(await ctx.chainOf(p.minter, organisationId))) {
|
|
46
|
+
throw toServiceError('minter_not_found');
|
|
47
|
+
}
|
|
48
|
+
const result = await ctx.issuer.issue({
|
|
49
|
+
grants: p.grants,
|
|
50
|
+
minter: p.minter,
|
|
51
|
+
expiresAt: p.expiresAt,
|
|
52
|
+
// A root's key is unique across the table, so another organisation's key must not meet it.
|
|
53
|
+
idempotencyKey: p.idempotencyKey === undefined ? undefined : `${organisationId}:${p.idempotencyKey}`,
|
|
54
|
+
environment: p.environment,
|
|
55
|
+
organisationId,
|
|
56
|
+
purpose: 'ordinary',
|
|
57
|
+
});
|
|
58
|
+
if (!result.ok)
|
|
59
|
+
throw toServiceError(result.reason, result.retryAfterMs);
|
|
60
|
+
const row = (await ctx.chainOf(result.id, organisationId))?.[0];
|
|
61
|
+
if (!row)
|
|
62
|
+
throw toServiceError('not_found');
|
|
63
|
+
return json({ id: result.id, secret: result.secret, expiresAt: row.expiresAt }, result.secret === null ? 200 : 201);
|
|
64
|
+
},
|
|
65
|
+
}),
|
|
66
|
+
defineRoute({
|
|
67
|
+
method: 'POST',
|
|
68
|
+
path: '/v1/issued/verify',
|
|
69
|
+
permission: 'keys:verify',
|
|
70
|
+
resource: 'keys.credential',
|
|
71
|
+
scope: 'organisationId',
|
|
72
|
+
input: 'body',
|
|
73
|
+
fields: ['organisationId', 'secret'],
|
|
74
|
+
parse: (input) => secretField(input, 'secret'),
|
|
75
|
+
async run(ctx, organisationId, secret) {
|
|
76
|
+
const result = await ctx.issuer.check(secret, { organisationId });
|
|
77
|
+
if (!result.ok) {
|
|
78
|
+
if (result.reason === 'rate_limited') {
|
|
79
|
+
throw toServiceError('rate_limited', result.retryAfterMs);
|
|
80
|
+
}
|
|
81
|
+
return json({ valid: false, reason: result.reason });
|
|
82
|
+
}
|
|
83
|
+
const row = (await ctx.chainOf(result.id, organisationId))?.[0];
|
|
84
|
+
if (!row)
|
|
85
|
+
return json({ valid: false, reason: 'not_found' });
|
|
86
|
+
return json({
|
|
87
|
+
valid: true,
|
|
88
|
+
id: result.id,
|
|
89
|
+
grants: result.grants,
|
|
90
|
+
expiresAt: row.expiresAt,
|
|
91
|
+
});
|
|
92
|
+
},
|
|
93
|
+
}),
|
|
94
|
+
defineRoute({
|
|
95
|
+
method: 'POST',
|
|
96
|
+
path: '/v1/issued/:id/rotate',
|
|
97
|
+
permission: 'keys:rotate',
|
|
98
|
+
resource: 'keys.credential',
|
|
99
|
+
scope: 'organisationId',
|
|
100
|
+
input: 'body',
|
|
101
|
+
fields: ['organisationId', 'graceMs'],
|
|
102
|
+
parse: (input, id) => {
|
|
103
|
+
pathIdOf(id);
|
|
104
|
+
return graceField(input, 'graceMs');
|
|
105
|
+
},
|
|
106
|
+
async run(ctx, organisationId, graceMs, id) {
|
|
107
|
+
const chain = await ctx.chainOf(id, organisationId);
|
|
108
|
+
// A platform master is the platform's, whatever organisation its row carries.
|
|
109
|
+
if (!chain || chain[0]?.purpose === 'platform_master')
|
|
110
|
+
throw toServiceError('not_found');
|
|
111
|
+
const result = await ctx.issuer.rotate(id, { graceMs });
|
|
112
|
+
if (!result.ok)
|
|
113
|
+
throw toServiceError(result.reason, result.retryAfterMs);
|
|
114
|
+
return json({ id, secret: result.secret });
|
|
115
|
+
},
|
|
116
|
+
}),
|
|
117
|
+
defineRoute({
|
|
118
|
+
method: 'POST',
|
|
119
|
+
path: '/v1/issued/:id/revoke',
|
|
120
|
+
permission: 'keys:revoke',
|
|
121
|
+
resource: 'keys.credential',
|
|
122
|
+
scope: 'organisationId',
|
|
123
|
+
input: 'body',
|
|
124
|
+
fields: ['organisationId', 'cascade'],
|
|
125
|
+
parse: (input, id) => {
|
|
126
|
+
pathIdOf(id);
|
|
127
|
+
return optionalBooleanField(input, 'cascade');
|
|
128
|
+
},
|
|
129
|
+
async run(ctx, organisationId, cascade, id) {
|
|
130
|
+
if (!(await ctx.chainOf(id, organisationId)))
|
|
131
|
+
throw toServiceError('not_found');
|
|
132
|
+
// Never `revoke`: that one reaches protected roots.
|
|
133
|
+
const result = await ctx.issuer.revokeForCompany(id, cascade === undefined ? { organisationId } : { cascade, organisationId });
|
|
134
|
+
if (!result.ok)
|
|
135
|
+
throw toServiceError(result.reason);
|
|
136
|
+
return json({ revoked: result.revoked });
|
|
137
|
+
},
|
|
138
|
+
}),
|
|
139
|
+
defineRoute({
|
|
140
|
+
method: 'GET',
|
|
141
|
+
path: '/v1/issued/:id/lineage',
|
|
142
|
+
permission: 'keys:lineage',
|
|
143
|
+
resource: 'keys.credential',
|
|
144
|
+
scope: 'organisationId',
|
|
145
|
+
input: 'query',
|
|
146
|
+
fields: ['organisationId'],
|
|
147
|
+
parse: (_input, id) => pathIdOf(id),
|
|
148
|
+
async run(ctx, organisationId, id) {
|
|
149
|
+
const chain = await ctx.chainOf(id, organisationId);
|
|
150
|
+
if (!chain)
|
|
151
|
+
throw toServiceError('not_found');
|
|
152
|
+
// The wire carries the fields of `LineageLink` in `@wtfalch/keys-client`, not `purpose`.
|
|
153
|
+
return json({
|
|
154
|
+
chain: chain.map((l) => ({
|
|
155
|
+
id: l.id,
|
|
156
|
+
issuedById: l.issuedById,
|
|
157
|
+
grants: l.grants,
|
|
158
|
+
expiresAt: l.expiresAt,
|
|
159
|
+
revokedAt: l.revokedAt,
|
|
160
|
+
environment: l.environment,
|
|
161
|
+
})),
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
}),
|
|
165
|
+
defineRoute({
|
|
166
|
+
method: 'POST',
|
|
167
|
+
path: '/v1/held/put',
|
|
168
|
+
permission: 'keys:put',
|
|
169
|
+
resource: 'keys.held',
|
|
170
|
+
scope: 'tenantId',
|
|
171
|
+
input: 'body',
|
|
172
|
+
fields: ['tenantId', 'entryId', 'value'],
|
|
173
|
+
parse: (input) => ({
|
|
174
|
+
entryId: idField(input, 'entryId'),
|
|
175
|
+
value: textField(input, 'value'),
|
|
176
|
+
}),
|
|
177
|
+
async run(ctx, tenantId, p) {
|
|
178
|
+
const { version } = await ctx.held.put({ tenantId, entryId: p.entryId }, p.value);
|
|
179
|
+
return json({ version }, 201);
|
|
180
|
+
},
|
|
181
|
+
}),
|
|
182
|
+
defineRoute({
|
|
183
|
+
method: 'POST',
|
|
184
|
+
path: '/v1/held/revoke',
|
|
185
|
+
permission: 'keys:held-revoke',
|
|
186
|
+
resource: 'keys.held',
|
|
187
|
+
scope: 'tenantId',
|
|
188
|
+
input: 'body',
|
|
189
|
+
fields: ['tenantId', 'entryId'],
|
|
190
|
+
parse: (input) => idField(input, 'entryId'),
|
|
191
|
+
async run(ctx, tenantId, entryId) {
|
|
192
|
+
await ctx.held.revokeEntry({ tenantId, entryId });
|
|
193
|
+
return json({ revoked: true });
|
|
194
|
+
},
|
|
195
|
+
}),
|
|
196
|
+
defineRoute({
|
|
197
|
+
method: 'POST',
|
|
198
|
+
path: '/v1/held/shred',
|
|
199
|
+
permission: 'keys:shred',
|
|
200
|
+
resource: 'keys.held',
|
|
201
|
+
scope: null,
|
|
202
|
+
input: 'none',
|
|
203
|
+
fields: [],
|
|
204
|
+
parse: () => null,
|
|
205
|
+
async run(ctx) {
|
|
206
|
+
return json({ shredded: await ctx.shred() });
|
|
207
|
+
},
|
|
208
|
+
}),
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
function normaliseBasePath(basePath) {
|
|
212
|
+
const path = basePath ?? '';
|
|
213
|
+
if (!/^(\/[A-Za-z0-9._~-]+)*$/.test(path)) {
|
|
214
|
+
throw new RangeError('basePath must be empty, or start with / and have no trailing /');
|
|
215
|
+
}
|
|
216
|
+
return path;
|
|
217
|
+
}
|
|
218
|
+
/** Matches `/v1/issued/:id/rotate` against a path: the `:id` segment ('' when the pattern has none), or `undefined` for a different path. */
|
|
219
|
+
function matchPath(pattern, pathname) {
|
|
220
|
+
const want = pattern.split('/');
|
|
221
|
+
const have = pathname.split('/');
|
|
222
|
+
if (want.length !== have.length)
|
|
223
|
+
return undefined;
|
|
224
|
+
let id = '';
|
|
225
|
+
for (let i = 0; i < want.length; i++) {
|
|
226
|
+
if (want[i] === ':id')
|
|
227
|
+
id = have[i];
|
|
228
|
+
else if (want[i] !== have[i])
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
return id;
|
|
232
|
+
}
|
|
233
|
+
function resourceFor(caller, route, scopeId, id) {
|
|
234
|
+
return {
|
|
235
|
+
id: id !== '' ? id : scopeId !== '' ? scopeId : 'keys-held',
|
|
236
|
+
type: route.resource,
|
|
237
|
+
applicationId: caller.applicationId,
|
|
238
|
+
platformId: caller.platformId,
|
|
239
|
+
organisationId: route.scope === null ? null : scopeId,
|
|
240
|
+
teamId: null,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* `createKeysHandler(...)` returns `(request) => Promise<Response>` for the keys routes of C7
|
|
245
|
+
* (docs/contracts.md). Every route runs in one order: principal, a bounded body, authorization on
|
|
246
|
+
* the scoping id alone, the other fields, then the library. A refusal at any step is the error
|
|
247
|
+
* envelope of `@wtfalch/contracts`. Nothing escapes as a raw 500.
|
|
248
|
+
*/
|
|
249
|
+
export function createKeysHandler(options) {
|
|
250
|
+
const basePath = normaliseBasePath(options.basePath);
|
|
251
|
+
const worker = withWorkerTimeout(options.worker, options.workerTimeoutMs ?? DEFAULT_WORKER_TIMEOUT_MS);
|
|
252
|
+
const issuer = createCredentialIssuer({
|
|
253
|
+
db: options.db,
|
|
254
|
+
worker,
|
|
255
|
+
credential: options.credential,
|
|
256
|
+
verifyKeys: options.verifyKeys,
|
|
257
|
+
prefix: options.prefix,
|
|
258
|
+
auditInTransaction: recordEventInTransaction,
|
|
259
|
+
rateLimiter: options.rateLimiter,
|
|
260
|
+
now: options.now,
|
|
261
|
+
});
|
|
262
|
+
const now = options.now ?? Date.now;
|
|
263
|
+
const held = createHeldKeys({
|
|
264
|
+
db: options.db,
|
|
265
|
+
worker,
|
|
266
|
+
credential: options.credential,
|
|
267
|
+
// No route opens a value, so `key.used` is never emitted here.
|
|
268
|
+
audit: (event) => recordEvent(options.db, event),
|
|
269
|
+
auditInTransaction: (tx, event) => recordEvent(tx, event),
|
|
270
|
+
now,
|
|
271
|
+
});
|
|
272
|
+
const ctx = {
|
|
273
|
+
issuer,
|
|
274
|
+
held,
|
|
275
|
+
shred: () => options.db.transaction(async (tx) => {
|
|
276
|
+
const shredded = await shredExpired(tx);
|
|
277
|
+
await recordEvent(tx, { name: 'held.shredded', at: now() });
|
|
278
|
+
return shredded;
|
|
279
|
+
}),
|
|
280
|
+
async chainOf(id, organisationId) {
|
|
281
|
+
const chain = [];
|
|
282
|
+
for (const link of await issuer.lineageOf(id)) {
|
|
283
|
+
if (link.organisationId !== organisationId)
|
|
284
|
+
break;
|
|
285
|
+
chain.push(link);
|
|
286
|
+
}
|
|
287
|
+
return chain[0]?.id === id ? chain : undefined;
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
const routes = routeTable();
|
|
291
|
+
const audit = auditEndpoint({ db: options.db, token: options.auditToken, now: options.now });
|
|
292
|
+
const auditPath = `${basePath}/v1/keys/audit`;
|
|
293
|
+
return async (request) => {
|
|
294
|
+
try {
|
|
295
|
+
const url = new URL(request.url);
|
|
296
|
+
if (url.pathname === auditPath)
|
|
297
|
+
return await audit(request);
|
|
298
|
+
const caller = await options.principal(request);
|
|
299
|
+
if (caller === null)
|
|
300
|
+
throw new ServiceError('unauthorized', 'unauthorized');
|
|
301
|
+
let route;
|
|
302
|
+
let id = '';
|
|
303
|
+
for (const candidate of routes) {
|
|
304
|
+
const matched = matchPath(`${basePath}${candidate.path}`, url.pathname);
|
|
305
|
+
if (matched !== undefined && candidate.method === request.method) {
|
|
306
|
+
route = candidate;
|
|
307
|
+
id = matched;
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (!route)
|
|
312
|
+
throw toServiceError('not_found');
|
|
313
|
+
const input = route.input === 'body'
|
|
314
|
+
? await readObjectBody(request)
|
|
315
|
+
: route.input === 'query'
|
|
316
|
+
? queryFields(url)
|
|
317
|
+
: {};
|
|
318
|
+
const scopeId = route.scope === null ? '' : idField(input, route.scope);
|
|
319
|
+
if (!caller.access.allows(route.permission, resourceFor(caller, route, scopeId, id))) {
|
|
320
|
+
throw new ServiceError('forbidden', 'forbidden');
|
|
321
|
+
}
|
|
322
|
+
return await route.run(ctx, scopeId, input, id);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
return serviceErrorResponse(toServiceError(error));
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `./service`: the HTTP half of the keys tables, for a company data service to mount. See the
|
|
3
|
+
* package README's "Adopting ./service" and C7 in docs/contracts.md.
|
|
4
|
+
*/
|
|
5
|
+
export { createKeysHandler, DEFAULT_WORKER_TIMEOUT_MS, type CreateKeysHandlerOptions, type Principal, } from './handler.js';
|
|
6
|
+
export { policyModule, type Permission } from './policy.js';
|
|
7
|
+
export { REFUSAL_CODES, toServiceError, type Refusal } from './errors.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `./service`: the HTTP half of the keys tables, for a company data service to mount. See the
|
|
3
|
+
* package README's "Adopting ./service" and C7 in docs/contracts.md.
|
|
4
|
+
*/
|
|
5
|
+
export { createKeysHandler, DEFAULT_WORKER_TIMEOUT_MS, } from './handler.js';
|
|
6
|
+
export { policyModule } from './policy.js';
|
|
7
|
+
export { REFUSAL_CODES, toServiceError } from './errors.js';
|