@wtfalch/keys 0.7.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +349 -7
  2. package/dist/held/index.d.ts +116 -6
  3. package/dist/held/index.js +247 -25
  4. package/dist/held/schema.d.ts +17 -0
  5. package/dist/held/schema.js +12 -0
  6. package/dist/held/shred.d.ts +6 -0
  7. package/dist/held/shred.js +6 -0
  8. package/dist/held-edge/index.d.ts +17 -2
  9. package/dist/held-edge/index.js +51 -9
  10. package/dist/host/audit-endpoint.js +2 -8
  11. package/dist/host/company-registrar-keys.d.ts +106 -0
  12. package/dist/host/company-registrar-keys.js +211 -0
  13. package/dist/host/events.d.ts +19 -3
  14. package/dist/host/events.js +55 -20
  15. package/dist/host/index.d.ts +15 -1
  16. package/dist/host/index.js +15 -1
  17. package/dist/host/native-build.d.ts +126 -0
  18. package/dist/host/native-build.js +322 -0
  19. package/dist/host/registrar.d.ts +87 -0
  20. package/dist/host/registrar.js +284 -0
  21. package/dist/host/rotation-sweep.d.ts +56 -0
  22. package/dist/host/rotation-sweep.js +89 -0
  23. package/dist/issued/encoding.d.ts +4 -0
  24. package/dist/issued/encoding.js +22 -0
  25. package/dist/issued/index.d.ts +148 -7
  26. package/dist/issued/index.js +320 -34
  27. package/dist/issued/resign.d.ts +16 -0
  28. package/dist/issued/resign.js +55 -2
  29. package/dist/issued/tables.d.ts +38 -0
  30. package/dist/issued/tables.js +6 -0
  31. package/dist/issued/verify.d.ts +14 -3
  32. package/dist/issued/verify.js +10 -3
  33. package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
  34. package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
  35. package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
  36. package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
  37. package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
  38. package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
  39. package/dist/service/body.d.ts +21 -0
  40. package/dist/service/body.js +128 -0
  41. package/dist/service/errors.d.ts +24 -0
  42. package/dist/service/errors.js +89 -0
  43. package/dist/service/handler.d.ts +35 -0
  44. package/dist/service/handler.js +328 -0
  45. package/dist/service/index.d.ts +7 -0
  46. package/dist/service/index.js +7 -0
  47. package/dist/service/policy.d.ts +130 -0
  48. package/dist/service/policy.js +123 -0
  49. package/dist/service/timeout.d.ts +6 -0
  50. package/dist/service/timeout.js +34 -0
  51. package/dist/testing/index.d.ts +3 -0
  52. package/dist/testing/index.js +3 -0
  53. package/dist/webhooks.d.ts +40 -17
  54. package/dist/webhooks.js +70 -26
  55. package/dist/worker-contract.d.ts +43 -6
  56. package/dist/worker-contract.js +37 -0
  57. package/dist/worker.d.ts +1 -1
  58. package/dist/worker.js +7 -28
  59. package/package.json +21 -3
