@query-farm/vgi 0.51.0 → 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 (70) 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/storage-blobs.d.ts +173 -0
  5. package/dist/functions/storage-cf-do.d.ts +12 -0
  6. package/dist/functions/storage.d.ts +22 -0
  7. package/dist/functions/table.d.ts +6 -1
  8. package/dist/generated/vgi-client.d.ts +7 -1
  9. package/dist/generated/vgi-protocol-schemas.d.ts +10 -9
  10. package/dist/generated/vgi-protocol-types.d.ts +244 -2
  11. package/dist/generated/vgi-service.d.ts +1 -1
  12. package/dist/hosted.d.ts +117 -0
  13. package/dist/http/blob-vendor.d.ts +33 -0
  14. package/dist/http/fetch.d.ts +53 -2
  15. package/dist/http/hosted-auth.d.ts +45 -0
  16. package/dist/index.core.d.ts +9 -2
  17. package/dist/index.js +5238 -3619
  18. package/dist/index.js.map +44 -28
  19. package/dist/protocol/arguments-ref.d.ts +107 -0
  20. package/dist/protocol/dispatch.d.ts +3 -2
  21. package/dist/protocol/handlers/function.d.ts +21 -0
  22. package/dist/protocol/serialize.d.ts +1 -1
  23. package/dist/protocol/serializers/bind.d.ts +27 -1
  24. package/dist/protocol/serializers/cardinality.d.ts +1 -1
  25. package/dist/protocol/serializers/splits.d.ts +7 -0
  26. package/dist/protocol/state-serializer.d.ts +8 -7
  27. package/dist/protocol/stream-init.d.ts +17 -0
  28. package/dist/protocol/types.d.ts +24 -0
  29. package/dist/secrets/lookups.d.ts +31 -0
  30. package/dist/serve-entry.d.ts +25 -4
  31. package/dist/serve-entry.js +2940 -1219
  32. package/dist/serve-entry.js.map +44 -29
  33. package/dist/worker-cf-entry.d.ts +5 -0
  34. package/dist/worker-cf-entry.js +2928 -1223
  35. package/dist/worker-cf-entry.js.map +47 -31
  36. package/package.json +5 -4
  37. package/src/functions/storage-blobs.ts +654 -0
  38. package/src/functions/storage-cf-do.ts +24 -0
  39. package/src/functions/storage.ts +54 -5
  40. package/src/functions/table-buffering.ts +14 -4
  41. package/src/functions/table.ts +8 -4
  42. package/src/generated/vgi-client.ts +9 -2
  43. package/src/generated/vgi-protocol-schemas.ts +115 -107
  44. package/src/generated/vgi-protocol-types.ts +640 -3
  45. package/src/generated/vgi-service.ts +2 -2
  46. package/src/hosted.ts +254 -0
  47. package/src/http/blob-vendor.ts +80 -0
  48. package/src/http/fetch.ts +170 -8
  49. package/src/http/hosted-auth.ts +326 -0
  50. package/src/index.core.ts +64 -1
  51. package/src/protocol/arguments-ref.ts +260 -0
  52. package/src/protocol/dispatch.ts +3 -2
  53. package/src/protocol/handlers/function.ts +109 -60
  54. package/src/protocol/handlers/table-buffering.ts +5 -0
  55. package/src/protocol/serialize.ts +3 -0
  56. package/src/protocol/serializers/bind.ts +96 -69
  57. package/src/protocol/serializers/cardinality.ts +4 -7
  58. package/src/protocol/serializers/init.ts +5 -11
  59. package/src/protocol/serializers/splits.ts +31 -4
  60. package/src/protocol/state-serializer.ts +27 -39
  61. package/src/protocol/stream-init.ts +87 -0
  62. package/src/protocol/types.ts +25 -0
  63. package/src/secrets/lookups.ts +53 -0
  64. package/src/serve-entry.ts +105 -8
  65. package/src/worker-cf-entry.ts +33 -0
  66. package/src/worker.ts +25 -0
  67. package/dist/protocol/carried-init-request.d.ts +0 -28
  68. package/dist/util/zstd-sync.d.ts +0 -7
  69. package/src/protocol/carried-init-request.ts +0 -139
  70. package/src/util/zstd-sync.ts +0 -50
@@ -13,7 +13,8 @@ import type { BindRequest } from "../types.js";
13
13
  import { OrderByDirection, OrderByNullOrder } from "../types.js";
14
14
  import { deserializeBatch, batchToScalarDict } from "../../util/arrow/index.js";
15
15
  import { toUint8Array } from "./shared.js";
16
- import { deserializeBindRequest } from "./bind.js";
16
+ import { toUint8Array as bytesOf } from "../../util/bytes.js";
17
+ import { decodeBindCall } from "./bind.js";
17
18
 
18
19
  /**
19
20
  * One named, independently redeemable unit of scan work.
@@ -164,8 +165,7 @@ export const PLAN_RESPONSE_SCHEMA: VgiSchema = TableFunctionPlanResultSchema as
164
165
  * not set — so every field but `bind_call` is read defensively.
165
166
  */
