@query-farm/vgi 0.48.3 → 0.48.5

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 (50) hide show
  1. package/README.md +51 -0
  2. package/dist/attach-secret-keyfile.d.ts +11 -0
  3. package/dist/attach-secret-options.d.ts +96 -0
  4. package/dist/catalog/attach-option.d.ts +6 -0
  5. package/dist/catalog/descriptors.d.ts +30 -0
  6. package/dist/catalog/interface.d.ts +43 -0
  7. package/dist/catalog/read-only.d.ts +16 -2
  8. package/dist/client-entry.js +1 -1
  9. package/dist/client-entry.js.map +4 -4
  10. package/dist/index.core.d.ts +4 -0
  11. package/dist/index.js +5854 -5234
  12. package/dist/index.js.map +28 -25
  13. package/dist/protocol/dispatch.d.ts +11 -0
  14. package/dist/protocol/handlers/catalog/admin.d.ts +1 -1
  15. package/dist/protocol/handlers/catalog/index.d.ts +1 -1
  16. package/dist/protocol/handlers/catalog/index_methods.d.ts +1 -1
  17. package/dist/protocol/handlers/catalog/macro.d.ts +1 -1
  18. package/dist/protocol/handlers/catalog/shared.d.ts +36 -3
  19. package/dist/protocol/handlers/catalog/table.d.ts +1 -1
  20. package/dist/protocol/handlers/catalog/view.d.ts +1 -1
  21. package/dist/protocol/handlers/function.d.ts +2 -0
  22. package/dist/protocol/handlers/table-buffering.d.ts +1 -1
  23. package/dist/serve-entry.d.ts +5 -0
  24. package/dist/serve-entry.js +514 -99
  25. package/dist/serve-entry.js.map +18 -16
  26. package/dist/worker-cf-entry.js +629 -108
  27. package/dist/worker-cf-entry.js.map +21 -18
  28. package/dist/worker.d.ts +10 -0
  29. package/dist/write-results.d.ts +57 -0
  30. package/package.json +1 -1
  31. package/src/attach-secret-keyfile.ts +185 -0
  32. package/src/attach-secret-options.ts +418 -0
  33. package/src/catalog/attach-option.ts +6 -0
  34. package/src/catalog/descriptors.ts +30 -0
  35. package/src/catalog/interface.ts +70 -0
  36. package/src/catalog/read-only.ts +123 -18
  37. package/src/index.core.ts +33 -0
  38. package/src/protocol/dispatch.ts +14 -2
  39. package/src/protocol/handlers/catalog/admin.ts +33 -18
  40. package/src/protocol/handlers/catalog/index.ts +6 -5
  41. package/src/protocol/handlers/catalog/index_methods.ts +5 -3
  42. package/src/protocol/handlers/catalog/macro.ts +7 -5
  43. package/src/protocol/handlers/catalog/shared.ts +69 -6
  44. package/src/protocol/handlers/catalog/table.ts +58 -19
  45. package/src/protocol/handlers/catalog/view.ts +9 -7
  46. package/src/protocol/handlers/function.ts +53 -19
  47. package/src/protocol/handlers/table-buffering.ts +2 -1
  48. package/src/serve-entry.ts +6 -1
  49. package/src/worker.ts +12 -0
  50. package/src/write-results.ts +174 -0
@@ -17,6 +17,30 @@ import {
17
17
  ATTACH_UUID_LEN,
18
18
  TRANSACTION_ENVELOPE_VERSION,
19
19
  } from "../../../crypto.js";
20
+ import { openFrameworkAttach, packAttachOptionsTrailer } from "../../../attach-secret-options.js";
21
+
22
+ /**
23
+ * The keys a catalog handler group opens opaque values with: the HTTP signing
24
+ * key (absent on stdio / unix) and the optional explicit root key for secret
25
+ * ATTACH options (`attachSecretKey`; see ../../../attach-secret-options.ts).
26
+ */
27
+ export interface OpaqueKeys {
28
+ signingKey?: Uint8Array | undefined;
29
+ attachSecretKey?: Uint8Array | undefined;
30
+ }
31
+
32
+ /**
33
+ * The options a catalog_attach packs into the attach value after the catalog's
34
+ * own bytes (secret ones encrypted). See ../../../attach-secret-options.ts.
35
+ */
36
+ export interface AttachOptionsToPack {
37
+ /** The request's `options` IPC batch (null / empty: no options, no trailer). */
38
+ optionsIpc: Uint8Array | null | undefined;
39
+ /** Lower-cased names of the options declared `secret: true`. */
40
+ secretNames: ReadonlySet<string>;
41
+ /** Explicit root key for the secret options, if configured. */
42
+ attachSecretKey?: Uint8Array | undefined;
43
+ }
20
44
 
21
45
  export type GetCatalog = () => CatalogInterface;
22
46
 
@@ -36,17 +60,31 @@ export type GetCatalog = () => CatalogInterface;
36
60
  * across re-seals and globally unique, unlike the random-nonce ciphertext or
37
61
  * the (possibly non-unique) catalog bytes. openAttach strips the UUID back off
