@jxsuite/server 9.0.3 → 9.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jxsuite/server",
3
- "version": "9.0.3",
3
+ "version": "9.1.0",
4
4
  "description": "Jx development server with live reload, server-side proxy, and studio integration",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -56,18 +56,18 @@
56
56
  "upgrade": "bun update --latest && bun install"
57
57
  },
58
58
  "dependencies": {
59
- "@jxsuite/ai": "^0.43.7",
60
- "@jxsuite/catalog": "^0.1.15",
61
- "@jxsuite/collab": "^0.12.2",
62
- "@jxsuite/compiler": "^9.1.0",
63
- "@jxsuite/create": "^1.8.3",
64
- "@jxsuite/erase": "^0.3.2",
65
- "@jxsuite/import": "^0.44.5",
66
- "@jxsuite/protocol": "^6.4.2",
67
- "@jxsuite/runtime": "^7.1.0",
68
- "@jxsuite/schema": "^6.0.2",
69
- "@jxsuite/site": "^2.8.0",
70
- "@jxsuite/starters": "^3.7.1",
59
+ "@jxsuite/ai": "^0.44.0",
60
+ "@jxsuite/catalog": "^0.1.16",
61
+ "@jxsuite/collab": "^0.12.3",
62
+ "@jxsuite/compiler": "^10.0.0",
63
+ "@jxsuite/create": "^1.8.4",
64
+ "@jxsuite/erase": "^0.3.3",
65
+ "@jxsuite/import": "^0.44.6",
66
+ "@jxsuite/protocol": "^6.5.0",
67
+ "@jxsuite/runtime": "^8.0.0",
68
+ "@jxsuite/schema": "^7.0.0",
69
+ "@jxsuite/site": "^3.0.0",
70
+ "@jxsuite/starters": "^4.0.0",
71
71
  "@npmcli/arborist": "^10.0.4",
72
72
  "chokidar": "^6.0.0",
73
73
  "kysely": "^0.29.9",
@@ -77,9 +77,9 @@
77
77
  "zod": "^4.6.7"
78
78
  },
