@wtfalch/keys 0.6.0 → 0.7.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 CHANGED
@@ -141,6 +141,23 @@ transport/protocol failures. It makes one attempt per call: a request ID is audi
141
141
  correlation, not an idempotency guarantee. Host authentication and grant policy
142
142
  remain outside the transport. Existing injected clients remain supported.
143
143
 
144
+ ## Adopting `./held-edge`
145
+
146
+ `@wtfalch/keys/held-edge` is `./held`'s envelope encryption for a Cloudflare Worker: WebCrypto only, no `node:` import, no Postgres. A random AES-256-GCM data key per version encrypts the value, the same custody Worker wraps that data key, and the same AAD (tenant, entry, version; shared with `./held`, never copied) binds both layers. Storage stays with the caller: keep the returned `SealedHeld` as JSON.
147
+
148
+ ```ts
149
+ import { openHeld, sealHeld } from '@wtfalch/keys/held-edge';
150
+
151
+ const sealed = await sealHeld({ worker, credential, tenantId, entryId, version: 1, plaintext });
152
+ const plaintext = await openHeld({ worker, credential, tenantId, entryId, sealed });
153
+ ```
154
+
155
+ - `worker` is any `WorkerClient` (only `wrap` and `unwrap` are used); `credential` is the serialized bearer credential the custody Worker checks. Pass `timeoutMs` (default 10 s) to bound each Worker call.
156
+ - `version` is chosen and incremented by the caller. Opening with the wrong tenant, entry or version fails (`aad_mismatch` from the Worker, `unseal_failed` locally).
157
+ - `tenantId` and `entryId` must match `/^[A-Za-z0-9_-]{1,128}$/`; a bad id throws `HeldEdgeError('bad_request')` before any network call.
158
+ - Errors are `HeldEdgeError` with a `code`: the Worker's own code, `bad_request`, `unseal_failed` or `timeout`. A message never carries the plaintext, a key, or the Worker's free-text message.
159
+ - `createWorkerClient` (`./worker`) uses `Buffer`: on a Worker, enable `nodejs_compat` for it, or inject your own `WorkerClient`. `./held-edge` itself needs neither.
160
+
144
161
  ## Adopting `./host`
145
162
 