38
62
  * so the catalog only ever sees its own bytes. Mirrors vgi-python/-go.
63
+ *
64
+ * With `options`, the attach's ATTACH options are packed after the catalog's
65
+ * bytes (secret ones encrypted, never plaintext) so `attachOptions()` can hand
66
+ * them to every function call and transaction hook of this attach.
39
67
  */
40
68
  export async function sealAttach(
41
69
  plaintext: Uint8Array,
42
70
  auth: AuthContext | undefined,
43
71
  signingKey: Uint8Array | undefined,
72
+ options?: AttachOptionsToPack,
44
73
  ): Promise<Uint8Array> {
45
74
  const uuid = new Uint8Array(ATTACH_UUID_LEN);
46
75
  crypto.getRandomValues(uuid);
47
- const minted = new Uint8Array(ATTACH_UUID_LEN + plaintext.length);
76
+ // The attach's options ride after the catalog's bytes, the secret ones
77
+ // encrypted under a key bound to this uuid (empty when there are none).
78
+ const trailer = options
79
+ ? await packAttachOptionsTrailer(uuid, options.optionsIpc, options.secretNames, {
80
+ explicit: options.attachSecretKey,
81
+ signingKey,
82
+ })
83
+ : new Uint8Array(0);
84
+ const minted = new Uint8Array(ATTACH_UUID_LEN + plaintext.length + trailer.length);
48
85
  minted.set(uuid, 0);
49
86
  minted.set(plaintext, ATTACH_UUID_LEN);
87
+ minted.set(trailer, ATTACH_UUID_LEN + plaintext.length);
50
88
  if (!signingKey) return minted;
51
89
  return sealBytes(minted, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION);
52
90
  }
@@ -73,9 +111,12 @@ export async function openAttach(
73
111
  envelope: Uint8Array,
74
112
  auth: AuthContext | undefined,
75
113
  signingKey: Uint8Array | undefined,
114
+ attachSecretKey?: Uint8Array,
76
115
  ): Promise<Uint8Array> {
77
116
  const full = await openAttachFull(envelope, auth, signingKey);
78
- return full.length < ATTACH_UUID_LEN ? full : full.subarray(ATTACH_UUID_LEN);
117
+ // Strips the uuid and the options trailer, decrypting secret options and
118
+ // recording all of them for attachOptions().
119
+ return openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
79
120
  }
80
121
 
81
122
  /** Hex of a byte array (lowercase). */
@@ -128,6 +169,23 @@ export async function sealTransaction(
128
169
  return sealBytes(plaintext, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION);
129
170
  }
130
171
 
172
+ /**
173
+ * Open a transaction_opaque_data envelope (sealed on HTTP only, no UUID prefix).
174
+ * `attachEnvelope` is the request's *sealed* attach, which the transaction
175
+ * envelope's AAD binds. A pass-through without a signing key or for an empty
176
+ * value. Catalog hooks and function bodies must see the same plaintext, or a
177
+ * worker cannot tie a function call to its transaction's commit/rollback.
178
+ */
179
+ export async function openTransaction(
180
+ envelope: Uint8Array,
181
+ attachEnvelope: Uint8Array,
182
+ auth: AuthContext | undefined,
183
+ signingKey: Uint8Array | undefined,
184
+ ): Promise<Uint8Array> {
185
+ if (!signingKey || envelope.length === 0) return envelope;
186
+ return openBytes(envelope, signingKey, transactionAad(auth, attachEnvelope), TRANSACTION_ENVELOPE_VERSION, "transaction_opaque_data");
187
+ }
188
+
131
189
  /**
132
190
  * Unwrap the attach_opaque_data / transaction_opaque_data fields of a catalog
133
191
  * request in place, so handler bodies always see plaintext. The transaction
@@ -137,8 +195,9 @@ export async function sealTransaction(
137
195
  async function unwrapParamsOpaque(
138
196
  params: Record<string, any>,
139
197
  ctx: CallContext | undefined,
140
- signingKey: Uint8Array | undefined,
198
+ keys: OpaqueKeys,
141
199
  ): Promise<void> {
200
+ const { signingKey, attachSecretKey } = keys;
142
201
  const auth = ctx?.auth;
143
202
  let sealedAttach: Uint8Array = new Uint8Array(0);
144
203
  if (params.attach_opaque_data != null) {
@@ -154,7 +213,7 @@ async function unwrapParamsOpaque(
154
213
  const full = signingKey
155
214
  ? await openBytes(env, signingKey, attachAad(auth), ATTACH_ENVELOPE_VERSION, "attach_opaque_data")
156
215
  : env;
157
- params.attach_opaque_data = full.length < ATTACH_UUID_LEN ? full : full.subarray(ATTACH_UUID_LEN);
216
+ params.attach_opaque_data = await openFrameworkAttach(full, { explicit: attachSecretKey, signingKey });
158
217
  }
159
218
  }
160
219
  // transaction_opaque_data is sealed only on HTTP (no UUID prefix); subprocess
@@ -180,9 +239,13 @@ async function unwrapParamsOpaque(
180
239
  * bespoke. The body sees the flattened params as a plain record.
181
240
  */