@@ -0,0 +1,123 @@
1
+ // `@wtfalch/authz` reserves any permission whose action is exactly "write", "admin", "manage" or
2
+ // "read-all". None of these eight collide with it.
3
+ const base = {
4
+ scopes: ['organisation'],
5
+ relations: ['any'],
6
+ tenantKinds: ['customer', 'operator'],
7
+ assignable: true,
8
+ };
9
+ /**
10
+ * The eight permissions `./service` checks. `keys:put` and `keys:held-revoke` name the tenant in
11
+ * `./held`'s sense, which plays the part an organisation plays for the issued routes.
12
+ * `keys:shred` is a sweep over every tenant, so it is platform-wide and never offered to a company.
13
+ */
14
+ export const policyModule = {
15
+ namespace: 'keys',
16
+ permissions: [
17
+ {
18
+ ...base,
19
+ id: 'keys:issue',
20
+ label: 'Issue a credential',
21
+ description: 'Mint a new issued credential, optionally as a child of another.',
22
+ resourceType: 'keys.credential',
23
+ effect: 'write',
24
+ boundaries: ['organisation'],
25
+ offered: true,
26
+ sensitive: true,
27
+ survives: [],
28
+ support: 'never',
29
+ },
30
+ {
31
+ ...base,
32
+ id: 'keys:verify',
33
+ label: 'Verify a credential',
34
+ description: 'Check a presented bearer secret against an issued credential.',
35
+ resourceType: 'keys.credential',
36
+ effect: 'read',
37
+ boundaries: ['organisation'],
38
+ offered: true,
39
+ sensitive: false,
40
+ survives: ['read_only'],
41
+ support: 'read',
42
+ },
43
+ {
44
+ ...base,
45
+ id: 'keys:rotate',
46
+ label: 'Rotate a credential',
47
+ description: "Replace an issued credential's secret, keeping the old one for a grace period.",
48
+ resourceType: 'keys.credential',
49
+ effect: 'write',
50
+ boundaries: ['organisation'],
51
+ offered: true,
52
+ sensitive: true,
53
+ survives: [],
54
+ support: 'never',
55
+ },
56
+ {
57
+ ...base,
58
+ id: 'keys:revoke',
59
+ label: 'Revoke a credential',
60
+ description: 'Revoke an ordinary issued credential and, by default, its descendants.',
61
+ resourceType: 'keys.credential',
62
+ effect: 'write',
63
+ boundaries: ['organisation'],
64
+ offered: true,
65
+ sensitive: true,
66
+ survives: [],
67
+ support: 'never',
68
+ },
69
+ {
70
+ ...base,
71
+ id: 'keys:lineage',
72
+ label: 'Read a credential lineage',
73
+ description: "Read a credential's chain back to its root.",
74
+ resourceType: 'keys.credential',
75
+ effect: 'read',
76
+ boundaries: ['organisation'],
77
+ offered: true,
78
+ sensitive: false,
79
+ survives: ['read_only'],
80
+ support: 'read',
81
+ },
82
+ {
83
+ ...base,
84
+ id: 'keys:put',
85
+ label: 'Put a held key',
86
+ description: 'Seal a new version of a held key under one entry.',
87
+ resourceType: 'keys.held',
88
+ effect: 'write',
89
+ boundaries: ['organisation'],
90
+ offered: true,
91
+ sensitive: true,
92
+ survives: [],
93
+ support: 'never',
94
+ },
95
+ {
96
+ ...base,
97
+ id: 'keys:held-revoke',
98
+ label: 'Revoke a held key',
99
+ description: 'Revoke one held entry so no version of it opens again.',
100
+ resourceType: 'keys.held',
101
+ effect: 'write',
102
+ boundaries: ['organisation'],
103
+ offered: true,
104
+ sensitive: true,
105
+ survives: [],
106
+ support: 'never',
107
+ },
108
+ {
109
+ ...base,
110
+ id: 'keys:shred',
111
+ label: 'Shred expired held keys',
112
+ description: 'Run the housekeeping sweep that erases eligible held-key versions.',
113
+ resourceType: 'keys.held',
114
+ effect: 'write',
115
+ tenantKinds: ['operator'],
116
+ boundaries: ['platform'],
117
+ offered: false,
118
+ sensitive: true,
119
+ survives: [],
120
+ support: 'never',
121
+ },
122
+ ],
123
+ };
@@ -0,0 +1,6 @@
1
+ import type { WorkerClient } from '../worker-contract.js';
2
+ /**
3
+ * The four Worker calls this service makes, each bounded. A hung, rejecting or synchronously
4
+ * throwing Worker is `unreachable`; the thrown value is dropped, so nothing it carries is logged.
5
+ */
6
+ export declare function withWorkerTimeout<TGrant>(worker: Pick<WorkerClient<TGrant>, 'wrap' | 'unwrap' | 'rewrap' | 'signRow'>, ms: number): Pick<WorkerClient<TGrant>, 'wrap' | 'unwrap' | 'rewrap' | 'signRow'>;
@@ -0,0 +1,34 @@
1
+ /** What a call that threw, rejected or ran past its time answers. */
2
+ const UNREACHABLE = {
3
+ ok: false,
4
+ error: { code: 'unreachable', message: 'the Worker did not answer' },
5
+ };
6
+ /**
7
+ * Runs `call` and answers `UNREACHABLE` when it throws (also synchronously), rejects, or has not
8
+ * answered in `ms`. The timer is always cleared.
9
+ */
10
+ async function bounded(call, ms) {
11
+ let timer;
12
+ const late = new Promise((resolve) => {
13
+ timer = setTimeout(() => resolve(UNREACHABLE), ms);
14
+ });
15
+ const answer = new Promise((resolve) => resolve(call())).catch(() => UNREACHABLE);
16
+ try {
17
+ return await Promise.race([answer, late]);
18
+ }
19
+ finally {
20
+ clearTimeout(timer);
21
+ }
22
+ }
23
+ /**
24
+ * The four Worker calls this service makes, each bounded. A hung, rejecting or synchronously
25
+ * throwing Worker is `unreachable`; the thrown value is dropped, so nothing it carries is logged.
26
+ */
27
+ export function withWorkerTimeout(worker, ms) {
28
+ return {
29
+ wrap: (req) => bounded(() => worker.wrap(req), ms),
30
+ unwrap: (req) => bounded(() => worker.unwrap(req), ms),
31
+ rewrap: (req) => bounded(() => worker.rewrap(req), ms),
32
+ signRow: (req) => bounded(() => worker.signRow(req), ms),
33
+ };
34
+ }
@@ -5,5 +5,8 @@
5
5
  * `pickSignable` are re-exported here -- not from `./issued` or the
