@wtfalch/keys 0.2.1 → 0.4.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.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * #48: outbound HTTP delivery for the events `./issued`'s `AuditCallback`
3
+ * and `./held`'s `audit: (event: KeyUsedEvent) => …` already carry
4
+ * in-process. `createWebhookDispatcher` is a drop-in for either option --
5
+ * both already call their callback with one JSON-serializable event object
6
+ * carrying a `name` -- so a stamped service (agora, manage, operator) can
7
+ * subscribe to key lifecycle events over HTTP instead of polling another
8
+ * service's database.
9
+ *
10
+ * `node:crypto`, not WebCrypto: this runs host-side only, the same posture
11
+ * as `secret.ts`.
12
+ */
13
+ export interface WebhookDeliveryOptions {
14
+ readonly url: string;
15
+ /**
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.
21
+ */
22
+ readonly secret?: string;
23
+ /** Defaults to the global `fetch`. Tests pass a stub. */
24
+ readonly fetch?: typeof fetch;
25
+ /**
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.
33
+ */
34
+ readonly onDeliveryError?: (error: unknown, event: unknown) => void;
35
+ }
36
+ /**
37
+ * An `AuditCallback` (`./issued`) or `KeyUsedEvent` callback (`./held`) that
38
+ * POSTs the event as JSON to `options.url`.
39
+ */
40
+ export declare function createWebhookDispatcher<TEvent extends {
41
+ readonly name: string;
42
+ }>(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;
45
+ /**
46
+ * Constant-time check that `signature` (as received in `X-Keys-Signature`)
47
+ * matches `body` under `secret`. What a webhook receiver calls before
48
+ * trusting a delivered event.
49
+ *
50
+ * `body` must be the exact raw request body bytes (as text) the signature
51
+ * was computed over -- parsing it to JSON and re-serializing it before
52
+ * verifying, or trimming/normalizing whitespace, changes the bytes and the
53
+ * signature will not match even for a genuine delivery.
54
+ */
55
+ export declare function verifyWebhookSignature(body: string, signature: string, secret: string): boolean;
@@ -0,0 +1,51 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * An `AuditCallback` (`./issued`) or `KeyUsedEvent` callback (`./held`) that
4
+ * POSTs the event as JSON to `options.url`.
5
+ */
6
+ export function createWebhookDispatcher(options) {
7
+ 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
+ }
19
+ }
20
+ catch (err) {
21
+ options.onDeliveryError?.(err, event);
22
+ }
23
+ };
24
+ }
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');
28
+ }
29
+ /**
30
+ * Constant-time check that `signature` (as received in `X-Keys-Signature`)
31
+ * matches `body` under `secret`. What a webhook receiver calls before
32
+ * trusting a delivered event.
33
+ *
34
+ * `body` must be the exact raw request body bytes (as text) the signature
35
+ * was computed over -- parsing it to JSON and re-serializing it before
36
+ * verifying, or trimming/normalizing whitespace, changes the bytes and the
37
+ * signature will not match even for a genuine delivery.
38
+ */
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;
47
+ }
48
+ if (presented.length !== expected.length)
49
+ return false;
50
+ return timingSafeEqual(presented, expected);
51
+ }
@@ -0,0 +1,13 @@
1
+ import { type WorkerClient } from './worker-contract.js';
2
+ export type * from './worker-contract.js';
3
+ export { WORKER_HTTP } from './worker-contract.js';
4
+ export interface CreateWorkerClientOptions {
5
+ /** Must be an https origin; checked once here, not on every call. */
6
+ readonly url: string;
7
+ /** Defaults to the global `fetch`. A test passes a fake. */
8
+ readonly fetch?: typeof fetch;
9
+ /** Per-call timeout in milliseconds. Default 10s. */
10
+ readonly timeoutMs?: number;
11
+ }
12
+ /** HTTP transport only: no auth policy or automatic retries. */
13
+ export declare function createWorkerClient<TGrant = unknown>(options: CreateWorkerClientOptions): WorkerClient<TGrant>;
package/dist/worker.js ADDED
@@ -0,0 +1,263 @@
1
+ import { ID_PATTERN, WORKER_HTTP, } from './worker-contract.js';
2
+ export { WORKER_HTTP } from './worker-contract.js';
3
+ const DEFAULT_TIMEOUT_MS = 10_000;
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.
14
+ */
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
+ ]);
32
+ /** 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
+ const KNOWN_FAILURE_STATUSES = new Set([400, 401, 403, 429]);
34
+ function assertHttpsOrigin(url) {
35
+ let parsed;
36
+ try {
37
+ parsed = new URL(url);
38
+ }
39
+ catch {
40
+ throw new Error('createWorkerClient: url must be an absolute URL');
41
+ }
42
+ if (parsed.protocol !== 'https:' ||
43
+ parsed.username ||
44
+ parsed.password ||
45
+ parsed.pathname !== '/' ||
46
+ parsed.search ||
47
+ parsed.hash) {
48
+ throw new Error('createWorkerClient: url must be an https origin');
49
+ }
50
+ }
51
+ // ---------------------------------------------------------------------------
52
+ // base64url -- the wire encoding for every Uint8Array field (worker-contract.ts)
53
+ // ---------------------------------------------------------------------------
54
+ function encodeBase64Url(bytes) {
55
+ return Buffer.from(bytes).toString('base64url');
56
+ }
57
+ /**
58
+ * `null` on anything that is not exactly one round trip of `encodeBase64Url`
59
+ * -- wrong type, empty, stray characters, or a value `Buffer` would decode
60
+ * leniently but which was never produced by this encoding. A decode failure
61
+ * here is always a shape-invalid body, never a thrown exception: the caller
62
+ * turns it into `unreachable`.
63
+ */
64
+ function decodeBase64Url(value) {
65
+ if (typeof value !== 'string' || value.length === 0 || !/^[A-Za-z0-9_-]+$/.test(value)) {
66
+ return null;
67
+ }
68
+ const bytes = new Uint8Array(Buffer.from(value, 'base64url'));
69
+ return encodeBase64Url(bytes) === value ? bytes : null;
70
+ }
71
+ /**
72
+ * One request/response round trip. Returns `null` for anything that is not
73
+ * a completed HTTP exchange -- a thrown `fetch` (DNS, TLS, connection
74
+ * refused), an aborted one (the timeout below firing), or any other
75
+ * network failure. Every caller below turns a `null` into `unreachable`.
76
+ *
77
+ * `redirect: 'manual'`: a Worker never redirects, so a 3xx is either a
78
+ * misconfigured `url` or a network intermediary -- never followed, and
79
+ * (per `KNOWN_FAILURE_STATUSES` below) never treated as a real response
80
+ * either. `AbortSignal.timeout` covers both "took too long" and "hung
81
+ * forever" the same way a thrown error does.
82
+ */
83
+ async function post(fetchImpl, base, path, credential, body, timeoutMs) {
84
+ let response;
85
+ try {
86
+ response = await fetchImpl(new URL(path, base), {
87
+ method: 'POST',
88
+ redirect: 'manual',
89
+ signal: AbortSignal.timeout(timeoutMs),
90
+ headers: {
91
+ 'content-type': 'application/json',
92
+ authorization: `Bearer ${credential}`,
93
+ },
94
+ body: JSON.stringify(body),
95
+ });
96
+ }
97
+ catch {
98
+ // Never logs `err`: it can carry the request (credential included).
99
+ return null;
100
+ }
101
+ let json;
102
+ try {
103
+ json = await response.json();
104
+ }
105
+ catch {
106
+ json = undefined;
107
+ }
108
+ return { status: response.status, headers: response.headers, json };
109
+ }
110
+ function unreachable() {
111
+ return { ok: false, error: { code: 'unreachable' } };
112
+ }
113
+ /**
114
+ * Decodes a non-200 body into `WorkerFailure`, or `unreachable` when the
115
+ * status is not one `errors.ts` ever sends, the body is not `{ error: {
116
+ * code } }`, or `code` is not one of `KNOWN_ERROR_CODES`. A malformed or
117
+ * unrecognized refusal is never partially trusted.
118
+ */
119
+ function decodeFailure(outcome) {
120
+ if (!KNOWN_FAILURE_STATUSES.has(outcome.status))
121
+ return unreachable();
122
+ if (typeof outcome.json !== 'object' || outcome.json === null)
123
+ return unreachable();
124
+ const error = outcome.json.error;
125
+ if (typeof error !== 'object' || error === null)
126
+ return unreachable();
127
+ const e = error;
128
+ if (typeof e.code !== 'string' || !KNOWN_ERROR_CODES.has(e.code))
129
+ return unreachable();
130
+ const expectedStatus = e.code === 'bad_request'
131
+ ? 400
132
+ : e.code.startsWith('credential_')
133
+ ? 401
134
+ : e.code === 'rate_limited'
135
+ ? 429
136
+ : 403;
137
+ if (outcome.status !== expectedStatus)
138
+ return unreachable();
139
+ // Safe: membership in `KNOWN_ERROR_CODES` is exactly the `WorkerErrorCode`
140
+ // union minus `'unreachable'`, which the Worker never sends (checked above).
141
+ const code = e.code;
142
+ // Per WORKER_HTTP's own mapping comment: "429 ... with Retry-After in
143
+ // seconds" -- the header, not the body's own (undocumented-as-public)
144
+ // `retryAfterMs` mirror, is this client's source of truth.
145
+ let retryAfterMs;
146
+ if (outcome.status === 429) {
147
+ const header = outcome.headers.get('retry-after');
148
+ const seconds = header !== null && /^\d+$/.test(header) ? Number(header) : Number.NaN;
149
+ if (Number.isSafeInteger(seconds * 1000))
150
+ retryAfterMs = seconds * 1000;
151
+ }
152
+ const message = typeof e.message === 'string' ? e.message : undefined;
153
+ return {
154
+ ok: false,
155
+ error: {
156
+ code,
157
+ ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
158
+ ...(message !== undefined ? { message } : {}),
159
+ },
160
+ };
161
+ }
162
+ /**
163
+ * Everything the six methods below share: POST, map network failure to
164
+ * `unreachable`, hand a non-200 to `decodeFailure`, and otherwise hand the
165
+ * parsed body to `decodeSuccess` -- which itself returns `null` for
166
+ * anything shape-invalid, turned into `unreachable` here rather than in
167
+ * each of the six call sites.
168
+ */
169
+ async function call(fetchImpl, base, path, credential, body, timeoutMs, decodeSuccess) {
170
+ const outcome = await post(fetchImpl, base, path, credential, body, timeoutMs);
171
+ if (!outcome)
172
+ return unreachable();
173
+ if (outcome.status !== 200)
174
+ return decodeFailure(outcome);
175
+ return decodeSuccess(outcome.json) ?? unreachable();
176
+ }
177
+ function asRecord(json) {
178
+ return typeof json === 'object' && json !== null ? json : null;
179
+ }
180
+ /** HTTP transport only: no auth policy or automatic retries. */
181
+ export function createWorkerClient(options) {
182
+ assertHttpsOrigin(options.url);
183
+ const fetchImpl = options.fetch ?? fetch;
184
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
185
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) {
186
+ throw new RangeError('timeoutMs must be an integer from 1 to 2147483647');
187
+ }
188
+ const base = options.url;
189
+ const post6 = (path, credential, body, decodeSuccess) => call(fetchImpl, base, path, credential, body, timeoutMs, decodeSuccess);
190
+ return {
191
+ wrap: (req) => post6(WORKER_HTTP.wrap.path, req.credential, { requestId: req.requestId, binding: req.binding }, (json) => {
192
+ const v = asRecord(json);
193
+ if (!v)
194
+ return null;
195
+ const dataKey = decodeBase64Url(v.dataKey);
196
+ const wrappedKey = decodeBase64Url(v.wrappedKey);
197
+ if (!dataKey ||
198
+ !wrappedKey ||
199
+ dataKey.length !== 32 ||
200
+ wrappedKey.length !== 60 ||
201
+ typeof v.kekId !== 'string' ||
202
+ !ID_PATTERN.test(v.kekId))
203
+ return null;
204
+ return { ok: true, dataKey, wrappedKey, kekId: v.kekId };
205
+ }),
206
+ unwrap: (req) => post6(WORKER_HTTP.unwrap.path, req.credential, {
207
+ requestId: req.requestId,
208
+ kekId: req.kekId,
209
+ wrappedKey: encodeBase64Url(req.wrappedKey),
210
+ binding: req.binding,
211
+ }, (json) => {
212
+ const dataKey = decodeBase64Url(asRecord(json)?.dataKey);
213
+ return dataKey?.length === 32 ? { ok: true, dataKey } : null;
214
+ }),
215
+ rewrap: (req) => post6(WORKER_HTTP.rewrap.path, req.credential, {
216
+ requestId: req.requestId,
217
+ kekIdOld: req.kekIdOld,
218
+ kekIdNew: req.kekIdNew,
219
+ wrappedKey: encodeBase64Url(req.wrappedKey),
220
+ binding: req.binding,
221
+ }, (json) => {
222
+ const wrappedKey = decodeBase64Url(asRecord(json)?.wrappedKey);
223
+ return wrappedKey?.length === 60 ? { ok: true, wrappedKey } : null;
224
+ }),
225
+ signRow: (req) => post6(WORKER_HTTP.signRow.path, req.credential, {
226
+ requestId: req.requestId,
227
+ candidate: req.candidate,
228
+ minter: req.minter
229
+ ? { row: req.minter.row, signature: encodeBase64Url(req.minter.signature) }
230
+ : null,
231
+ }, (json) => {
232
+ const v = asRecord(json);
233
+ const signature = decodeBase64Url(v?.signature);
234
+ if (signature?.length !== 64 ||
235
+ typeof v?.generationId !== 'string' ||
236
+ !ID_PATTERN.test(v.generationId)) {
237
+ return null;
238
+ }
239
+ return { ok: true, signature, generationId: v.generationId };
240
+ }),
241
+ resign: (req) => post6(WORKER_HTTP.resign.path, req.credential, {
242
+ requestId: req.requestId,
243
+ row: req.row,
244
+ oldSignature: encodeBase64Url(req.oldSignature),
245
+ oldGenerationId: req.oldGenerationId,
246
+ }, (json) => {
247
+ const v = asRecord(json);
248
+ const signature = decodeBase64Url(v?.signature);
249
+ if (signature?.length !== 64 ||
250
+ typeof v?.generationId !== 'string' ||
251
+ !ID_PATTERN.test(v.generationId)) {
252
+ return null;
253
+ }
254
+ return { ok: true, signature, generationId: v.generationId };
255
+ }),
256
+ recordEviction: (req) => post6(WORKER_HTTP.recordEviction.path, req.credential, { requestId: req.requestId, credentialId: req.credentialId, revokedAt: req.revokedAt }, (json) => {
257
+ const receiptId = asRecord(json)?.receiptId;
258
+ return typeof receiptId === 'string' && ID_PATTERN.test(receiptId)
259
+ ? { ok: true, receiptId }
260
+ : null;
261
+ }),
262
+ };
263
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/keys",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "The estate's own bearer keys, issued to callers and held on their behalf: two entries, issued and held, nothing stored in common.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -11,7 +11,9 @@
11
11
  "type": "module",
12
12
  "files": ["dist"],
13
13
  "bin": {
14
- "keys-migrations": "dist/bin/migrations.js"
14
+ "keys-migrations": "dist/bin/migrations.js",
15
+ "keys-build": "dist/bin/build.js",
16
+ "keys-build-scan": "dist/bin/build-scan.js"
15
17
  },
16
18
  "exports": {
17
19
  "./issued": {
@@ -22,8 +24,20 @@
22
24
  "types": "./dist/held/index.d.ts",
23
25
  "default": "./dist/held/index.js"
24
26
  },
27
+ "./webhooks": {
28
+ "types": "./dist/webhooks.d.ts",
29
+ "default": "./dist/webhooks.js"
30
+ },
25
31
  "./migrations/*.sql": "./dist/migrations/*.sql",
26
- "./package.json": "./package.json"
32
+ "./package.json": "./package.json",
33
+ "./worker": {
34
+ "types": "./dist/worker.d.ts",
35
+ "default": "./dist/worker.js"
36
+ },
37
+ "./build": {
38
+ "types": "./dist/build/index.d.ts",
39
+ "default": "./dist/build/index.js"
40
+ }
27
41
  },
28
42
  "sideEffects": false,
29
43
  "publishConfig": {