@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
@@ -2,7 +2,7 @@
2
2
  // GENERATED by vgi.codegen.ts_registry. DO NOT EDIT BY HAND.
3
3
  //
4
4
  // Generator: python -m vgi.codegen.ts_registry v1
5
- // Content hash: c142d70fe6ee
5
+ // Content hash: 481e7e7cd682
6
6
  //
7
7
  // To regenerate:
8
8
  // uv run --project ~/Development/vgi-python python scripts/regen_generated.py
@@ -38,7 +38,7 @@ import {
38
38
  export const VGI_PROTOCOL_NAME = "vgi.v3";
39
39
 
40
40
  /** The protocol's semver, stamped on every request by a client of this protocol. */
41
- export const VGI_PROTOCOL_VERSION = "3.3.0";
41
+ export const VGI_PROTOCOL_VERSION = "3.4.0";
42
42
 
43
43
  /** What a unary handler returns: the result row, now or later. */
44
44
  export type VgiReply<T> = T | ExternalRef | Promise<T | ExternalRef>;
package/src/hosted.ts ADDED
@@ -0,0 +1,254 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // Orchard hosted mode (`VGI_ORCHARD_HOSTED=1`): configuration and the
3
+ // fail-closed startup checks.
4
+ //
5
+ // A hosted worker (a *Field Worker*) serves VGI over HTTP to callers who hold a
6
+ // *Pass*: a short-lived RFC 9068 access token (`typ: at+jwt`, ES256) issued by
7
+ // the Orchard Front Desk for exactly one canonical Desk Address. The worker
8
+ // verifies Passes locally against the Front Desk's JWKS and accepts nothing
9
+ // else. Everything here fails closed:
10
+ //
11
+ // - Startup is refused unless `VGI_JWT_ISSUER`, `VGI_JWT_AUDIENCE` and
12
+ // `VGI_JWT_JWKS_URI` are all set to a single non-empty value.
13
+ // - Startup is refused when any other way in is configured: static bearer
14
+ // tokens, sealed-grant keys, a `resolveToken` / `mintGrant` hook, OAuth
15
+ // resource metadata, a proxy-proof gate, Iroh or other peer identity, a
16
+ // custom `authenticate` callback, or a non-HTTP transport.
17
+ // - Startup is refused without a stable, operator-configured signing key.
18
+ //
19
+ // The Pass verifier and the request gate live in `http/hosted-auth.ts`; this
20
+ // module has no dependencies so the stdio `Worker` can refuse hosted mode
21
+ // without loading a JOSE library. Neither module imports `node:*`: hosted mode
22
+ // runs on Node, Bun and Cloudflare Workers alike.
23
+ //
24
+ // The reference implementation is vgi-python's `vgi/hosted.py`; the design is
25
+ // in the extension repository's `docs/location-delegation.md` ("The Pass" and
26
+ // "The Field Worker: SDK hosted mode").
27
+
28
+ /** Environment variable that turns hosted mode on. Baked into the hosted base image. */
29
+ export const HOSTED_ENV = "VGI_ORCHARD_HOSTED";
30
+
31
+ /** The challenge on every hosted-mode 401. No `resource_metadata`: a Field
32
+ * Worker never sends a client off to discover an authorization server. */
33
+ export const HOSTED_CHALLENGE = 'Bearer error="invalid_token"';
34
+
35
+ /** `AuthContext.domain` of a caller authenticated by a Pass. */
36
+ export const HOSTED_AUTH_DOMAIN = "orchard";
37
+
38
+ /** Default (and only-by-override) signing algorithm for Passes. */
39
+ export const DEFAULT_HOSTED_ALGORITHMS: readonly string[] = Object.freeze(["ES256"]);
40
+ /** Required JOSE `typ` (RFC 9068). */
41
+ export const REQUIRED_TYP = "at+jwt";
42
+ /** Clock skew allowed on `exp` / `nbf`, seconds. */
43
+ export const LEEWAY_SECONDS = 60;
44
+ /** Hard upper bound on how long JWKS keys are trusted, seconds. */
45
+ export const JWKS_MAX_AGE_SECONDS = 600;
46
+ /** Minimum time between JWKS re-fetches triggered by an unknown `kid`, seconds. */
47
+ export const JWKS_REFRESH_MIN_INTERVAL_SECONDS = 60;
48
+ /** Timeout for each JWKS request, seconds. */
49
+ export const JWKS_FETCH_TIMEOUT_SECONDS = 10;
50
+ /** The shortest signing key a hosted worker accepts, bytes. */
51
+ export const MIN_SIGNING_KEY_BYTES = 32;
52
+ /**
53
+ * The request cap a hosted worker serves with when neither
54
+ * `VGI_RPC_MAX_REQUEST_BYTES` nor `maxRequestBytes` sets one: 32 MiB
55
+ * (vgi-python `HOSTED_DEFAULT_MAX_REQUEST_BYTES`). Advertised as
56
+ * `VGI-Max-Request-Bytes`, so with the blob vendor a larger request goes up
57
+ * through an upload URL instead.
58
+ */
59
+ export const HOSTED_DEFAULT_MAX_REQUEST_BYTES = 32 * 1024 * 1024;
60
+
61
+ const TRUE_VALUES: ReadonlySet<string> = new Set(["1", "true", "yes", "on"]);
62
+ const FALSE_VALUES: ReadonlySet<string> = new Set(["", "0", "false", "no", "off"]);
63
+
64
+ /** An environment: `process.env`, a Cloudflare Worker's `env`, or a test map. */
65
+ export type HostedEnv = Readonly<Record<string, string | undefined>>;
66
+
67
+ /**
68
+ * A hosted-mode configuration error. The worker must not start.
69
+ *
70
+ * `serveVgiWorker` and `Worker.run` print the message and exit non-zero;
71
+ * `createVgiFetch` / `createVgiWorkerFetch` throw it at construction.
72
+ */
73
+ export class OrchardHostedConfigError extends Error {
74
+ constructor(reason: string, options?: { raw?: boolean }) {
75
+ super(options?.raw ? reason : `${HOSTED_ENV}=1 (Orchard hosted mode): ${reason}`);
76
+ this.name = "OrchardHostedConfigError";
77
+ }
78
+ }
79
+
80
+ /** Verified hosted-mode settings, read from the environment. */
81
+ export interface HostedConfig {
82
+ /** The Front Desk issuer (`iss`), matched exactly. */
83
+ readonly issuer: string;
84
+ /** The one canonical Desk Address (`aud`), matched exactly. */
85
+ readonly audience: string;
86
+ /** Where the Front Desk publishes its signing keys. */
87
+ readonly jwksUri: string;
88
+ /** Accepted JWS algorithms (`ES256` unless overridden). */
89
+ readonly algorithms: readonly string[];
90
+ }
91
+
92
+ function processEnv(): HostedEnv {
93
+ return ((globalThis as { process?: { env?: HostedEnv } }).process?.env ?? {}) as HostedEnv;
94
+ }
95
+
96
+ /**
97
+ * Whether `VGI_ORCHARD_HOSTED` turns hosted mode on.
98
+ *
99
+ * True for `1`/`true`/`yes`/`on` (any case), false when unset or
100
+ * `0`/`false`/`no`/`off`/empty. Any other value throws
101
+ * {@link OrchardHostedConfigError}: a typo must not quietly start a worker
102
+ * without authentication.
103
+ */
104
+ export function hostedModeEnabled(env: HostedEnv = processEnv()): boolean {
105
+ const raw = env[HOSTED_ENV];
106
+ if (raw === undefined) return false;
107
+ const value = raw.trim().toLowerCase();
108
+ if (TRUE_VALUES.has(value)) return true;
109
+ if (FALSE_VALUES.has(value)) return false;
110
+ throw new OrchardHostedConfigError(
111
+ `${HOSTED_ENV} must be 1 or 0 (or true/false), got ${JSON.stringify(raw)}`,
112
+ { raw: true },
113
+ );
114
+ }
115
+
116
+ function singleValue(env: HostedEnv, name: string): string {
117
+ const value = (env[name] ?? "").trim();
118
+ if (!value) {
119
+ throw new OrchardHostedConfigError(`${name} must be set (unset and empty are both errors).`);
120
+ }
121
+ if (value.includes(",")) {
122
+ throw new OrchardHostedConfigError(
123
+ `${name} must be exactly one value; got a comma-separated list. ` +
124
+ "A Pass is issued for one canonical Desk Address and one issuer.",
125
+ );
126
+ }
127
+ return value;
128
+ }
129
+
130
+ /**
131
+ * Parse a `VGI_JWT_ALGORITHMS` value: comma-separated JWS algorithm names.
132
+ * `none` and `HS*` are always refused: an HMAC algorithm checked against a
133
+ * JWKS lets anyone holding the *public* key mint tokens.
134
+ *
135
+ * Returns the default (`ES256`) when unset or blank.
136
+ */
137
+ export function parseJwtAlgorithms(raw: string | undefined): readonly string[] {
138
+ if (raw === undefined || !raw.trim()) return DEFAULT_HOSTED_ALGORITHMS;
139
+ const algorithms = raw.split(",").map((a) => a.trim()).filter(Boolean);
140
+ const forbidden = algorithms.some((a) => {
141
+ const lowered = a.toLowerCase();
142
+ return lowered === "none" || lowered.startsWith("hs");
143
+ });
144
+ if (algorithms.length === 0 || forbidden) {
145
+ throw new OrchardHostedConfigError(
146
+ `VGI_JWT_ALGORITHMS=${JSON.stringify(raw)} is not allowed; Passes are asymmetric ` +
147
+ "(default ES256), never 'none' or HS*.",
148
+ );
149
+ }
150
+ return Object.freeze(algorithms);
151
+ }
152
+
153
+ /**
154
+ * Read and validate the hosted-mode environment.
155
+ *
156
+ * @throws OrchardHostedConfigError when a required variable is missing, empty
157
+ * or multi-valued, or `VGI_JWT_ALGORITHMS` is unusable.
158
+ */
159
+ export function resolveHostedConfig(env: HostedEnv = processEnv()): HostedConfig {
160
+ const issuer = singleValue(env, "VGI_JWT_ISSUER");
161
+ const audience = singleValue(env, "VGI_JWT_AUDIENCE");
162
+ const jwksUri = singleValue(env, "VGI_JWT_JWKS_URI");
163
+ const algorithms = parseJwtAlgorithms(env.VGI_JWT_ALGORITHMS);
164
+ return Object.freeze({ issuer, audience, jwksUri, algorithms });
165
+ }
166
+
167
+ /**
168
+ * Refuse when the environment configures another credential.
169
+ *
170
+ * The TypeScript SDK reads none of these itself, but a hosted image built from
171
+ * another SDK's conventions may carry them, and each one means the operator
172
+ * expects a second way in. Refusing is the only answer that cannot be wrong.
173
+ *
174
+ * @throws OrchardHostedConfigError on `VGI_BEARER_TOKENS`, `VGI_RPC_GRANT_KEYS`,
175
+ * `VGI_OAUTH_RESOURCE` or an active `VGI_PROXY_PROOF_MODE`.
176
+ */
177
+ export function checkHostedEnvironment(env: HostedEnv = processEnv()): void {
178
+ const conflicts: ReadonlyArray<readonly [string, string]> = [
179
+ ["VGI_BEARER_TOKENS", "static bearer tokens"],
180
+ ["VGI_RPC_GRANT_KEYS", "sealed-grant keys"],
181
+ ["VGI_OAUTH_RESOURCE", "OAuth resource metadata (a Field Worker never advertises resource_metadata)"],
182
+ ];
183
+ for (const [name, what] of conflicts) {
184
+ if ((env[name] ?? "").trim()) {
185
+ throw new OrchardHostedConfigError(
186
+ `${name} is set (${what}); the only credential a hosted worker accepts is a Pass.`,
187
+ );
188
+ }
189
+ }
190
+ const proofMode = (env.VGI_PROXY_PROOF_MODE ?? "off").trim().toLowerCase() || "off";
191
+ if (proofMode !== "off") {
192
+ throw new OrchardHostedConfigError("VGI_PROXY_PROOF_MODE must be off; hosted workers authenticate by Pass only.");
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Refuse a hosted worker whose signing key is not stable across restarts.
198
+ *
199
+ * The key seals catalog opaque data and HTTP state tokens. A Field Worker's
200
+ * machines stop and start, and a deployment can run on several of them: a key
201
+ * generated per process makes every restart (and every other machine) reject
202
+ * the sessions DuckDB already holds.
203
+ *
204
+ * @param env the environment (`VGI_SIGNING_KEY`, `VGI_SIGNING_KEY_MINTED`).
205
+ * @param explicit a key passed in code, if any. It counts as configured.
206
+ * @throws OrchardHostedConfigError when there is no configured key, the
207
+ * environment marks it as minted by a parent process, or it is shorter than
208
+ * {@link MIN_SIGNING_KEY_BYTES}.
209
+ */
210
+ export function checkHostedSigningKey(env: HostedEnv, explicit?: Uint8Array | string): void {
211
+ const minted = (env.VGI_SIGNING_KEY_MINTED ?? "").trim();
212
+ const raw = (env.VGI_SIGNING_KEY ?? "").trim();
213
+ if ((explicit === undefined && !raw) || (minted && minted !== "0")) {
214
+ throw new OrchardHostedConfigError(
215
+ "VGI_SIGNING_KEY is not set; hosted workers need a stable key shared by every machine of the " +
216
+ "deployment, or every restart breaks attached sessions.",
217
+ );
218
+ }
219
+ const lengths: number[] = [];
220
+ if (raw) lengths.push(new TextEncoder().encode(raw).byteLength);
221
+ if (typeof explicit === "string") lengths.push(new TextEncoder().encode(explicit).byteLength);
222
+ else if (explicit !== undefined) lengths.push(explicit.byteLength);
223
+ if (lengths.some((n) => n < MIN_SIGNING_KEY_BYTES)) {
224
+ throw new OrchardHostedConfigError(`VGI_SIGNING_KEY must be at least ${MIN_SIGNING_KEY_BYTES} bytes.`);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Hosted mode from an environment, for `createVgiFetch({ orchardHosted })`.
230
+ *
231
+ * Returns `undefined` when `VGI_ORCHARD_HOSTED` is off. When it is on, returns
232
+ * the validated configuration after checking the environment for any other
233
+ * credential. Cloudflare Workers pass the Worker's `env`; `serveVgiWorker`
234
+ * reads `process.env` itself.
235
+ *
236
+ * @throws OrchardHostedConfigError on any misconfiguration.
237
+ */
238
+ export function orchardHostedFromEnv(env: HostedEnv = processEnv()): HostedConfig | undefined {
239
+ if (!hostedModeEnabled(env)) return undefined;
240
+ const config = resolveHostedConfig(env);
241
+ checkHostedEnvironment(env);
242
+ return config;
243
+ }
244
+
245
+ /** Refuse a non-HTTP transport (stdio, AF_UNIX, TCP, the Iroh raw upstream,
246
+ * a caller-provided byte stream) when hosted mode is on: none carries a Pass. */
247
+ export function refuseNonHttpTransportInHostedMode(transport: string, env: HostedEnv = processEnv()): void {
248
+ if (hostedModeEnabled(env)) {
249
+ throw new OrchardHostedConfigError(
250
+ `only HTTP is allowed (serveVgiWorker / createVgiWorkerFetch / createVgiFetch); the ${transport} ` +
251
+ "transport carries no Pass (stdio, --unix, --tcp and --iroh-raw-upstream are all refused).",
252
+ );
253
+ }
254
+ }
@@ -0,0 +1,80 @@
1
+ // Copyright 2025, 2026 Query Farm LLC - https://query.farm
2
+ // HTTP server settings derived from the blob-vendor environment.
3
+ // Port of vgi-python's `vgi.serve.resolve_blob_vendor_http_config`.
4
+ //
5
+ // `VGI_BLOB_VENDOR_URL` (with `VGI_BLOB_VENDOR_TOKEN`, falling back to
6
+ // `VGI_CF_DO_TOKEN`) turns on result externalization
7
+ // (`VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES`, default 1 MiB;
8
+ // `VGI_RPC_EXTERNAL_COMPRESSION`) and client upload URLs
9
+ // (`VGI_RPC_MAX_UPLOAD_BYTES`). `VGI_RPC_MAX_REQUEST_BYTES` is read either way:
10
+ // it is an explicit operator setting, advertised and enforced, and clients
11
+ // (the DuckDB extension) only take the upload-URL path for a request larger
12
+ // than it, so set it with the vendor.
13
+ //
14
+ // Runtime-agnostic: serveVgiWorker reads it from `process.env`; a Cloudflare
15
+ // Worker passes its own `env` and spreads the result into createVgiFetch:
16
+ //
17
+ // createVgiFetch({ ...blobVendorHttpConfigFromEnv(env), protocol, signingKey, landingInfo });
18
+
19
+ import {
20
+ externalConfigFromEnv,
21
+ maxUploadBytesFromEnv,
22
+ type ExternalLocationConfig,
23
+ type UploadUrlProvider,
24
+ } from "@query-farm/vgi-rpc";
25
+
26
+ /** The variables {@link blobVendorHttpConfigFromEnv} reads. */
27
+ export interface BlobVendorEnv {
28
+ VGI_BLOB_VENDOR_URL?: string | undefined;
29
+ VGI_BLOB_VENDOR_TOKEN?: string | undefined;
30
+ VGI_CF_DO_TOKEN?: string | undefined;
31
+ VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES?: string | undefined;
32
+ VGI_RPC_EXTERNAL_COMPRESSION?: string | undefined;
33
+ VGI_RPC_MAX_REQUEST_BYTES?: string | undefined;
34
+ VGI_RPC_MAX_UPLOAD_BYTES?: string | undefined;
35
+ }
36
+
37
+ /** HTTP handler options from the blob-vendor environment. Every field is
38
+ * absent when nothing is configured. */
39
+ export interface BlobVendorHttpConfig {
40
+ /** Large results are uploaded to the vendor and replaced by a pointer
41
+ * carrying `vgi_rpc.location.sha256`; inbound pointers are fetched only from
42
+ * the vendor's storage hosts. */
43
+ externalLocation?: ExternalLocationConfig | undefined;
44
+ /** The vendor, vending pre-signed upload URLs (`__upload_url__/init`) so
45
+ * clients can send requests over {@link maxRequestBytes}. */
46
+ uploadUrlProvider?: UploadUrlProvider | undefined;
47
+ /** `VGI_RPC_MAX_UPLOAD_BYTES`, advertised as `VGI-Max-Upload-Bytes`. */
48
+ maxUploadBytes?: number | undefined;
49
+ /** `VGI_RPC_MAX_REQUEST_BYTES`, advertised as `VGI-Max-Request-Bytes` and enforced. */
50
+ maxRequestBytes?: number | undefined;
51
+ }
52
+
53
+ function positiveInt(env: BlobVendorEnv, name: keyof BlobVendorEnv): number | undefined {
54
+ const raw = (env[name] ?? "").trim();
55
+ if (!raw) return undefined;
56
+ if (!/^[+-]?\d+$/.test(raw)) throw new Error(`${name} must be an integer, got ${JSON.stringify(raw)}`);
57
+ const value = Number(raw);
58
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${name} must be positive, got ${value}`);
59
+ return value;
60
+ }
61
+
62
+ /**
63
+ * Read the blob-vendor HTTP settings from `env`.
64
+ *
65
+ * @throws Error if a variable is set but malformed, or the vendor URL is set
66
+ * without a token.
67
+ */
68
+ export function blobVendorHttpConfigFromEnv(env: BlobVendorEnv): BlobVendorHttpConfig {
69
+ const config: BlobVendorHttpConfig = {};
70
+ const maxRequestBytes = positiveInt(env, "VGI_RPC_MAX_REQUEST_BYTES");
71
+ if (maxRequestBytes !== undefined) config.maxRequestBytes = maxRequestBytes;
72
+ const vendorEnv = env as Readonly<Record<string, string | undefined>>;
73
+ const external = externalConfigFromEnv(vendorEnv);
74
+ if (external === null) return config;
75
+ config.externalLocation = external;
76
+ config.uploadUrlProvider = external.storage;
77
+ const maxUploadBytes = maxUploadBytesFromEnv(vendorEnv);
78
+ if (maxUploadBytes !== null) config.maxUploadBytes = maxUploadBytes;
79
+ return config;
80
+ }
package/src/http/fetch.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  // `buildVgiProtocol` as `signingKey`, from one source. Passing different keys to
11
11
  // those two seams produces a worker that mints tokens it cannot recover.
12
12
 
13
+ import { ARGUMENTS_REF_BYTES_HEADER, argumentsRefHeaderValue } from "../protocol/arguments-ref.js";
13
14
  import { omitUndefined } from "../util/defined.js";
14
15
  import {
15
16
  AuthContext,
@@ -29,8 +30,22 @@ import { createLandingRoutes, type LandingInfo } from "./landing.js";
29
30
  import { buildRpcServer, type HostingOptions } from "../rpc-server.js";
30
31
  import { setRequestAuthScope, type RequestAuthHolder } from "../request-auth.js";
31
32
  import { checkReservedAttachOptions } from "../catalog/attach-option.js";
33
+ import type { BlobVendorHttpConfig } from "./blob-vendor.js";
34
+ import {
35
+ HOSTED_DEFAULT_MAX_REQUEST_BYTES,
36
+ OrchardHostedConfigError,
37
+ MIN_SIGNING_KEY_BYTES,
38
+ type HostedConfig,
39
+ } from "../hosted.js";
40
+ import { createHostedGate, isHostedAuthenticate, type HostedGate, type HostedVerifierDeps } from "./hosted-auth.js";
32
41
 
33
- export interface VgiFetchOptions extends HostingOptions {
42
+ /**
43
+ * The external-location fields ({@link BlobVendorHttpConfig}) are forwarded to
44
+ * vgi-rpc's handler: spread `blobVendorHttpConfigFromEnv(env)` in to serve
45
+ * through the blob vendor (results over the threshold become pointers, large
46
+ * requests arrive through vended upload URLs).
47
+ */
48
+ export interface VgiFetchOptions extends HostingOptions, BlobVendorHttpConfig {
34
49
  /** Wire-protocol config (registry + catalogInterface). */
35
50
  protocol: ProtocolConfig;
36
51
  /** HMAC key for state-token signing. Pass a stable, secret 32-byte key
@@ -50,8 +65,27 @@ export interface VgiFetchOptions extends HostingOptions {
50
65
  * bytes to use unchanged. Defaults to {@link signingKey}'s bytes.
51
66
  */
52
67
  storageSealKey?: Uint8Array | string | undefined;
53
- /** State-token TTL in seconds (default 3600). */
68
+ /** State-token TTL in seconds (default 21600, 6 h: vgi-rpc STATE_REF_V1.md). */
54
69
  tokenTtl?: number | undefined;
70
+ /**
71
+ * vgi-rpc's cursor rule for a stream state token over its turn budget
72
+ * (STATE_REF_V1.md §9). Defaults to `"error"` (`cursor_too_large`): this SDK
73
+ * carries its init request as an `init` StateRef, so a cursor over budget
74
+ * is a bug to surface, not a size to tolerate.
75
+ */
76
+ cursorRule?: "warn" | "error" | undefined;
77
+ /**
78
+ * The `VGI-Arguments-Ref-Bytes` value advertised when the server vends
79
+ * upload URLs and its storage is a vgi-rpc ObjectStore (protocol 3.4
80
+ * argument references). Defaults to `$VGI_ARGUMENTS_REF_BYTES`, else 4 MiB.
81
+ */
82
+ argumentsRefBytes?: number | undefined;
83
+ /**
84
+ * Environment read for `VGI_ARGUMENTS_REF_BYTES` and the test switch
85
+ * `VGI_TEST_DISABLE_ARGUMENTS_REF` (a Cloudflare Worker passes its `env`).
86
+ * Defaults to `process.env` where there is one.
87
+ */
88
+ env?: Readonly<Record<string, string | undefined>> | undefined;
55
89
  /** URL path prefix for VGI requests (default "/vgi"). Pass "" to mount at
56
90
  * the root, which is what a dedicated single-worker HTTP server wants. */
57
91
  prefix?: string | undefined;
@@ -100,6 +134,64 @@ export interface VgiFetchOptions extends HostingOptions {
100
134
  peerAuthenticationPolicy?: PeerAuthenticationPolicy | undefined;
101
135
  /** Host adapter supplying the physical peer and multiplicity-preserving headers. */
102
136
  peerResolutionContext?: ((request: Request) => PeerResolutionOptions | Promise<PeerResolutionOptions>) | undefined;
137
+ /**
138
+ * Orchard hosted mode: accept only Orchard Passes (RFC 9068 JWT access
139
+ * tokens) on every request except `HEAD /health` and CORS preflights. Pass
140
+ * `orchardHostedFromEnv(env)`, which is `undefined` unless
141
+ * `VGI_ORCHARD_HOSTED` is on. `serveVgiWorker` / `createVgiWorkerFetch` set
142
+ * it from `process.env` themselves.
143
+ *
144
+ * Construction throws `OrchardHostedConfigError` when any other way in is
145
+ * configured (`authenticate`, `grantKeys`, `resolveToken`, `mintGrant`, peer
146
+ * identity) or the signing key is not a configured one. CORS is forced open
147
+ * (`*`): the only credential is the bearer Pass.
148
+ */
149
+ orchardHosted?: HostedConfig | undefined;
150
+ /** Test seam for hosted mode's JWKS fetch and clock. */
151
+ orchardHostedDeps?: HostedVerifierDeps | undefined;
152
+ }
153
+
154
+ /**
155
+ * Refuse a `createVgiFetch` configuration that admits a caller without a Pass.
156
+ * Called by `createVgiFetch` whenever `orchardHosted` is set; throws
157
+ * {@link OrchardHostedConfigError}.
158
+ */
159
+ export function checkHostedFetchOptions(opts: VgiFetchOptions): void {
160
+ if (opts.authenticate !== undefined && !isHostedAuthenticate(opts.authenticate)) {
161
+ throw new OrchardHostedConfigError(
162
+ "a custom authenticate callback is configured; hosted workers verify Passes only.",
163
+ );
164
+ }
165
+ if (opts.grantKeys !== undefined && opts.grantKeys !== null) {
166
+ throw new OrchardHostedConfigError("sealed-grant keys (--grant-key / VGI_RPC_GRANT_KEYS / grantKeys) are configured.");
167
+ }
168
+ if (opts.resolveToken !== undefined) {
169
+ throw new OrchardHostedConfigError("the worker supplies a resolveToken hook (resolve_token); hosted workers accept Passes only.");
170
+ }
171
+ if (opts.mintGrant !== undefined) {
172
+ throw new OrchardHostedConfigError("the worker supplies a mintGrant hook (mint_grant / issue_grant); hosted workers accept Passes only.");
173
+ }
174
+ if (
175
+ (opts.peerIdentityProviders?.length ?? 0) > 0 ||
176
+ opts.peerAuthenticationPolicy !== undefined ||
177
+ opts.peerResolutionContext !== undefined
178
+ ) {
179
+ throw new OrchardHostedConfigError("peer identity (Iroh, Tailscale, ...) is configured; hosted workers accept Passes only.");
180
+ }
181
+ if (opts.signingKeyConfigured === false) {
182
+ throw new OrchardHostedConfigError(
183
+ "VGI_SIGNING_KEY is not set; hosted workers need a stable key shared by every machine of the " +
184
+ "deployment, or every restart breaks attached sessions.",
185
+ );
186
+ }
187
+ if (opts.signingKey.byteLength < MIN_SIGNING_KEY_BYTES) {
188
+ throw new OrchardHostedConfigError(`VGI_SIGNING_KEY must be at least ${MIN_SIGNING_KEY_BYTES} bytes.`);
189
+ }
190
+ }
191
+
192
+ function hostedDebugEnabled(): boolean {
193
+ const flag = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.VGI_DEBUG;
194
+ return flag !== undefined && flag !== "" && flag !== "0";
103
195
  }
104
196
 
105
197
  // ---------------------------------------------------------------------------
@@ -185,6 +277,41 @@ const REQUEST_AUTH_DISPATCH_HOOK: DispatchHook = {
185
277
  },
186
278
  };
187
279
 
280
+ /** Default state-token TTL: 6 h (vgi-rpc STATE_REF_V1.md, protocol 3.4). */
281
+ export const DEFAULT_TOKEN_TTL = 21600;
282
+
283
+ /**
284
+ * Add `VGI-Arguments-Ref-Bytes` to every response, next to vgi-rpc's own
285
+ * capability headers (which it sets on every response, capability discovery
286
+ * included), and expose it to browsers alongside them.
287
+ */
288
+ function withArgumentsRefHeader(
289
+ handler: (req: Request) => Promise<Response> | Response,
290
+ value: number,
291
+ ): (req: Request) => Promise<Response> {
292
+ const text = String(value);
293
+ return async (req: Request) => {
294
+ const response = await handler(req);
295
+ try {
296
+ response.headers.set(ARGUMENTS_REF_BYTES_HEADER, text);
297
+ return addExposed(response);
298
+ } catch {
299
+ // Immutable headers (a fetched Response): rebuild around the same body.
300
+ const copy = new Response(response.body, response);
301
+ copy.headers.set(ARGUMENTS_REF_BYTES_HEADER, text);
302
+ return addExposed(copy);
303
+ }
304
+ };
305
+ }
306
+
307
+ function addExposed(response: Response): Response {
308
+ const exposed = response.headers.get("Access-Control-Expose-Headers");
309
+ if (exposed && exposed !== "*" && !exposed.toLowerCase().includes(ARGUMENTS_REF_BYTES_HEADER.toLowerCase())) {
310
+ response.headers.set("Access-Control-Expose-Headers", `${exposed}, ${ARGUMENTS_REF_BYTES_HEADER}`);
311
+ }
312
+ return response;
313
+ }
314
+
188
315
  /**
189
316
  * Build a fetch handler suitable for `export default { fetch }` in a CF
190
317
  * Worker module, or for `Bun.serve({ fetch })`. The returned handler is
@@ -203,7 +330,28 @@ export function createVgiFetch(opts: VgiFetchOptions): (req: Request) => Promise
203
330
  "and GET /vgi-client.js 404s.",
204
331
  );
205
332
  }
206
- const tokenTtl = opts.tokenTtl ?? 3600;
333
+ // Orchard hosted mode: refuse every other way in, then put the Pass gate in
334
+ // front of the handler and hand the handler an authenticate that returns the
335
+ // identity the gate verified.
336
+ let gate: HostedGate | undefined;
337
+ if (opts.orchardHosted) {
338
+ checkHostedFetchOptions(opts);
339
+ const debug = hostedDebugEnabled() ? (m: string) => console.error(m) : undefined;
340
+ gate = createHostedGate(opts.orchardHosted, { debug, ...opts.orchardHostedDeps });
341
+ }
342
+ const authenticate = gate ? gate.authenticate : opts.authenticate;
343
+ // A hosted worker always has a request cap (VGI_RPC_MAX_REQUEST_BYTES, else
344
+ // 32 MiB), advertised, as in vgi-python's hosted mode.
345
+ const maxRequestBytes = opts.maxRequestBytes ?? (gate ? HOSTED_DEFAULT_MAX_REQUEST_BYTES : undefined);
346
+ const tokenTtl = opts.tokenTtl ?? DEFAULT_TOKEN_TTL;
347
+ // Protocol 3.4: argument references are on whenever the server can mint and
348
+ // resolve them, and the header is the mandatory signal that they are.
349
+ const argumentsRefBytes = argumentsRefHeaderValue({
350
+ uploadUrlProvider: opts.uploadUrlProvider,
351
+ externalLocation: opts.externalLocation,
352
+ explicit: opts.argumentsRefBytes,
353
+ ...(opts.env ? { env: opts.env } : {}),
354
+ });
207
355
  // `?? "/vgi"` and not `|| "/vgi"`: an explicit "" means "mount at root".
208
356
  const prefix = opts.prefix ?? "/vgi";
209
357
  const serverId = opts.serverId ?? "vgi-cf";
@@ -220,7 +368,9 @@ export function createVgiFetch(opts: VgiFetchOptions): (req: Request) => Promise
220
368
  // authenticates callers -- vgi_rpc.Identity.v2 when the worker opts in.
221
369
  // Built at construction, so a worker that opts into introspection without an
222
370
  // allowlist fails here rather than serving traffic.
223
- const server = buildRpcServer(protocol, opts, {
371
+ // Hosted mode never reads sealed-grant keys from the environment (the
372
+ // hosted checks refused them; this keeps a Worker-less process.env out too).
373
+ const server = buildRpcServer(protocol, gate ? { ...opts, grantKeys: null } : opts, {
224
374
  transport: "http",
225
375
  serverId,
226
376
  attachTickets: {
@@ -240,23 +390,31 @@ export function createVgiFetch(opts: VgiFetchOptions): (req: Request) => Promise
240
390
  // `VgiRpcServer.identity` is `IdentityImpl | undefined` while `ProtocolHost`
241
391
  // declares `identity?: {...}` without `| undefined`. Both mean "may be
242
392
  // absent"; the cast only bridges the declarations.
243
- const handler = createHttpHandler(server as Parameters<typeof createHttpHandler>[0], omitUndefined({
393
+ const rpcHandler = createHttpHandler(server as Parameters<typeof createHttpHandler>[0], omitUndefined({
244
394
  prefix,
245
395
  serverId,
246
396
  tokenKey: opts.signingKey,
247
397
  tokenTtl,
398
+ cursorRule: opts.cursorRule ?? "error",
248
399
  stateSerializer: arrowStateSerializer,
249
400
  // Records the dispatching principal on the request scope opened below, so
250
401
  // stream `init` — the one handler the framework passes no CallContext to —
251
402
  // can still open the identity-bound attach and split envelopes.
252
403
  dispatchHook: REQUEST_AUTH_DISPATCH_HOOK,
253
- authenticate: opts.authenticate,
404
+ authenticate,
405
+ // Hosted mode: a Pass is the only bearer; nothing is composed beside it.
406
+ identityBearer: gate ? false : undefined,
254
407
  peerIdentityProviders: opts.peerIdentityProviders,
255
408
  peerAuthenticationPolicy: opts.peerAuthenticationPolicy,
256
409
  peerResolutionContext: opts.peerResolutionContext,
257
- // `null` is the explicit opt-out; `undefined` (omitted) means "*".
258
- corsOrigins: opts.corsOrigins === null ? undefined : (opts.corsOrigins ?? "*"),
410
+ // `null` is the explicit opt-out; `undefined` (omitted) means "*". Hosted
411
+ // mode is always open: the only credential is the bearer Pass.
412
+ corsOrigins: gate ? "*" : opts.corsOrigins === null ? undefined : (opts.corsOrigins ?? "*"),
259
413
  repositoryUrl: opts.repositoryUrl,
414
+ externalLocation: opts.externalLocation,
415
+ uploadUrlProvider: opts.uploadUrlProvider,
416
+ maxRequestBytes,
417
+ maxUploadBytes: opts.maxUploadBytes,
260
418
  // The landing surface is ours, contributed into vgi-rpc's routing rather
261
419
  // than built there. `enableLandingPage: false` drops vgi-rpc's generic
262
420
  // "this is an RPC endpoint" page, which would otherwise sit behind ours for
@@ -264,6 +422,10 @@ export function createVgiFetch(opts: VgiFetchOptions): (req: Request) => Promise
264
422
  extraRoutes: createLandingRoutes(opts.landingInfo),
265
423
  enableLandingPage: false,
266
424
  }));
425
+ // Hosted mode authenticates before vgi-rpc routes anything, so no page,
426
+ // probe or body handling is reachable without a Pass.
427
+ const gated = gate ? gate.wrap(rpcHandler, prefix) : rpcHandler;
428
+ const handler = argumentsRefBytes === null ? gated : withArgumentsRefHeader(gated, argumentsRefBytes);
267
429
  return async (req: Request) => {
268
430
  await reservedCheck;
269
431
  const storage = await ensureRequestAuthStorage();