6
6
  * public root -- because they exist for building test fixtures, not for a
7
7
  * host's runtime code, which never needs to construct signed bytes itself.
8
+ *
9
+ * @deprecated `@wtfalch/keys/testing` is removed in 1.0.0. It still works
10
+ * unchanged in 0.x.
8
11
  */
9
12
  export { createKeysWorkerStub, TEST_CREDENTIAL, canonicalJson, encodeSigned, pickSignable, type CreateKeysWorkerStubOptions, type KeysWorkerStub, } from './worker-stub.js';
@@ -5,5 +5,8 @@
5
5
  * `pickSignable` are re-exported here -- not from `./issued` or the
6
6
  * public root -- because they exist for building test fixtures, not for a
7
7
  * host's runtime code, which never needs to construct signed bytes itself.
8
+ *
9
+ * @deprecated `@wtfalch/keys/testing` is removed in 1.0.0. It still works
10
+ * unchanged in 0.x.
8
11
  */
9
12
  export { createKeysWorkerStub, TEST_CREDENTIAL, canonicalJson, encodeSigned, pickSignable, } from './worker-stub.js';
@@ -10,46 +10,69 @@
10
10
  * `node:crypto`, not WebCrypto: this runs host-side only, the same posture
11
11
  * as `secret.ts`.
12
12
  */
13
+ /** Each delivery is aborted after this long. Nothing waits on it: the caller has already returned. */
14
+ export declare const WEBHOOK_TIMEOUT_MS = 5000;
15
+ /** How far a delivery's `x-keys-timestamp` may be from the receiver's clock. */
16
+ export declare const DEFAULT_WEBHOOK_TOLERANCE_MS: number;
13
17
  export interface WebhookDeliveryOptions {
14
18
  readonly url: string;
15
19
  /**
16
- * HMAC-SHA256 over the raw JSON body, sent hex-encoded as
17
- * `X-Keys-Signature`. Omit only when the endpoint's own network
18
- * boundary (an internal-only URL, a bearer token baked into `url`) is
19
- * the sole protection -- `verifyWebhookSignature` is how the receiver
20
- * checks it.
20
+ * With a secret, each delivery carries `x-keys-timestamp` (Unix
21
+ * milliseconds) and `x-keys-signature`, the hex HMAC-SHA256 of
22
+ * `<timestamp>.<body>`. The receiver checks both with
23
+ * `verifyWebhookSignature(body, signature, secret, { timestamp })`.
24
+ * Omit only when the endpoint's own network boundary (an internal-only URL,
25
+ * a bearer token baked into `url`) is the sole protection.
21
26
  */
22
27
  readonly secret?: string;
23
28
  /** Defaults to the global `fetch`. Tests pass a stub. */
24
29
  readonly fetch?: typeof fetch;
25
30
  /**
26
- * Called with whatever made one delivery fail -- a thrown error, or an
27
- * `Error` wrapping a non-2xx response -- and the event that failed to
28
- * deliver. Never rethrown: a webhook subscriber's outage must never fail
29
- * the `issue()`/`rotate()`/`revoke()`/`open()` call that produced the
30
- * event. Delivery is fire-and-forget and best-effort, not at-least-once;
31
- * a host that needs a retried or durable queue puts one in front of
32
- * `url`, or wraps this callback itself.
31
+ * Called with whatever made one delivery fail -- a thrown error, a timeout
32
+ * after 5 seconds, or an `Error` for a non-2xx response -- and the event
33
+ * that failed to deliver. Never rethrown, and a throw from this callback is
34
+ * logged by error name and swallowed: a webhook subscriber's outage must
35
+ * never fail the `issue()`/`rotate()`/`revoke()`/`open()` call that
36
+ * produced the event. Delivery is best-effort and not retried; a host that
37
+ * needs a durable queue puts one in front of `url`.
33
38
  */
34
39
  readonly onDeliveryError?: (error: unknown, event: unknown) => void;
35
40
  }
