diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fff260049..0b487004ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Changes +- **dist is self-contained again: the zod leak from the jimp image-rescale lane is bundled away, with a build gate to keep it away (#3511 P0).** #3425 inlined jimp (pure-JS image encoder, devDependency), and jimp imports zod at module scope — leaking 16 STATIC `from"zod"` imports into `dist/index.js` and `dist/agent/pi-native.js`. Static imports resolve at module load with no degrade path, so installs that ship the package without its node_modules (dsh profile bare copies, thin plugin copies — the real dsh/pi plugin shapes) died with `ERR_MODULE_NOT_FOUND` and model traffic silently went direct, uncompressed. zod is now bundled like every other transitive of an inlined dependency (dist/index.js grows ~1.4 MB); the ONE sanctioned external consumer — the opencode V1 host interop, which wants the HOST's zod instance and already degrades when unresolvable — keeps its own runtime resolution through an opaque specifier. `npm run build` now fails on any static zod import surviving into dist (`scripts/check-dist-external-zod.mjs`). Verified: a bare `dist/` copy with zero node_modules runs `node dist/index.js --version` clean. - **dsh web settings panel: the embed pre-flight gets its CORS answer (#3513).** The #3100 pre-flight fetches `/__bili/?embed=1` CROSS-origin — the dsh web page lives on the host's port, the proxy on its own, and while both are loopback names (so the trusted-origin gate admits the request), a cors-mode fetch is only readable when the response carries `access-control-allow-origin`. It never did: the browser rejected the probe, the verdict never landed, and the pane stayed on "connecting to the bili proxy…" forever while the proxy itself (model traffic, iframe navigation) kept working. The embed-face GET now echoes the requesting Origin — a static HTML shell with no state, reachable only by origins the #115/#1537 gates already admitted; clients without an Origin header (curl, CLIs) see no header at all, and the DNS-rebinding gates are untouched. - **Egress image downscale + `read_original_image` (#3400).** Redoes the image pre-compression removed in #3295 in simplified form — **behavior change**: since #3295 every image passed through byte-identical at original resolution; from this version on, large outbound images are sent SHRUNKEN by default. On every outbound request (after kernel folding, before protocol encoding, all protocols share one pass) an image whose longest edge exceeds 1600 px (`BILI_IMAGE_RESCALE_MAX_DIM`) or whose base64 body exceeds 100 KB is re-encoded fit-inside (never upscaled, original format kept) on an OUTBOUND COPY only — session storage keeps the original bytes byte-exact. A re-encode saving less than 20% of the bytes is discarded (keep-smaller), so small and low-benefit images pass through untouched; only PNG/JPEG/BMP are handled (pure-JS jimp encoder, zero native dependencies — sharp does not return). Each shrunken image carries a stable annotation beside it reporting current vs original size; lanes that register bili tools (proxy-injection lanes, plugin lanes via the plugin manifest) also get the tool named in the annotation — `read_original_image("mNNNNN")` returns the original bytes from local session storage — while tool-rejecting lanes (codex) get size-only notes and no tool. Tool results are structurally exempt from re-shrinking (zero-state loop guard against the #3266 guess-reject-resend disease). Output is deterministic (content-hash cached, one encode per unique image; same history → byte-identical outbound bodies) so upstream prefix caching is undisturbed. Observability: one log line per unique image (dims+bytes before/after) and one per original-image read (ref, sizes, session cumulative count+bytes) — no hard cap, the model was told the sizes. Knobs: `BILI_IMAGE_RESCALE` (`"0"`/`"false"` off; default on), `BILI_IMAGE_RESCALE_MAX_DIM` (default 1600, env-only), config-file key `imageRescale`. Legacy `compress.imageCompression.*` INERT warnings remain owned by #3344/#3355. - **Lane-decisions 收尾:四处 B 类旁路迁入统一决策点 + nudgeOn 单点(#3482,承接 #3417)。** ①omp 身份戳通道(`stampPromptCacheKey` 的 `agent !== "omp"` 门)改为注册表属性 `stampsBodyPromptCacheKey`;OMP Cowork 直连传输的"是否可能"进注册表(`coworkTransportPossible`),逐请求真相仍由环境观察(`ompCoworkTransportBypassesFetch`)给出。②codex/claude-responses 的 instructions 指纹键控从散落头名比较收进 `WIRE_CLIENTS` 注册表(`instructionsFingerprintKeyed`;信号检测留在 session-id,决策表只在注册表)。③计费块(#2189)提取改由 `laneDecisions.billingBlockWanted` 门控:profile 声明(dsh)或 wire 观察到块任一成立即提取——证据优先,与 toolsReachable 同形状;零 wire 字节变更。④四份手抄 `willInjectNudge` 合取收敛为 `nudgeOn()` 九入参纯函数:responses 的两处有意差异(compaction-trigger 豁免、codex-intercept 健康窗)显式入参,openai/google 的冗余 `shouldInject` 合取被 `compressSurfaceOn` 吸收;1024 点布尔立方等价测试 + 四车道旧公式逐位对照钉死。结构守卫扩展:B 类站点禁裸 lane 名门控,`WIRE_CLIENTS` 注册表条目必须有 `matches()`。⑤HostProfile 注册表整体落在零导入叶子模块 `src/host-profiles.ts`(review 修正:首版让 agent 侧直接 import lane-decisions,preflight→kernel 整链被拖进 dist/agent/pi.js、omp.js,两个宿主扩展包体积翻倍;拆出后两者回到原尺寸,结构守卫钉死该模块必须无 import)。`wantsBillingBlock` 死属性落位为真实消费者(上述③)。dshLedgerFloorTokens 本无 lane 名查(issue 前提修正:#1729 守卫故意 identity-blind,#2193)——三处 ledger floor 调用点保持不动并在 PR 说明。 diff --git a/package.json b/package.json index db5fd6170a..5d5508b867 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "bili-proxy": "./dist/index.js" }, "scripts": { - "build": "npm --prefix kernel run build && npm --prefix pi-subagents run build && tsup && node scripts/write-build-info.mjs && node scripts/check-dist-import-annotations.mjs", + "build": "npm --prefix kernel run build && npm --prefix pi-subagents run build && tsup && node scripts/write-build-info.mjs && node scripts/check-dist-import-annotations.mjs && node scripts/check-dist-external-zod.mjs", "prepare": "node scripts/check-dist-ready.mjs", "registry:snapshot": "node scripts/update-registry-snapshot.mjs", "codex-models:snapshot": "node scripts/update-codex-models-snapshot.mjs", diff --git a/scripts/check-dist-external-zod.mjs b/scripts/check-dist-external-zod.mjs new file mode 100644 index 0000000000..58c766309d --- /dev/null +++ b/scripts/check-dist-external-zod.mjs @@ -0,0 +1,86 @@ +// Build gate: fail if any STATIC import of "zod" survives into dist. +// +// zod is a declared runtime dependency for exactly one sanctioned consumer: +// the opencode V1 host interop (src/agent/opencode-native.ts), which loads it +// LAZILY through an opaque specifier so it resolves the HOST's zod instance +// inside opencode and degrades to proxy mode on thin installs. Everything +// else must be bundled: #3425 inlined jimp (devDependency, noExternal) whose +// module-scope `import { z } from "zod"` leaked 16 static `from"zod"` imports +// into dist/index.js and dist/agent/pi-native.js. Static imports resolve at +// module load with NO degrade path — installs that ship the package without +// its node_modules (dsh profile bare copies, thin plugin copies: the real +// dsh/pi plugin shapes) died with ERR_MODULE_NOT_FOUND and model traffic +// silently went direct, uncompressed (#3511 P0). The fix bundles zod via +// noExternal; this check keeps it bundled. +// +// Violations matched (specifier must be the bare literal "zod"): +// - import ... from "zod" (any static import form) +// - export ... from "zod" +// - require("zod") +// - import("zod") (literal dynamic — esbuild would have +// bundled or rewritten it; the sanctioned +// lazy load goes through a variable) +// +// Bare-specifier NODE builtins are fine (node:*, fs, crypto, ...); other +// packages are inlined by noExternal, so "zod" is the only name that can +// appear here legitimately only through the sanctioned opaque path, which +// this regex cannot match. + +import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { fileURLToPath } from "node:url"; + +const STATIC_ZOD = [ + /import\s*[^;(]*?from\s*(["'])zod\1/g, + /export\s*[^;(]*?from\s*(["'])zod\1/g, + /require\s*\(\s*(["'])zod\1\s*\)/g, + /import\s*\(\s*(["'])zod\1\s*\)/g, +]; + +export function findStaticZodRefs(text) { + const hits = []; + for (const re of STATIC_ZOD) { + re.lastIndex = 0; + let m; + while ((m = re.exec(text)) !== null) { + const line = text.slice(0, m.index).split("\n").length; + hits.push(`${re.source.slice(0, 40)}… line ${line}`); + } + } + return hits; +} + +export function checkDistExternalZod(distDir) { + const violations = []; + const walk = (dir) => { + for (const name of readdirSync(dir)) { + const full = path.join(dir, name); + const st = statSync(full); + if (st.isDirectory()) { walk(full); continue; } + if (!name.endsWith(".js")) continue; + const refs = findStaticZodRefs(readFileSync(full, "utf8")); + if (refs.length > 0) violations.push({ file: full, refs }); + } + }; + walk(distDir); + return violations; +} + +const invoked = process.argv[1]; +// Realpath both sides: Node resolves entry-point symlinks, so argv[1] can differ from import.meta.url +const isMain = !!invoked && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(invoked); +if (isMain) { + const distDir = process.argv[2] ?? "dist"; + const violations = checkDistExternalZod(distDir); + if (violations.length > 0) { + for (const v of violations) { + console.error(`dist-external-zod: ${v.file}:`); + for (const r of v.refs.slice(0, 5)) console.error(` ${r}`); + if (v.refs.length > 5) console.error(` … (+${v.refs.length - 5} more)`); + } + console.error(`dist-external-zod: FAIL — ${violations.reduce((n, v) => n + v.refs.length, 0)} static zod import ref(s) across ${violations.length} file(s). dist must stay self-contained: bundle zod (tsup noExternal) or load it through the sanctioned opaque lazy path (opencode V1 interop). Static zod imports crash thin installs (no node_modules) with ERR_MODULE_NOT_FOUND (#3511 P0).`); + process.exit(1); + } + console.log("dist-external-zod: OK"); +} diff --git a/src/agent/opencode-native.ts b/src/agent/opencode-native.ts index 62818d15ee..387c38bf59 100644 --- a/src/agent/opencode-native.ts +++ b/src/agent/opencode-native.ts @@ -807,7 +807,14 @@ const server = async (ctx: V1PluginContext): Promise => { console.log(`[bili-opencode-native] v1 active (proxy ${origin})`); let z: ZodLike | undefined; try { - z = (await import("zod")) as ZodLike; + // Opaque specifier on purpose (#3511 P0 follow-up): zod is now bundled + // into dist for the jimp lane, and a literal import("zod") here would + // let esbuild rewrite it to that inlined copy. The V1 interop needs the + // HOST's zod instance when running inside opencode (the host registry + // safeParses with its own zod object shapes), and thin installs without + // node_modules must keep the documented degrade to proxy mode. + const zodSpecifier = "zod"; + z = (await import(zodSpecifier)) as ZodLike; } catch { z = undefined; } diff --git a/tests/check-dist-external-zod.test.ts b/tests/check-dist-external-zod.test.ts new file mode 100644 index 0000000000..c3dbabc839 --- /dev/null +++ b/tests/check-dist-external-zod.test.ts @@ -0,0 +1,47 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +const gateSpec = "../scripts/check-dist-external-zod.mjs"; +const { findStaticZodRefs, checkDistExternalZod } = await import(gateSpec) as { + findStaticZodRefs: (text: string) => string[]; + checkDistExternalZod: (distDir: string) => Array<{ file: string; refs: string[] }>; +}; + +/** The guard exists because #3425's jimp inlining leaked 16 STATIC + * `from"zod"` imports into dist — module-load-time imports with no degrade + * path, crashing every thin install (package without node_modules). These + * tests pin the regex so the gate keeps catching exactly that class and + * never flags the sanctioned lazy path (opaque specifier) or plain + * "zod" strings (zod's own vendor markers survive bundling). */ + +test("static zod import forms are violations (the #3425 leak shapes)", () => { + const hits = findStaticZodRefs( + `import{z as z2}from"zod";const r=require("zod");await import("zod");export{x}from"zod";`, + ); + assert.equal(hits.length, 4, "minified static import, require, literal dynamic import, re-export"); +}); + +test("the sanctioned lazy path and incidental zod strings are not violations", () => { + const clean = findStaticZodRefs( + `const zodSpecifier="zod";const z=await import(zodSpecifier);const v={vendor:"zod"};`, + ); + assert.equal(clean.length, 0); +}); + +test("checkDistExternalZod reports per file", async () => { + const { mkdirSync, writeFileSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const path = await import("node:path"); + const dir = path.join(tmpdir(), `bili-zod-guard-${process.pid}-${Date.now()}`); + mkdirSync(dir, { recursive: true }); + try { + writeFileSync(path.join(dir, "good.js"), `const s="zod";await import(s);\n`, "utf8"); + writeFileSync(path.join(dir, "bad.js"), `import{z}from"zod";\n`, "utf8"); + writeFileSync(path.join(dir, "not-js.txt"), `import{z}from"zod"\n`, "utf8"); + const violations = checkDistExternalZod(dir); + assert.equal(violations.length, 1); + assert.match(violations[0].file, /bad\.js$/); + assert.equal(violations[0].refs.length, 1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/tsup.config.ts b/tsup.config.ts index 6867e1b58b..8f9ad90a1d 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -45,7 +45,19 @@ defineConfig({ // so its dist is self-contained too. // jimp (#3400): pure-JS image encoder, devDependency inlined like every // other bundled dep — dist stays self-contained, zero native modules. - noExternal: ["acp-kernel", "billion-context-pi-subagents", "fzstd", "jimp", "node-forge", "semver", "tar", "undici", "jsonc-parser", "ws"], + // zod (#3511 P0): jimp imports zod at module scope, so inlining jimp + // leaked 16 STATIC `from"zod"` imports into dist/index.js and + // dist/agent/pi-native.js. zod is a real runtime dependency (opencode V1 + // host interop), which kept it external — but static module-load imports + // have no degrade path, so thin installs (dsh profile bare copies, pi + // plugin copies: the package without its node_modules) died with + // ERR_MODULE_NOT_FOUND and traffic silently went direct. Bundle zod like + // every other transitive of an inlined dep. The opencode V1 host-interop + // load keeps its OWN runtime resolution (opaque specifier in + // opencode-native.ts) so the HOST's zod instance still wins there, and + // thin installs keep the documented degrade. scripts/check-dist-external- + // zod.mjs fails the build if a static zod import ever reappears. + noExternal: ["acp-kernel", "billion-context-pi-subagents", "fzstd", "jimp", "node-forge", "semver", "tar", "undici", "jsonc-parser", "ws", "zod"], banner: { // node-forge is a CommonJS dependency that calls require("crypto") etc. // inlined into our ESM output, esbuild's __require shim throws in an