@query-farm/vgi 0.50.1 → 0.52.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.
Files changed (84) hide show
  1. package/README.md +45 -3
  2. package/dist/client-entry.js +833 -775
  3. package/dist/client-entry.js.map +10 -10
  4. package/dist/functions/aggregate.d.ts +25 -21
  5. package/dist/functions/execution-cache.d.ts +11 -0
  6. package/dist/functions/storage-blobs.d.ts +173 -0
  7. package/dist/functions/storage-cf-do.d.ts +50 -0
  8. package/dist/functions/storage-seal.d.ts +27 -0
  9. package/dist/functions/storage.d.ts +71 -1
  10. package/dist/functions/table-buffering.d.ts +30 -0
  11. package/dist/functions/table.d.ts +6 -1
  12. package/dist/generated/vgi-client.d.ts +7 -1
  13. package/dist/generated/vgi-protocol-schemas.d.ts +10 -9
  14. package/dist/generated/vgi-protocol-types.d.ts +244 -2
  15. package/dist/generated/vgi-service.d.ts +1 -1
  16. package/dist/hosted.d.ts +117 -0
  17. package/dist/http/blob-vendor.d.ts +33 -0
  18. package/dist/http/fetch.d.ts +60 -2
  19. package/dist/http/hosted-auth.d.ts +45 -0
  20. package/dist/index.core.d.ts +11 -3
  21. package/dist/index.js +8661 -6677
  22. package/dist/index.js.map +52 -34
  23. package/dist/protocol/arguments-ref.d.ts +107 -0
  24. package/dist/protocol/dispatch.d.ts +12 -2
  25. package/dist/protocol/handlers/aggregate.d.ts +1 -1
  26. package/dist/protocol/handlers/catalog/shared.d.ts +10 -0
  27. package/dist/protocol/handlers/function.d.ts +23 -0
  28. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  29. package/dist/protocol/serialize.d.ts +1 -1
  30. package/dist/protocol/serializers/bind.d.ts +27 -1
  31. package/dist/protocol/serializers/cardinality.d.ts +1 -1
  32. package/dist/protocol/serializers/splits.d.ts +7 -0
  33. package/dist/protocol/state-serializer.d.ts +8 -7
  34. package/dist/protocol/stream-init.d.ts +17 -0
  35. package/dist/protocol/types.d.ts +32 -0
  36. package/dist/secrets/lookups.d.ts +31 -0
  37. package/dist/serve-entry.d.ts +41 -6
  38. package/dist/serve-entry.js +8531 -6302
  39. package/dist/serve-entry.js.map +52 -35
  40. package/dist/worker-cf-entry.d.ts +5 -0
  41. package/dist/worker-cf-entry.js +7191 -4990
  42. package/dist/worker-cf-entry.js.map +59 -41
  43. package/package.json +5 -4
  44. package/src/functions/aggregate.ts +101 -152
  45. package/src/functions/copy-from.ts +2 -2
  46. package/src/functions/execution-cache.ts +59 -0
  47. package/src/functions/storage-blobs.ts +654 -0
  48. package/src/functions/storage-cf-do.ts +176 -22
  49. package/src/functions/storage-seal.ts +208 -0
  50. package/src/functions/storage.ts +174 -8
  51. package/src/functions/table-buffering.ts +104 -18
  52. package/src/functions/table-in-out.ts +3 -1
  53. package/src/functions/table.ts +12 -8
  54. package/src/generated/vgi-client.ts +9 -2
  55. package/src/generated/vgi-protocol-schemas.ts +115 -107
  56. package/src/generated/vgi-protocol-types.ts +640 -3
  57. package/src/generated/vgi-service.ts +2 -2
  58. package/src/hosted.ts +254 -0
  59. package/src/http/blob-vendor.ts +80 -0
  60. package/src/http/fetch.ts +179 -8
  61. package/src/http/hosted-auth.ts +326 -0
  62. package/src/index.core.ts +66 -1
  63. package/src/protocol/arguments-ref.ts +260 -0
  64. package/src/protocol/dispatch.ts +15 -4
  65. package/src/protocol/handlers/aggregate.ts +123 -82
  66. package/src/protocol/handlers/catalog/shared.ts +20 -0
  67. package/src/protocol/handlers/function.ts +135 -59
  68. package/src/protocol/handlers/table-buffering.ts +49 -32
  69. package/src/protocol/serialize.ts +3 -0
  70. package/src/protocol/serializers/bind.ts +96 -69
  71. package/src/protocol/serializers/cardinality.ts +4 -7
  72. package/src/protocol/serializers/init.ts +5 -11
  73. package/src/protocol/serializers/splits.ts +31 -4
  74. package/src/protocol/state-serializer.ts +27 -39
  75. package/src/protocol/stream-init.ts +87 -0
  76. package/src/protocol/types.ts +33 -0
  77. package/src/secrets/lookups.ts +53 -0
  78. package/src/serve-entry.ts +138 -11
  79. package/src/worker-cf-entry.ts +33 -0
  80. package/src/worker.ts +25 -0
  81. package/dist/protocol/carried-init-request.d.ts +0 -28
  82. package/dist/util/zstd-sync.d.ts +0 -7
  83. package/src/protocol/carried-init-request.ts +0 -139
  84. package/src/util/zstd-sync.ts +0 -50