36
41
  /**
37
42
  * An `AuditCallback` (`./issued`) or `KeyUsedEvent` callback (`./held`) that
38
- * POSTs the event as JSON to `options.url`.
43
+ * POSTs the event as JSON to `options.url`. It returns at once and delivers
44
+ * outside the caller's path, with a 5-second timeout (`AbortSignal.timeout`,
45
+ * whose timer does not keep the process alive). A delivery that fails in any
46
+ * way goes to `onDeliveryError`; it never becomes an unhandled rejection.
39
47
  */
40
48
  export declare function createWebhookDispatcher<TEvent extends {
41
49
  readonly name: string;
42
50
  }>(options: WebhookDeliveryOptions): (event: TEvent) => Promise<void>;
43
- /** Hex HMAC-SHA256 of `body` under `secret`. What `X-Keys-Signature` carries. */
44
- export declare function signWebhookBody(body: string, secret: string): string;
51
+ /**
52
+ * Hex HMAC-SHA256 of `body` under `secret`. With `timestamp`, the HMAC covers
53
+ * `<timestamp>.<body>`, which is what `x-keys-signature` carries. Without it,
54
+ * the old form over the body alone (deprecated, removed at 1.0.0).
55
+ */
56
+ export declare function signWebhookBody(body: string, secret: string, timestamp?: string): string;
57
+ export interface VerifyWebhookOptions {
58
+ /** The `x-keys-timestamp` header. Present: the signature covers `<timestamp>.<body>` and the timestamp must be fresh. Absent: the old body-only form, deprecated. */
59
+ readonly timestamp?: string;
60
+ /** Largest accepted distance between the timestamp and `now`, either way. Default 5 minutes. */
61
+ readonly toleranceMs?: number;
62
+ /** Unix milliseconds. Defaults to `Date.now`. */
63
+ readonly now?: () => number;
64
+ }
45
65
  /**
46
66
  * Constant-time check that `signature` (as received in `X-Keys-Signature`)
47
67
  * matches `body` under `secret`. What a webhook receiver calls before
48
- * trusting a delivered event.
68
+ * trusting a delivered event. Pass the `x-keys-timestamp` header as
69
+ * `options.timestamp`: a timestamp further than the tolerance from now, or
70
+ * not a plain integer, is refused. Without `options.timestamp` only the old
71
+ * form verifies, and it cannot refuse a replay.
49
72
  *
50
73
  * `body` must be the exact raw request body bytes (as text) the signature
51
74
  * was computed over -- parsing it to JSON and re-serializing it before
52
75
  * verifying, or trimming/normalizing whitespace, changes the bytes and the
53
76
  * signature will not match even for a genuine delivery.
54
77
  */
55
- export declare function verifyWebhookSignature(body: string, signature: string, secret: string): boolean;
78
+ export declare function verifyWebhookSignature(body: string, signature: string, secret: string, options?: VerifyWebhookOptions): boolean;
package/dist/webhooks.js CHANGED
@@ -1,50 +1,94 @@
1
1
  import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * #48: outbound HTTP delivery for the events `./issued`'s `AuditCallback`
