@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
@@ -0,0 +1,326 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Orchard hosted mode: the Pass verifier and the request gate.
3
+ //
4
+ // The verifier checks an RFC 9068 JWT access token against the Front Desk's
5
+ // JWKS with `jose` (Web Crypto based, so the same code runs on Node, Bun and
6
+ // Cloudflare Workers; no `node:*` imports here). The JWKS cache is our own,
7
+ // not `createRemoteJWKSet`, because the contract pins behaviour jose's cache
8
+ // does not have: a hard 10-minute lifetime that a shorter
9
+ // `Cache-Control: max-age` lowers, keys discarded (never reused stale) once it
10
+ // passes, a failed re-fetch answered as 503 rather than 401, and unknown-`kid`
11
+ // re-fetches limited to one per minute.
12
+ //
13
+ // The gate sits in front of vgi-rpc's HTTP handler. It authenticates every
14
+ // request except `HEAD /health` and CORS preflights *before* the handler sees
15
+ // it, so the body is never read, size-checked or decompressed for a caller
16
+ // without a Pass, and the landing page, describe page, `GET /health` and
17
+ // unknown paths (which vgi-rpc serves without consulting `authenticate`) all
18
+ // need one too. Its 401 carries `WWW-Authenticate: Bearer
19
+ // error="invalid_token"`, `VGI-Auth-Reason` and the usual VGI capability
20
+ // headers. The `Authorization` header is never logged.
21
+
22
+ import { createLocalJWKSet, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from "jose";
23
+ import {
24
+ AUTH_REASON_HEADER,
25
+ AuthContext,
26
+ AuthFailure,
27
+ AuthReason,
28
+ AuthUnavailableError,
29
+ type AuthenticateFn,
30
+ } from "@query-farm/vgi-rpc";
31
+ import {
32
+ HOSTED_AUTH_DOMAIN,
33
+ HOSTED_CHALLENGE,
34
+ JWKS_FETCH_TIMEOUT_SECONDS,
35
+ JWKS_MAX_AGE_SECONDS,
36
+ JWKS_REFRESH_MIN_INTERVAL_SECONDS,
37
+ LEEWAY_SECONDS,
38
+ REQUIRED_TYP,
39
+ type HostedConfig,
40
+ } from "../hosted.js";
41
+
42
+ /** The slice of `fetch` the JWKS client uses. */
43
+ export type JwksFetch = (url: string, init: RequestInit) => Promise<Response>;
44
+
45
+ /** Injection points for tests. Production uses the global `fetch` and clock. */
46
+ export interface HostedVerifierDeps {
47
+ /** Fetch used for the JWKS (default `globalThis.fetch`). */
48
+ fetch?: JwksFetch | undefined;
49
+ /** Clock, milliseconds since the epoch (default `Date.now`). */
50
+ now?: (() => number) | undefined;
51
+ /** Operator warnings (JWKS failures). Never receives a credential. Default `console.error`. */
52
+ warn?: ((message: string) => void) | undefined;
53
+ /** Debug lines (per-request rejections). Never receives a credential. Default: off. */
54
+ debug?: ((message: string) => void) | undefined;
55
+ }
56
+
57
+ const HOSTED_MARK: unique symbol = Symbol.for("@query-farm/vgi.orchard-hosted-authenticate");
58
+
59
+ const MAX_AGE_RE = /(?:^|,)\s*max-age\s*=\s*"?(\d+)"?\s*(?=,|$)/i;
60
+
61
+ /** The `max-age` directive of a `Cache-Control` header, seconds, or `null`. */
62
+ export function cacheControlMaxAge(value: string | null | undefined): number | null {
63
+ if (!value) return null;
64
+ const match = MAX_AGE_RE.exec(value);
65
+ return match ? Number(match[1]) : null;
66
+ }
67
+
68
+ /** Media types compare case-insensitively; `application/` is optional (RFC 9068 §2.1). */
69
+ function normalizeTyp(value: string): string {
70
+ const lowered = value.trim().toLowerCase();
71
+ return lowered.startsWith("application/") ? lowered.slice("application/".length) : lowered;
72
+ }
73
+
74
+ function errorCode(error: unknown): string {
75
+ const code = (error as { code?: unknown } | null)?.code;
76
+ return typeof code === "string" ? code : error instanceof Error ? error.name : "unknown";
77
+ }
78
+
79
+ interface CachedKeys {
80
+ readonly keys: JWTVerifyGetKey;
81
+ /** Epoch ms at which the keys stop being usable. */
82
+ readonly expiresAt: number;
83
+ }
84
+
85
+ /**
86
+ * Build the Pass verifier for `config`: an `AuthenticateFn` returning an
87
+ * `AuthContext` with domain `"orchard"`, principal `sub` and the Pass's claims
88
+ * exactly as decoded (booleans stay booleans, numbers stay numbers).
89
+ *
90
+ * It throws `AuthFailure` (401) with reason `missing_credential`,
91
+ * `invalid_credential` or `expired_credential`, and `AuthUnavailableError`
92
+ * (503 with `Retry-After`) when no JWKS within its maximum age can be fetched.
93
+ */
94
+ export function hostedAuthenticate(config: HostedConfig, deps: HostedVerifierDeps = {}): AuthenticateFn {
95
+ const doFetch: JwksFetch = deps.fetch ?? ((url, init) => globalThis.fetch(url, init));
96
+ const now = deps.now ?? Date.now;
97
+ const warn = deps.warn ?? ((m: string) => console.error(m));
98
+ const debug = deps.debug;
99
+ const algorithms = [...config.algorithms];
100
+
101
+ let cache: CachedKeys | null = null;
102
+ let inflight: Promise<JWTVerifyGetKey> | null = null;
103
+ let lastFetchAttempt: number | null = null;
104
+
105
+ const usable = (entry: CachedKeys | null, at: number): entry is CachedKeys => entry !== null && at < entry.expiresAt;
106
+
107
+ async function fetchOnce(): Promise<JWTVerifyGetKey> {
108
+ const started = now();
109
+ lastFetchAttempt = started;
110
+ try {
111
+ // No redirects: the JWKS URI is configuration, and following one would
112
+ // let whoever controls the redirect choose the keys.
113
+ const response = await doFetch(config.jwksUri, {
114
+ headers: { Accept: "application/json" },
115
+ redirect: "manual",
116
+ signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_SECONDS * 1000),
117
+ });
118
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
119
+ const keys = createLocalJWKSet(await response.json());
120
+ const advertised = cacheControlMaxAge(response.headers.get("cache-control"));
121
+ const ttl = advertised === null ? JWKS_MAX_AGE_SECONDS : Math.min(JWKS_MAX_AGE_SECONDS, advertised);
122
+ // Measured from when the fetch started, so a slow response cannot
123
+ // stretch the bound.
124
+ cache = { keys, expiresAt: started + ttl * 1000 };
125
+ return keys;
126
+ } catch (error) {
127
+ // Never fall back to stale keys: drop an expired entry so nothing can
128
+ // read it, and make the caller fail closed (503, not 401).
129
+ if (!usable(cache, now())) cache = null;
130
+ warn(`[vgi] Orchard hosted mode: JWKS fetch failed (${errorCode(error)})`);
131
+ throw new AuthUnavailableError("JWKS endpoint unavailable", 5);
132
+ }
133
+ }
134
+
135
+ /** One fetch at a time; concurrent callers share it. */
136
+ function fetchKeys(): Promise<JWTVerifyGetKey> {
137
+ if (inflight) return inflight;
138
+ const pending = fetchOnce();
139
+ inflight = pending;
140
+ pending.then(
141
+ () => { if (inflight === pending) inflight = null; },
142
+ () => { if (inflight === pending) inflight = null; },
143
+ );
144
+ return pending;
145
+ }
146
+
147
+ /** Keys within their maximum age, fetching when there are none. */
148
+ function currentKeys(): Promise<JWTVerifyGetKey> {
149
+ if (usable(cache, now())) return Promise.resolve(cache.keys);
150
+ cache = null;
151
+ return fetchKeys();
152
+ }
153
+
154
+ /** Re-fetch after an unknown `kid`; `null` when rate limited. A refresh
155
+ * another request already made is reused instead of stampeding the JWKS
156
+ * endpoint during a key rotation. */
157
+ function refreshForUnknownKid(seen: JWTVerifyGetKey): Promise<JWTVerifyGetKey> | null {
158
+ const at = now();
159
+ if (usable(cache, at) && cache.keys !== seen) return Promise.resolve(cache.keys);
160
+ if (inflight) return inflight;
161
+ if (lastFetchAttempt !== null && at - lastFetchAttempt < JWKS_REFRESH_MIN_INTERVAL_SECONDS * 1000) return null;
162
+ return fetchKeys();
163
+ }
164
+
165
+ async function verifyWith(token: string, keys: JWTVerifyGetKey): Promise<JWTPayload> {
166
+ const { payload, protectedHeader } = await jwtVerify(token, keys, {
167
+ algorithms,
168
+ issuer: config.issuer,
169
+ audience: config.audience,
170
+ clockTolerance: LEEWAY_SECONDS,
171
+ requiredClaims: ["exp"],
172
+ currentDate: new Date(now()),
173
+ });
174
+ const typ = protectedHeader.typ;
175
+ if (typeof typ !== "string" || normalizeTyp(typ) !== REQUIRED_TYP) {
176
+ throw new AuthFailure(AuthReason.InvalidCredential, `JOSE header 'typ' must be '${REQUIRED_TYP}'`);
177
+ }
178
+ // Exactly one audience: a Pass names one Desk Address. A token naming
179
+ // several is refused even if one of them is ours.
180
+ const aud = payload.aud;
181
+ if (!(typeof aud === "string" || (Array.isArray(aud) && aud.length === 1))) {
182
+ throw new AuthFailure(AuthReason.InvalidCredential, "Pass must name exactly one audience");
183
+ }
184
+ return payload;
185
+ }
186
+
187
+ function reject(error: unknown): AuthFailure {
188
+ if (error instanceof AuthFailure) return error;
189
+ const code = errorCode(error);
190
+ const reason = code === "ERR_JWT_EXPIRED" ? AuthReason.ExpiredCredential : AuthReason.InvalidCredential;
191
+ debug?.(`[vgi] Orchard hosted mode: Pass rejected (${reason}: ${code})`);
192
+ return new AuthFailure(reason, "invalid Pass");
193
+ }
194
+
195
+ const authenticate = async function orchardHostedAuthenticate(request: Request): Promise<AuthContext> {
196
+ const header = request.headers.get("Authorization") ?? "";
197
+ if (!header.trim()) {
198
+ debug?.("[vgi] Orchard hosted mode: request without a Pass");
199
+ throw new AuthFailure(AuthReason.MissingCredential, "Missing Authorization header");
200
+ }
201
+ // The scheme is case-insensitive (RFC 9110 §11.1).
202
+ const match = /^bearer +(\S+) *$/i.exec(header);
203
+ if (!match) {
204
+ // Worded so no log line ever reads "Bearer <something>", which a leak
205
+ // scanner rightly treats as a logged credential.
206
+ debug?.("[vgi] Orchard hosted mode: Pass rejected (invalid_credential: unsupported Authorization scheme)");
207
+ throw new AuthFailure(AuthReason.InvalidCredential, "Authorization header is not a Bearer credential");
208
+ }
209
+ const token = match[1]!;
210
+
211
+ const keys = await currentKeys();
212
+ let claims: JWTPayload;
213
+ try {
214
+ claims = await verifyWith(token, keys);
215
+ } catch (error) {
216
+ if (errorCode(error) !== "ERR_JWKS_NO_MATCHING_KEY") throw reject(error);
217
+ // Unknown kid: refresh the JWKS (rate limited) and retry once. A failed
218
+ // refresh is an AuthUnavailableError (503), not a rejection.
219
+ const refreshed = refreshForUnknownKid(keys);
220
+ if (refreshed === null) throw reject(error);
221
+ const fresh = await refreshed;
222
+ try {
223
+ claims = await verifyWith(token, fresh);
224
+ } catch (retryError) {
225
+ throw reject(retryError);
226
+ }
227
+ }
228
+ const principal = typeof claims.sub === "string" ? claims.sub : String(claims.sub ?? "");
229
+ return new AuthContext(HOSTED_AUTH_DOMAIN, true, principal, { ...claims });
230
+ };
231
+ Object.defineProperty(authenticate, HOSTED_MARK, { value: true });
232
+ return authenticate;
233
+ }
234
+
235
+ /** Whether `fn` was built by {@link hostedAuthenticate}. */
236
+ export function isHostedAuthenticate(fn: unknown): boolean {
237
+ return typeof fn === "function" && (fn as unknown as Record<symbol, unknown>)[HOSTED_MARK] === true;
238
+ }
239
+
240
+ /** Headers of the capability probe that do not belong on a 401/503. */
241
+ const PROBE_HEADERS_DROPPED: ReadonlySet<string> = new Set(["content-type", "content-length", "x-request-id"]);
242
+
243
+ /** A hosted gate: the verifier, the `authenticate` to hand vgi-rpc, and the wrapper. */
244
+ export interface HostedGate {
245
+ /** The Pass verifier. */
246
+ readonly verify: AuthenticateFn;
247
+ /**
248
+ * The `authenticate` to give `createHttpHandler`. It returns the identity
249
+ * the gate already verified for this request (re-verifying only if the
250
+ * handler was given a different `Request` object), so a Pass is checked
251
+ * once per request.
252
+ */
253
+ readonly authenticate: AuthenticateFn;
254
+ /** Put the gate in front of a vgi-rpc HTTP handler mounted at `prefix`. */
255
+ wrap(handler: (req: Request) => Promise<Response> | Response, prefix: string): (req: Request) => Promise<Response>;
256
+ }
257
+
258
+ /** Build the hosted-mode request gate for `config`. */
259
+ export function createHostedGate(config: HostedConfig, deps: HostedVerifierDeps = {}): HostedGate {
260
+ const verify = hostedAuthenticate(config, deps);
261
+ const verified = new WeakMap<Request, AuthContext>();
262
+ const authenticate: AuthenticateFn = async (request) => verified.get(request) ?? (await verify(request));
263
+ Object.defineProperty(authenticate, HOSTED_MARK, { value: true });
264
+
265
+ function wrap(handler: (req: Request) => Promise<Response> | Response, prefix: string) {
266
+ const healthPath = `${prefix}/health`;
267
+ let probe: Array<[string, string]> | undefined;
268
+
269
+ /** The capability (and CORS) headers the handler puts on `HEAD /health`.
270
+ * They depend only on configuration, so they are read once. */
271
+ async function capabilityHeaders(request: Request): Promise<Array<[string, string]>> {
272
+ if (probe) return probe;
273
+ const url = new URL(request.url);
274
+ url.pathname = healthPath;
275
+ url.search = "";
276
+ const response = await handler(new Request(url, { method: "HEAD" }));
277
+ const headers: Array<[string, string]> = [];
278
+ response.headers.forEach((value, name) => {
279
+ if (!PROBE_HEADERS_DROPPED.has(name.toLowerCase())) headers.push([name, value]);
280
+ });
281
+ probe = headers;
282
+ return headers;
283
+ }
284
+
285
+ async function refusal(error: unknown, request: Request): Promise<Response> {
286
+ const headers = new Headers();
287
+ for (const [name, value] of await capabilityHeaders(request)) headers.set(name, value);
288
+ headers.set("Content-Type", "application/json");
289
+ headers.set("Cache-Control", "no-store");
290
+ if (error instanceof AuthUnavailableError) {
291
+ const retryAfter = Number.isFinite(error.retryAfter) && error.retryAfter >= 0 ? Math.ceil(error.retryAfter) : 5;
292
+ headers.set("Retry-After", String(retryAfter));
293
+ const body = { error: "authentication_unavailable", detail: "authentication authority unavailable" };
294
+ return new Response(JSON.stringify(body), { status: 503, headers });
295
+ }
296
+ // Anything that is not a classified rejection (a bug in the verifier)
297
+ // still fails closed, as an invalid credential.
298
+ const reason = error instanceof AuthFailure ? error.reason : AuthReason.InvalidCredential;
299
+ headers.set("WWW-Authenticate", HOSTED_CHALLENGE);
300
+ headers.set(AUTH_REASON_HEADER, reason);
301
+ const body = { error: "unauthorized", reason, detail: "authentication rejected" };
302
+ return new Response(JSON.stringify(body), { status: 401, headers });
303
+ }
304
+
305
+ return async function orchardHostedGate(request: Request): Promise<Response> {
306
+ const pathname = new URL(request.url).pathname;
307
+ const path = pathname.includes("//") ? pathname.replace(/\/{2,}/g, "/") : pathname;
308
+ // The Front Desk's liveness probe, and CORS preflights (which browsers
309
+ // send without credentials), are the only anonymous requests.
310
+ if (request.method === "HEAD" && path === healthPath) return handler(request);
311
+ if (request.method === "OPTIONS" && request.headers.has("Access-Control-Request-Method")) {
312
+ return handler(request);
313
+ }
314
+ let auth: AuthContext;
315
+ try {
316
+ auth = await verify(request);
317
+ } catch (error) {
318
+ return refusal(error, request);
319
+ }
320
+ verified.set(request, auth);
321
+ return handler(request);
322
+ };
323
+ }
324
+
325
+ return { verify, authenticate, wrap };
326
+ }
package/src/index.core.ts CHANGED
@@ -130,6 +130,7 @@ export {
130
130
 
131
131
  // Protocol types
132
132
  export type {
133
+ ArgumentsLocation,
133
134
  BindRequest,
134
135
  BindResponse,
135
136
  BindRepeatability,
@@ -139,6 +140,24 @@ export type {
139
140
  GlobalInitResponse,
140
141
  TableCardinality,
141
142
  } from "./protocol/types.js";
143
+ // Protocol 3.4 argument references: the bind call's raw-preserving decode and
144
+ // the resolution every request entry runs (vgi docs/large-values-3.4.md §5a).
145
+ export { decodeBindCall, bindCallBytes, receivedBindCall } from "./protocol/serializers/bind.js";
146
+ export {
147
+ resolveBindCall,
148
+ argumentsResolved,
149
+ argumentsRefBytesFromEnv,
150
+ argumentsRefHeaderValue,
151
+ ARGUMENTS_REF_BYTES_HEADER,
152
+ ARGUMENTS_REF_BYTES_ENV,
153
+ DEFAULT_ARGUMENTS_REF_BYTES,
154
+ DISABLE_ARGUMENTS_REF_ENV,
155
+ ARGUMENTS_REF_MISSING_KIND,
156
+ ARGUMENTS_REF_MISSING_MESSAGE,
157
+ INVALID_BIND_REQUEST_KIND,
158
+ INVALID_BIND_REQUEST_MESSAGE,
159
+ INVALID_ARGUMENTS_REF_KIND,
160
+ } from "./protocol/arguments-ref.js";
142
161
  export type {
143
162
  ScanSplit,
144
163
  PlanResult,
@@ -321,6 +340,8 @@ export {
321
340
  normalizeRequiredSecrets,
322
341
  } from "./secrets/requirements.js";
323
342
 
343
+ export type { SecretLookupFields } from "./secrets/lookups.js";
344
+
324
345
  export {
325
346
  serializeSchema,
326
347
  deserializeSchema,
@@ -415,7 +436,33 @@ export {
415
436
  shardKeyOf,
416
437
  storage as functionStorage,
417
438
  } from "./functions/storage.js";
418
- export { FunctionStorageCfDo, type FetchLike, type CfDoRetryOptions } from "./functions/storage-cf-do.js";
439
+ export {
440
+ FunctionStorageCfDo,
441
+ MAX_VALUE_BYTES as CF_DO_MAX_VALUE_BYTES,
442
+ type FetchLike,
443
+ type CfDoRetryOptions,
444
+ } from "./functions/storage-cf-do.js";
445
+ // Value envelope + blob-vendor externalization over any FunctionStorage.
446
+ export {
447
+ ExternalizingStorage,
448
+ type ExternalizingStorageOptions,
449
+ StorageBlobError,
450
+ StorageBlobIntegrityError,
451
+ StorageBlobMissingError,
452
+ StorageEnvelopeError,
453
+ StorageValueTooLargeError,
454
+ DEFAULT_EXTERNALIZE_BYTES,
455
+ blobClientFromEnv,
456
+ externalizeBytesFromEnv,
457
+ wrapStorageFromEnv,
458
+ type WrapStorageOptions,
459
+ } from "./functions/storage-blobs.js";
460
+ // HTTP server settings from the blob-vendor environment.
461
+ export {
462
+ blobVendorHttpConfigFromEnv,
463
+ type BlobVendorEnv,
464
+ type BlobVendorHttpConfig,
465
+ } from "./http/blob-vendor.js";
419
466
  export { StoragePayloadError } from "./functions/storage-seal.js";
420
467
 
421
468
  // Client
@@ -460,6 +507,22 @@ export {
460
507
  StatusError,
461
508
  } from "@query-farm/vgi-rpc";
462
509
  export type { GrantMinter, IssuedGrant, TokenIdentity, TokenResolver } from "@query-farm/vgi-rpc";
510
+ // Orchard hosted mode (VGI_ORCHARD_HOSTED=1): Pass-only HTTP serving. See
511
+ // docs/orchard-hosted.md.
512
+ export {
513
+ HOSTED_ENV,
514
+ HOSTED_CHALLENGE,
515
+ HOSTED_AUTH_DOMAIN,
516
+ OrchardHostedConfigError,
517
+ hostedModeEnabled,
518
+ resolveHostedConfig,
519
+ orchardHostedFromEnv,
520
+ checkHostedEnvironment,
521
+ checkHostedSigningKey,
522
+ type HostedConfig,
523
+ type HostedEnv,
524
+ } from "./hosted.js";
525
+ export { hostedAuthenticate, isHostedAuthenticate, type HostedVerifierDeps } from "./http/hosted-auth.js";
463
526
  export { normalizeSchemaPath, schemaPathDisplay, schemaPathKey, schemaPathsEqual, type SchemaPath } from "./schema-path.js";
464
527
 
465
528
  // Optional scalar projection negotiation and its explicit offer.
@@ -0,0 +1,260 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Argument references (protocol 3.4): resolving `BindRequest.arguments_location`.
3
+ //
4
+ // A client binding a function with a large argument over HTTP uploads the
5
+ // arguments once, through this worker's `__upload_url__` grant, and sends a
6
+ // BindRequest whose `arguments` is null and whose `arguments_location` carries
7
+ // the grant's sealed `ref` plus the upload's size and SHA-256 (vgi
8
+ // docs/large-values-3.4.md §2, §5a). Every request embedding that bind call
9
+ // (cardinality, statistics, plan, projection, dynamic-to-string, init) carries
10
+ // the small location, never the value.
11
+ //
12
+ // The framework resolves the location once per request, at its entry (where a
13
+ // call context exists), and hands function code a bind call whose `arguments`
14
+ // holds the resolved value -- so code reading `bindCall.arguments` keeps
15
+ // working. That bind call still re-encodes as the bytes the client sent
16
+ // (serializers/bind.ts `bindCallBytes`), so the reference, never the value,
17
+ // goes back on the wire, into stream state or into table-buffering storage.
18
+ // vgi-rpc does the opening, the object cache (one `get` per object id per
19
+ // process, single-flight) and the size / SHA-256 checks.
20
+ //
21
+ // A worker advertises support with the `VGI-Arguments-Ref-Bytes` capability
22
+ // header ({@link argumentsRefHeaderValue}); without it the extension never
23
+ // externalizes arguments.
24
+
25
+ import { StatusError, isObjectStore } from "@query-farm/vgi-rpc";
26
+ import { Arguments } from "../arguments/arguments.js";
27
+ import { deserializeArguments } from "./serializers/arguments.js";
28
+ import type { BindRequest } from "./types.js";
29
+
30
+ /** The capability header telling the client this worker accepts argument references, and above how many bytes of arguments IPC to use one. */
31
+ export const ARGUMENTS_REF_BYTES_HEADER = "VGI-Arguments-Ref-Bytes";
32
+ /** Operator override of the advertised value. */
33
+ export const ARGUMENTS_REF_BYTES_ENV = "VGI_ARGUMENTS_REF_BYTES";
34
+ /** The default advertised value: 4 MiB. */
35
+ export const DEFAULT_ARGUMENTS_REF_BYTES = 4 * 1024 * 1024;
36
+ /**
37
+ * Test switch: the HTTP server stops sending the header (the extension's
38
+ * `arguments_ref_fallback.test`), behaving like a worker without argument
39
+ * references while still vending upload URLs.
40
+ */
41
+ export const DISABLE_ARGUMENTS_REF_ENV = "VGI_TEST_DISABLE_ARGUMENTS_REF";
42
+
43
+ /** Kind of the refusal for a bind that does not set exactly one of `arguments` / `arguments_location`. */
44
+ export const INVALID_BIND_REQUEST_KIND = "invalid_bind_request";
45
+ /** Its exact message (large-values spec §2). */
46
+ export const INVALID_BIND_REQUEST_MESSAGE = "BindRequest must set exactly one of 'arguments' and 'arguments_location'";
47
+ /** Kind of the refusal for a malformed or unopenable argument reference. */
48
+ export const INVALID_ARGUMENTS_REF_KIND = "invalid_arguments_ref";
49
+ /** Kind of the refusal for an argument object storage reports gone. */
50
+ export const ARGUMENTS_REF_MISSING_KIND = "arguments_ref_missing";
51
+ /**
52
+ * The exact message for it (large-values spec §5a, "Prepared statements"):
53
+ * argument objects live about a day, so a prepared statement's large argument
54
+ * can expire, and there is no transparent rebind. Same text as vgi-python.
55
+ */
56
+ export const ARGUMENTS_REF_MISSING_MESSAGE = "this prepared statement's large argument has expired; prepare it again";
57
+
58
+ const MAX_HEADER_DIGITS = 19;
59
+
60
+ /** `invalid_bind_request` (`INVALID_ARGUMENT`). */
61
+ export function invalidBindRequest(): StatusError {
62
+ return new StatusError(INVALID_BIND_REQUEST_MESSAGE, { code: "INVALID_ARGUMENT", kind: INVALID_BIND_REQUEST_KIND });
63
+ }
64
+
65
+ /**
66
+ * `invalid_arguments_ref` (`INVALID_ARGUMENT`). The message names the kind
67
+ * too: a client that shows only "<type>: <message>" (the DuckDB extension)
68
+ * would otherwise never show the reason a caller can act on.
69
+ */
70
+ export function invalidArgumentsRef(message: string): StatusError {
71
+ return new StatusError(`${INVALID_ARGUMENTS_REF_KIND}: ${message}`, {
72
+ code: "INVALID_ARGUMENT",
73
+ kind: INVALID_ARGUMENTS_REF_KIND,
74
+ });
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // The unresolved placeholder
79
+ // ---------------------------------------------------------------------------
80
+
81
+ const placeholders = new WeakSet<object>();
82
+
83
+ function notResolved(): never {
84
+ throw new StatusError("BindRequest arguments are externalized (arguments_location) and were not resolved", {
85
+ code: "FAILED_PRECONDITION",
86
+ kind: "arguments_not_resolved",
87
+ });
88
+ }
89
+
90
+ /**
91
+ * The `arguments` of a bind call decoded with an `arguments_location`, until
92
+ * the framework resolves it. Every read throws `arguments_not_resolved`, so a
93
+ * path that forgot to resolve fails loudly instead of running the function
94
+ * with zero arguments (what a 3.3 worker silently did with a 3.4 bind).
95
+ */
96
+ export function unresolvedArguments(): Arguments {
97
+ const placeholder = Object.create(Arguments.prototype) as Arguments;
98
+ for (const key of ["positional", "named", "argumentsSchema", "length"]) {
99
+ Object.defineProperty(placeholder, key, { get: notResolved, enumerable: false });
100
+ }
101
+ Object.defineProperty(placeholder, "get", { value: notResolved, enumerable: false });
102
+ placeholders.add(placeholder);
103
+ return placeholder;
104
+ }
105
+
106
+ /** Whether `bindCall.arguments` holds a value (inline, or already resolved). */
107
+ export function argumentsResolved(bindCall: BindRequest): boolean {
108
+ return !placeholders.has(bindCall.arguments);
109
+ }
110
+
111
+ // ---------------------------------------------------------------------------
112
+ // Resolution
113
+ // ---------------------------------------------------------------------------
114
+
115
+ /** What resolution needs from a call context (vgi-rpc's CallContext, StreamInitContext and OutputCollector all have it). */
116
+ export interface ArgumentRefResolver {
117
+ resolveArgumentRef(ref: Uint8Array, location: { size: number; sha256: string }): Promise<Uint8Array>;
118
+ }
119
+
120
+ function errorKindOf(error: unknown): string {
121
+ if (error === null || typeof error !== "object") return "";
122
+ const own = (error as { errorKind?: unknown }).errorKind;
123
+ if (typeof own === "string") return own;
124
+ const ctor = (error as { constructor?: { errorKind?: unknown } }).constructor;
125
+ return typeof ctor?.errorKind === "string" ? ctor.errorKind : "";
126
+ }
127
+
128
+ /**
129
+ * Resolve a bind call's `arguments_location` in place, at the request's
130
+ * entry: open the sealed reference under this request's principal and check
131
+ * its size and SHA-256 equal the location's; look the object up in vgi-rpc's
132
+ * object cache by `object_id`; on a miss fetch it once (single-flight); verify
133
+ * its length and SHA-256; decode it as the arguments IPC stream.
134
+ *
135
+ * Only `arguments` changes; `arguments_location` and the received bytes stay,
136
+ * so the bind call still re-encodes as the reference. A bind call whose
137
+ * arguments came inline (or are already resolved) is returned untouched.
138
+ *
139
+ * @throws StatusError `invalid_arguments_ref` (`INVALID_ARGUMENT`) for a
140
+ * reference that does not open or match, no storage, or no context;
141
+ * `arguments_ref_integrity` (`DATA_LOSS`) for fetched bytes that differ;
142
+ * `arguments_ref_missing` (`NOT_FOUND`) with the prepared-statement message
143
+ * when storage reports the object gone. vgi-rpc's `storage_unavailable`
144
+ * passes through for transient storage failures.
145
+ */
146
+ export async function resolveBindCall<B extends BindRequest>(
147
+ bindCall: B,
148
+ ctx: ArgumentRefResolver | null | undefined,
149
+ ): Promise<B> {
150
+ if (argumentsResolved(bindCall)) return bindCall;
151
+ const location = bindCall.arguments_location;
152
+ if (location == null) notResolved();
153
+ if (!ctx || typeof ctx.resolveArgumentRef !== "function") {
154
+ throw invalidArgumentsRef("argument references need the request's context to resolve");
155
+ }
156
+ let data: Uint8Array;
157
+ try {
158
+ data = await ctx.resolveArgumentRef(location.ref, { size: location.size, sha256: location.sha256 });
159
+ } catch (error) {
160
+ const kind = errorKindOf(error);
161
+ if (kind === ARGUMENTS_REF_MISSING_KIND) {
162
+ throw new StatusError(ARGUMENTS_REF_MISSING_MESSAGE, { code: "NOT_FOUND", kind: ARGUMENTS_REF_MISSING_KIND });
163
+ }
164
+ if (kind === INVALID_ARGUMENTS_REF_KIND || kind === "arguments_ref_integrity") {
165
+ const message = error instanceof Error ? error.message : String(error);
166
+ throw new StatusError(message.startsWith(`${kind}:`) ? message : `${kind}: ${message}`, {
167
+ code: kind === INVALID_ARGUMENTS_REF_KIND ? "INVALID_ARGUMENT" : "DATA_LOSS",
168
+ kind,
169
+ });
170
+ }
171
+ throw error;
172
+ }
173
+ let args: Arguments;
174
+ try {
175
+ args = deserializeArguments(data);
176
+ } catch (error) {
177
+ // The bytes are exactly what the client uploaded and claimed (size and
178
+ // SHA-256 checked), so a bad stream is the client's.
179
+ throw invalidArgumentsRef(
180
+ `the uploaded arguments are not a valid arguments IPC stream: ${error instanceof Error ? error.message : String(error)}`,
181
+ );
182
+ }
183
+ bindCall.arguments = args;
184
+ return bindCall;
185
+ }
186
+
187
+ /** Resolve the bind call a request embeds (`request.bind_call`), in place. */
188
+ export async function resolveRequestArguments<R extends { bind_call: BindRequest }>(
189
+ request: R,
190
+ ctx: ArgumentRefResolver | null | undefined,
191
+ ): Promise<R> {
192
+ await resolveBindCall(request.bind_call, ctx);
193
+ return request;
194
+ }
195
+
196
+ // ---------------------------------------------------------------------------
197
+ // The capability header
198
+ // ---------------------------------------------------------------------------
199
+
200
+ type EnvLike = Readonly<Record<string, string | undefined>>;
201
+
202
+ function processEnv(): EnvLike {
203
+ return (globalThis as { process?: { env?: EnvLike } }).process?.env ?? {};
204
+ }
205
+
206
+ /**
207
+ * The `VGI-Arguments-Ref-Bytes` value to advertise: `VGI_ARGUMENTS_REF_BYTES`
208
+ * when set, else 4 MiB.
209
+ *
210
+ * @throws Error when the variable is not a positive decimal integer of at most
211
+ * 19 digits (the header's grammar), so a typo stops startup instead of
212
+ * silently advertising nothing.
213
+ */
214
+ export function argumentsRefBytesFromEnv(env: EnvLike = processEnv()): number {
215
+ const raw = (env[ARGUMENTS_REF_BYTES_ENV] ?? "").trim();
216
+ if (!raw) return DEFAULT_ARGUMENTS_REF_BYTES;
217
+ if (!/^[1-9][0-9]*$/.test(raw) || raw.length > MAX_HEADER_DIGITS || !Number.isSafeInteger(Number(raw))) {
218
+ throw new Error(
219
+ `${ARGUMENTS_REF_BYTES_ENV} must be a positive integer number of bytes ` +
220
+ `(no sign, no leading zero, at most ${MAX_HEADER_DIGITS} digits), got ${JSON.stringify(raw)}`,
221
+ );
222
+ }
223
+ return Number(raw);
224
+ }
225
+
226
+ /**
227
+ * The `VGI-Arguments-Ref-Bytes` value an HTTP server advertises, or `null`
228
+ * when it advertises nothing.
229
+ *
230
+ * The header is the mandatory capability signal (large-values spec §5): sent
231
+ * whenever the server vends upload URLs (the grant) AND its storage can fetch
232
+ * the uploaded object back by id (vgi-rpc `ObjectStore`), never otherwise.
233
+ * `VGI_TEST_DISABLE_ARGUMENTS_REF=1` turns it off (the extension's fallback
234
+ * test).
235
+ *
236
+ * @param explicit A server option overriding `VGI_ARGUMENTS_REF_BYTES`.
237
+ */
238
+ export function argumentsRefHeaderValue(opts: {
239
+ uploadUrlProvider?: unknown;
240
+ externalLocation?: { storage?: unknown } | null | undefined;
241
+ explicit?: number | undefined;
242
+ env?: EnvLike;
243
+ }): number | null {
244
+ const env = opts.env ?? processEnv();
245
+ if (opts.uploadUrlProvider == null) return null;
246
+ if (!isObjectStore(opts.externalLocation?.storage)) {
247
+ console.warn(
248
+ "argument references disabled: the configured storage cannot fetch objects by id (no ObjectStore)",
249
+ );
250
+ return null;
251
+ }
252
+ if (["1", "true", "yes"].includes((env[DISABLE_ARGUMENTS_REF_ENV] ?? "").trim().toLowerCase())) return null;
253
+ if (opts.explicit !== undefined) {
254
+ if (!Number.isSafeInteger(opts.explicit) || opts.explicit < 1) {
255
+ throw new Error(`argumentsRefBytes must be a positive integer, got ${opts.explicit}`);
256
+ }
257
+ return opts.explicit;
258
+ }
259
+ return argumentsRefBytesFromEnv(env);
260
+ }