@@ -4,8 +4,9 @@
4
4
  // Port of vgi-python's vgi/function_storage_cf_do.py. Talks the Cloudflare
5
5
  // Worker + Durable Object's unified state_* / queue_* protocol
6
6
  // (vgi-cloudflare-durable-object-storage/src/index.ts). Every request carries
7
- // the per-attach `shard_key` (set via forShard); destructive ops carry a fresh
8
- // 32-hex `attempt_id`. The DO is single-threaded SQLite, so ops are atomic.
7
+ // the per-attach `shard_key` (BoundStorage calls forShard with the shard the
8
+ // framework derived from the request's attach; "" goes to `loc-anon`);
9
+ // destructive ops carry a fresh 32-hex `attempt_id`, reused across retries. The DO is single-threaded SQLite, so ops are atomic.
9
10
  //
10
11
  // Usage:
11
12
  // Set `VGI_WORKER_SHARED_STORAGE=cloudflare-do` plus `VGI_CF_DO_URL`.
@@ -18,14 +19,55 @@ import { UnknownInvocationError, workerStateKey } from "./storage.js";
18
19
  * Cloudflare service-binding Fetcher (`env.<BINDING>`). */
19
20
  export type FetchLike = (
20
21
  input: string,
21
- init?: { method?: string; headers?: Record<string, string>; body?: string },
22
+ init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal },
22
23
  ) => Promise<Response>;
23
24
 
25
+ /**
26
+ * The storage service's per-value cap (`MAX_VALUE_BYTES` in its src/index.ts).
27
+ * `resolveStorageFromEnv` / `setStorage` wrap this backend in
28
+ * `ExternalizingStorage` with this cap, which envelopes every value and moves
29
+ * large ones to the blob vendor.
30
+ */
31
+ export const MAX_VALUE_BYTES = 1024 * 1024;
32
+
33
+ /** The DO server's shard_key rule (vgi-cloudflare-durable-object-storage). */
34
+ export const SHARD_KEY_RE = /^[A-Za-z0-9._-]{1,128}$/;
35
+
36
+ /**
37
+ * Shard for a call not bound to an ATTACH (no attach uuid to shard on): one
38
+ * shared DO per tenant, as vgi-python's client does. Every attach-bound call
39
+ * carries its own `att-<uuid hex>` shard instead.
40
+ */
41
+ export const ANONYMOUS_SHARD_KEY = "loc-anon";
42
+
43
+ /** Retry policy for the DO client. */
44
+ export interface CfDoRetryOptions {
45
+ /** Per-attempt fetch timeout, ms (default 30000; 0 disables). */
46
+ timeoutMs?: number;
47
+ /** Total attempts including the first (default 4). */
48
+ maxAttempts?: number;
49
+ /** First backoff, ms (default 100); doubles per attempt, full jitter. */
50
+ baseDelayMs?: number;
51
+ /** Backoff cap, ms (default 2000). */
52
+ maxDelayMs?: number;
53
+ }
54
+
55
+ /** A transient failure worth retrying: transport error, timeout, 5xx or 429. */
56
+ class RetryableError extends Error {
57
+ constructor(message: string, readonly retryAfterMs: number | null = null) {
58
+ super(message);
59
+ }
60
+ }
61
+
24
62
  // Namespaces under the unified state_* table for the legacy worker/queue