4
+ * and `./held`'s `audit: (event: KeyUsedEvent) => …` already carry
5
+ * in-process. `createWebhookDispatcher` is a drop-in for either option --
6
+ * both already call their callback with one JSON-serializable event object
7
+ * carrying a `name` -- so a stamped service (agora, manage, operator) can
8
+ * subscribe to key lifecycle events over HTTP instead of polling another
9
+ * service's database.
10
+ *
11
+ * `node:crypto`, not WebCrypto: this runs host-side only, the same posture
12
+ * as `secret.ts`.
13
+ */
14
+ /** Each delivery is aborted after this long. Nothing waits on it: the caller has already returned. */
15
+ export const WEBHOOK_TIMEOUT_MS = 5000;
16
+ /** How far a delivery's `x-keys-timestamp` may be from the receiver's clock. */
17
+ export const DEFAULT_WEBHOOK_TOLERANCE_MS = 5 * 60 * 1000;
2
18
  /**
3
19
  * An `AuditCallback` (`./issued`) or `KeyUsedEvent` callback (`./held`) that
4
- * POSTs the event as JSON to `options.url`.
20
+ * POSTs the event as JSON to `options.url`. It returns at once and delivers
21
+ * outside the caller's path, with a 5-second timeout (`AbortSignal.timeout`,
22
+ * whose timer does not keep the process alive). A delivery that fails in any
23
+ * way goes to `onDeliveryError`; it never becomes an unhandled rejection.
5
24
  */