146
163
  `@wtfalch/keys/host` (added in **0.6.0**) is the host-side plumbing every
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `./held-edge`: the `./held` envelope model for a Cloudflare Worker.
3
+ *
4
+ * Same model as `../held/index.ts`: a random AES-256-GCM data key per version
5
+ * encrypts the value, the custody Worker wraps that data key, and the AAD
6
+ * (`../held/aad.ts`, shared, not copied) binds tenant, entry and version to
7
+ * both layers. Unlike `./held` there is no Postgres and no `node:crypto`:
8
+ * WebCrypto only. Storage of the `SealedHeld` stays with the caller.
9
+ *
10
+ * This file imports nothing from `node:` and only `../held/aad.ts` and types
11
+ * and constants from `../worker-contract.ts`. The `WorkerClient` is injected
12
+ * (`createWorkerClient` from `../worker` needs `nodejs_compat`).
13
+ */
14
+ import { type SerializedCredential, type WorkerClient, type WorkerErrorCode } from '../worker-contract.js';
15
+ export { encodeAad } from '../held/aad.js';
16
+ export interface SealedHeld {
17
+ v: 1;
18
+ kekId: string;
19
+ /** base64url, the custody Worker's wrapped data key. */
20
+ wrappedKey: string;
21
+ /** base64url, 12 bytes. */
22
+ iv: string;
23
+ /** base64url, ciphertext with the GCM tag appended. */
24
+ ct: string;
25
+ version: number;
26
+ }
27
+ /** Local refusals plus the Worker's own code, verbatim. Never carries a value or a key. */
28
+ export type HeldEdgeErrorCode = WorkerErrorCode | 'bad_request' | 'unseal_failed' | 'timeout';
29
+ export declare class HeldEdgeError extends Error {
30
+ readonly code: HeldEdgeErrorCode;
31
+ constructor(code: HeldEdgeErrorCode, message?: string);
32
+ }
33
+ interface CallOptions {
34
+ readonly worker: Pick<WorkerClient, 'wrap' | 'unwrap'>;
35
+ /** Sent to the custody Worker as the bearer credential. */
36
+ readonly credential: SerializedCredential;
37
+ readonly tenantId: string;
38
+ readonly entryId: string;
39
+ /** Per-call limit on the Worker call. Default 10s. */
40
+ readonly timeoutMs?: number;
41
+ }
42
+ export interface SealHeldOptions extends CallOptions {
43
+ readonly version: number;
44
+ readonly plaintext: string;
45
+ }
46
+ export interface OpenHeldOptions extends CallOptions {
47
+ readonly sealed: SealedHeld;
48
+ }
49
+ export declare function sealHeld(o: SealHeldOptions): Promise<SealedHeld>;
50
+ export declare function openHeld(o: OpenHeldOptions): Promise<string>;
@@ -0,0 +1,175 @@
1
+ import { encodeAad } from '../held/aad.js';
2
+ /**
3
+ * `./held-edge`: the `./held` envelope model for a Cloudflare Worker.
4
+ *
5
+ * Same model as `../held/index.ts`: a random AES-256-GCM data key per version
6
+ * encrypts the value, the custody Worker wraps that data key, and the AAD
7
+ * (`../held/aad.ts`, shared, not copied) binds tenant, entry and version to
8
+ * both layers. Unlike `./held` there is no Postgres and no `node:crypto`:
9
+ * WebCrypto only. Storage of the `SealedHeld` stays with the caller.
10
+ *
11
+ * This file imports nothing from `node:` and only `../held/aad.ts` and types
12
+ * and constants from `../worker-contract.ts`. The `WorkerClient` is injected
13
+ * (`createWorkerClient` from `../worker` needs `nodejs_compat`).
14
+ */
15
+ import { ID_PATTERN, } from '../worker-contract.js';
16
+ export { encodeAad } from '../held/aad.js';
17
+ const DEFAULT_TIMEOUT_MS = 10_000;
18
+ const IV_BYTES = 12;
19
+ const DATA_KEY_BYTES = 32;
20
+ const WRAPPED_KEY_BYTES = 60;
21
+ const TAG_BYTES = 16;
22
+ export class HeldEdgeError extends Error {
23
+ code;
24
+ constructor(code, message) {
25
+ super(message ?? code);
26
+ this.name = 'HeldEdgeError';
27
+ this.code = code;
28
+ }
29
+ }
30
+ function toBase64Url(bytes) {
31
+ let bin = '';
32
+ for (const b of bytes)
33
+ bin += String.fromCharCode(b);
34
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
35
+ }
36
+ /** `null` unless `text` is exactly one round trip of `toBase64Url`. */
37
+ function fromBase64Url(text) {
38
+ if (typeof text !== 'string' || !/^[A-Za-z0-9_-]+$/.test(text))
39
+ return null;
40
+ try {
41
+ const std = text.replace(/-/g, '+').replace(/_/g, '/');
42
+ const bin = atob(std + '='.repeat((4 - (std.length % 4)) % 4));
43
+ const out = new Uint8Array(bin.length);
44
+ for (let i = 0; i < bin.length; i++)
45
+ out[i] = bin.charCodeAt(i);
46
+ return toBase64Url(out) === text ? out : null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ function checkIds(tenantId, entryId) {
53
+ if (typeof tenantId !== 'string' || !ID_PATTERN.test(tenantId)) {
54
+ throw new HeldEdgeError('bad_request', 'tenantId does not match the id pattern');
55
+ }
56
+ if (typeof entryId !== 'string' || !ID_PATTERN.test(entryId)) {
57
+ throw new HeldEdgeError('bad_request', 'entryId does not match the id pattern');
58
+ }
59
+ }
60
+ function checkVersion(version) {
61
+ if (!Number.isSafeInteger(version) || version < 1) {
62
+ throw new HeldEdgeError('bad_request', 'version must be a positive integer');
63
+ }
64
+ }
65
+ function checkTimeout(timeoutMs) {
66
+ const ms = timeoutMs ?? DEFAULT_TIMEOUT_MS;
67
+ if (!Number.isSafeInteger(ms) || ms < 1 || ms > 2_147_483_647) {
68
+ throw new RangeError('timeoutMs must be an integer from 1 to 2147483647');
69
+ }
70
+ return ms;
71
+ }
72
+ /** Races the Worker call against a timer; the timer is always cleared. */
73
+ async function withTimeout(call, ms) {
74
+ let timer;
75
+ const timeout = new Promise((_, reject) => {
76
+ timer = setTimeout(() => reject(new HeldEdgeError('timeout', 'custody Worker timed out')), ms);
77
+ });
78
+ try {
79
+ return await Promise.race([call, timeout]);
80
+ }
81
+ finally {
82
+ clearTimeout(timer);
83
+ }
84
+ }
85
+ /** Surfaces the Worker's code only: its free-text message is never copied. */
86
+ function fromWorker(code) {
87
+ return new HeldEdgeError(code, `custody Worker refused: ${code}`);
88
+ }
89
+ async function importDataKey(dataKey, usage) {
90
+ if (dataKey.length !== DATA_KEY_BYTES)
91
+ throw new HeldEdgeError('unseal_failed');
92
+ return crypto.subtle.importKey('raw', dataKey, { name: 'AES-GCM' }, false, [usage]);
93
+ }
94
+ export async function sealHeld(o) {
95
+ checkIds(o.tenantId, o.entryId);
96
+ checkVersion(o.version);
97
+ if (typeof o.plaintext !== 'string') {
98
+ throw new HeldEdgeError('bad_request', 'plaintext must be a string');
99
+ }
100
+ const ms = checkTimeout(o.timeoutMs);
101
+ const binding = { tenantId: o.tenantId, entryId: o.entryId, version: o.version };
102
+ const aad = encodeAad(binding);
103
+ const result = await withTimeout(o.worker.wrap({ requestId: crypto.randomUUID(), credential: o.credential, binding }), ms);
104
+ if (!result.ok)
105
+ throw fromWorker(result.error.code);
106
+ const dataKey = result.dataKey;
107
+ try {
108
+ // Refuse here what openHeld refuses, or the value would be sealed but never open again.
109
+ if (!ID_PATTERN.test(result.kekId) || result.wrappedKey.length !== WRAPPED_KEY_BYTES) {
110
+ throw new HeldEdgeError('bad_request', 'custody worker returned a malformed wrap');
111
+ }
112
+ const key = await importDataKey(dataKey, 'encrypt');
113
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
114
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, new TextEncoder().encode(o.plaintext)));
115
+ return {
116
+ v: 1,
117
+ kekId: result.kekId,
118
+ wrappedKey: toBase64Url(result.wrappedKey),
119
+ iv: toBase64Url(iv),
120
+ ct: toBase64Url(ct),
121
+ version: o.version,
122
+ };
123
+ }
124
+ finally {
125
+ dataKey.fill(0);
126
+ }
127
+ }
128
+ export async function openHeld(o) {
129
+ checkIds(o.tenantId, o.entryId);
130
+ const s = o.sealed;
131
+ if (typeof s !== 'object' || s === null || s.v !== 1) {
132
+ throw new HeldEdgeError('bad_request', 'sealed is not a v1 SealedHeld');
133
+ }
134
+ checkVersion(s.version);
135
+ if (typeof s.kekId !== 'string' || !ID_PATTERN.test(s.kekId)) {
136
+ throw new HeldEdgeError('bad_request', 'sealed.kekId does not match the id pattern');
137
+ }
138
+ const wrappedKey = fromBase64Url(s.wrappedKey);
139
+ const iv = fromBase64Url(s.iv);
140
+ const ct = fromBase64Url(s.ct);
141
+ if (wrappedKey?.length !== WRAPPED_KEY_BYTES ||
142
+ iv?.length !== IV_BYTES ||
143
+ !ct ||
144
+ ct.length < TAG_BYTES) {
145
+ throw new HeldEdgeError('bad_request', 'sealed has a malformed field');
146
+ }
147
+ const ms = checkTimeout(o.timeoutMs);
148
+ const binding = { tenantId: o.tenantId, entryId: o.entryId, version: s.version };
149
+ const aad = encodeAad(binding);
150
+ const result = await withTimeout(o.worker.unwrap({
151
+ requestId: crypto.randomUUID(),
152
+ credential: o.credential,
153
+ kekId: s.kekId,
154
+ wrappedKey,
155
+ binding,
156
+ }), ms);
157
+ if (!result.ok)
158
+ throw fromWorker(result.error.code);
159
+ const dataKey = result.dataKey;
160
+ try {
161
+ const key = await importDataKey(dataKey, 'decrypt');
162
+ let plain;
163
+ try {
164
+ plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: aad }, key, ct);
165
+ }
166
+ catch {
167
+ // The WebCrypto error is dropped: it says nothing a caller may use.
168
+ throw new HeldEdgeError('unseal_failed', 'that version could not be opened with the given data key');
169
+ }
170
+ return new TextDecoder().decode(plain);
171
+ }
172
+ finally {
173
+ dataKey.fill(0);
174
+ }
175
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/keys",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",
@@ -24,6 +24,10 @@
24
24
  "types": "./dist/held/index.d.ts",
25
25
  "default": "./dist/held/index.js"
26
26
  },
27
+ "./held-edge": {
28
+ "types": "./dist/held-edge/index.d.ts",
29
+ "default": "./dist/held-edge/index.js"
30
+ },
27
31
  "./webhooks": {
28
32
  "types": "./dist/webhooks.d.ts",
29
33
  "default": "./dist/webhooks.js"