Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/services/research/broker.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Egress broker (contract: docs/next/CONTRACT.md §9.2): the only network endpoint a sandboxed process can reach.47 *48 * It listens on 127.0.0.1 on a random port and does two things, both authenticated by the per-process token the49 * sandbox was given:50 *51 * - Market data. GET /fmp/<path>?… → FMP, with the server's key added52 * ANY /findata/api/v1/… → the FinData lake, with the server's key added53 * The notebook helpers (prices(), closes(), fmp.*, findata.*) call these exactly as they called the providers,54 * so analysis code never holds a provider key.55 *56 * - HTTPS proxy (CONNECT). By default only the package index hosts are allowed, so `pip`/`uv` can install. A run57 * that the person explicitly approved for open network may reach any public host; private, loopback and58 * link-local addresses are refused in every case (the node sits on a LAN with other machines), and each59 * destination is written to the run's network log.60 *61 * Nothing here ever returns a key: upstream errors are passed through redactSecrets.62 */63import http, { type IncomingMessage, type ServerResponse } from "node:http";64import net from "node:net";65import dns from "node:dns/promises";66import { randomBytes, timingSafeEqual } from "node:crypto";67import fs from "node:fs";68import path from "node:path";69import { redactSecrets } from "../python/lab";7071export interface BrokerGrant {72 owner: string;73 workspace: string;74 /** "default" = data + package index; "open" = any public host (approved and audited by the caller) */75 network: "default" | "open";76 label?: string;77}7879const PACKAGE_HOSTS = ["pypi.org", "files.pythonhosted.org"];80/** VQ_FMP_UPSTREAM exists for tests (a local stand-in for the provider). */81const fmpUpstream = () => (process.env.VQ_FMP_UPSTREAM || "https://financialmodelingprep.com/stable").replace(/\/+$/, "");82const grants = new Map<string, BrokerGrant & { issuedAt: number; requests: number; windowStart: number }>();83const MAX_REQUESTS_PER_MINUTE = 900;8485let server: http.Server | null = null;86let port = 0;87let starting: Promise<number> | null = null;8889export function allowedHosts(): string[] {90 const extra = (process.env.VQ_RESEARCH_ALLOW_HOSTS ?? "").split(",").map((h) => h.trim().toLowerCase()).filter((h) => /^[a-z0-9.-]+$/.test(h));91 return [...PACKAGE_HOSTS, ...extra];92}9394/** A token for one sandboxed process. Revoke it when the process ends. */95export function issueToken(grant: BrokerGrant): string {96 const token = randomBytes(24).toString("hex");97 grants.set(token, { ...grant, issuedAt: Date.now(), requests: 0, windowStart: Date.now() });98 return token;99}100export function revokeToken(token: string | null | undefined): void {101 if (token) grants.delete(token);102}103104function grantOf(token: string | undefined): (BrokerGrant & { requests: number; windowStart: number }) | null {105 if (!token || token.length !== 48) return null;106 for (const [known, g] of grants) {107 if (known.length === token.length && timingSafeEqual(Buffer.from(known), Buffer.from(token))) {108 const now = Date.now();109 if (now - g.windowStart > 60_000) {110 g.windowStart = now;111 g.requests = 0;112 }113 g.requests++;114 return g;115 }116 }117 return null;118}119120/** Addresses a sandboxed process must never reach through the proxy, whatever was approved. */121export function isPrivateAddress(ip: string): boolean {122 if (net.isIPv4(ip)) {123 const [a, b] = ip.split(".").map(Number);124 return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224;125 }126 const v6 = ip.toLowerCase();127 if (v6.startsWith("::ffff:")) return isPrivateAddress(v6.slice(7));128 return v6 === "::1" || v6 === "::" || v6.startsWith("fc") || v6.startsWith("fd") || v6.startsWith("fe8") || v6.startsWith("fe9") || v6.startsWith("fea") || v6.startsWith("feb") || v6.startsWith("ff");129}130131function tokenFromHeaders(req: IncomingMessage): string | undefined {132 const x = req.headers["x-vq-token"];133 if (typeof x === "string") return x;134 const auth = String(req.headers.authorization ?? "");135 if (auth.startsWith("Bearer ")) return auth.slice(7).trim();136 const proxy = String(req.headers["proxy-authorization"] ?? "");137 if (proxy.startsWith("Basic ")) return Buffer.from(proxy.slice(6), "base64").toString().split(":").slice(1).join(":");138 return undefined;139}140141function netLog(g: BrokerGrant, line: string): void {142 try {143 const dir = path.join(g.workspace, "logs");144 fs.mkdirSync(dir, { recursive: true });145 fs.appendFileSync(path.join(dir, "network.log"), `${new Date().toISOString()} ${g.label ?? "-"} ${line}\n`);146 } catch {147 /* the log is best effort */148 }149}150151const send = (res: ServerResponse, status: number, error: string): void => {152 if (res.headersSent) return void res.end();153 res.writeHead(status, { "Content-Type": "application/json" });154 res.end(JSON.stringify({ error }));155};156157async function relay(res: ServerResponse, url: string, init: RequestInit): Promise<void> {158 try {159 const upstream = await fetch(url, { ...init, signal: AbortSignal.timeout(150_000), redirect: "follow" });160 const type = upstream.headers.get("content-type") ?? "application/json";161 if (upstream.status >= 400) {162 // Provider errors sometimes echo the request, key included.163 const text = redactSecrets((await upstream.text()).slice(0, 4000));164 res.writeHead(upstream.status, { "Content-Type": type });165 res.end(text);166 return;167 }168 res.writeHead(upstream.status, { "Content-Type": type });169 if (!upstream.body) return void res.end();170 const reader = upstream.body.getReader();171 for (;;) {172 const { done, value } = await reader.read();173 if (done) break;174 res.write(value);175 }176 res.end();177 } catch (e) {178 send(res, 502, redactSecrets(`The data provider could not be reached: ${(e as Error).message}`));179 }180}181182function readBody(req: IncomingMessage, max = 4 * 1024 * 1024): Promise<Buffer> {183 return new Promise((resolve, reject) => {184 const chunks: Buffer[] = [];185 let size = 0;186 req.on("data", (c: Buffer) => {187 size += c.length;188 if (size > max) {189 reject(new Error("Request body too large"));190 req.destroy();191 } else chunks.push(c);192 });193 req.on("end", () => resolve(Buffer.concat(chunks)));194 req.on("error", reject);195 });196}197198async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {199 const url = new URL(req.url ?? "/", "http://broker");200 // The FMP client sends its "key" as the apikey parameter: in the sandbox that key is the broker token.201 const g = grantOf(tokenFromHeaders(req) ?? url.searchParams.get("apikey") ?? undefined);202 if (!g) return send(res, 401, "Unknown or expired sandbox token.");203 if (g.requests > MAX_REQUESTS_PER_MINUTE) return send(res, 429, "Too many requests from this run: slow down.");204 // A proxy-style request (absolute URL) for plain HTTP is not served: only CONNECT to allowed hosts.205 if (/^https?:\/\//i.test(req.url ?? "")) return send(res, 403, "Plain HTTP through the proxy is not available. Use https.");206 if (url.pathname.includes("..") || url.pathname.includes("//")) return send(res, 400, "Invalid path.");207208 if (url.pathname.startsWith("/fmp/")) {209 if (req.method !== "GET") return send(res, 405, "FMP is read-only.");210 const key = process.env.FMP_API_KEY;211 if (!key) return send(res, 503, "FMP is not configured on this server.");212 url.searchParams.set("apikey", key);213 return relay(res, `${fmpUpstream()}${url.pathname.slice(4)}?${url.searchParams.toString()}`, { method: "GET" });214 }215 if (url.pathname.startsWith("/findata/")) {216 const key = process.env.FINDATA_API_KEY;217 if (!key) return send(res, 503, "FinData is not configured on this server.");218 const base = (process.env.FINDATA_URL || "https://findata.spboucher.ai").replace(/\/+$/, "");219 const method = req.method ?? "GET";220 if (!["GET", "POST"].includes(method)) return send(res, 405, "Method not allowed.");221 const body = method === "POST" ? await readBody(req) : undefined;222 url.searchParams.delete("apikey");223 const qs = url.searchParams.toString();224 return relay(res, `${base}${url.pathname.slice(8)}${qs ? `?${qs}` : ""}`, { method, body, headers: { Authorization: `Bearer ${key}`, ...(body ? { "Content-Type": String(req.headers["content-type"] ?? "application/json") } : {}) } });225 }226 if (url.pathname === "/health") {227 res.writeHead(200, { "Content-Type": "application/json" });228 return void res.end(JSON.stringify({ ok: true, network: g.network, packageHosts: allowedHosts() }));229 }230 send(res, 404, "Unknown broker path. Market data: /fmp/… and /findata/…");231}232233async function connect(req: IncomingMessage, client: net.Socket, head: Buffer): Promise<void> {234 const refuse = (status: number, why: string) => {235 client.write(`HTTP/1.1 ${status} ${why}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n${why}\n`);236 client.destroy();237 };238 const g = grantOf(tokenFromHeaders(req));239 if (!g) return refuse(407, "Unknown or expired sandbox token");240 if (g.requests > MAX_REQUESTS_PER_MINUTE) return refuse(429, "Too many requests");241 const m = /^([A-Za-z0-9.-]+):(\d{1,5})$/.exec(req.url ?? "");242 if (!m) return refuse(400, "Bad CONNECT target");243 const host = m[1].toLowerCase();244 const targetPort = Number(m[2]);245 const listed = allowedHosts().includes(host);246 if (!listed && g.network !== "open") {247 netLog(g, `DENIED ${host}:${targetPort}`);248 return refuse(403, `Network access to ${host} is not allowed in this run. Only the package index is reachable; market data goes through prices()/fmp/findata. Ask the user for an open-network run if the research needs this host.`);249 }250 if (targetPort !== 443 && !(g.network === "open" && targetPort === 80)) return refuse(403, "Only HTTPS (port 443) is allowed");251 let address: string;252 try {253 address = net.isIP(host) ? host : (await dns.lookup(host, { family: 4 })).address;254 } catch {255 return refuse(502, `Cannot resolve ${host}`);256 }257 // Checked on the resolved address, and the connection is made to that same address (no second lookup to race).258 if (isPrivateAddress(address)) {259 netLog(g, `DENIED-PRIVATE ${host} (${address})`);260 return refuse(403, "Private, loopback and link-local addresses are never reachable from a run");261 }262 if (!listed) netLog(g, `CONNECT ${host}:${targetPort}`);263 const upstream = net.connect(targetPort, address, () => {264 client.write("HTTP/1.1 200 Connection Established\r\n\r\n");265 if (head.length) upstream.write(head);266 upstream.pipe(client);267 client.pipe(upstream);268 });269 upstream.setTimeout(300_000, () => upstream.destroy());270 upstream.on("error", () => client.destroy());271 client.on("error", () => upstream.destroy());272}273274/** Starts the broker if needed and returns its loopback port. */275export function ensureBroker(): Promise<number> {276 if (server && port) return Promise.resolve(port);277 starting ??= new Promise<number>((resolve, reject) => {278 const s = http.createServer((req, res) => {279 void handle(req, res).catch((e) => send(res, 500, redactSecrets(String((e as Error).message))));280 });281 s.on("connect", (req, socket, head) => void connect(req, socket as net.Socket, head).catch(() => (socket as net.Socket).destroy()));282 s.on("error", reject);283 s.listen(0, "127.0.0.1", () => {284 server = s;285 port = (s.address() as net.AddressInfo).port;286 s.unref();287 resolve(port);288 });289 });290 return starting;291}292293export function brokerUrl(p: number): string {294 return `http://127.0.0.1:${p}`;295}296297export async function __stopBroker(): Promise<void> {298 const s = server;299 server = null;300 port = 0;301 starting = null;302 grants.clear();303 if (s) await new Promise<void>((r) => s.close(() => r()));304}305