6
25
  export function createWebhookDispatcher(options) {
7
26
  const doFetch = options.fetch ?? fetch;
8
- return async (event) => {
9
- try {
10
- const body = JSON.stringify(event);
11
- const headers = { 'content-type': 'application/json' };
12
- if (options.secret !== undefined) {
13
- headers['x-keys-signature'] = signWebhookBody(body, options.secret);
14
- }
15
- const response = await doFetch(options.url, { method: 'POST', headers, body });
16
- if (!response.ok) {
17
- throw new Error(`webhook delivery to ${options.url} got HTTP ${response.status}`);
18
- }
27
+ async function deliver(event) {
28
+ const body = JSON.stringify(event);
29
+ const headers = { 'content-type': 'application/json' };
30
+ if (options.secret !== undefined) {
31
+ const timestamp = String(Date.now());
32
+ headers['x-keys-timestamp'] = timestamp;
33
+ headers['x-keys-signature'] = signWebhookBody(body, options.secret, timestamp);
19
34
  }
20
- catch (err) {
21
- options.onDeliveryError?.(err, event);
35
+ const response = await doFetch(options.url, {
36
+ method: 'POST',
37
+ headers,
38
+ body,
39
+ signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),
40
+ });
41
+ if (!response.ok) {
42
+ throw new Error(`webhook delivery got HTTP ${response.status}`);
22
43
  }
44
+ }
45
+ return (event) => {
46
+ deliver(event).catch((err) => {
47
+ try {
48
+ options.onDeliveryError?.(err, event);
49
+ }
50
+ catch (hookError) {
51
+ const name = hookError instanceof Error ? hookError.name : typeof hookError;
52
+ console.error(`keys: onDeliveryError threw for ${event.name}: ${name}`);
53
+ }
54
+ });
55
+ return Promise.resolve();
23
56
  };
24
57
  }
25
- /** Hex HMAC-SHA256 of `body` under `secret`. What `X-Keys-Signature` carries. */
26
- export function signWebhookBody(body, secret) {
27
- return createHmac('sha256', secret).update(body, 'utf8').digest('hex');
58
+ /**
59
+ * Hex HMAC-SHA256 of `body` under `secret`. With `timestamp`, the HMAC covers
60
+ * `<timestamp>.<body>`, which is what `x-keys-signature` carries. Without it,
61
+ * the old form over the body alone (deprecated, removed at 1.0.0).
62
+ */
63
+ export function signWebhookBody(body, secret, timestamp) {
64
+ const signed = timestamp === undefined ? body : `${timestamp}.${body}`;
65
+ return createHmac('sha256', secret).update(signed, 'utf8').digest('hex');
28
66
  }
29
67
  /**
30
68
  * Constant-time check that `signature` (as received in `X-Keys-Signature`)
31
69
  * matches `body` under `secret`. What a webhook receiver calls before
32
- * trusting a delivered event.
70
+ * trusting a delivered event. Pass the `x-keys-timestamp` header as
71
+ * `options.timestamp`: a timestamp further than the tolerance from now, or
72
+ * not a plain integer, is refused. Without `options.timestamp` only the old
73
+ * form verifies, and it cannot refuse a replay.
33
74
  *
34
75
  * `body` must be the exact raw request body bytes (as text) the signature
35
76
  * was computed over -- parsing it to JSON and re-serializing it before
36
77
  * verifying, or trimming/normalizing whitespace, changes the bytes and the
37
78
  * signature will not match even for a genuine delivery.
38
79
  */
39
- export function verifyWebhookSignature(body, signature, secret) {
40
- const expected = Buffer.from(signWebhookBody(body, secret), 'hex');
41
- let presented;
42
- try {
43
- presented = Buffer.from(signature, 'hex');
44
- }
45
- catch {
46
- return false;
80
+ export function verifyWebhookSignature(body, signature, secret, options = {}) {
81
+ const { timestamp } = options;
82
+ if (timestamp !== undefined) {
83
+ if (!/^\d{1,16}$/.test(timestamp))
84
+ return false;
85
+ const now = (options.now ?? Date.now)();
86
+ const tolerance = options.toleranceMs ?? DEFAULT_WEBHOOK_TOLERANCE_MS;
87
+ if (!(Math.abs(now - Number(timestamp)) <= tolerance))
88
+ return false;
47
89
  }
90
+ const expected = Buffer.from(signWebhookBody(body, secret, timestamp), 'hex');
91
+ const presented = Buffer.from(signature, 'hex');
48
92
  if (presented.length !== expected.length)
49
93
  return false;
50
94
  return timingSafeEqual(presented, expected);
@@ -145,6 +145,11 @@ export interface SignableRow<TGrant> {
145
145
  export interface SignedRow<TGrant> extends SignableRow<TGrant> {
146
146
  readonly signature: Uint8Array;
147
147
  }
148
+ /**
149
+ * Every `WorkerErrorCode`, in the order of the union. The union is closed: adding a
150
+ * member is a major change after 1.0.0, and `src/exports.test.ts` pins this list.
151
+ */
152
+ export declare const WORKER_ERROR_CODES: readonly ["credential_invalid", "credential_expired", "credential_revoked", "grant_missing", "rate_limited", "bad_request", "aad_mismatch", "unknown_generation", "bad_minter_signature", "minter_expired", "minter_revoked", "minter_exceeded", "lineage_mismatch", "bad_old_signature", "unlogged_row", "not_in_lineage", "unreachable"];
148
153
  export type WorkerErrorCode =
149
154
  /** The bearer credential does not parse, or its signature does not verify. */
150
155
  'credential_invalid'
@@ -166,8 +171,10 @@ export type WorkerErrorCode =
166
171
  | 'bad_minter_signature'
167
172
  /** `signRow`: the minter row's `expiresAt` has passed. */
168
173
  | 'minter_expired'
169
- /** `signRow`: the minter row's id is in `revoked_credentials`. */
174
+ /** `signRow`: the minter row's id, or any ancestor's, is in `revoked_credentials`. */
170
175
  | 'minter_revoked'
176
+ /** `signRow`: the candidate expires after its minter, or carries a grant its minter does not hold. */
177
+ | 'minter_exceeded'
171
178
  /**
172
179
  * `signRow`: the candidate's `issuedById` is not the minter row's `id`, a
173
180
  * root mint names a parent, or the minter row was not minted by this host.
@@ -253,11 +260,14 @@ export interface SignRowRequest<TGrant> extends RequestMeta {
253
260
  /**
254
261
  * The minting credential's own signed row, or `null` for a root mint
255
262
  * (then `candidate.issuedById` must be `null`). The Worker checks: the
256
- * row's signature verifies, its `expiresAt` has not passed, its id is not
257
- * revoked, its id was minted by this host (mint log), and
258
- * `candidate.issuedById === minter.row.id`. It does not judge
259
- * `candidate.grants`: attenuation runs on the host, through
260
- * `@wtfalch/authz`, before `issue()`.
263
+ * row's signature verifies, its `expiresAt` has not passed, neither its id
264
+ * nor any ancestor's is evicted, its id was minted by this host (mint log),
265
+ * and `candidate.issuedById === minter.row.id`. It then refuses
266
+ * `minter_exceeded` for a candidate that expires after the minter, or that
267
+ * holds a grant the minter lacks. A grant is contained when it is deep-equal
268
+ * to one of the minter's under canonical JSON, or when both are objects with
269
+ * the same string `tenantId`. Attenuation beyond that stays on the host,
270
+ * through `@wtfalch/authz`.
261
271
  */
262
272
  readonly minter: {
263
273
  readonly row: SignableRow<TGrant>;
@@ -358,3 +368,30 @@ export declare const WORKER_HTTP: {
358
368
  readonly grant: "evict";
359
369
  };
360
370
  };
371
+ /**
372
+ * Worker routes outside `WorkerClient`: the operator and minter surface that
373
+ * `docs/contracts.md` C3 names. No host calls these through `./issued` or
374
+ * `./held`. The first three need a host in `DERIVE_MINTERS` as well as the grant.
375
+ */
376
+ export declare const WORKER_OPERATOR_HTTP: {
377
+ readonly derivedCredential: {
378
+ readonly method: "POST";
379
+ readonly path: "/v1/derived/credential";
380
+ readonly grant: "wrap";
381
+ };
382
+ readonly derivedEpoch: {
383
+ readonly method: "POST";
384
+ readonly path: "/v1/derived/epoch";
385
+ readonly grant: "wrap";
386
+ };
387
+ readonly derivedRevoke: {
388
+ readonly method: "POST";
389
+ readonly path: "/v1/derived/revoke";
390
+ readonly grant: "wrap";
391
+ };
392
+ readonly credentialRevoke: {
393
+ readonly method: "POST";
394
+ readonly path: "/v1/credentials/revoke";
395
+ readonly grant: "evict";
396
+ };
397
+ };
@@ -66,6 +66,32 @@ export const SIGNED_PREFIX = 'wtfalch-keys:';
66
66
  */
67
67
  export const AAD_PREFIX = 'wtfalch-keys:aad:v1\n';
68
68
  // ---------------------------------------------------------------------------
69
+ // Errors
70
+ // ---------------------------------------------------------------------------
71
+ /**
72
+ * Every `WorkerErrorCode`, in the order of the union. The union is closed: adding a
73
+ * member is a major change after 1.0.0, and `src/exports.test.ts` pins this list.
74
+ */
75
+ export const WORKER_ERROR_CODES = [
76
+ 'credential_invalid',
77
+ 'credential_expired',
78
+ 'credential_revoked',
79
+ 'grant_missing',
80
+ 'rate_limited',
81
+ 'bad_request',
82
+ 'aad_mismatch',
83
+ 'unknown_generation',
84
+ 'bad_minter_signature',
85
+ 'minter_expired',
86
+ 'minter_revoked',
87
+ 'minter_exceeded',
88
+ 'lineage_mismatch',
89
+ 'bad_old_signature',
90
+ 'unlogged_row',
91
+ 'not_in_lineage',
92
+ 'unreachable',
93
+ ];
94
+ // ---------------------------------------------------------------------------
69
95
  // HTTP mapping
70
96
  // ---------------------------------------------------------------------------
71
97
  /**
@@ -92,3 +118,14 @@ export const WORKER_HTTP = {
92
118
  resign: { method: 'POST', path: '/v1/issued/resign', grant: 'resign' },
93
119
  recordEviction: { method: 'POST', path: '/v1/issued/evictions', grant: 'evict' },
94
120
  };
121
+ /**
122
+ * Worker routes outside `WorkerClient`: the operator and minter surface that
123
+ * `docs/contracts.md` C3 names. No host calls these through `./issued` or
124
+ * `./held`. The first three need a host in `DERIVE_MINTERS` as well as the grant.
125
+ */
126
+ export const WORKER_OPERATOR_HTTP = {
127
+ derivedCredential: { method: 'POST', path: '/v1/derived/credential', grant: 'wrap' },
128
+ derivedEpoch: { method: 'POST', path: '/v1/derived/epoch', grant: 'wrap' },
129
+ derivedRevoke: { method: 'POST', path: '/v1/derived/revoke', grant: 'wrap' },
130
+ credentialRevoke: { method: 'POST', path: '/v1/credentials/revoke', grant: 'evict' },
131
+ };
package/dist/worker.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type WorkerClient } from './worker-contract.js';
2
2
  export type * from './worker-contract.js';
3
- export { WORKER_HTTP } from './worker-contract.js';
3
+ export { WORKER_ERROR_CODES, WORKER_HTTP } from './worker-contract.js';
4
4
  export interface CreateWorkerClientOptions {
5
5
  /** Must be an https origin; checked once here, not on every call. */
6
6
  readonly url: string;
package/dist/worker.js CHANGED
@@ -1,34 +1,13 @@
1
- import { ID_PATTERN, WORKER_HTTP, } from './worker-contract.js';
2
- export { WORKER_HTTP } from './worker-contract.js';
1
+ import { ID_PATTERN, WORKER_ERROR_CODES, WORKER_HTTP, } from './worker-contract.js';
2
+ export { WORKER_ERROR_CODES, WORKER_HTTP } from './worker-contract.js';
3
3
  const DEFAULT_TIMEOUT_MS = 10_000;
4
4
  /**
5
- * The 15 codes the Worker itself ever sends (`errors.ts`'s `statusFor`
6
- * covers exactly these). `unreachable` is deliberately excluded: the
7
- * contract says the Worker never sends it, so a response body claiming
8
- * that code is exactly as untrustworthy as one claiming a code that does
9
- * not exist at all -- both are `unreachable` from here.
10
- *
11
- * A value-level mirror, not a type import: `WorkerErrorCode` is a union of
12
- * string literals, which has no runtime representation to check a decoded
13
- * body's `error.code` against.
5
+ * The codes the Worker itself ever sends: `WORKER_ERROR_CODES` without
6
+ * `unreachable`. The contract says the Worker never sends `unreachable`, so a
7
+ * response body claiming it is exactly as untrustworthy as one claiming a code
8
+ * from a newer Worker that this client does not know: both become `unreachable`.
14
9
  */
15
- const KNOWN_ERROR_CODES = new Set([
16
- 'credential_invalid',
17
- 'credential_expired',
18
- 'credential_revoked',
19
- 'grant_missing',
20
- 'rate_limited',
21
- 'bad_request',
22
- 'aad_mismatch',
23
- 'unknown_generation',
24
- 'bad_minter_signature',
25
- 'minter_expired',
26
- 'minter_revoked',
27
- 'lineage_mismatch',
28
- 'bad_old_signature',
29
- 'unlogged_row',
30
- 'not_in_lineage',
31
- ]);
10
+ const KNOWN_ERROR_CODES = new Set(WORKER_ERROR_CODES.filter((c) => c !== 'unreachable'));
32
11
  /** The only statuses `errors.ts` ever sends for a refusal. Anything else -- 3xx, 5xx, 0 (an opaque redirect) -- is `unreachable`, whatever its body says. */
33
12
  const KNOWN_FAILURE_STATUSES = new Set([400, 401, 403, 429]);
34
13
  function assertHttpsOrigin(url) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/keys",
3
- "version": "0.7.0",
3
+ "version": "0.12.1",
4
4
  "description": "The estate's own bearer keys, issued to callers and held on their behalf: two entries, issued and held, nothing stored in common.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -53,6 +53,10 @@
53
53
  "./testing": {
54
54
  "types": "./dist/testing/index.d.ts",
55
55
  "default": "./dist/testing/index.js"
56
+ },
57
+ "./service": {
58
+ "types": "./dist/service/index.d.ts",
59
+ "default": "./dist/service/index.js"
56
60
  }
57
61
  },
58
62
  "sideEffects": false,
@@ -69,15 +73,29 @@
69
73
  "test": "vitest run"
70
74
  },
71
75
  "peerDependencies": {
72
- "drizzle-orm": ">=0.45.2 <1.0.0"
76
+ "drizzle-orm": ">=0.45.2 <1.0.0",
77
+ "@wtfalch/authz": "0.18.0"
78
+ },
79
+ "dependencies": {
80
+ "@wtfalch/utils": "0.1.0",
81
+ "jose": "6.2.12",
82
+ "@wtfalch/contracts": "0.2.0"
73
83
  },
74
84
  "devDependencies": {
75
85
  "@electric-sql/pglite": "^0.5.8",
76
86
  "@types/node": "^22",
77
87
  "@wtfalch/db": "0.5.2",
88
+ "@wtfalch/keys-client": "workspace:^",
78
89
  "drizzle-orm": "0.45.2",
79
90
  "postgres": "^3.4.5",
80
91
  "typescript": "^5.9.0",
81
- "vitest": "^4.1.6"
92
+ "vitest": "^4.1.6",
93
+ "@wtfalch/authz": "0.18.0",
94
+ "zod": "^4.1.13"
95
+ },
96
+ "peerDependenciesMeta": {
97
+ "@wtfalch/authz": {
98
+ "optional": true
99
+ }
82
100
  }
83
101
  }