25
63
  // families the DO no longer has dedicated endpoints for.
26
64
  const NS_WORKER = new TextEncoder().encode("worker");
27
65
 
28
66
  export class FunctionStorageCfDo implements FunctionStorage {
67
+ /** Marks this backend for `setStorage`, which always envelopes it. */
68
+ readonly storageKind = "cloudflare-do";
69
+ /** The service's per-value cap ({@link MAX_VALUE_BYTES}). */
70
+ readonly maxValueBytes = MAX_VALUE_BYTES;
29
71
  private readonly _baseUrl: string;
30
72
  private readonly _token: string | null;
31
73
  /** Per-attach routing key (att-<hex uuid>); "" until pinned via forShard. */
@@ -35,18 +77,39 @@ export class FunctionStorageCfDo implements FunctionStorage {
35
77
  * the same account/zone — a same-zone public-URL fetch is rejected (CF
36
78
  * error 1042), but a service binding routes worker-to-worker directly. */
37
79
  private readonly _fetch: FetchLike;
80
+ private readonly _retry: Required<CfDoRetryOptions>;
81
+ /** Test hook: how the client waits between attempts. */
82
+ private readonly _sleep: (ms: number) => Promise<void>;
38
83
 
39
84
  constructor(opts: {
40
85
  url: string;
41
86
  token?: string | null;
42
87
  shardKey?: string;
43
88
  fetch?: FetchLike;
89
+ retry?: CfDoRetryOptions;
90
+ sleep?: (ms: number) => Promise<void>;
44
91
  }) {
45
92
  // Strip trailing slash so endpoint paths can be appended unconditionally.
46
93
  this._baseUrl = opts.url.replace(/\/+$/, "");
47
94
  this._token = opts.token ?? null;
48
- this._shardKey = opts.shardKey ?? "";
95
+ const shard = opts.shardKey ?? "";
96
+ if (shard !== "" && !SHARD_KEY_RE.test(shard)) {
97
+ throw new Error(`invalid CF DO shard_key ${JSON.stringify(shard)} (1-128 chars, [A-Za-z0-9._-])`);
98
+ }
99
+ this._shardKey = shard;
49
100
  this._fetch = opts.fetch ?? ((input, init) => fetch(input as any, init));
101
+ this._retry = {
102
+ timeoutMs: opts.retry?.timeoutMs ?? 30_000,
103
+ maxAttempts: Math.max(1, opts.retry?.maxAttempts ?? 4),
104
+ baseDelayMs: opts.retry?.baseDelayMs ?? 100,
105
+ maxDelayMs: opts.retry?.maxDelayMs ?? 2_000,
106
+ };
107
+ this._sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
108
+ }
109
+
110
+ /** The shard this instance routes to ("" = the anonymous shard). */
111
+ get shardKey(): string {
112
+ return this._shardKey;
50
113
  }
51
114
 
52
115
  /** Build an instance from environment variables. */
@@ -69,11 +132,14 @@ export class FunctionStorageCfDo implements FunctionStorage {
69
132
  * per logical ATTACH. Shares the URL/token; only the shard key differs.
70
133
  */
71
134
  forShard(shardKey: string): FunctionStorageCfDo {
135
+ if (shardKey === this._shardKey) return this;
72
136
  return new FunctionStorageCfDo({
73
137
  url: this._baseUrl,
74
138
  token: this._token,
75
139
  shardKey,
76
140
  fetch: this._fetch,
141
+ retry: this._retry,
142
+ sleep: this._sleep,
77
143
  });
78
144
  }
79
145
 
@@ -123,17 +189,42 @@ export class FunctionStorageCfDo implements FunctionStorage {
123
189
  // --- Namespaced key/value state ---
124
190
 
125
191
  async stateGet(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array): Promise<Uint8Array | null> {
192
+ return (await this.stateGetMany(scopeId, ns, [key]))[0] ?? null;
193
+ }
194
+
195
+ async statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void> {
196
+ await this._statePutMany(scopeId, ns, [[key, value]]);
197
+ }
198
+
199
+ async stateGetMany(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<Array<Uint8Array | null>> {
200
+ if (keys.length === 0) return [];
126
201
  const data = await this._post<{ rows: Array<{ value: string } | null> }>("state_get_many", {
127
202
  scope_id: bytesToB64(scopeId),
128
203
  ns: bytesToB64(ns),
129
- keys: [bytesToB64(key)],
204
+ keys: keys.map(bytesToB64),
205
+ });
206
+ const rows = data.rows ?? [];
207
+ return keys.map((_, i) => {
208
+ const row = rows[i];
209
+ return row ? b64ToBytes(row.value) : null;
130
210
  });
131
- const row = (data.rows ?? [])[0];
132
- return row ? b64ToBytes(row.value) : null;
133
211
  }
134
212
 
135
- async statePut(scopeId: Uint8Array, ns: Uint8Array, key: Uint8Array, value: Uint8Array): Promise<void> {
136
- await this._statePutMany(scopeId, ns, [[key, value]]);
213
+ async statePutMany(scopeId: Uint8Array, ns: Uint8Array, items: Array<[Uint8Array, Uint8Array]>): Promise<void> {
214
+ if (items.length === 0) return;
215
+ await this._statePutMany(scopeId, ns, items);
216
+ }
217
+
218
+ async stateDelete(scopeId: Uint8Array, ns: Uint8Array, keys: Uint8Array[]): Promise<number> {
219
+ if (keys.length === 0) return 0;
220
+ // Naturally idempotent; the attempt_id is for audit only.
221
+ const data = await this._post<{ deleted: number }>("state_delete", {
222
+ scope_id: bytesToB64(scopeId),
223
+ ns: bytesToB64(ns),
224
+ keys: keys.map(bytesToB64),
225
+ attempt_id: newAttemptId(),
226
+ });
227
+ return Number(data.deleted ?? 0);
137
228
  }
138
229
 
139
230
  // --- Append-only log ---
@@ -216,6 +307,14 @@ export class FunctionStorageCfDo implements FunctionStorage {
216
307
 
217
308
  // --- HTTP plumbing ---
218
309
 
310
+ /**
311
+ * POST one call. The body (and so its `attempt_id`, for destructive ops) is
312
+ * built once and resent unchanged on every retry, so the DO's replay
313
+ * detection makes a retried put/drain/pop a no-op. Retries transport errors,
314
+ * timeouts, 5xx and 429 with exponential backoff and full jitter, bounded by
315
+ * `maxAttempts`. 4xx other than 429 is the caller's error and is not retried.
316
+ * The bearer token never appears in an error message.
317
+ */
219
318
  private async _post<T = Record<string, unknown>>(
220
319
  endpoint: string,
221
320
  body: Record<string, unknown>,
@@ -224,24 +323,73 @@ export class FunctionStorageCfDo implements FunctionStorage {
224
323
  const headers: Record<string, string> = { "Content-Type": "application/json" };
225
324
  if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
226
325
  // The Worker routes on shard_key (idFromName) and rejects requests without
227
- // one — always splice it in.
228
- const payload = JSON.stringify({ ...body, shard_key: this._shardKey });
326
+ // one. An attach-bound call carries att-<uuid hex>; one bound to no ATTACH
327
+ // goes to the shared anonymous shard, as in vgi-python.
328
+ const payload = JSON.stringify({ ...body, shard_key: this._shardKey || ANONYMOUS_SHARD_KEY });
329
+
330
+ const { maxAttempts, baseDelayMs, maxDelayMs } = this._retry;
331
+ let lastErr: Error | undefined;
332
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
333
+ if (attempt > 0) {
334
+ const cap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
335
+ const jittered = Math.random() * cap;
336
+ const hinted = lastErr instanceof RetryableError && lastErr.retryAfterMs != null
337
+ ? Math.min(maxDelayMs, lastErr.retryAfterMs)
338
+ : 0;
339
+ await this._sleep(Math.max(jittered, hinted));
340
+ }
341
+ try {
342
+ return await this._once<T>(url, endpoint, headers, payload);
343
+ } catch (e) {
344
+ if (!(e instanceof RetryableError)) throw e;
345
+ lastErr = e;
346
+ }
347
+ }
348
+ throw new Error(
349
+ `CF DO storage ${endpoint} failed after ${maxAttempts} attempts: ${lastErr?.message ?? "unknown error"}`,
350
+ );
351
+ }
229
352
 
230
- let lastErr: unknown;
231
- // One retry on transport-level failures, matching the python client.
232
- for (let attempt = 0; attempt < 2; attempt++) {
353
+ private async _once<T>(
354
+ url: string,
355
+ endpoint: string,
356
+ headers: Record<string, string>,
357
+ payload: string,
358
+ ): Promise<T> {
359
+ const { timeoutMs } = this._retry;
360
+ const controller = timeoutMs > 0 ? new AbortController() : null;
361
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
362
+ try {
233
363
  let resp: Response;
234
364
  try {
235
- resp = await this._fetch(url, { method: "POST", headers, body: payload });
236
- } catch (err) {
237
- lastErr = err;
238
- continue;
365
+ resp = await this._fetch(url, {
366
+ method: "POST",
367
+ headers,
368
+ body: payload,
369
+ ...(controller ? { signal: controller.signal } : {}),
370
+ });
371
+ } catch (err: any) {
372
+ if (controller?.signal.aborted) {
373
+ throw new RetryableError(`timed out after ${timeoutMs} ms on ${endpoint}`);
374
+ }
375
+ throw new RetryableError(`transport error on ${endpoint}: ${err?.message ?? String(err)}`);
376
+ }
377
+
378
+ if (resp.status === 429 || resp.status >= 500) {
379
+ const text = await resp.text().catch(() => "");
380
+ throw new RetryableError(
381
+ `CF DO storage error ${resp.status} on ${endpoint}: ${text.slice(0, 200) || "<empty body>"}`,
382
+ parseRetryAfter(resp.headers?.get?.("Retry-After") ?? null),
383
+ );
239
384
  }
240
385
 
241
386
  let data: any;
242
387
  try {
243
388
  data = await resp.json();
244
- } catch {
389
+ } catch (err: any) {
390
+ if (controller?.signal.aborted) {
391
+ throw new RetryableError(`timed out after ${timeoutMs} ms reading ${endpoint}`);
392
+ }
245
393
  if (!resp.ok) {
246
394
  throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: <non-json body>`);
247
395
  }
@@ -261,13 +409,19 @@ export class FunctionStorageCfDo implements FunctionStorage {
261
409
  throw new Error(`CF DO storage error ${resp.status} on ${endpoint}: ${JSON.stringify(data)}`);
262
410
  }
263
411
  return data as T;
412
+ } finally {
413
+ if (timer) clearTimeout(timer);
264
414
  }
265
- throw lastErr instanceof Error
266
- ? lastErr
267
- : new Error(`CF DO storage transport error on ${endpoint}: ${String(lastErr)}`);
268
415
  }
269
416
  }
270
417
 
418
+ /** `Retry-After` in ms (delta-seconds form only), or null. */
419
+ function parseRetryAfter(v: string | null): number | null {
420
+ if (!v) return null;
421
+ const n = Number(v.trim());
422
+ return Number.isFinite(n) && n >= 0 ? n * 1000 : null;
423
+ }
424
+
271
425
  /** Fresh 32-char lowercase-hex idempotency token (the DO's attempt_id shape). */
272
426
  function newAttemptId(): string {
273
427
  const b = new Uint8Array(16);
@@ -0,0 +1,208 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Authenticated encryption of framework payloads written to FunctionStorage.
3
+ //
4
+ // The framework persists some of its own context to shared storage so any
5
+ // worker process can serve any RPC of an execution: the buffered-table init
6
+ // (the InitRequest, including `bind_call.secrets`) and the aggregate bind
7
+ // context (constant arguments, input schema). Storage may be a SQLite file or
8
+ // a Cloudflare Durable Object reached over the network, so none of that may
9
+ // sit there in plaintext, and nothing read back may be trusted unauthenticated.
10
+ //
11
+ // Sealed framework payload v1 (the same format in every VGI SDK; vgi-python's
12
+ // vgi/_storage_seal.py is the reference):
13
+ //
14
+ // K = HKDF-SHA256(ikm, salt = "", info = "vgi.storage.payload.v1", L = 32)
15
+ // ikm is the worker's signing key exactly as this SDK resolved it (the
16
+ // 32 bytes decoded from the VGI_SIGNING_KEY hex, or the explicit
17
+ // `signingKey` option). Without a signing key (stdio / AF_UNIX /
18
+ // launcher) it is the host-local key file every VGI worker process of
19
+ // this user on this host shares (./attach-secret-keyfile.ts), since one
20
+ // query's RPCs are spread over several processes sharing one SQLite file.
21
+ // AEAD = AES-256-GCM (WebCrypto, so it runs on Cloudflare Workers too),
22
+ // random 12-byte nonce, 16-byte tag.
23
+ // AAD = "vgi.storage.payload.v1" || u32be(len)||shard_key
24
+ // || u32be(len)||scope_id || u32be(len)||namespace || u32be(len)||key
25
+ // so a payload copied to another execution, slot or attach shard fails.
26
+ // wire = 0x01 || nonce(12) || ciphertext || tag(16)
27
+ //
28
+ // A payload that fails to open (unknown version, too short, tampered, wrong
29
+ // key, moved, or an unsealed value from an older release) throws
30
+ // StoragePayloadError. There is no plaintext fallback: executions are
31
+ // short-lived and their ids are never reused, so nothing needs migrating.
32
+ //
33
+ // Data user code writes to storage (buffered process() state, aggregate group
34
+ // states, table-in-out state, finalize output, work-queue items) is the
35
+ // function's own data and is not sealed.
36
+
37
+ import { hostLocalAttachSecretKey } from "../attach-secret-keyfile.js";
38
+
39
+ export const STORAGE_PAYLOAD_INFO = "vgi.storage.payload.v1";
40
+ export const STORAGE_PAYLOAD_VERSION = 0x01;
41
+ const KEY_LEN = 32;
42
+ const NONCE_LEN = 12;
43
+ const TAG_LEN = 16;
44
+ const UTF8 = new TextEncoder();
45
+ const INFO_BYTES = UTF8.encode(STORAGE_PAYLOAD_INFO);
46
+
47
+ /** A framework payload read from storage could not be authenticated. */
48
+ export class StoragePayloadError extends Error {
49
+ constructor(message: string) {
50
+ super(message);
51
+ this.name = "StoragePayloadError";
52
+ }
53
+ }
54
+
55
+ /** The storage slot a payload is bound to. */
56
+ export interface StorageSlot {
57
+ shardKey: string;
58
+ scopeId: Uint8Array;
59
+ ns: Uint8Array;
60
+ key: Uint8Array;
61
+ }
62
+
63
+ function lp(b: Uint8Array): Uint8Array {
64
+ const out = new Uint8Array(4 + b.length);
65
+ new DataView(out.buffer).setUint32(0, b.length, false);
66
+ out.set(b, 4);
67
+ return out;
68
+ }
69
+
70
+ function concat(parts: Uint8Array[]): Uint8Array {
71
+ let n = 0;
72
+ for (const p of parts) n += p.length;
73
+ const out = new Uint8Array(n);
74
+ let off = 0;
75
+ for (const p of parts) {
76
+ out.set(p, off);
77
+ off += p.length;
78
+ }
79
+ return out;
80
+ }
81
+
82
+ function hex(b: Uint8Array): string {
83
+ let s = "";
84
+ for (let i = 0; i < b.length; i++) s += b[i]!.toString(16).padStart(2, "0");
85
+ return s;
86
+ }
87
+
88
+ /** The associated data binding a payload to its storage slot. */
89
+ export function storagePayloadAad(slot: StorageSlot): Uint8Array {
90
+ return concat([INFO_BYTES, lp(UTF8.encode(slot.shardKey)), lp(slot.scopeId), lp(slot.ns), lp(slot.key)]);
91
+ }
92
+
93
+ /** `HKDF-SHA256(ikm, salt = "", info = "vgi.storage.payload.v1", 32)` as raw bytes. */
94
+ export async function deriveStoragePayloadKey(ikm: Uint8Array): Promise<Uint8Array> {
95
+ const base = await crypto.subtle.importKey("raw", ikm as BufferSource, "HKDF", false, ["deriveBits"]);
96
+ const bits = await crypto.subtle.deriveBits(
97
+ { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: INFO_BYTES },
98
+ base,
99
+ KEY_LEN * 8,
100
+ );
101
+ return new Uint8Array(bits);
102
+ }
103
+
104
+ // Derived AES keys, by ikm. Tiny (one or two entries in practice: the signing
105
+ // key, or the host-local key), bounded so a test that churns keys cannot grow it.
106
+ const KEY_CACHE_MAX = 16;
107
+ const keyCache = new Map<string, Promise<CryptoKey>>();
108
+
109
+ function aesKey(ikm: Uint8Array): Promise<CryptoKey> {
110
+ const id = hex(ikm);
111
+ let k = keyCache.get(id);
112
+ if (!k) {
113
+ k = (async () => {
114
+ const raw = await deriveStoragePayloadKey(ikm);
115
+ return crypto.subtle.importKey("raw", raw as BufferSource, "AES-GCM", false, ["encrypt", "decrypt"]);
116
+ })();
117
+ if (keyCache.size >= KEY_CACHE_MAX) keyCache.delete(keyCache.keys().next().value!);
118
+ keyCache.set(id, k);
119
+ // A failed derivation must not stay cached.
120
+ k.catch(() => keyCache.delete(id));
121
+ }
122
+ return k;
123
+ }
124
+
125
+ /** Seal under an explicit `ikm`. `nonce` exists for test vectors only. */
126
+ export async function sealWith(
127
+ payload: Uint8Array,
128
+ ikm: Uint8Array,
129
+ slot: StorageSlot,
130
+ nonce?: Uint8Array,
131
+ ): Promise<Uint8Array> {
132
+ if (nonce !== undefined && nonce.length !== NONCE_LEN) throw new Error(`nonce must be ${NONCE_LEN} bytes`);
133
+ const iv = nonce ?? crypto.getRandomValues(new Uint8Array(NONCE_LEN));
134
+ const ct = new Uint8Array(
135
+ await crypto.subtle.encrypt(
136
+ { name: "AES-GCM", iv: iv as BufferSource, additionalData: storagePayloadAad(slot) as BufferSource, tagLength: TAG_LEN * 8 },
137
+ await aesKey(ikm),
138
+ payload as BufferSource,
139
+ ),
140
+ );
141
+ const out = new Uint8Array(1 + NONCE_LEN + ct.length);
142
+ out[0] = STORAGE_PAYLOAD_VERSION;
143
+ out.set(iv, 1);
144
+ out.set(ct, 1 + NONCE_LEN);
145
+ return out;
146
+ }
147
+
148
+ /** Open under an explicit `ikm`; {@link StoragePayloadError} on any failure. */
149
+ export async function openWith(blob: Uint8Array, ikm: Uint8Array, slot: StorageSlot): Promise<Uint8Array> {
150
+ const what = `framework storage payload ${JSON.stringify(new TextDecoder().decode(slot.ns))} for execution ${hex(slot.scopeId)}`;
151
+ if (blob.length < 1 + NONCE_LEN + TAG_LEN) {
152
+ throw new StoragePayloadError(`${what} is too short to be a sealed payload`);
153
+ }
154
+ if (blob[0] !== STORAGE_PAYLOAD_VERSION) {
155
+ throw new StoragePayloadError(`${what} has unknown seal version 0x${blob[0]!.toString(16).padStart(2, "0")}`);
156
+ }
157
+ const iv = blob.subarray(1, 1 + NONCE_LEN);
158
+ const body = blob.subarray(1 + NONCE_LEN);
159
+ try {
160
+ return new Uint8Array(
161
+ await crypto.subtle.decrypt(
162
+ { name: "AES-GCM", iv: iv as BufferSource, additionalData: storagePayloadAad(slot) as BufferSource, tagLength: TAG_LEN * 8 },
163
+ await aesKey(ikm),
164
+ body as BufferSource,
165
+ ),
166
+ );
167
+ } catch {
168
+ throw new StoragePayloadError(`${what} failed authentication (tampered, moved, or sealed under another key)`);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * The input key material: the worker's signing key, else the host-local key.
174
+ * Overridable for tests (`setStorageSealHostLocalKey`).
175
+ */
176
+ let hostLocalOverride: (() => Promise<Uint8Array>) | null = null;
177
+
178
+ /** Test hook: replace the host-local key source (null restores the key file). */
179
+ export function setStorageSealHostLocalKey(fn: (() => Promise<Uint8Array>) | null): void {
180
+ hostLocalOverride = fn;
181
+ }
182
+
183
+ async function ikmFor(signingKey: Uint8Array | undefined): Promise<Uint8Array> {
184
+ if (signingKey && signingKey.length > 0) return signingKey;
185
+ try {
186
+ return await (hostLocalOverride ?? hostLocalAttachSecretKey)();
187
+ } catch (e: any) {
188
+ throw new StoragePayloadError(`no key to seal framework storage payloads: ${e?.message ?? e}`);
189
+ }
190
+ }
191
+
192
+ /** Seal a framework payload bound to its storage slot. */
193
+ export async function sealPayload(
194
+ payload: Uint8Array,
195
+ signingKey: Uint8Array | undefined,
196
+ slot: StorageSlot,
197
+ ): Promise<Uint8Array> {
198
+ return sealWith(payload, await ikmFor(signingKey), slot);
199
+ }
200
+
201
+ /** Open an envelope from {@link sealPayload} for the same slot. */
202
+ export async function openPayload(
203
+ blob: Uint8Array,
204
+ signingKey: Uint8Array | undefined,
205
+ slot: StorageSlot,
206
+ ): Promise<Uint8Array> {
207
+ return openWith(blob, await ikmFor(signingKey), slot);
208
+ }