79
79
  "devDependencies": {
80
- "@jxsuite/auth": "^0.8.11",
81
- "@jxsuite/connector": "^0.8.11",
82
- "@jxsuite/parser": "^5.0.2",
80
+ "@jxsuite/auth": "^0.8.12",
81
+ "@jxsuite/connector": "^0.8.12",
82
+ "@jxsuite/parser": "^5.1.0",
83
83
  "@jxsuite/test-support": "^0.0.0",
84
84
  "@types/npm-package-arg": "^6.1.4",
85
85
  "@types/npmcli__arborist": "^6.3.3",
package/src/ai-api.ts CHANGED
@@ -22,6 +22,11 @@
22
22
  * 2. Fallback: OPENAI_BASE_URL env var
23
23
  * 3. Default: https://api.openai.com/v1
24
24
  *
25
+ * Whichever it is, it is judged before anything is contacted (specs/ai.md §4): it must be an http
26
+ * or https URL, and its host must not be a link-local address or a cloud metadata endpoint, in any
27
+ * spelling. An upstream's redirect is not followed, so the host that was judged is the only one
28
+ * contacted.
29
+ *
25
30
  * Provider family (specs/ai.md §2.6): a request carrying `X-Api-Provider: anthropic` is served by
26
31
  * the Anthropic Messages API instead, with the same two flows read from ANTHROPIC_API_KEY,
27
32
  * ANTHROPIC_BASE_URL and `https://api.anthropic.com`. An env key is still attached only to its own
@@ -29,7 +34,8 @@
29
34
  * endpoint. Any other value is refused: a key must never be sent to a provider it was not meant
30
35
  * for. The models route lists both families in `providers`.
31
36
  *
32
- * A base URL resolving to a cloud metadata / link-local host is refused (SSRF defense).
37
+ * `resolveAiConfig` is that whole policy for one request, and every server route that forwards a
38
+ * provider key upstream calls it: both routes here, and the site import's component-naming pass.
33
39
  *
34
40
  * Prompt-cache affinity: a request carrying a valid X-Jx-Ai-Session header (the client's
35
41
  * conversation id) is forwarded with `sessionAffinity` set to a hash of it, scoped to this server
@@ -41,7 +47,9 @@
41
47
  * upstream's own listing.
42
48
  *
43
49
  * @license MIT
50
+ * @docs extending/embedding/backend-protocol
44
51
  */
52
+ import { BlockList, isIP } from "node:net";
45
53
  import {
46
54
  AI_SESSION_HEADER,
47
55
  affinityKey,
@@ -93,32 +101,90 @@ interface ModelEntry {
93
101
  }
94
102
 
95
103
  /**
96
- * SSRF defense: refuse to proxy to a cloud metadata endpoint or a link-local host. Loopback and
97
- * private-LAN hosts are intentionally allowed — self-hosted / local LLMs run there. An unparseable
98
- * base URL is blocked. `169.254.169.254` (the AWS/GCP/Azure metadata IP) lives in the link-local
99
- * `169.254.0.0/16` range, which is the primary thing this stops.
104
+ * The IPv4 ranges a base URL may not address: the link-local range, where the cloud metadata
105
+ * services listen (`169.254.169.254`), and the one metadata address outside it, Alibaba Cloud's.
106
+ * Each as `[address, prefix length]`.
107
+ */
108
+ const REFUSED_IPV4: readonly (readonly [string, number])[] = [
109
+ ["169.254.0.0", 16],
110
+ ["100.100.100.200", 32],
111
+ ];
112
+
113
+ /** The IPv6 ranges: link-local, and EC2's IPv6 metadata address, which sits in unique-local space. */
114
+ const REFUSED_IPV6: readonly (readonly [string, number])[] = [
115
+ ["fe80::", 10],
116
+ ["fd00:ec2::254", 128],
117
+ ];
118
+
119
+ /**
120
+ * The IPv6 prefixes under which an address carries an IPv4 address in its low 32 bits, and is
121
+ * judged as that address: NAT64's well-known prefix and the deprecated IPv4-compatible form. The
122
+ * IPv4-mapped form (`::ffff:0:0/96`) is the third, and `BlockList` applies every IPv4 rule to it
123
+ * already.
124
+ */
125
+ const IPV4_EMBEDDING_PREFIXES = ["::", "64:ff9b::"] as const;
126
+
127
+ /** Every refused address, in whichever family and spelling it arrives. */
128
+ const REFUSED_ADDRESSES = new BlockList();
129
+ for (const [address, prefix] of REFUSED_IPV4) {
130
+ REFUSED_ADDRESSES.addSubnet(address, prefix, "ipv4");
131
+ for (const embedding of IPV4_EMBEDDING_PREFIXES) {
132
+ REFUSED_ADDRESSES.addSubnet(`${embedding}${address}`, 96 + prefix, "ipv6");
133
+ }
134
+ }
135
+ for (const [address, prefix] of REFUSED_IPV6) {
136
+ REFUSED_ADDRESSES.addSubnet(address, prefix, "ipv6");
137
+ }
138
+
139
+ /** Host names refused outright. A name is never resolved, so this is by name alone. */
140
+ const REFUSED_NAMES: ReadonlySet<string> = new Set(["metadata.google.internal"]);
141
+
142
+ /** What a base URL that is not an http(s) URL, or not a URL at all, is refused with. */
143
+ const NOT_HTTP = "Base URL must be an http or https URL.";
144
+
145
+ /** What a base URL whose host is refused is answered with. */
146
+ const HOST_NOT_PERMITTED = "Base URL host is not permitted.";
147
+
148
+ /**
149
+ * Why a provider base URL may not be contacted, or null when it may (specs/ai.md §4).
150
+ *
151
+ * - A URL that does not parse, or whose scheme is not `http:` or `https:`, is refused: the provider
152
+ * is an HTTP endpoint, and this runtime's `fetch` would read a `file:` URL from disk.
153
+ * - A host that is an address in a refused range is refused, in every spelling the URL parser accepts
154
+ * (a decimal or hexadecimal IPv4, an IPv4-mapped, NAT64 or IPv4-compatible IPv6).
155
+ * - A host that is a refused name is refused, with or without a trailing dot.
156
+ *
157
+ * Loopback and private-LAN hosts are deliberately allowed: self-hosted and local models run there.
158
+ * **A name is not resolved**, so a DNS name that resolves into a refused range is not caught: a
159
+ * check made before the request is undone by an answer that changes before the connection opens,
160
+ * and `fetch` cannot be pinned to the address that was checked.
161
+ *
162
+ * @param {string} rawUrl - The base URL a request would be forwarded to
163
+ * @returns {string | null} The sentence the refusal carries, or null
100
164
  */
101
- function isBlockedHost(rawUrl: string): boolean {
102
- let host: string;
165
+ export function baseUrlRefusal(rawUrl: string): string | null {
166
+ let url: URL;
103
167
  try {
104
- host = new URL(rawUrl).hostname.toLowerCase();
168
+ url = new URL(rawUrl);
105
169
  } catch {
106
- return true;
107
- }
108
- const h = host.startsWith("[") ? host.slice(1, -1) : host;
109
- if (h === "metadata.google.internal") {
110
- return true;
170
+ return NOT_HTTP;
111
171
  }
112
- if (h.startsWith("169.254.")) {
113
- return true; // IPv4 link-local, incl. the cloud metadata IP
172
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
173
+ return NOT_HTTP;
114
174
  }
115
- if (h.startsWith("fe80:")) {
116
- return true; // IPv6 link-local
175
+ // The parser lower-cases the host and writes an IPv6 address in brackets.
176
+ const host = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname;
177
+ const family = isIP(host);
178
+ if (family === 0) {
179
+ return REFUSED_NAMES.has(host.endsWith(".") ? host.slice(0, -1) : host)
180
+ ? HOST_NOT_PERMITTED
181
+ : null;
117
182
  }
118
- return false;
183
+ return REFUSED_ADDRESSES.check(host, family === 6 ? "ipv6" : "ipv4") ? HOST_NOT_PERMITTED : null;
119
184
  }
120
185
 
121
- interface AiConfig {
186
+ /** What this server decided for one request: where it goes and with whose key, or why it does not. */
187
+ export interface AiConfig {
122
188
  family: AiProviderFamily;
123
189
  apiKey: string | null;
124
190
  baseUrl: string;
@@ -158,7 +224,16 @@ function familyOf(req: Request): AiProviderFamily | null {
158
224
  return named === "anthropic" ? "anthropic" : null;
159
225
  }
160
226
 
161
- function getConfig(req: Request): AiConfig {
227
+ /**
228
+ * This server's whole provider policy for one request (specs/ai.md §4): the family it names, the
229
+ * base URL it resolves to and whether that URL may be contacted, and the key it may carry there. A
230
+ * `reject` means the request goes nowhere. Every route that forwards a provider key upstream calls
231
+ * this and honours `reject`.
232
+ *
233
+ * @param {Request} req
234
+ * @returns {AiConfig}
235
+ */
236
+ export function resolveAiConfig(req: Request): AiConfig {
162
237
  const authHeader = req.headers.get("Authorization") || "";
163
238
  const apiKeyHeader = req.headers.get("X-Api-Key") || "";
164
239
  const baseUrlHeader = req.headers.get("X-Api-Base-URL") || "";
@@ -195,13 +270,14 @@ function getConfig(req: Request): AiConfig {
195
270
  const baseUrl =
196
271
  baseUrlHeader || process.env[environment.baseUrlVariable] || environment.defaultBaseUrl;
197
272
 
198
- if (isBlockedHost(baseUrl)) {
273
+ const refused = baseUrlRefusal(baseUrl);
274
+ if (refused !== null) {
199
275
  return {
200
276
  apiKey: null,
201
277
  baseUrl,
202
278
  family,
203
279
  missingKey: true,
204
- reject: { status: 403, message: "Base URL host is not permitted." },
280
+ reject: { status: 403, message: refused },
205
281
  };
206
282
  }
207
283
 
@@ -249,7 +325,7 @@ function refuse(status: number, message: string): GatewayRefusal {
249
325
  * session header adds the hashed affinity key; an invalid one is ignored rather than refused.
250
326
  */
251
327
  async function resolveUpstream(req: Request): Promise<Upstream | GatewayRefusal> {
252
- const { apiKey, baseUrl, family, reject } = getConfig(req);
328
+ const { apiKey, baseUrl, family, reject } = resolveAiConfig(req);
253
329
  if (reject) {
254
330
  return refuse(reject.status, reject.message);
255
331
  }
@@ -275,7 +351,19 @@ async function resolveUpstream(req: Request): Promise<Upstream | GatewayRefusal>
275
351
 
276
352
  // ─── /__studio/ai/chat — SSE streaming proxy ───────────────────────────────
277
353
 
354
+ /**
355
+ * The fetch every upstream request is made with: the global one, read at call time, following no
356
+ * redirect. A redirect is the one way a host that was judged can send the proxy to one that was
357
+ * not, so the upstream's `3xx` is reported as the status it is (specs/ai.md §4).
358
+ */
359
+ const upstreamFetch: typeof fetch = Object.assign(
360
+ (input: Parameters<typeof fetch>[0], init?: RequestInit) =>
361
+ fetch(input, { ...init, redirect: "manual" }),
362
+ { preconnect: fetch.preconnect },
363
+ );
364
+
278
365
  const chatHandler = createChatHandler<{ readonly signal: AbortSignal }>({
366
+ fetch: upstreamFetch,
279
367
  resolveUpstream: (request) => resolveUpstream(request),
280
368
  });
281
369
 
@@ -295,7 +383,7 @@ export async function handleChat(req: Request): Promise<Response> {
295
383
  * key is available.
296
384
  */
297
385
  export async function handleModels(req: Request): Promise<Response> {
298
- const { apiKey, baseUrl, family, missingKey, reject } = getConfig(req);
386
+ const { apiKey, baseUrl, family, missingKey, reject } = resolveAiConfig(req);
299
387
  if (reject) {
300
388
  return problemResponse(refuse(reject.status, reject.message));
301
389
  }
@@ -322,7 +410,7 @@ export async function handleModels(req: Request): Promise<Response> {
322
410
  // Key is available — proxy to the upstream /models endpoint.
323
411
  try {
324
412
  const upstreamUrl = `${baseUrl}/models`;
325
- const upstreamResp = await fetch(upstreamUrl, {
413
+ const upstreamResp = await upstreamFetch(upstreamUrl, {
326
414
  headers: { Authorization: `Bearer ${apiKey}` },
327
415
  });
328
416
 
@@ -358,12 +446,14 @@ export async function handleModels(req: Request): Promise<Response> {
358
446
  : Array.isArray(data.data)
359
447
  ? data.data
360
448
  : [];
361
- const models = rawModels.map(({ id, context_window, owned_by }) => ({
362
- id,
363
- name: id,
364
- contextWindow: context_window || 0,
365
- ownedBy: owned_by,
366
- }));
449
+ // `modelsResponse` drops a window that is not positive, so an upstream that sent none says none.
450
+ const models = rawModels.map(({ id, context_window, owned_by }): AiModelInfo => {
451
+ const model: AiModelInfo = { contextWindow: context_window || 0, id, name: id };
452
+ if (owned_by !== undefined) {
453
+ model.ownedBy = owned_by;
454
+ }
455
+ return model;
456
+ });
367
457
 
368
458
  return modelsResponse({ models, configured: true, managed: false, providers: PROVIDERS });
369
459
  } catch (error) {
@@ -391,7 +481,7 @@ async function anthropicModels(apiKey: string | null, baseUrl: string): Promise<
391
481
  if (!apiKey) {
392
482
  return modelsResponse({ ...declared, configured: false, models: ANTHROPIC_DEFAULTS });
393
483
  }
394
- const listing = await listAnthropicModels({ apiKey, baseUrl });
484
+ const listing = await listAnthropicModels({ apiKey, baseUrl }, upstreamFetch);
395
485
  if (listing.ok) {
396
486
  return modelsResponse({ ...declared, configured: true, models: listing.models });
397
487
  }
package/src/import-api.ts CHANGED
@@ -21,15 +21,16 @@
21
21
  * it find" — and a caller that waits for the second to learn the first spends the whole crawl with
22
22
  * nothing to show.
23
23
  *
24
- * LLM key flow (matches ai-api.ts): X-Api-Key / Authorization: Bearer header, falling back to the
25
- * OPENAI_API_KEY env var; base URL from X-Api-Base-URL / OPENAI_BASE_URL. When AI component naming
26
- * is requested but no key resolves, the import proceeds without the AI pass and emits a warning
27
- * line instead of failing.
24
+ * The component-naming pass reaches the provider under the AI proxy's own policy
25
+ * (`resolveAiConfig`, specs/ai.md §4): the same headers, the same key provenance, the same base-URL
26
+ * guard. When naming is requested but that policy refuses the endpoint or resolves no key, the
27
+ * import proceeds without the AI pass and says why in a progress line instead of failing.
28
28
  *
29
29
  * @license MIT
30
30
  */
31
31
 
32
32
  import { readFile } from "node:fs/promises";
33
+ import { resolveAiConfig } from "./ai-api.ts";
33
34
  import { problem } from "./problem.ts";
34
35
  import type { BreakpointPolicy, BreakpointRounding } from "@jxsuite/import/breakpoint-plan";
35
36
  import type { ImportProgressEvent } from "@jxsuite/import/pipeline";
@@ -90,12 +91,6 @@ type ImportStreamLine =
90
91
  | { type: "done"; root: string; config: ProjectConfig; result: ImportDoneSummary }
91
92
  | { type: "error"; error: string };
92
93
 
93
- /** The AI pass's credentials, resolved from the request headers or the environment. */
94
- interface AiConfig {
95
- apiKey: string | null;
96
- baseUrl: string | undefined;
97
- }
98
-
99
94
  /** Seconds between keep-alive lines while a phase is silent (browser launch is the longest gap). */
100
95
  const HEARTBEAT_INTERVAL_MS = 15_000;
101
96
 
@@ -155,26 +150,6 @@ function readBreakpointPolicy(
155
150
  return undefined;
156
151
  }
157
152
 
158
- function getAiConfig(req: Request): AiConfig {
159
- const authHeader = req.headers.get("Authorization") || "";
160
- const apiKeyHeader = req.headers.get("X-Api-Key") || "";
161
- const baseUrlHeader = req.headers.get("X-Api-Base-URL") || "";
162
-
163
- let apiKey: string | null = null;
164
- if (authHeader.startsWith("Bearer ")) {
165
- apiKey = authHeader.slice(7).trim();
166
- }
167
- if (apiKeyHeader) {
168
- apiKey = apiKeyHeader.trim();
169
- }
170
- if (!apiKey && process.env.OPENAI_API_KEY) {
171
- apiKey = process.env.OPENAI_API_KEY;
172
- }
173
-
174
- const baseUrl = baseUrlHeader || process.env.OPENAI_BASE_URL || undefined;
175
- return { apiKey, baseUrl };
176
- }
177
-
178
153
  /** Handle POST /__studio/import-site — run the import pipeline, streaming NDJSON progress. */
179
154
  async function handleImportSite(req: Request, opts: ImportApiOptions): Promise<Response> {
180
155
  let body: ImportRequestBody;
@@ -231,7 +206,7 @@ async function handleImportSite(req: Request, opts: ImportApiOptions): Promise<R
231
206
  const maxPages = clamp(body.maxPages ?? 20, 1, IMPORT_MAX_PAGES);
232
207
  const maxNodesPerPage = clamp(body.maxNodesPerPage ?? 5000, 100, 50_000);
233
208
  const breakpoints = readBreakpointPolicy(body.breakpoints);
234
- const { apiKey, baseUrl } = getAiConfig(req);
209
+ const { apiKey, baseUrl, reject } = resolveAiConfig(req);
235
210
  const toRoot = opts.toRoot ?? ((p: string) => p);
236
211
 
237
212
  const encoder = new TextEncoder();
@@ -259,7 +234,13 @@ async function handleImportSite(req: Request, opts: ImportApiOptions): Promise<R
259
234
  | false
260
235
  | { apiKey: string; baseUrl?: string | undefined; model?: string | undefined } = false;
261
236
  if (body.aiComponents) {
262
- if (apiKey) {
237
+ if (reject) {
238
+ writeLine({
239
+ type: "progress",
240
+ phase: "ai",
241
+ message: `⚠ AI component naming skipped: ${reject.message} Continuing with heuristic names.`,
242
+ });
243
+ } else if (apiKey) {
263
244
  ai = { apiKey, baseUrl, model: body.aiModel };
264
245
  } else {
265
246
  writeLine({
package/src/problem.ts CHANGED
@@ -74,6 +74,9 @@ export function problemTypeForStatus(status: number): ProblemTypeName {
74
74
  case 413: {
75
75
  return "payloadTooLarge";
76
76
  }
77
+ case 429: {
78
+ return "rateLimited";
79
+ }
77
80
  case 501: {
78
81
  return "capabilityUnavailable";
79
82
  }