166
167
  export function deserializePlanRequest(params: Record<string, any>): TableFunctionPlanRequest {
167
- const bindCallBytes = toUint8Array(params.bind_call);
168
- const bindCall = deserializeBindRequest(batchToScalarDict(deserializeBatch(bindCallBytes)));
168
+ const bindCall = decodeBindCall(toUint8Array(params.bind_call), "TableFunctionPlanRequest.bind_call");
169
169
 
170
170
  let projectionIds: number[] | null = null;
171
171
  if (params.projection_ids != null) {
@@ -224,6 +224,13 @@ export function deserializePlanRequest(params: Record<string, any>): TableFuncti
224
224
  * that minted a token and the init that redeems it. A decoded-then-re-encoded
225
225
  * argument list is not guaranteed to round-trip to identical bytes; the wire
226
226
  * bytes are.
227
+ *
228
+ * `args` is tagged (large-values spec §5a, "Split-token fingerprints"):
229
+ * inline arguments contribute `0x00 || u64le(len) || IPC bytes`; an argument
230
+ * reference contributes `0x01 || u64le(size) || sha256[32]`, never the sealed
231
+ * `ref` (it holds a random nonce). Without the location branch every bind of
232
+ * externalized arguments would fingerprint the same empty bytes, and a split
233
+ * token would redeem across different large arguments.
227
234
  */
228
235
  export function fingerprintInputs(bindCallBytes: Uint8Array): {
229
236
  schemaPath: string[];
@@ -237,11 +244,31 @@ export function fingerprintInputs(bindCallBytes: Uint8Array): {
237
244
  ? []
238
245
  : (Array.isArray(dict.schema_path) ? dict.schema_path : [...dict.schema_path]).map(String),
239
246
  functionName: String(dict.function_name ?? ""),
240
- args: dict.arguments ? toUint8Array(dict.arguments) : new Uint8Array(0),
247
+ args: argumentsFingerprintInput(dict.arguments, dict.arguments_location),
241
248
  settings: dict.settings ? toUint8Array(dict.settings) : new Uint8Array(0),
242
249
  };
243
250
  }
244
251
 
252
+ const ARGS_INLINE = 0x00;
253
+ const ARGS_LOCATION = 0x01;
254
+
255
+ function argumentsFingerprintInput(argumentsValue: unknown, location: any): Uint8Array {
256
+ if (location != null) {
257
+ const sha = String(location.sha256 ?? "");
258
+ const out = new Uint8Array(1 + 8 + 32);
259
+ out[0] = ARGS_LOCATION;
260
+ new DataView(out.buffer).setBigUint64(1, BigInt(location.size ?? 0), true);
261
+ for (let i = 0; i < 32; i++) out[9 + i] = parseInt(sha.slice(i * 2, i * 2 + 2), 16) || 0;
262
+ return out;
263
+ }
264
+ const raw = argumentsValue != null ? bytesOf(argumentsValue) : new Uint8Array(0);
265
+ const out = new Uint8Array(1 + 8 + raw.byteLength);
266
+ out[0] = ARGS_INLINE;
267
+ new DataView(out.buffer).setBigUint64(1, BigInt(raw.byteLength), true);
268
+ out.set(raw, 9);
269
+ return out;
270
+ }
271
+
245
272
  /** Build the row dict for one `ScanSplit`. */
246
273
  export function scanSplitRow(split: ScanSplit, token: Uint8Array): Record<string, any> {
247
274
  const asBigInt = (v: number | bigint | null | undefined): bigint | null =>
@@ -25,9 +25,8 @@ import {
25
25
  } from "../arrow/index.js";
26
26
  import { codecFor } from "../arrow/codec/registry.js";
27
27
  import type { StateSerializer } from "@query-farm/vgi-rpc";
28
- import { toUint8Array } from "../util/bytes.js";
29
28
  import { decodeFilterHistory, encodeFilterHistory } from "../filter-pushdown/history.js";
30
- import { packInitRequest } from "./carried-init-request.js";
29
+ import { StateRef } from "@query-farm/vgi-rpc";
31
30
 
32
31
  /**
33
32
  * The fields of the exchange state an HTTP cursor carries, by name and type.
@@ -38,12 +37,11 @@ import { packInitRequest } from "./carried-init-request.js";
38
37
  */
39
38
  export const EXCHANGE_STATE_SCHEMA = makeSchema([
40
39
  field("function_name", binary(), false),
41
- // The init request, packed by carried-init-request.ts (a codec byte, then
42
- // the IPC bytes, zstd-compressed where the runtime can).
43
- field("init_request", binary(), false),
44
- field("execution_id", binary(), false),
45
- field("max_workers", int64(), false),
46
- field("opaque_data", binary(), true),
40
+ // The stream's `init`: a vgi-rpc StateRef (its encoded bytes) to the init
41
+ // request as received plus the worker's init response (stream-init.ts).
42
+ // Inline and compressed in the common case, a sealed stored tag for a large
43
+ // init. Created on the init turn only; every continuation copies it.
44
+ field("init", binary(), false),
47
45
  field("is_producer", bool(), false),
48
46
  field("user_state", binary(), true),
49
47
  // The stream's compacted dynamic-filter history (filter-pushdown/history.ts),
@@ -59,9 +57,8 @@ const TEXT_ENCODER = new TextEncoder();
59
57
  const TEXT_DECODER = new TextDecoder();
60
58
 
61
59
  /** Version byte of the exchange state frame (never 0xFF, the first byte of an Arrow IPC stream). */
62
- const STATE_FORMAT_VERSION = 1;
60
+ const STATE_FORMAT_VERSION = 2;
63
61
  const FLAG_PRODUCER = 1;
64
- const FLAG_OPAQUE_DATA = 2;
65
62
  const FLAG_USER_STATE = 4;
66
63
  const FLAG_FILTER_HISTORY = 8;
67
64
  const FLAG_MORE_PENDING = 16;
@@ -223,44 +220,41 @@ export function deserializeUserState(bytes: Uint8Array | null): any {
223
220
  * {@link EXCHANGE_STATE_SCHEMA} names; `user_state` stays Arrow IPC inside the
224
221
  * frame, because it carries typed user values.
225
222
  *
226
- * Layout (little-endian): `u8 version | u8 flags | f64 max_workers |
227
- * bytes function_name | bytes init_request | bytes execution_id |
228
- * [bytes opaque_data] [bytes user_state] [bytes filter_history]`, where
229
- * `bytes` is `u32 length, payload` and a bracketed field is present only when
230
- * its flag bit is set. The frame never leaves this worker unsealed, so the
231
- * version byte exists to turn a token minted by another build into a clean
232
- * refusal rather than a misread.
223
+ * Layout (little-endian): `u8 version | u8 flags | bytes function_name |
224
+ * bytes init | [bytes user_state] [bytes filter_history]`, where `bytes` is
225
+ * `u32 length, payload` and a bracketed field is present only when its flag
226
+ * bit is set. `init` is the encoded vgi-rpc StateRef the init handler created
227
+ * (`StateRef.toBytes()`; vgi-rpc decides its form while minting the token and
228
+ * caches the encoding, so continuations re-emit the same bytes). The frame
229
+ * never leaves this worker unsealed, so the version byte exists to turn a
230
+ * token minted by another build into a clean refusal rather than a misread.
233
231
  *
234
232
  * The name is kept for API stability; the Arrow in it is the user state.
235
233
  */
236
234
  export const arrowStateSerializer: StateSerializer = {
237
235
  serialize(state: any): Uint8Array {
238
236
  const functionName = TEXT_ENCODER.encode(state.functionName ?? "");
239
- // Packed on the init turn (the only one holding the raw bytes); every
240
- // continuation carries the packed bytes through unchanged.
241
- const initRequest: Uint8Array = state.initRequestPacked ?? packInitRequest(state.initRequestIpc);
242
- const executionId = toUint8Array(state.executionId);
243
- const opaqueData = state.opaqueData != null ? toUint8Array(state.opaqueData) : null;
237
+ if (!StateRef.isStateRef(state.init)) {
238
+ throw new Error("exchange state carries no init StateRef (the stream's init handler creates it)");
239
+ }
240
+ const init = (state.init as StateRef).toBytes();
244
241
  const userState = serializeUserState(state.userState);
245
242
  const filterHistory = encodeFilterHistory(state.filterHistory);
246
243
  const flags =
247
244
  (state.isProducer ? FLAG_PRODUCER : 0) |
248
- (opaqueData ? FLAG_OPAQUE_DATA : 0) |
249
245
  (userState ? FLAG_USER_STATE : 0) |
250
246
  (filterHistory ? FLAG_FILTER_HISTORY : 0) |
251
247
  (state.morePending ? FLAG_MORE_PENDING : 0);
252
- const chunks = [functionName, initRequest, executionId];
253
- if (opaqueData) chunks.push(opaqueData);
248
+ const chunks = [functionName, init];
254
249
  if (userState) chunks.push(userState);
255
250
  if (filterHistory) chunks.push(filterHistory);
256
- let size = 2 + 8;
251
+ let size = 2;
257
252
  for (const chunk of chunks) size += 4 + chunk.byteLength;
258
253
  const out = new Uint8Array(size);
259
254
  const view = new DataView(out.buffer);
260
255
  out[0] = STATE_FORMAT_VERSION;
261
256
  out[1] = flags;
262
- view.setFloat64(2, Number(state.maxWorkers ?? 1), true);
263
- let offset = 10;
257
+ let offset = 2;
264
258
  for (const chunk of chunks) {
265
259
  view.setUint32(offset, chunk.byteLength, true);
266
260
  out.set(chunk, offset + 4);
@@ -271,12 +265,11 @@ export const arrowStateSerializer: StateSerializer = {
271
265
 
272
266
  deserialize(bytes: Uint8Array): any {
273
267
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
274
- if (bytes.byteLength < 10 || bytes[0] !== STATE_FORMAT_VERSION) {
268
+ if (bytes.byteLength < 2 || bytes[0] !== STATE_FORMAT_VERSION) {
275
269
  throw new Error("exchange state has an unknown format (minted by another build of this worker?)");
276
270
  }
277
- const flags = bytes[1]!; // in range: byteLength >= 10 was checked above
278
- const maxWorkers = view.getFloat64(2, true);
279
- let offset = 10;
271
+ const flags = bytes[1]!; // in range: byteLength >= 2 was checked above
272
+ let offset = 2;
280
273
  // Each field is copied out, not viewed: Arrow readers want a buffer of
281
274
  // their own (byteOffset 0), and nothing should pin the whole frame.
282
275
  const take = (): Uint8Array => {
@@ -289,19 +282,14 @@ export const arrowStateSerializer: StateSerializer = {
289
282
  return chunk;
290
283
  };
291
284
  const functionName = TEXT_DECODER.decode(take());
292
- const initRequestPacked = take();
293
- const executionId = take();
294
- const opaqueData = flags & FLAG_OPAQUE_DATA ? take() : null;
285
+ const init = StateRef.fromBytes(take());
295
286
  const userStateBytes = flags & FLAG_USER_STATE ? take() : null;
296
287
  const filterHistoryBytes = flags & FLAG_FILTER_HISTORY ? take() : null;
297
288
  if (offset !== bytes.byteLength) throw new Error("exchange state has trailing bytes");
298
289
  const isProducer = (flags & FLAG_PRODUCER) !== 0;
299
290
  return {
300
291
  functionName,
301
- initRequestPacked,
302
- executionId,
303
- maxWorkers,
304
- opaqueData,
292
+ init,
305
293
  isProducer,
306
294
  // vgi-rpc dispatch reads __isProducer to choose producer vs exchange mode
307
295
  __isProducer: isProducer,
@@ -0,0 +1,87 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // The value of an HTTP stream's `init` StateRef (vgi docs/large-values-3.4.md §6).
3
+ //
4
+ // An HTTP stream has no memory between turns, so its cursor has to carry what
5
+ // the init turn knew: the init request as received (bind call, output schema,
6
+ // filters, join keys, split tokens, opaque data) and the worker's init response.
7
+ // Both are immutable for the life of the stream, so they ride as ONE vgi-rpc
8
+ // StateRef field, `init`, created with `ctx.stateRef()` in the init handler and
9
+ // copied unchanged by every later turn:
10
+ //
11
+ // - small inits (the common case) are inline: vgi-rpc compresses the payload
12
+ // inside the ref, which is why this SDK no longer packs (zstd) the init
13
+ // request itself;
14
+ // - a large init (a 1000-value IN list) is stored once at /init and costs a
15
+ // ~130-byte sealed tag per turn after that.
16
+ //
17
+ // With argument references the init request holds the reference, never the
18
+ // argument, so it normally stays inline even for a very large argument.
19
+ //
20
+ // There is deliberately no per-process parse memo (spec decision 3): an inline
21
+ // init is decompressed and parsed on every turn, which measured as immaterial.
22
+ // The 128-entry LRU this SDK used to keep pinned parsed requests, and with them
23
+ // resolved arguments of any size.
24
+
25
+ /** Version byte of the value; a different build's frame is a clean refusal, not a misread. */
26
+ const STREAM_INIT_VERSION = 1;
27
+ const FLAG_OPAQUE_DATA = 1;
28
+
29
+ /** What an HTTP stream's `init` StateRef holds. */
30
+ export interface StreamInit {
31
+ /** The init request's IPC bytes exactly as received (the `request` column of the init call). */
32
+ initRequestIpc: Uint8Array;
33
+ /** The worker's init response. */
34
+ executionId: Uint8Array;
35
+ maxWorkers: number;
36
+ opaqueData: Uint8Array | null;
37
+ }
38
+
39
+ /**
40
+ * Encode the `init` value: `u8 version | u8 flags | f64 max_workers |
41
+ * bytes init_request | bytes execution_id | [bytes opaque_data]`, `bytes`
42
+ * being `u32 length (LE), payload`.
43
+ */
44
+ export function encodeStreamInit(init: StreamInit): Uint8Array {
45
+ const chunks = [init.initRequestIpc, init.executionId];
46
+ if (init.opaqueData != null) chunks.push(init.opaqueData);
47
+ let size = 2 + 8;
48
+ for (const chunk of chunks) size += 4 + chunk.byteLength;
49
+ const out = new Uint8Array(size);
50
+ const view = new DataView(out.buffer);
51
+ out[0] = STREAM_INIT_VERSION;
52
+ out[1] = init.opaqueData != null ? FLAG_OPAQUE_DATA : 0;
53
+ view.setFloat64(2, Number(init.maxWorkers ?? 1), true);
54
+ let offset = 10;
55
+ for (const chunk of chunks) {
56
+ view.setUint32(offset, chunk.byteLength, true);
57
+ out.set(chunk, offset + 4);
58
+ offset += 4 + chunk.byteLength;
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** Decode an `init` value written by {@link encodeStreamInit}. */
64
+ export function decodeStreamInit(bytes: Uint8Array): StreamInit {
65
+ if (bytes.byteLength < 10 || bytes[0] !== STREAM_INIT_VERSION) {
66
+ throw new Error("stream init state has an unknown format (minted by another build of this worker?)");
67
+ }
68
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
69
+ const flags = bytes[1]!;
70
+ const maxWorkers = view.getFloat64(2, true);
71
+ let offset = 10;
72
+ const take = (): Uint8Array => {
73
+ if (offset + 4 > bytes.byteLength) throw new Error("stream init state is truncated");
74
+ const length = view.getUint32(offset, true);
75
+ offset += 4;
76
+ if (offset + length > bytes.byteLength) throw new Error("stream init state is truncated");
77
+ // Copied, not viewed: Arrow readers want a buffer of their own.
78
+ const chunk = bytes.slice(offset, offset + length);
79
+ offset += length;
80
+ return chunk;
81
+ };
82
+ const initRequestIpc = take();
83
+ const executionId = take();
84
+ const opaqueData = flags & FLAG_OPAQUE_DATA ? take() : null;
85
+ if (offset !== bytes.byteLength) throw new Error("stream init state has trailing bytes");
86
+ return { initRequestIpc, executionId, maxWorkers, opaqueData };
87
+ }
@@ -56,8 +56,26 @@ export interface CopyToContext {
56
56
  file_path: string;
57
57
  }
58
58
 
59
+ /**
60
+ * Where a bind's externalized arguments live (protocol 3.4 argument
61
+ * references, vgi docs/large-values-3.4.md §2). The client uploaded the
62
+ * arguments IPC stream once through this worker's `__upload_url__` grant;
63
+ * `ref` is the grant's sealed reference, `size` / `sha256` describe exactly
64
+ * the uploaded bytes. Mirrors vgi-python's `protocol.ArgumentsLocation`.
65
+ */
66
+ export interface ArgumentsLocation {
67
+ ref: Uint8Array;
68
+ size: number;
69
+ sha256: string;
70
+ }
71
+
59
72
  export interface BindRequest {
60
73
  function_name: string;
74
+ /**
75
+ * The bound arguments. When the bind arrived by reference
76
+ * (`arguments_location`), the framework resolves them at the entry of every
77
+ * request before any function code runs, so this always holds the value.
78
+ */
61
79
  arguments: Arguments;
62
80
  function_type: FunctionType;
63
81
  input_schema: VgiSchema | null;
@@ -110,6 +128,13 @@ export interface BindRequest {
110
128
  * named varargs retain the caller-provided name. `null` means unavailable.
111
129
  */
112
130
  argument_names?: (string | null)[] | null;
131
+ /**
132
+ * Protocol 3.4: the location the arguments arrived by, when the client sent
133
+ * them as an argument reference instead of inline; `null`/absent for inline
134
+ * arguments. `arguments` still holds the resolved value; this is what the
135
+ * bind call re-serializes as (never the value).
136
+ */
137
+ arguments_location?: ArgumentsLocation | null;
113
138
  }
114
139
 
115
140
  /** Equivalent scans of one bound state within a query; independent binds may differ. */
@@ -0,0 +1,53 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+
3
+ /**
4
+ * The secret-lookup fields an `onBind` may return to ask DuckDB for secrets.
5
+ *
6
+ * The three lists are parallel: entry `i` requests a secret of type
7
+ * `lookupSecretTypes[i]`, optionally narrowed by `lookupScopes[i]` and
8
+ * `lookupNames[i]` (`""` or a missing entry = unset). A lookup without a type
9
+ * cannot be expressed, so `lookupSecretTypes` drives the request.
10
+ */
11
+ export interface SecretLookupFields {
12
+ lookupSecretTypes?: string[];
13
+ lookupScopes?: string[];
14
+ lookupNames?: string[];
15
+ }
16
+
17
+ /**
18
+ * Check an `onBind` result's secret-lookup lists before they go on the wire.
19
+ *
20
+ * The extension reads one lookup per `lookupSecretTypes` entry, so a scope or
21
+ * name with no type at the same index was silently dropped: returning
22
+ * `lookupNames: ["prod"]` alone requested nothing and the secret arrived
23
+ * missing. That is now a bind error naming the fix.
24
+ *
25
+ * @param fnName function name, for the error message.
26
+ * @param result the `onBind` return value.
27
+ * @returns the three lists for `BindResponse`.
28
+ * @throws Error when `lookupScopes` or `lookupNames` is longer than `lookupSecretTypes`.
29
+ */
30
+ export function secretLookupWire(
31
+ fnName: string,
32
+ result: SecretLookupFields,
33
+ ): { lookup_secret_types: string[] | undefined; lookup_scopes: string[] | undefined; lookup_names: string[] | undefined } {
34
+ const types = result.lookupSecretTypes ?? [];
35
+ for (const [key, list] of [
36
+ ["lookupScopes", result.lookupScopes],
37
+ ["lookupNames", result.lookupNames],
38
+ ] as const) {
39
+ if (list && list.length > types.length) {
40
+ throw new Error(
41
+ `${fnName}: onBind returned ${list.length} ${key} but ${types.length} lookupSecretTypes. ` +
42
+ "The lists are parallel (entry i is lookupSecretTypes[i] narrowed by lookupScopes[i] / " +
43
+ "lookupNames[i]); every lookup needs a secret type, so the extra entries would request nothing. " +
44
+ 'Return e.g. { lookupSecretTypes: ["my_type"], lookupScopes: [""], lookupNames: ["prod"] }.',
45
+ );
46
+ }
47
+ }
48
+ return {
49
+ lookup_secret_types: result.lookupSecretTypes,
50
+ lookup_scopes: result.lookupScopes,
51
+ lookup_names: result.lookupNames,
52
+ };
53
+ }
@@ -33,10 +33,36 @@ import {
33
33
  type PeerResolutionOptions,
34
34
  } from "@query-farm/vgi-rpc";
35
35
  import { createVgiFetch } from "./http/fetch.js";
36
+ import { blobVendorHttpConfigFromEnv, type BlobVendorEnv, type BlobVendorHttpConfig } from "./http/blob-vendor.js";
36
37
  import { grantKeysFromArgv, type HostingOptions } from "./rpc-server.js";
38
+ import {
39
+ checkHostedEnvironment,
40
+ checkHostedSigningKey,
41
+ hostedModeEnabled,
42
+ OrchardHostedConfigError,
43
+ resolveHostedConfig,
44
+ type HostedConfig,
45
+ } from "./hosted.js";
46
+
47
+ // Orchard hosted mode (VGI_ORCHARD_HOSTED=1): Pass-only HTTP serving. See
48
+ // docs/orchard-hosted.md.
49
+ export {
50
+ HOSTED_ENV,
51
+ HOSTED_CHALLENGE,
52
+ HOSTED_AUTH_DOMAIN,
53
+ OrchardHostedConfigError,
54
+ hostedModeEnabled,
55
+ resolveHostedConfig,
56
+ orchardHostedFromEnv,
57
+ checkHostedEnvironment,
58
+ checkHostedSigningKey,
59
+ type HostedConfig,
60
+ type HostedEnv,
61
+ } from "./hosted.js";
62
+ export { hostedAuthenticate, isHostedAuthenticate, type HostedVerifierDeps } from "./http/hosted-auth.js";
37
63
 
38
64
  /** Environment variables `serveVgiWorker` reads. Injectable for testing. */
39
- export interface ServeEnv {
65
+ export interface ServeEnv extends BlobVendorEnv {
40
66
  PORT?: string;
41
67
  VGI_SIGNING_KEY?: string;
42
68
  VGI_TOKEN_TTL?: string;
@@ -49,10 +75,21 @@ export interface ServeEnv {
49
75
  VGI_RPC_GRANT_MAX_TTL_SECONDS?: string;
50
76
  /** Principals allowed to call `introspect_token`, comma-separated. */
51
77
  VGI_INTROSPECT_PRINCIPALS?: string;
78
+ /** `1` turns on Orchard hosted mode (see `docs/orchard-hosted.md`). */
79
+ VGI_ORCHARD_HOSTED?: string;
80
+ /** Hosted mode: the Front Desk issuer, exactly one value. */
81
+ VGI_JWT_ISSUER?: string;
82
+ /** Hosted mode: the canonical Desk Address, exactly one value. */
83
+ VGI_JWT_AUDIENCE?: string;
84
+ /** Hosted mode: the Front Desk's JWKS URL, exactly one value. */
85
+ VGI_JWT_JWKS_URI?: string;
86
+ /** Hosted mode: accepted Pass algorithms (default ES256; never none/HS*). */
87
+ VGI_JWT_ALGORITHMS?: string;
52
88
  }
53
89
 
54
90
  export const DEFAULT_PORT = 8787;
55
- export const DEFAULT_TOKEN_TTL = 3600;
91
+ /** Default state-token TTL: 6 h (vgi-rpc STATE_REF_V1.md, protocol 3.4). */
92
+ export const DEFAULT_TOKEN_TTL = 21600;
56
93
  /** Bytes of HMAC key `createHttpHandler` expects; 64 hex characters. */
57
94
  export const SIGNING_KEY_BYTES = 32;
58
95
 
@@ -71,7 +108,14 @@ export interface IrohHttpBridgeOptions {
71
108
  peerResolutionContext?: ((request: Request) => PeerResolutionOptions | Promise<PeerResolutionOptions>) | undefined;
72
109
  }
73
110
 
74
- export interface ServeVgiWorkerOptions extends HostingOptions {
111
+ /**
112
+ * The external-location fields ({@link BlobVendorHttpConfig}) default to the
113
+ * blob-vendor environment (`VGI_BLOB_VENDOR_URL`, `VGI_BLOB_VENDOR_TOKEN`,
114
+ * `VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES`, `VGI_RPC_EXTERNAL_COMPRESSION`,
115
+ * `VGI_RPC_MAX_REQUEST_BYTES`, `VGI_RPC_MAX_UPLOAD_BYTES`); an explicit option
116
+ * wins.
117
+ */
118
+ export interface ServeVgiWorkerOptions extends HostingOptions, BlobVendorHttpConfig {
75
119
  /** Short worker name shown on the landing page, e.g. "ishares". */
76
120
  name: string;
77
121
  /** One-line description of what the worker serves. */
@@ -100,7 +144,7 @@ export interface ServeVgiWorkerOptions extends HostingOptions {
100
144
  * `attach_opaque_data` for `attachOptions()`). Defaults to the signing key.
101
145
  */
102
146
  attachSecretKey?: Uint8Array | undefined;
103
- /** Overrides `$VGI_TOKEN_TTL` (default 3600 seconds). */
147
+ /** Overrides `$VGI_TOKEN_TTL` (default 21600 seconds, 6 h). */
104
148
  tokenTtl?: number | undefined;
105
149
  /** Overrides `$CORS_ORIGINS` (default "*"). Pass `null` to disable CORS. */
106
150
  corsOrigins?: string | null | undefined;
@@ -253,6 +297,11 @@ export function createVgiWorkerFetch(
253
297
  opts: ServeVgiWorkerOptions,
254
298
  ): (req: Request) => Promise<Response> {
255
299
  const env = opts.env ?? (process.env as ServeEnv);
300
+ const argv = opts.argv ?? process.argv.slice(2);
301
+ // Orchard hosted mode is checked first, before the signing key is parsed or
302
+ // grant keys are read, so every misconfiguration surfaces as a hosted-mode
303
+ // refusal rather than whatever error the generic path would raise.
304
+ const orchardHosted = resolveServeHostedMode(opts, env, argv);
256
305
  const signingKey = resolveSigningKey(
257
306
  typeof opts.signingKey === "string" ? parseSigningKeyHex(opts.signingKey) : opts.signingKey,
258
307
  env,
@@ -274,13 +323,20 @@ export function createVgiWorkerFetch(
274
323
  );
275
324
  }
276
325
  const trustedProxyAddresses = bridge?.trustedProxyAddresses ?? ["127.0.0.1"];
326
+ const blobVendor = blobVendorHttpConfigFromEnv(env);
277
327
 
278
328
  return createVgiFetch({
329
+ externalLocation: opts.externalLocation ?? blobVendor.externalLocation,
330
+ uploadUrlProvider: opts.uploadUrlProvider ?? blobVendor.uploadUrlProvider,
331
+ maxRequestBytes: opts.maxRequestBytes ?? blobVendor.maxRequestBytes,
332
+ maxUploadBytes: opts.maxUploadBytes ?? blobVendor.maxUploadBytes,
279
333
  protocol: { registry: opts.registry, catalogInterface: opts.catalogInterface, attachSecretKey: opts.attachSecretKey },
280
334
  signingKey,
281
335
  signingKeyConfigured,
282
336
  storageSealKey,
283
337
  tokenTtl,
338
+ cursorRule: "error",
339
+ env: env as Readonly<Record<string, string | undefined>>,
284
340
  prefix: opts.prefix ?? "",
285
341
  serverId: opts.serverId ?? opts.name,
286
342
  corsOrigins,
@@ -299,14 +355,44 @@ export function createVgiWorkerFetch(
299
355
  mintGrant: opts.mintGrant,
300
356
  introspectPrincipals: opts.introspectPrincipals,
301
357
  maxAuthAge: opts.maxAuthAge,
302
- grantKeys:
303
- opts.grantKeys !== undefined
358
+ grantKeys: orchardHosted
359
+ ? undefined
360
+ : opts.grantKeys !== undefined
304
361
  ? opts.grantKeys
305
- : (grantKeysFromArgv(opts.argv ?? process.argv.slice(2), env as Record<string, string | undefined>) ??
362
+ : (grantKeysFromArgv(argv, env as Record<string, string | undefined>) ??
306
363
  GrantKeys.fromEnv(env as Record<string, string | undefined>)),
364
+ orchardHosted,
307
365
  });
308
366
  }
309
367
 
368
+ /**
369
+ * Orchard hosted mode for {@link createVgiWorkerFetch}: `undefined` when
370
+ * `VGI_ORCHARD_HOSTED` is off, else the validated configuration once every
371
+ * check has passed. Throws {@link OrchardHostedConfigError}.
372
+ */
373
+ function resolveServeHostedMode(
374
+ opts: ServeVgiWorkerOptions,
375
+ env: ServeEnv,
376
+ argv: readonly string[],
377
+ ): HostedConfig | undefined {
378
+ const hostedEnv = env as Record<string, string | undefined>;
379
+ if (!hostedModeEnabled(hostedEnv)) return undefined;
380
+ checkHostedSigningKey(hostedEnv, opts.signingKey);
381
+ checkHostedEnvironment(hostedEnv);
382
+ if (opts.grantKeys !== undefined && opts.grantKeys !== null) {
383
+ throw new OrchardHostedConfigError("sealed-grant keys (grantKeys) are configured.");
384
+ }
385
+ if (argv.some((a) => a === "--grant-key" || a.startsWith("--grant-key="))) {
386
+ throw new OrchardHostedConfigError("sealed-grant keys (--grant-key) are configured.");
387
+ }
388
+ if (opts.irohBridge) {
389
+ throw new OrchardHostedConfigError("an Iroh HTTP bridge (peer identity) is configured; hosted workers accept Passes only.");
390
+ }
391
+ // authenticate / resolveToken / mintGrant / peer identity are refused by
392
+ // createVgiFetch, which sees the same options.
393
+ return resolveHostedConfig(hostedEnv);
394
+ }
395
+
310
396
  /**
311
397
  * Serve a VGI worker over HTTP on Bun and return the running server.
312
398
  *
@@ -345,7 +431,18 @@ export function serveVgiWorker(opts: ServeVgiWorkerOptions): VgiHttpServer {
345
431
  },
346
432
  }
347
433
  : opts.irohBridge;
348
- const fetch = createVgiWorkerFetch({ ...opts, irohBridge: bridge });
434
+ let fetch: (req: Request) => Promise<Response>;
435
+ try {
436
+ fetch = createVgiWorkerFetch({ ...opts, irohBridge: bridge });
437
+ } catch (error) {
438
+ // A hosted-mode refusal is an operator error with one fix, not a crash:
439
+ // say what is wrong and exit non-zero, without a stack trace.
440
+ if (error instanceof OrchardHostedConfigError) {
441
+ process.stderr.write(`Error: ${error.message}\n`);
442
+ process.exit(1);
443
+ }
444
+ throw error;
445
+ }
349
446
  server = runtime.serve({ port, hostname, fetch });
350
447
 
351
448
  if (!opts.quiet) {
@@ -15,7 +15,40 @@
15
15
 
16
16
  export { createVgiFetch } from "./http/fetch.js";
17
17
  export type { VgiFetchOptions } from "./http/fetch.js";
18
+ // Blob vendor: spread blobVendorHttpConfigFromEnv(env) into createVgiFetch, and
19
+ // wrap the Durable Object storage with wrapStorageFromEnv(cfDo, { maxValueBytes:
20
+ // CF_DO_MAX_VALUE_BYTES, env }) before setStorage, so both read the Worker's env.
21
+ export { blobVendorHttpConfigFromEnv } from "./http/blob-vendor.js";
22
+ export type { BlobVendorEnv, BlobVendorHttpConfig } from "./http/blob-vendor.js";
23
+ export {
24
+ FunctionStorageCfDo,
25
+ CF_DO_MAX_VALUE_BYTES,
26
+ ExternalizingStorage,
27
+ wrapStorageFromEnv,
28
+ setStorage,
29
+ StorageBlobError,
30
+ StorageBlobIntegrityError,
31
+ StorageBlobMissingError,
32
+ StorageEnvelopeError,
33
+ StorageValueTooLargeError,
34
+ } from "./index.core.js";
18
35
  export type { HostingOptions } from "./rpc-server.js";
36
+ // Orchard hosted mode (VGI_ORCHARD_HOSTED=1): Pass-only HTTP serving. See
37
+ // docs/orchard-hosted.md.
38
+ export {
39
+ HOSTED_ENV,
40
+ HOSTED_CHALLENGE,
41
+ HOSTED_AUTH_DOMAIN,
42
+ OrchardHostedConfigError,
43
+ hostedModeEnabled,
44
+ resolveHostedConfig,
45
+ orchardHostedFromEnv,
46
+ checkHostedEnvironment,
47
+ checkHostedSigningKey,
48
+ type HostedConfig,
49
+ type HostedEnv,
50
+ } from "./hosted.js";
51
+ export { hostedAuthenticate, isHostedAuthenticate, type HostedVerifierDeps } from "./http/hosted-auth.js";
19
52
  export {
20
53
  AuthUnavailableError,
21
54
  GrantKeys,
package/src/worker.ts CHANGED
@@ -19,6 +19,7 @@ import { schemaDescriptorPath, type CatalogDescriptor } from "./catalog/descript
19
19
  import type { CatalogInterface } from "./catalog/interface.js";
20
20
  import { ReadOnlyCatalogInterface } from "./catalog/read-only.js";
21
21
  import { checkReservedAttachOptions } from "./catalog/attach-option.js";
22
+ import { hostedModeEnabled, OrchardHostedConfigError, refuseNonHttpTransportInHostedMode } from "./hosted.js";
22
23
 
23
24
  /**
24
25
  * Startup/lifecycle tracing, off unless `VGI_DEBUG` is set to something other
@@ -71,6 +72,20 @@ function parseTcpSpec(spec: string, out: LauncherArgs): void {
71
72
  }
72
73
  }
73
74
 
75
+ /** The transport `run()` would serve for `argv`, as named in a refusal. */
76
+ function transportName(argv: readonly string[]): string {
77
+ let launcher: LauncherArgs;
78
+ try {
79
+ launcher = parseLauncherArgs(argv);
80
+ } catch {
81
+ return "requested";
82
+ }
83
+ if (launcher.irohRawUpstream) return "--iroh-raw-upstream";
84
+ if (launcher.unixPath !== undefined) return "--unix";
85
+ if (launcher.tcpPort !== undefined) return "--tcp";
86
+ return "stdio";
87
+ }
88
+
74
89
  function parseLauncherArgs(argv: readonly string[]): LauncherArgs {
75
90
  const out: LauncherArgs = { irohTrustedProxyAddresses: [], irohAuthenticate: true };
76
91
  for (let i = 0; i < argv.length; i++) {
@@ -193,6 +208,15 @@ export class Worker {
193
208
 
194
209
  run(argv: readonly string[] = process.argv.slice(2)): void {
195
210
  debug(() => `[worker] starting, pid=${process.pid}`);
211
+ // Orchard hosted mode serves HTTP only (serveVgiWorker); every transport
212
+ // run() offers -- stdio, --unix, --tcp, --iroh-raw-upstream -- carries no Pass.
213
+ try {
214
+ if (hostedModeEnabled()) refuseNonHttpTransportInHostedMode(transportName(argv));
215
+ } catch (err) {
216
+ if (!(err instanceof OrchardHostedConfigError)) throw err;
217
+ process.stderr.write(`Error: ${err.message}\n`);
218
+ process.exit(1);
219
+ }
196
220
  // Refuse to serve a catalog that declares the reserved `vgi_attach_ticket`
197
221
  // attach option, before anything is read off the transport.
198
222
  checkReservedAttachOptions(this._catalogInterface).then(
@@ -330,6 +354,7 @@ export class Worker {
330
354
  readable: ReadableStream<Uint8Array> | NodeJS.ReadableStream,
331
355
  writable?: number | import("node:net").Socket | import("@query-farm/vgi-rpc").ByteSink,
332
356
  ): Promise<void> {
357
+ refuseNonHttpTransportInHostedMode("byte-stream");
333
358
  await serveStreamRpc(this.buildServer(this.buildProtocol(), "stream"), omitUndefined({ readable, writable }));
334
359
  }
335
360
  }