182
241
  export function catalogHandler<R>(
183
- signingKey: Uint8Array | undefined,
242
+ keysOrSigningKey: OpaqueKeys | Uint8Array | undefined,
184
243
  handler: (params: Record<string, any>, ctx: CallContext) => R | Promise<R>,
185
244
  ): (params: object, ctx: CallContext) => Promise<R> {
245
+ const keys: OpaqueKeys =
246
+ keysOrSigningKey instanceof Uint8Array || keysOrSigningKey === undefined
247
+ ? { signingKey: keysOrSigningKey }
248
+ : keysOrSigningKey;
186
249
  return async (wire: object, ctx: CallContext) => {
187
250
  let params = wire as Record<string, any>;
188
251
  // catalog_create / catalog_table_create / catalog_macro_create (and
@@ -197,7 +260,7 @@ export function catalogHandler<R>(
197
260
  params = unwrapRequest(params.request);
198
261
  }
199
262
  normalizeRequestSchemaPaths(params);
200
- await unwrapParamsOpaque(params, ctx, signingKey);
263
+ await unwrapParamsOpaque(params, ctx, keys);
201
264
  return handler(params, ctx);
202
265
  };
203
266
  }
@@ -22,6 +22,7 @@ import {
22
22
  import {
23
23
  type GetCatalog,
24
24
  catalogHandler,
25
+ type OpaqueKeys,
25
26
  } from "./shared.js";
26
27
 
27
28
  function requireFlatColumnPath(value: unknown, operation: string): string[] {
@@ -35,9 +36,10 @@ function requireFlatColumnPath(value: unknown, operation: string): string[] {
35
36
  return path as string[];
36
37
  }
37
38
 
38
- export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8Array): Partial<VgiService> {
39
+ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8Array, attachSecretKey?: Uint8Array): Partial<VgiService> {
40
+ const keys: OpaqueKeys = { signingKey, attachSecretKey };
39
41
  // catalog_table_get
40
- const catalogTableGet = catalogHandler(signingKey, async (params) => {
42
+ const catalogTableGet = catalogHandler(keys, async (params) => {
41
43
  const cat = getCatalog();
42
44
  const info = await cat.tableGet(
43
45
  toUint8Array(params.attach_opaque_data),
@@ -53,7 +55,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
53
55
  });
54
56
 
55
57
  // catalog_table_create
56
- const catalogTableCreate = catalogHandler(signingKey, async (params) => {
58
+ const catalogTableCreate = catalogHandler(keys, async (params) => {
57
59
  if (params.constraint_definitions == null) throw new Error("constraint_definitions is required");
58
60
  const definitions = Array.from(params.constraint_definitions as Iterable<unknown>, (d) => toUint8Array(d as Uint8Array));
59
61
  if (params.comment != null || params.tags != null || params.options != null || params.layout != null) {
@@ -89,7 +91,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
89
91
 
90
92
  // catalog_table_constraints_apply (ALTER TABLE ... SET/DROP NOT NULL and
91
93
  // every other canonical constraint change).
92
- const catalogTableConstraintsApply = catalogHandler(signingKey, async (params) => {
94
+ const catalogTableConstraintsApply = catalogHandler(keys, async (params) => {
93
95
  const attach = toUint8Array(params.attach_opaque_data);
94
96
  const cat = getCatalog();
95
97
  const caps = await cat.catalogCapabilities(attach);
@@ -124,7 +126,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
124
126
  });
125
127
 
126
128
  // catalog_table_drop
127
- const catalogTableDrop = catalogHandler(signingKey, async (params) => {
129
+ const catalogTableDrop = catalogHandler(keys, async (params) => {
128
130
  const cat = getCatalog();
129
131
  await cat.tableDrop(
130
132
  toUint8Array(params.attach_opaque_data),
@@ -137,7 +139,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
137
139
  });
138
140
 
139
141
  // catalog_table_column_statistics_get
140
- const catalogTableColumnStatisticsGet = catalogHandler(signingKey, async (params) => {
142
+ const catalogTableColumnStatisticsGet = catalogHandler(keys, async (params) => {
141
143
  const cat = getCatalog();
142
144
  const stats = await cat.tableColumnStatisticsGet(
143
145
  toUint8Array(params.attach_opaque_data),
@@ -149,7 +151,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
149
151
  });
150
152
 
151
153
  // catalog_table_scan_function_get
152
- const catalogTableScanFunctionGet = catalogHandler(signingKey, async (params) => {
154
+ const catalogTableScanFunctionGet = catalogHandler(keys, async (params) => {
153
155
  const cat = getCatalog();
154
156
  const scanResult = await cat.tableScanFunctionGet(
155
157
  toUint8Array(params.attach_opaque_data),
@@ -162,10 +164,44 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
162
164
  return wrapResult(scanResult, ScanFunctionResultSchema);
163
165
  });
164
166
 
167
+ // catalog_table_{insert,update,delete}_function_get — the table in-out
168
+ // function backing each DML statement. A catalog whose tables inline these
169
+ // into TableInfo is only asked when the client skipped the inline value.
170
+ const optionalTx = (params: Record<string, any>): Uint8Array | undefined =>
171
+ params.transaction_opaque_data ? toUint8Array(params.transaction_opaque_data) : undefined;
172
+ const catalogTableInsertFunctionGet = catalogHandler(keys, async (params) => {
173
+ const result = await getCatalog().tableInsertFunctionGet(
174
+ toUint8Array(params.attach_opaque_data),
175
+ params.schema_path,
176
+ params.name,
177
+ optionalTx(params),
178
+ params.writable_branch_function_name ?? null,
179
+ );
180
+ return wrapResult(result, ScanFunctionResultSchema);
181
+ });
182
+ const catalogTableUpdateFunctionGet = catalogHandler(keys, async (params) => {
183
+ const result = await getCatalog().tableUpdateFunctionGet(
184
+ toUint8Array(params.attach_opaque_data),
185
+ params.schema_path,
186
+ params.name,
187
+ optionalTx(params),
188
+ );
189
+ return wrapResult(result, ScanFunctionResultSchema);
190
+ });
191
+ const catalogTableDeleteFunctionGet = catalogHandler(keys, async (params) => {
192
+ const result = await getCatalog().tableDeleteFunctionGet(
193
+ toUint8Array(params.attach_opaque_data),
194
+ params.schema_path,
195
+ params.name,
196
+ optionalTx(params),
197
+ );
198
+ return wrapResult(result, ScanFunctionResultSchema);
199
+ });
200
+
165
201
  // catalog_table_scan_branches_get — branches-aware variant of
166
202
  // scan_function_get. The branches-aware C++ extension calls this for every
167
203
  // table scan; single-source catalogs synthesise a one-branch result.
168
- const catalogTableScanBranchesGet = catalogHandler(signingKey, async (params) => {
204
+ const catalogTableScanBranchesGet = catalogHandler(keys, async (params) => {
169
205
  const cat = getCatalog();
170
206
  const branchesResult = await cat.tableScanBranchesGet(
171
207
  toUint8Array(params.attach_opaque_data),
@@ -179,7 +215,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
179
215
  });
180
216
 
181
217
  // catalog_table_comment_set
182
- const catalogTableCommentSet = catalogHandler(signingKey, async (params) => {
218
+ const catalogTableCommentSet = catalogHandler(keys, async (params) => {
183
219
  const cat = getCatalog();
184
220
  await cat.tableCommentSet(
185
221
  toUint8Array(params.attach_opaque_data),
@@ -193,7 +229,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
193
229
  });
194
230
 
195
231
  // catalog_table_rename
196
- const catalogTableRename = catalogHandler(signingKey, async (params) => {
232
+ const catalogTableRename = catalogHandler(keys, async (params) => {
197
233
  const cat = getCatalog();
198
234
  await cat.tableRename(
199
235
  toUint8Array(params.attach_opaque_data),
@@ -207,7 +243,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
207
243
  });
208
244
 
209
245
  // catalog_table_column_add
210
- const catalogTableColumnAdd = catalogHandler(signingKey, async (params) => {
246
+ const catalogTableColumnAdd = catalogHandler(keys, async (params) => {
211
247
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_add");
212
248
  validateColumnMetadataIpc(toUint8Array(params.column_definition));
213
249
  validateColumnExpressionsIpc(toUint8Array(params.column_definition), params.schema_path);
@@ -225,7 +261,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
225
261
  return {};
226
262
  });
227
263
  // catalog_table_column_drop
228
- const catalogTableColumnDrop = catalogHandler(signingKey, async (params) => {
264
+ const catalogTableColumnDrop = catalogHandler(keys, async (params) => {
229
265
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_drop");
230
266
  const cat = getCatalog();
231
267
  await cat.tableColumnDrop(
@@ -241,7 +277,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
241
277
  return {};
242
278
  });
243
279
  // catalog_table_column_rename
244
- const catalogTableColumnRename = catalogHandler(signingKey, async (params) => {
280
+ const catalogTableColumnRename = catalogHandler(keys, async (params) => {
245
281
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_rename");
246
282
  const cat = getCatalog();
247
283
  await cat.tableColumnRename(
@@ -256,7 +292,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
256
292
  return {};
257
293
  });
258
294
  // catalog_table_column_comment_set
259
- const catalogTableColumnCommentSet = catalogHandler(signingKey, async (params) => {
295
+ const catalogTableColumnCommentSet = catalogHandler(keys, async (params) => {
260
296
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_comment_set");
261
297
  const cat = getCatalog();
262
298
  await cat.tableColumnCommentSet(
@@ -271,7 +307,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
271
307
  return {};
272
308
  });
273
309
  // catalog_table_column_default_set
274
- const catalogTableColumnDefaultSet = catalogHandler(signingKey, async (params) => {
310
+ const catalogTableColumnDefaultSet = catalogHandler(keys, async (params) => {
275
311
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_default_set");
276
312
  const cat = getCatalog();
277
313
  await cat.tableColumnDefaultSet(
@@ -286,7 +322,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
286
322
  return {};
287
323
  });
288
324
  // catalog_table_column_default_drop
289
- const catalogTableColumnDefaultDrop = catalogHandler(signingKey, async (params) => {
325
+ const catalogTableColumnDefaultDrop = catalogHandler(keys, async (params) => {
290
326
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_default_drop");
291
327
  const cat = getCatalog();
292
328
  await cat.tableColumnDefaultDrop(
@@ -300,7 +336,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
300
336
  return {};
301
337
  });
302
338
  // catalog_table_column_type_change
303
- const catalogTableColumnTypeChange = catalogHandler(signingKey, async (params) => {
339
+ const catalogTableColumnTypeChange = catalogHandler(keys, async (params) => {
304
340
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_column_type_change");
305
341
  const cat = getCatalog();
306
342
  await cat.tableColumnTypeChange(
@@ -316,7 +352,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
316
352
  return {};
317
353
  });
318
354
  // catalog_table_not_null_set
319
- const catalogTableNotNullSet = catalogHandler(signingKey, async (params) => {
355
+ const catalogTableNotNullSet = catalogHandler(keys, async (params) => {
320
356
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_not_null_set");
321
357
  const cat = getCatalog();
322
358
  await cat.tableNotNullSet(
@@ -330,7 +366,7 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
330
366
  return {};
331
367
  });
332
368
  // catalog_table_not_null_drop
333
- const catalogTableNotNullDrop = catalogHandler(signingKey, async (params) => {
369
+ const catalogTableNotNullDrop = catalogHandler(keys, async (params) => {
334
370
  params.column_path = requireFlatColumnPath(params.column_path, "catalog_table_not_null_drop");
335
371
  const cat = getCatalog();
336
372
  await cat.tableNotNullDrop(
@@ -350,6 +386,9 @@ export function catalogTableHandlers(getCatalog: GetCatalog, signingKey?: Uint8A
350
386
  catalogTableDrop,
351
387
  catalogTableColumnStatisticsGet,
352
388
  catalogTableScanFunctionGet,
389
+ catalogTableInsertFunctionGet,
390
+ catalogTableUpdateFunctionGet,
391
+ catalogTableDeleteFunctionGet,
353
392
  catalogTableScanBranchesGet,
354
393
  catalogTableCommentSet,
355
394
  catalogTableRename,
@@ -15,11 +15,13 @@ import {
15
15
  import {
16
16
  type GetCatalog,
17
17
  catalogHandler,
18
+ type OpaqueKeys,
18
19
  } from "./shared.js";
19
20
 
20
- export function catalogViewHandlers(getCatalog: GetCatalog, signingKey?: Uint8Array): Partial<VgiService> {
21
+ export function catalogViewHandlers(getCatalog: GetCatalog, signingKey?: Uint8Array, attachSecretKey?: Uint8Array): Partial<VgiService> {
22
+ const keys: OpaqueKeys = { signingKey, attachSecretKey };
21
23
  // catalog_view_get
22
- const catalogViewGet = catalogHandler(signingKey, async (params) => {
24
+ const catalogViewGet = catalogHandler(keys, async (params) => {
23
25
  const cat = getCatalog();
24
26
  const info = await cat.viewGet(
25
27
  toUint8Array(params.attach_opaque_data),
@@ -33,7 +35,7 @@ export function catalogViewHandlers(getCatalog: GetCatalog, signingKey?: Uint8Ar
33
35
  });
34
36
 
35
37
  // catalog_view_create
36
- const catalogViewCreate = catalogHandler(signingKey, async (params) => {
38
+ const catalogViewCreate = catalogHandler(keys, async (params) => {
37
39
  if (params.security !== "regular") throw new Error(`view security mode ${params.security} is unsupported`);
38
40
  const tags = catalogStringMap(params.tags);
39
41
  const columnComments = catalogStringMap(params.column_comments);
@@ -55,7 +57,7 @@ export function catalogViewHandlers(getCatalog: GetCatalog, signingKey?: Uint8Ar
55
57
  });
56
58
 
57
59
  // catalog_view_drop
58
- const catalogViewDrop = catalogHandler(signingKey, async (params) => {
60
+ const catalogViewDrop = catalogHandler(keys, async (params) => {
59
61
  const cat = getCatalog();
60
62
  await cat.viewDrop(
61
63
  toUint8Array(params.attach_opaque_data),
@@ -68,7 +70,7 @@ export function catalogViewHandlers(getCatalog: GetCatalog, signingKey?: Uint8Ar
68
70
  });
69
71
 
70
72
  // catalog_view_rename
71
- const catalogViewRename = catalogHandler(signingKey, async (params) => {
73
+ const catalogViewRename = catalogHandler(keys, async (params) => {
72
74
  const cat = getCatalog();
73
75
  await cat.viewRename(
74
76
  toUint8Array(params.attach_opaque_data),
@@ -82,7 +84,7 @@ export function catalogViewHandlers(getCatalog: GetCatalog, signingKey?: Uint8Ar
82
84
  });
83
85
 
84
86
  // catalog_view_comment_set
85
- const catalogViewCommentSet = catalogHandler(signingKey, async (params) => {
87
+ const catalogViewCommentSet = catalogHandler(keys, async (params) => {
86
88
  const cat = getCatalog();
87
89
  await cat.viewCommentSet(
88
90
  toUint8Array(params.attach_opaque_data),
@@ -95,7 +97,7 @@ export function catalogViewHandlers(getCatalog: GetCatalog, signingKey?: Uint8Ar
95
97
  return {};
96
98
  });
97
99
 
98
- const catalogViewColumnCommentSet = catalogHandler(signingKey, async (params) => {
100
+ const catalogViewColumnCommentSet = catalogHandler(keys, async (params) => {
99
101
  const path: string[] = Array.from(params.column_path);
100
102
  if (path.length !== 1 || !path[0] || path[0].includes("\0")) throw new Error("view column comments require one raw output identifier");
101
103
  await getCatalog().viewColumnCommentSet(
@@ -34,7 +34,7 @@ import {
34
34
  } from "../../generated/vgi-protocol-schemas.js";
35
35
  import { unwrapRequest, wrapResult, overloadContext } from "./shared.js";
36
36
  import { parseCarriedInitRequest } from "../carried-init-request.js";
37
- import { openAttach } from "./catalog/shared.js";
37
+ import { openAttach, openTransaction } from "./catalog/shared.js";
38
38
  import { currentRequestAuth } from "../../request-auth.js";
39
39
  import { batchFromColumns, serializeBatch } from "../../util/arrow/index.js";
40
40
  import {
@@ -56,6 +56,8 @@ import {
56
56
  export interface FunctionHandlerConfig {
57
57
  registry: FunctionRegistry;
58
58
  signingKey?: Uint8Array | undefined;
59
+ /** Explicit root key for secret ATTACH options (see attach-secret-options.ts). */
60
+ attachSecretKey?: Uint8Array | undefined;
59
61
  /**
60
62
  * Used to map a bind's `attach_opaque_data` to its catalog, so resolution can
61
63
  * be scoped when two catalogs declare the same schema and function name.
@@ -90,12 +92,22 @@ async function liveSplitAnchor(
90
92
  bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null },
91
93
  auth: AuthContext | undefined,
92
94
  signingKey: Uint8Array | undefined,
95
+ attachSecretKey?: Uint8Array,
93
96
  ): Promise<Uint8Array | undefined> {
94
97
  if (!catalogInterface?.version || bindCall.attach_opaque_data == null) return undefined;
95
98
  const raw = toUint8Array(bindCall.attach_opaque_data);
96
- const txn = bindCall.transaction_opaque_data
97
- ? toUint8Array(bindCall.transaction_opaque_data)
98
- : undefined;
99
+ // The transaction id is likewise sealed at `plan` (HTTP) and already open at
100
+ // `init`; the catalog's version() takes plaintext, as its own RPC does, so
101
+ // open it when it opens under this attach and use it as-is otherwise. Both
102
+ // stages must ask the same question or mint and redemption disagree.
103
+ let txn = bindCall.transaction_opaque_data ? toUint8Array(bindCall.transaction_opaque_data) : undefined;
104
+ if (txn && txn.length > 0 && signingKey) {
105
+ try {
106
+ txn = await openTransaction(txn, raw, auth, signingKey);
107
+ } catch {
108
+ // already plaintext (init), keep it
109
+ }
110
+ }
99
111
 
100
112
  // The two call sites see the attach envelope at DIFFERENT processing stages —
101
113
  // `plan` receives it with the framework's 16-byte UUID prefix still attached,
@@ -114,7 +126,7 @@ async function liveSplitAnchor(
114
126
  // every non-HTTP transport).
115
127
  const forms: Array<() => Promise<Uint8Array>> = [
116
128
  async () => raw,
117
- async () => openAttach(raw, auth, signingKey),
129
+ async () => openAttach(raw, auth, signingKey, attachSecretKey),
118
130
  ];
119
131
  for (const form of forms) {
120
132
  try {
@@ -159,6 +171,7 @@ async function resolveSplitPayloads(
159
171
  opts: {
160
172
  auth: any;
161
173
  signingKey: Uint8Array | undefined;
174
+ attachSecretKey?: Uint8Array | undefined;
162
175
  catalogInterface: any;
163
176
  checkAnchor: boolean;
164
177
  },
@@ -173,7 +186,7 @@ async function resolveSplitPayloads(
173
186
  new Uint8Array(0),
174
187
  );
175
188
  const currentAnchor = opts.checkAnchor
176
- ? await liveSplitAnchor(opts.catalogInterface, request.bind_call as any, opts.auth, opts.signingKey)
189
+ ? await liveSplitAnchor(opts.catalogInterface, request.bind_call as any, opts.auth, opts.signingKey, opts.attachSecretKey)
177
190
  : undefined;
178
191
  request.split_payloads = [];
179
192
  for (const token of request.split_tokens) {
@@ -193,7 +206,7 @@ async function resolveSplitPayloads(
193
206
 
194
207
  /** The per-function lifecycle's `vgi.v3` handlers. */
195
208
  export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiService> {
196
- const { registry, signingKey, catalogInterface } = config;
209
+ const { registry, signingKey, catalogInterface, attachSecretKey } = config;
197
210
 
198
211
  // The framework mints every attach as uuid(16) || catalog_bytes (sealed on
199
212
  // HTTP, plaintext on subprocess). Function bodies — like catalog bodies —
@@ -209,7 +222,27 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
209
222
  if (attach == null) return null;
210
223
  const env = toUint8Array(attach);
211
224
  if (env.length === 0) return env;
212
- return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey);
225
+ return openAttach(env, ctx?.auth ?? currentRequestAuth(), signingKey, attachSecretKey);
226
+ }
227
+
228
+ // Unseal a bind call's opaque values in place, as the catalog handlers do:
229
+ // the transaction first (its envelope binds the *sealed* attach), then the
230
+ // attach. Every function-side request goes through this, so function bodies
231
+ // see the same transaction plaintext that transactionCommit/Rollback get.
232
+ async function openOpaque(
233
+ bindCall: { attach_opaque_data?: Uint8Array | null; transaction_opaque_data?: Uint8Array | null },
234
+ ctx: any,
235
+ ): Promise<void> {
236
+ const sealedAttach = bindCall.attach_opaque_data != null ? toUint8Array(bindCall.attach_opaque_data) : new Uint8Array(0);
237
+ if (bindCall.transaction_opaque_data != null) {
238
+ bindCall.transaction_opaque_data = await openTransaction(
239
+ toUint8Array(bindCall.transaction_opaque_data),
240
+ sealedAttach,
241
+ ctx?.auth ?? currentRequestAuth(),
242
+ signingKey,
243
+ );
244
+ }
245
+ bindCall.attach_opaque_data = await stripAttach(bindCall.attach_opaque_data, ctx);
213
246
  }
214
247
 
215
248
  // Build an overload context whose attach has been unsealed, so catalog
@@ -218,13 +251,15 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
218
251
  // still holds the sealed envelope (73 bytes on HTTP vs 16 plaintext), whose
219
252
  // leading byte would otherwise route to an arbitrary catalog.
220
253
  async function strippedContext(bindCall: any, ctx?: any) {
221
- let attach: Uint8Array | null = null;
254
+ const copy = { ...bindCall };
222
255
  try {
223
- attach = await stripAttach(bindCall.attach_opaque_data, ctx);
256
+ await openOpaque(copy, ctx);
224
257
  } catch {
225
- attach = null; // Unopenable (wrong key / not sealed) — resolve unscoped.
258
+ // Unopenable (wrong key / not sealed) — resolve unscoped.
259
+ copy.attach_opaque_data = null;
260
+ copy.transaction_opaque_data = null;
226
261
  }
227
- return overloadContext({ ...bindCall, attach_opaque_data: attach }, catalogInterface);
262
+ return overloadContext(copy, catalogInterface);
228
263
  }
229
264
 
230
265
  const emptySchema = schema([]);
@@ -243,7 +278,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
243
278
  const bind: VgiService["bind"] = async (params, ctx) => {
244
279
  const innerParams = unwrapRequest(params.request);
245
280
  const request = deserializeBindRequest(innerParams);
246
- request.attach_opaque_data = await stripAttach(request.attach_opaque_data, ctx);
281
+ await openOpaque(request, ctx);
247
282
  const func = registry.get(request.function_name, overloadContext(request, catalogInterface));
248
283
  const response = await func.bind(request);
249
284
  validateProjectionOffer(response);
@@ -280,16 +315,14 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
280
315
  // attach_opaque_data not recognized` on its first scan, i.e. this worker
281
316
  // could not serve authenticated traffic at all.
282
317
  const auth = ctx?.auth ?? currentRequestAuth();
283
- request.bind_call.attach_opaque_data = await stripAttach(
284
- request.bind_call.attach_opaque_data,
285
- ctx,
286
- );
318
+ await openOpaque(request.bind_call, ctx);
287
319
 
288
320
  // Verify and strip the split envelopes BEFORE any user code runs, so an
289
321
  // unverified token can never be acted on.
290
322
  await resolveSplitPayloads(request, innerParams, {
291
323
  auth,
292
324
  signingKey,
325
+ attachSecretKey,
293
326
  catalogInterface,
294
327
  checkAnchor: true,
295
328
  });
@@ -381,7 +414,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
381
414
  // a hard error here, as on the init turn: the cursor is caller-bound.)
382
415
  // `carried.request.bind_call` is a per-call copy, so this does not
383
416
  // disturb the memoised parse other turns share.
384
- request.bind_call.attach_opaque_data = await stripAttach(request.bind_call.attach_opaque_data, undefined);
417
+ await openOpaque(request.bind_call, undefined);
385
418
  // Re-derive the split payloads. The cursor carries the wire request,
386
419
  // which has `split_tokens` but not the opened `split_payloads` — that
387
420
  // field only ever existed in memory on the init turn. Without this a
@@ -401,6 +434,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
401
434
  // authentication for every authenticated caller's own tokens.
402
435
  auth: currentRequestAuth(),
403
436
  signingKey,
437
+ attachSecretKey,
404
438
  catalogInterface,
405
439
  checkAnchor: false,
406
440
  });
@@ -540,7 +574,7 @@ export function functionHandlers(config: FunctionHandlerConfig): Partial<VgiServ
540
574
  const anchor =
541
575
  plan.catalogVersion != null
542
576
  ? splitAnchor(plan.catalogVersion)
543
- : ((await liveSplitAnchor(catalogInterface, request.bind_call as any, ctx?.auth, signingKey)) ??
577
+ : ((await liveSplitAnchor(catalogInterface, request.bind_call as any, ctx?.auth, signingKey, attachSecretKey)) ??
544
578
  splitAnchor(0));
545
579
 
546
580
  const blobs: Uint8Array[] = [];
@@ -37,6 +37,7 @@ import { Arguments } from "../../arguments/arguments.js";
37
37
  export function tableBufferingHandlers(
38
38
  registry: FunctionRegistry,
39
39
  signingKey?: Uint8Array,
40
+ attachSecretKey?: Uint8Array,
40
41
  ): Partial<VgiService> {
41
42
  // `schemaPath` scopes resolution to the schema the caller named. The
42
43
  // buffering process/combine RPCs carry it (protocol 1.2.0), so a name
@@ -74,7 +75,7 @@ export function tableBufferingHandlers(
74
75
  const rawAttach = inner.attach_opaque_data ? toUint8Array(inner.attach_opaque_data) : null;
75
76
  const attach =
76
77
  rawAttach && rawAttach.length > 0
77
- ? await openAttach(rawAttach, ctx?.auth, signingKey)
78
+ ? await openAttach(rawAttach, ctx?.auth, signingKey, attachSecretKey)
78
79
  : rawAttach;
79
80
  const transactionId = inner.transaction_id ? toUint8Array(inner.transaction_id) : null;
80
81
 
@@ -91,6 +91,11 @@ export interface ServeVgiWorkerOptions extends HostingOptions {
91
91
  hostname?: string | undefined;
92
92
  /** Overrides `$VGI_SIGNING_KEY`. 32 bytes. */
93
93
  signingKey?: Uint8Array | undefined;
94
+ /**
95
+ * Optional root key for secret ATTACH options (encrypted inside
96
+ * `attach_opaque_data` for `attachOptions()`). Defaults to the signing key.
97
+ */
98
+ attachSecretKey?: Uint8Array | undefined;
94
99
  /** Overrides `$VGI_TOKEN_TTL` (default 3600 seconds). */
95
100
  tokenTtl?: number | undefined;
96
101
  /** Overrides `$CORS_ORIGINS` (default "*"). Pass `null` to disable CORS. */
@@ -242,7 +247,7 @@ export function createVgiWorkerFetch(
242
247
  const trustedProxyAddresses = bridge?.trustedProxyAddresses ?? ["127.0.0.1"];
243
248
 
244
249
  return createVgiFetch({
245
- protocol: { registry: opts.registry, catalogInterface: opts.catalogInterface },
250
+ protocol: { registry: opts.registry, catalogInterface: opts.catalogInterface, attachSecretKey: opts.attachSecretKey },
246
251
  signingKey,
247
252
  signingKeyConfigured,
248
253
  tokenTtl,
package/src/worker.ts CHANGED
@@ -123,6 +123,15 @@ export interface WorkerConfig extends HostingOptions {
123
123
  * dispatches on. Omit to have the worker create its own.
124
124
  */
125
125
  registry?: FunctionRegistry;
126
+ /**
127
+ * Optional root key for secret ATTACH options (`AttachOptionSpec.secret`),
128
+ * which the framework encrypts inside `attach_opaque_data` for
129
+ * `attachOptions()`. Defaults to the host-local key file
130
+ * (`$VGI_ATTACH_SECRET_KEY_FILE`, else `vgi/attach-secret-options.key` under
131
+ * `$XDG_RUNTIME_DIR` or the per-user temp dir). Every worker process that may
132
+ * receive a given attach must use the same key.
133
+ */
134
+ attachSecretKey?: Uint8Array;
126
135
  }
127
136
 
128
137
  export class Worker {
@@ -130,8 +139,10 @@ export class Worker {
130
139
  private _hosting: HostingOptions;
131
140
  private _catalogInterface: CatalogInterface | undefined;
132
141
  private _catalogName: string | undefined;
142
+ private _attachSecretKey: Uint8Array | undefined;
133
143
 
134
144
  constructor(config: WorkerConfig) {
145
+ this._attachSecretKey = config.attachSecretKey;
135
146
  // Reuse the caller's registry when given: a catalogInterface built
136
147
  // elsewhere recorded its per-schema function ownership there, and that
137
148
  // index is what makes a schema-qualified bind resolve correctly.
@@ -297,6 +308,7 @@ export class Worker {
297
308
  registry: this._registry,
298
309
  catalogInterface: this._catalogInterface,
299
310
  catalogName: this._catalogName,
311
+ attachSecretKey: this._attachSecretKey,
300
312
  });
301
313
  }
302
314