diff --git a/.gitignore b/.gitignore
index 252a570..292412b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
node_modules/
+captcha_node/node_modules/
*.log
config.yaml
.omo/evidence/
diff --git a/captcha_node/package.json b/captcha_node/package.json
new file mode 100644
index 0000000..bb2c188
--- /dev/null
+++ b/captcha_node/package.json
@@ -0,0 +1,11 @@
+{
+ "name": "zcode-proxy-captcha-solver",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Headless Aliyun traceless captcha solver (jsdom)",
+ "type": "commonjs",
+ "main": "solver.js",
+ "dependencies": {
+ "jsdom": "^24.1.0"
+ }
+}
diff --git a/captcha_node/solver.js b/captcha_node/solver.js
new file mode 100644
index 0000000..866ee38
--- /dev/null
+++ b/captcha_node/solver.js
@@ -0,0 +1,225 @@
+const { JSDOM, VirtualConsole } = require('jsdom');
+const SCENE = process.argv[2] || '11xygtvd';
+const REGION = process.argv[3] || 'sgp';
+const PREFIX = process.argv[4] || 'no8xfe';
+
+const vc = new VirtualConsole();
+vc.on('error', (...a) => process.stderr.write('[jsdom] ' + a.join(' ') + '\n'));
+vc.on('warn', (...a) => process.stderr.write('[jsdom warn] ' + a.join(' ') + '\n'));
+
+const html = `
+
+
+`;
+
+const USER_AGENT =
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
+
+function applyPolyfills(window) {
+ window.matchMedia = () => ({
+ matches: false,
+ media: '',
+ onchange: null,
+ addListener() {},
+ removeListener() {},
+ addEventListener() {},
+ removeEventListener() {},
+ dispatchEvent() {
+ return false;
+ },
+ });
+
+ const proto = window.HTMLCanvasElement.prototype;
+ proto.getContext = function (type) {
+ if (/webgl/i.test(type)) {
+ return {
+ canvas: this,
+ getParameter: () => 'Intel Inc.',
+ getExtension: () => null,
+ getSupportedExtensions: () => ['WEBGL_debug_renderer_info'],
+ getContextAttributes: () => ({}),
+ getShaderPrecisionFormat: () => ({ precision: 23, rangeMin: 127, rangeMax: 127 }),
+ };
+ }
+ return {
+ canvas: this,
+ fillRect() {},
+ clearRect() {},
+ getImageData: (x, y, w = 1, h = 1) => ({ data: new Uint8ClampedArray(w * h * 4) }),
+ putImageData() {},
+ createImageData: (w = 1, h = 1) => ({ data: new Uint8ClampedArray(w * h * 4) }),
+ setTransform() {},
+ transform() {},
+ drawImage() {},
+ save() {},
+ restore() {},
+ beginPath() {},
+ moveTo() {},
+ lineTo() {},
+ bezierCurveTo() {},
+ quadraticCurveTo() {},
+ closePath() {},
+ clip() {},
+ stroke() {},
+ fill() {},
+ arc() {},
+ rect() {},
+ ellipse() {},
+ translate() {},
+ scale() {},
+ rotate() {},
+ fillText() {},
+ strokeText() {},
+ measureText: (t) => ({ width: ('' + t).length * 8 }),
+ createLinearGradient: () => ({ addColorStop() {} }),
+ createRadialGradient: () => ({ addColorStop() {} }),
+ createPattern: () => ({}),
+ isPointInPath: () => false,
+ font: '10px sans-serif',
+ textBaseline: 'alphabetic',
+ textAlign: 'start',
+ fillStyle: '#000',
+ strokeStyle: '#000',
+ globalAlpha: 1,
+ lineWidth: 1,
+ shadowBlur: 0,
+ shadowColor: '',
+ };
+ };
+ proto.toDataURL = () =>
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
+ proto.toBlob = (cb) => cb && cb(null);
+
+ window.Worker = class {
+ constructor() {}
+ postMessage() {}
+ terminate() {}
+ addEventListener() {}
+ removeEventListener() {}
+ onmessage = null;
+ onerror = null;
+ };
+ window.OffscreenCanvas =
+ window.OffscreenCanvas ||
+ class {
+ constructor(w, h) {
+ this.width = w;
+ this.height = h;
+ }
+ getContext() {
+ return proto.getContext.call(this);
+ }
+ };
+
+ try {
+ Object.defineProperty(window.document, 'hidden', { value: false, configurable: true });
+ Object.defineProperty(window.document, 'visibilityState', {
+ value: 'visible',
+ configurable: true,
+ });
+ } catch (_) {}
+
+ const nav = window.navigator;
+ const navPatch = {
+ userAgent: USER_AGENT,
+ platform: 'Win32',
+ language: 'en-US',
+ languages: ['en-US', 'en'],
+ vendor: 'Google Inc.',
+ webdriver: false,
+ hardwareConcurrency: 8,
+ deviceMemory: 8,
+ maxTouchPoints: 0,
+ cookieEnabled: true,
+ plugins: { length: 3, item: () => null, namedItem: () => null, refresh() {} },
+ mimeTypes: { length: 0, item: () => null, namedItem: () => null },
+ };
+ for (const [k, v] of Object.entries(navPatch)) {
+ try {
+ Object.defineProperty(nav, k, { value: v, configurable: true });
+ } catch (_) {}
+ }
+
+ window.screen = {
+ width: 1920,
+ height: 1080,
+ availWidth: 1920,
+ availHeight: 1040,
+ colorDepth: 24,
+ pixelDepth: 24,
+ };
+ window.chrome = { runtime: {} };
+ window.outerWidth = 1920;
+ window.outerHeight = 1080;
+ window.innerWidth = 1280;
+ window.innerHeight = 720;
+ window.devicePixelRatio = 1;
+}
+
+const dom = new JSDOM(html, {
+ url: 'https://zcode.z.ai/',
+ runScripts: 'dangerously',
+ resources: 'usable',
+ pretendToBeVisual: true,
+ virtualConsole: vc,
+ userAgent: USER_AGENT,
+ beforeParse(window) {
+ applyPolyfills(window);
+ window.AliyunCaptchaConfig = { region: REGION, prefix: PREFIX };
+ },
+});
+const { window } = dom;
+
+function waitFor(cond, t = 12000) {
+ return new Promise((res, rej) => {
+ const s = Date.now();
+ const i = setInterval(() => {
+ let ok = false;
+ try {
+ ok = cond();
+ } catch (_) {}
+ if (ok) {
+ clearInterval(i);
+ res();
+ } else if (Date.now() - s > t) {
+ clearInterval(i);
+ rej(new Error('timeout'));
+ }
+ }, 80);
+ });
+}
+
+(async () => {
+ await waitFor(() => typeof window.initAliyunCaptcha === 'function');
+ window.initAliyunCaptcha({
+ SceneId: SCENE,
+ mode: 'popup',
+ region: REGION,
+ prefix: PREFIX,
+ language: 'en',
+ element: '#cap',
+ button: '#btn',
+ captchaLogoImg: '',
+ showErrorTip: false,
+ getInstance: (inst) => {
+ try {
+ (inst.startTracelessVerification || inst.show).call(inst);
+ } catch (e) {
+ console.error('start', e.message);
+ }
+ },
+ success: (param) => {
+ console.log('VERIFY_PARAM=' + param);
+ process.exit(0);
+ },
+ fail: (err) => {
+ process.stderr.write('fail=' + JSON.stringify(err) + '\n');
+ process.exit(4);
+ },
+ onError: (err) => {
+ process.stderr.write('onError=' + JSON.stringify(err) + '\n');
+ process.exit(5);
+ },
+ });
+ setTimeout(() => process.exit(2), 25000);
+})().catch(() => process.exit(3));
diff --git a/package.json b/package.json
index 3573a00..caee16f 100644
--- a/package.json
+++ b/package.json
@@ -5,14 +5,13 @@
"scripts": {
"dev": "bun run src/index.ts",
"start": "bun run src/index.ts",
- "test": "bun test"
+ "test": "bun test",
+ "postinstall": "npm install --prefix captcha_node --omit=dev",
+ "test:start-plan": "node scripts/test-start-plan.mjs"
},
"dependencies": {
"yaml": "^2.5.0"
},
- "optionalDependencies": {
- "playwright": "^1.61.0"
- },
"devDependencies": {
"@types/bun": "latest"
}
diff --git a/scripts/test-start-plan.mjs b/scripts/test-start-plan.mjs
new file mode 100644
index 0000000..b6709cf
--- /dev/null
+++ b/scripts/test-start-plan.mjs
@@ -0,0 +1,153 @@
+/**
+ * Manual start-plan smoke test — run before opening PR.
+ * JWT: data/store.json (zcode_jwt) or ZCODE_JWT env override.
+ */
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const STORE = path.resolve(ROOT, "../../data/store.json");
+
+function readJwtFromStore() {
+ if (!fs.existsSync(STORE)) return null;
+ const store = JSON.parse(fs.readFileSync(STORE, "utf8"));
+ const acc = (store.accounts || []).find(
+ (a) => a.kind === "zcode_jwt" && a.api_key?.startsWith("eyJ") && a.status !== "disabled",
+ );
+ return acc?.api_key?.trim() || null;
+}
+
+const JWT = process.env.ZCODE_JWT?.trim() || readJwtFromStore();
+
+if (!JWT) {
+ console.error("No JWT: set ZCODE_JWT or add zcode_jwt account to data/store.json");
+ process.exit(1);
+}
+
+const MESSAGES_URL = "https://zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages";
+const BILLING_URL = "https://zcode.z.ai/api/v1/zcode-plan/billing/quota";
+const CONFIGS_URL = "https://zcode.z.ai/api/v1/client/configs?app_version=3.1.2&platform=win32-x64";
+
+const SYSTEM_BLOCKS = JSON.parse(
+ fs.readFileSync(path.join(ROOT, "src/proxy/zcode_system.json"), "utf8"),
+);
+
+async function fetchCaptchaConfig() {
+ const res = await fetch(CONFIGS_URL);
+ const json = await res.json();
+ const cap = json?.data?.configs?.captcha ?? {};
+ return {
+ sceneId: String(cap.sceneId || "11xygtvd"),
+ region: String(cap.region || "sgp"),
+ prefix: String(cap.prefix || "no8xfe"),
+ };
+}
+
+function solveCaptcha(scene, region, prefix) {
+ const solver = path.join(ROOT, "captcha_node/solver.js");
+ return new Promise((resolve, reject) => {
+ const proc = spawn("node", [solver, scene, region, prefix], {
+ cwd: path.join(ROOT, "captcha_node"),
+ stdio: ["ignore", "pipe", "pipe"],
+ windowsHide: true,
+ });
+ let stdout = "";
+ let stderr = "";
+ proc.stdout.on("data", (c) => (stdout += c));
+ proc.stderr.on("data", (c) => (stderr += c));
+ const timer = setTimeout(() => {
+ proc.kill("SIGKILL");
+ reject(new Error("captcha timeout"));
+ }, 45_000);
+ proc.on("close", (code) => {
+ clearTimeout(timer);
+ for (const line of stdout.split(/\r?\n/)) {
+ if (line.startsWith("VERIFY_PARAM=")) {
+ resolve(line.slice("VERIFY_PARAM=".length).trim());
+ return;
+ }
+ }
+ reject(new Error(`captcha exit ${code}: ${stderr.slice(0, 200) || stdout.slice(0, 200)}`));
+ });
+ });
+}
+
+function buildBody() {
+ return {
+ model: "GLM-5.2",
+ max_tokens: 64,
+ stream: false,
+ thinking: { type: "enabled", budget_tokens: 32000 },
+ output_config: { effort: "max" },
+ system: [...SYSTEM_BLOCKS],
+ messages: [{ role: "user", content: [{ type: "text", text: "ответь одним словом: ок" }] }],
+ };
+}
+
+function chatHeaders(captchaParam, region) {
+ return {
+ "content-type": "application/json",
+ "anthropic-version": "2023-06-01",
+ authorization: `Bearer ${JWT}`,
+ "http-referer": "https://zcode.z.ai",
+ "user-agent": "ZCode/3.1.2",
+ "x-zcode-app-version": "3.1.2",
+ "x-title": "Z Code@electron",
+ "x-zcode-agent": "glm",
+ "x-platform": "win32-x64",
+ "x-aliyun-captcha-verify-param": captchaParam,
+ "x-aliyun-captcha-verify-region": region,
+ };
+}
+
+async function main() {
+ console.log("=== 1. Billing ===");
+ const billingRes = await fetch(BILLING_URL, {
+ headers: { authorization: `Bearer ${JWT}`, accept: "application/json" },
+ });
+ const billingText = await billingRes.text();
+ console.log(`billing HTTP ${billingRes.status}: ${billingText.slice(0, 200)}`);
+
+ console.log("\n=== 2. Captcha (jsdom traceless) ===");
+ const cfg = await fetchCaptchaConfig();
+ console.log("config:", cfg);
+ const t0 = Date.now();
+ const verifyParam = await solveCaptcha(cfg.sceneId, cfg.region, cfg.prefix);
+ console.log(`captcha OK in ${Date.now() - t0}ms, param length=${verifyParam.length}`);
+
+ console.log("\n=== 3. Chat WITH system blocks + captcha ===");
+ const goodRes = await fetch(MESSAGES_URL, {
+ method: "POST",
+ headers: chatHeaders(verifyParam, cfg.region),
+ body: JSON.stringify(buildBody()),
+ });
+ const goodText = await goodRes.text();
+ console.log(`with fix HTTP ${goodRes.status}: ${goodText.slice(0, 500)}`);
+
+ let parsed;
+ try {
+ parsed = JSON.parse(goodText);
+ } catch {
+ parsed = null;
+ }
+
+ const reply = parsed?.content
+ ?.filter((b) => b.type === "text")
+ .map((b) => b.text)
+ .join("");
+
+ if (goodRes.ok && reply) {
+ console.log("\n✅ SUCCESS — reply:", reply.slice(0, 100));
+ process.exit(0);
+ }
+
+ console.log("\n❌ FAILED");
+ process.exit(1);
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/src/proxy/body-transformer.ts b/src/proxy/body-transformer.ts
index 663445d..8cb1f1d 100644
--- a/src/proxy/body-transformer.ts
+++ b/src/proxy/body-transformer.ts
@@ -14,13 +14,17 @@
* is safe and matches ZCode's `applyCacheControl: true` default.
* 3. Anthropic format + `ctx.userId` set → inject `metadata: { user_id }`.
* Mirrors `user_id: B.metadata.userId` at bundle offset ~4760586.
+ * 4. start-plan Anthropic → prepend official ZCode system gateway blocks (positions 0/1).
+ * Without these upstream returns 3012 "method not allowed".
*
* @see _reverse/NOTEPAD.md "How Credential is Used for LLM Calls"
*/
import type { Format } from "../translator/types.js";
+import { injectOfficialZcodeSystem } from "./system-prompt.js";
export interface TransformContext {
format: Format;
+ plan?: "coding-plan" | "start-plan";
/** When set (OAuth mode), the Anthropic-format body gets `metadata.user_id` injected. */
userId?: string;
}
@@ -47,6 +51,9 @@ export function transformRequestBody(body: string | undefined, ctx: TransformCon
}
if (ctx.format === "anthropic") {
const obj = parsed as Record;
+ if (ctx.plan === "start-plan") {
+ modified = injectOfficialZcodeSystem(obj) || modified;
+ }
modified = applyAnthropicCacheControl(obj) || modified;
if (ctx.userId) {
modified = applyAnthropicUserId(obj, ctx.userId) || modified;
diff --git a/src/proxy/captcha-jsdom.ts b/src/proxy/captcha-jsdom.ts
new file mode 100644
index 0000000..f030aca
--- /dev/null
+++ b/src/proxy/captcha-jsdom.ts
@@ -0,0 +1,136 @@
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
+const CAPTCHA_NODE_DIR = path.join(ROOT, "captcha_node");
+const SOLVER_JS = path.join(CAPTCHA_NODE_DIR, "solver.js");
+
+const CACHE_TTL_MS = Number(process.env.CAPTCHA_CACHE_TTL_MS || 45_000);
+const SOLVE_RETRIES = Number(process.env.ZCODE_CAPTCHA_RETRIES || 4);
+const SOLVE_TIMEOUT_MS = Number(process.env.ZCODE_CAPTCHA_TIMEOUT || 40) * 1000;
+const NODE_BIN = process.env.ZCODE_NODE_PATH?.trim() || "node";
+
+type CacheEntry = { param: string; cachedAt: number };
+
+class JsdomCaptchaManager {
+ private cache: CacheEntry | null = null;
+ private lock: Promise | null = null;
+
+ invalidate(): void {
+ this.cache = null;
+ }
+
+ async getVerifyParam(cfg: CaptchaConfig): Promise {
+ const now = Date.now();
+ if (this.cache && now - this.cache.cachedAt < CACHE_TTL_MS) {
+ return this.cache.param;
+ }
+
+ if (this.lock) return this.lock;
+
+ const work = this.solveFresh(cfg).finally(() => {
+ this.lock = null;
+ });
+ this.lock = work;
+ return work;
+ }
+
+ private async solveFresh(cfg: CaptchaConfig): Promise {
+ const now = Date.now();
+ if (this.cache && now - this.cache.cachedAt < CACHE_TTL_MS) {
+ return this.cache.param;
+ }
+
+ let lastErr: string | null = null;
+ for (let attempt = 1; attempt <= SOLVE_RETRIES; attempt++) {
+ try {
+ const param = await runSolver(cfg.sceneId, cfg.region, cfg.prefix);
+ if (param) {
+ this.cache = { param, cachedAt: Date.now() };
+ return param;
+ }
+ lastErr = "solver returned empty";
+ } catch (err) {
+ lastErr = err instanceof Error ? err.message : String(err);
+ }
+ }
+
+ throw new Error(`jsdom captcha failed after ${SOLVE_RETRIES} attempts: ${lastErr ?? "unknown"}`);
+ }
+}
+
+export interface CaptchaConfig {
+ enabled: boolean;
+ prefix: string;
+ sceneId: string;
+ region: string;
+}
+
+const manager = new JsdomCaptchaManager();
+
+export function invalidateJsdomCaptcha(): void {
+ manager.invalidate();
+}
+
+export async function solveCaptchaJsdom(cfg: CaptchaConfig): Promise {
+ if (!cfg.enabled || !cfg.prefix || !cfg.sceneId) {
+ throw new Error("Captcha config unavailable from ZCode API");
+ }
+ return manager.getVerifyParam(cfg);
+}
+
+function runSolver(scene: string, region: string, prefix: string): Promise {
+ if (!fs.existsSync(SOLVER_JS)) {
+ return Promise.reject(
+ new Error(`Missing ${SOLVER_JS}. Run: cd captcha_node && npm install`),
+ );
+ }
+
+ return new Promise((resolve, reject) => {
+ const proc = spawn(NODE_BIN, [SOLVER_JS, scene, region, prefix], {
+ cwd: CAPTCHA_NODE_DIR,
+ env: { ...process.env },
+ stdio: ["ignore", "pipe", "pipe"],
+ windowsHide: true,
+ });
+
+ let stdout = "";
+ let stderr = "";
+ proc.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ proc.stderr?.on("data", (chunk: Buffer) => {
+ stderr += chunk.toString("utf8");
+ });
+
+ const timer = setTimeout(() => {
+ proc.kill("SIGKILL");
+ reject(new Error(`jsdom captcha timeout (${SOLVE_TIMEOUT_MS}ms)`));
+ }, SOLVE_TIMEOUT_MS);
+
+ proc.on("error", (err) => {
+ clearTimeout(timer);
+ reject(new Error(`cannot spawn ${NODE_BIN}: ${err.message}`));
+ });
+
+ proc.on("close", (code) => {
+ clearTimeout(timer);
+ for (const line of stdout.split(/\r?\n/)) {
+ if (line.startsWith("VERIFY_PARAM=")) {
+ const param = line.slice("VERIFY_PARAM=".length).trim();
+ if (param.length > 20) {
+ resolve(param);
+ return;
+ }
+ }
+ }
+ reject(
+ new Error(
+ `jsdom captcha exit ${code ?? "?"}: ${stderr.slice(0, 200) || stdout.slice(0, 200) || "no output"}`,
+ ),
+ );
+ });
+ });
+}
diff --git a/src/proxy/captcha.ts b/src/proxy/captcha.ts
index 448f7d0..a53226d 100644
--- a/src/proxy/captcha.ts
+++ b/src/proxy/captcha.ts
@@ -1,29 +1,24 @@
/**
* Aliyun Captcha V3 headless solver for start-plan tier.
*
- * Captcha config (prefix/sceneId/region) is auto-fetched from
- * https://zcode.z.ai/api/v1/client/configs — no user configuration needed.
+ * Proactive traceless verification via jsdom + AliyunCaptcha.js (scene 11xygtvd).
+ * Config is auto-fetched from https://zcode.z.ai/api/v1/client/configs.
*
- * When zcode.z.ai returns a captcha challenge (response header
- * `x-aliyun-captcha-verify-param`), this module solves it headlessly via
- * Playwright + the official AliyunCaptcha.js SDK, then returns the solved token.
- *
- * @see _reverse/zcode.cjs `o5r()` / `createZcodePlanCaptchaEmptyStreamBusinessError`
+ * @see https://github.com/TriDefender/zcode-api/issues/2
*/
-const CAPTCHA_HEADER = "x-aliyun-captcha-verify-param";
-const REGION_HEADER = "x-aliyun-captcha-verify-region";
-const ALIYUN_CAPTCHA_SDK_URL = "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js";
-const CONFIGS_API = "https://zcode.z.ai/api/v1/client/configs";
+import { invalidateJsdomCaptcha, solveCaptchaJsdom, type CaptchaConfig } from "./captcha-jsdom.js";
-interface FetchedCaptchaConfig {
- enabled: boolean;
- prefix: string;
- sceneId: string;
- region: string;
-}
+export const CAPTCHA_HEADER = "x-aliyun-captcha-verify-param";
+export const REGION_HEADER = "x-aliyun-captcha-verify-region";
+export const RETRY_HEADERS = { PARAM: CAPTCHA_HEADER, REGION: REGION_HEADER };
-let cachedConfig: { value: FetchedCaptchaConfig | null; expiresAt: number } = { value: null, expiresAt: 0 };
+const CONFIGS_API = "https://zcode.z.ai/api/v1/client/configs";
+const DEFAULT_SCENE = "11xygtvd";
+const DEFAULT_PREFIX = "no8xfe";
+const DEFAULT_REGION = "sgp";
+
+let cachedConfig: { value: CaptchaConfig | null; expiresAt: number } = { value: null, expiresAt: 0 };
export function detectCaptchaChallenge(resp: Response): string | null {
const v = resp.headers.get(CAPTCHA_HEADER);
@@ -32,133 +27,58 @@ export function detectCaptchaChallenge(resp: Response): string | null {
return trimmed.length > 0 ? trimmed : null;
}
-async function fetchCaptchaConfig(): Promise {
+export async function fetchCaptchaConfig(): Promise {
if (cachedConfig.value && cachedConfig.expiresAt > Date.now()) {
return cachedConfig.value;
}
+
+ const defaults: CaptchaConfig = {
+ enabled: true,
+ prefix: DEFAULT_PREFIX,
+ sceneId: DEFAULT_SCENE,
+ region: DEFAULT_REGION,
+ };
+
try {
- const url = `${CONFIGS_API}?app_version=3.1.1&platform=win32-x64`;
+ const url = `${CONFIGS_API}?app_version=3.1.2&platform=win32-x64`;
const resp = await fetch(url);
- const json = (await resp.json()) as { code?: number; data?: { configs?: { captcha?: FetchedCaptchaConfig } } };
- const cfg = json?.data?.configs?.captcha ?? null;
- cachedConfig = { value: cfg, expiresAt: Date.now() + 60000 };
+ const json = (await resp.json()) as {
+ data?: { configs?: { captcha?: Partial } };
+ };
+ const cap = json?.data?.configs?.captcha;
+ const cfg: CaptchaConfig = {
+ enabled: cap?.enabled !== false,
+ prefix: String(cap?.prefix || DEFAULT_PREFIX),
+ sceneId: String(cap?.sceneId || DEFAULT_SCENE),
+ region: String(cap?.region || DEFAULT_REGION),
+ };
+ cachedConfig = { value: cfg, expiresAt: Date.now() + 60_000 };
return cfg;
} catch {
- return null;
+ cachedConfig = { value: defaults, expiresAt: Date.now() + 60_000 };
+ return defaults;
}
}
-/**
- * Solve an Aliyun captcha challenge headlessly.
- *
- * Fetches captcha config from ZCode API, launches Chromium, loads
- * AliyunCaptcha.js, and waits for the SDK success callback.
- *
- * @returns Object with verifyParam and region for the retry request headers
- * @throws Error if config unavailable, Playwright missing, or solve times out
- */
-export async function solveCaptcha(challenge: string): Promise<{ verifyParam: string; region: string }> {
+/** Proactive traceless solve — attach verifyParam before the chat request. */
+export async function getProactiveCaptchaHeaders(): Promise> {
const cfg = await fetchCaptchaConfig();
- if (!cfg || !cfg.enabled || !cfg.prefix || !cfg.sceneId) {
- throw new Error("Captcha config unavailable from ZCode API");
- }
-
- const playwright = await loadPlaywright();
- const browser = await playwright.chromium.launch({ headless: true });
- try {
- const page = await browser.newPage();
- await page.setContent(buildSolverHtml(cfg), { waitUntil: "domcontentloaded" });
- await page.addScriptTag({ url: ALIYUN_CAPTCHA_SDK_URL });
-
- const verifyParam = await page.evaluate(
- (args: { prefix: string; sceneId: string; region: string }): Promise => {
- const { prefix, sceneId, region } = args;
- return new Promise((resolve, reject) => {
- const timeout = setTimeout(() => reject(new Error("captcha solve timeout after 30s")), 30000);
- const w = window as unknown as {
- AliyunCaptchaConfig?: { region: string; prefix: string };
- initAliyunCaptcha?: (opts: Record) => void;
- };
- w.AliyunCaptchaConfig = { region, prefix };
- if (!w.initAliyunCaptcha) {
- clearTimeout(timeout);
- reject(new Error("AliyunCaptcha.js failed to load"));
- return;
- }
- w.initAliyunCaptcha({
- SceneId: sceneId,
- prefix,
- mode: "popup",
- language: "cn",
- showErrorTip: false,
- element: "#captcha-element",
- button: "#captcha-button",
- getInstance: () => {},
- success: (param: string) => {
- clearTimeout(timeout);
- resolve(param);
- },
- fail: (err: unknown) => {
- clearTimeout(timeout);
- reject(new Error(`Aliyun SDK fail: ${JSON.stringify(err)}`));
- },
- onError: (err: unknown) => {
- clearTimeout(timeout);
- reject(new Error(`Aliyun SDK error: ${JSON.stringify(err)}`));
- },
- });
- });
- },
- { prefix: cfg.prefix, sceneId: cfg.sceneId, region: cfg.region },
- );
-
- void challenge;
- return { verifyParam, region: cfg.region };
- } finally {
- await browser.close();
- }
-}
-
-function buildSolverHtml(cfg: FetchedCaptchaConfig): string {
- return `
-
-captcha-solver
-
-
-
-
-
-
-`;
-}
-
-export const RETRY_HEADERS = { PARAM: CAPTCHA_HEADER, REGION: REGION_HEADER };
-
-async function loadPlaywright(): Promise {
- const moduleName = "playwright";
- try {
- const mod = await import(/* @vite-ignore */ moduleName);
- return mod as unknown as PlaywrightModule;
- } catch {
- throw new Error(
- "playwright is not installed. Install with: bun add -d playwright && bunx playwright install chromium",
- );
- }
-}
-
-interface PlaywrightModule {
- chromium: {
- launch(opts: { headless: boolean }): Promise;
+ const verifyParam = await solveCaptchaJsdom(cfg);
+ return {
+ [CAPTCHA_HEADER]: verifyParam,
+ [REGION_HEADER]: cfg.region,
};
}
-interface PlaywrightBrowser {
- newPage(): Promise;
- close(): Promise;
+/**
+ * Solve captcha after a challenge header (legacy reactive path).
+ * Uses the same jsdom traceless solver.
+ */
+export async function solveCaptcha(_challenge: string): Promise<{ verifyParam: string; region: string }> {
+ invalidateJsdomCaptcha();
+ const cfg = await fetchCaptchaConfig();
+ const verifyParam = await solveCaptchaJsdom(cfg);
+ return { verifyParam, region: cfg.region };
}
-interface PlaywrightPage {
- setContent(html: string, opts: { waitUntil: string }): Promise;
- addScriptTag(opts: { url: string }): Promise;
- evaluate(fn: (args: { prefix: string; sceneId: string; region: string }) => Promise, args: { prefix: string; sceneId: string; region: string }): Promise;
-}
+export { invalidateJsdomCaptcha };
diff --git a/src/proxy/handler.ts b/src/proxy/handler.ts
index edefe3e..53b8241 100644
--- a/src/proxy/handler.ts
+++ b/src/proxy/handler.ts
@@ -5,10 +5,19 @@
import type { Format } from "../translator/types.js";
import type { ProxyConfig } from "../config/types.js";
import type { AuthManager } from "../auth/manager.js";
+import type { ProviderDef } from "../provider/types.js";
+import type { Credential } from "../auth/types.js";
+import type { ProxyIdentity } from "../config/types.js";
import { getProvider } from "../provider/providers.js";
import { buildUpstreamRequest } from "./upstream.js";
import { transformRequestBody } from "./body-transformer.js";
-import { detectCaptchaChallenge, solveCaptcha, RETRY_HEADERS } from "./captcha.js";
+import {
+ detectCaptchaChallenge,
+ getProactiveCaptchaHeaders,
+ invalidateJsdomCaptcha,
+ solveCaptcha,
+ RETRY_HEADERS,
+} from "./captcha.js";
/** Options for the proxy handler. */
export interface ProxyHandlerOptions {
@@ -65,8 +74,33 @@ export async function proxyRequest(
return errorResponse(400, "unsupported_format", "start-plan only supports the Anthropic API format. Use POST /v1/messages instead of /v1/chat/completions.");
}
- const transformedBody = transformRequestBody(body, { format, userId: cred.userId });
- let upstreamReq = buildUpstreamRequest(clientReq, format, provider, cred, transformedBody, config.identity, config.plan);
+ const transformedBody = transformRequestBody(body, {
+ format,
+ plan: config.plan,
+ userId: cred.userId,
+ });
+
+ let captchaHeaders: Record = {};
+ if (config.plan === "start-plan") {
+ try {
+ captchaHeaders = await getProactiveCaptchaHeaders();
+ console.log(`${reqId} proactive captcha ready (${captchaHeaders[RETRY_HEADERS.PARAM]?.length ?? 0} chars)`);
+ } catch (err) {
+ printRow(reqId, format, meta, 503, started, Date.now(), 0, 0, 0);
+ return errorResponse(503, "captcha_solve_failed", (err as Error).message);
+ }
+ }
+
+ let upstreamReq = buildUpstreamRequest(
+ clientReq,
+ format,
+ provider,
+ cred,
+ transformedBody,
+ config.identity,
+ config.plan,
+ captchaHeaders,
+ );
let upstreamResp: Response;
try {
@@ -82,30 +116,23 @@ export async function proxyRequest(
return errorResponse(401, "start_plan_jwt_invalid", "Start-plan JWT was rejected. Re-run: zcode-proxy auth login");
}
- // start-plan captcha challenge: detect via response header, solve headlessly, retry once
if (config.plan === "start-plan") {
- const challenge = detectCaptchaChallenge(upstreamResp);
- if (challenge) {
- try { upstreamResp.body?.cancel(); } catch {}
- console.log(`${reqId} captcha challenge detected, solving headlessly...`);
- const { verifyParam, region } = await solveCaptcha(challenge);
- console.log(`${reqId} captcha solved (token ${verifyParam.length} chars), retrying...`);
- upstreamReq = buildUpstreamRequest(clientReq, format, provider, cred, transformedBody, config.identity, config.plan, {
- [RETRY_HEADERS.PARAM]: verifyParam,
- [RETRY_HEADERS.REGION]: region,
- });
- try {
- upstreamResp = await fetchImpl(upstreamReq, { decompress: false });
- } catch (err) {
- printRow(reqId, format, meta, 502, started, Date.now(), 0, 0, 0);
- return errorResponse(502, "upstream_unreachable", (err as Error).message);
- }
- if (detectCaptchaChallenge(upstreamResp)) {
- try { upstreamResp.body?.cancel(); } catch {}
- printRow(reqId, format, meta, 403, started, Date.now(), 0, 0, 0);
- return errorResponse(403, "captcha_verification_failed", "Captcha was solved but upstream still rejected the token");
- }
+ const retried = await retryStartPlanIfNeeded({
+ fetchImpl,
+ clientReq,
+ format,
+ provider,
+ cred,
+ transformedBody,
+ identity: config.identity,
+ reqId,
+ upstreamResp,
+ });
+ if (retried.error) {
+ printRow(reqId, format, meta, retried.error.status, started, Date.now(), 0, 0, 0);
+ return retried.error;
}
+ upstreamResp = retried.response;
}
const isSSE = upstreamResp.headers.get("content-type")?.includes("text/event-stream") ?? false;
@@ -120,6 +147,93 @@ export async function proxyRequest(
return passthroughResponse(upstreamResp);
}
+async function retryStartPlanIfNeeded(opts: {
+ fetchImpl: typeof fetch;
+ clientReq: Request;
+ format: Format;
+ provider: ProviderDef;
+ cred: Credential;
+ transformedBody: string | undefined;
+ identity: ProxyIdentity;
+ reqId: string;
+ upstreamResp: Response;
+}): Promise<{ response: Response; error?: Response }> {
+ const needsRetry =
+ detectCaptchaChallenge(opts.upstreamResp) !== null ||
+ (await isCaptchaFailure(opts.upstreamResp));
+
+ if (!needsRetry) {
+ return { response: opts.upstreamResp };
+ }
+
+ try {
+ opts.upstreamResp.body?.cancel();
+ } catch {}
+
+ console.log(`${opts.reqId} captcha rejected — re-solving traceless and retrying once...`);
+ invalidateJsdomCaptcha();
+
+ let captchaHeaders: Record;
+ try {
+ captchaHeaders = await getProactiveCaptchaHeaders();
+ } catch (err) {
+ return {
+ response: opts.upstreamResp,
+ error: errorResponse(503, "captcha_solve_failed", (err as Error).message),
+ };
+ }
+
+ const challenge = detectCaptchaChallenge(opts.upstreamResp);
+ if (challenge) {
+ const { verifyParam, region } = await solveCaptcha(challenge);
+ captchaHeaders = {
+ [RETRY_HEADERS.PARAM]: verifyParam,
+ [RETRY_HEADERS.REGION]: region,
+ };
+ }
+
+ const upstreamReq = buildUpstreamRequest(
+ opts.clientReq,
+ opts.format,
+ opts.provider,
+ opts.cred,
+ opts.transformedBody,
+ opts.identity,
+ "start-plan",
+ captchaHeaders,
+ );
+
+ try {
+ const upstreamResp = await opts.fetchImpl(upstreamReq, { decompress: false });
+ if (detectCaptchaChallenge(upstreamResp) || (await isCaptchaFailure(upstreamResp))) {
+ try {
+ upstreamResp.body?.cancel();
+ } catch {}
+ return {
+ response: upstreamResp,
+ error: errorResponse(
+ 403,
+ "captcha_verification_failed",
+ "Captcha was solved but upstream still rejected the token",
+ ),
+ };
+ }
+ return { response: upstreamResp };
+ } catch (err) {
+ return {
+ response: opts.upstreamResp,
+ error: errorResponse(502, "upstream_unreachable", (err as Error).message),
+ };
+ }
+}
+
+async function isCaptchaFailure(resp: Response): Promise {
+ if (resp.status === 403 || resp.status === 405) return true;
+ const text = await resp.clone().text().catch(() => "");
+ const low = text.toLowerCase();
+ return low.includes("captcha") || low.includes("3007") || low.includes("3012");
+}
+
/** Read the request body as a string, returning undefined for empty bodies. */
async function readBody(req: Request): Promise {
if (req.method === "GET" || req.method === "HEAD") return undefined;
diff --git a/src/proxy/system-prompt.ts b/src/proxy/system-prompt.ts
new file mode 100644
index 0000000..a43347a
--- /dev/null
+++ b/src/proxy/system-prompt.ts
@@ -0,0 +1,45 @@
+import systemBlocks from "./zcode_system.json" with { type: "json" };
+
+type SystemBlock = {
+ type: "text";
+ text: string;
+ cache_control?: { type: "ephemeral" };
+};
+
+/** Official ZCode gateway blocks (positions 0/1) — required or upstream returns 3012. */
+export const ZCODE_SYSTEM_BLOCKS = systemBlocks as SystemBlock[];
+
+function normalizeUserSystem(system: unknown): SystemBlock[] {
+ if (system == null) return [];
+ if (typeof system === "string") {
+ const text = system.trim();
+ return text ? [{ type: "text", text }] : [];
+ }
+ if (!Array.isArray(system)) return [];
+ const out: SystemBlock[] = [];
+ for (const item of system) {
+ if (typeof item === "string") {
+ if (item.trim()) out.push({ type: "text", text: item });
+ } else if (item && typeof item === "object" && (item as SystemBlock).type === "text") {
+ const b = item as SystemBlock;
+ if ((b.text || "").trim()) {
+ out.push({
+ type: "text",
+ text: b.text,
+ ...(b.cache_control ? { cache_control: b.cache_control } : {}),
+ });
+ }
+ }
+ }
+ return out;
+}
+
+/** Prepend official blocks; client system (if any) goes after position 1. */
+export function injectOfficialZcodeSystem(body: Record): boolean {
+ const userBlocks = normalizeUserSystem(body.system);
+ const official = ZCODE_SYSTEM_BLOCKS.map((b) => structuredClone(b));
+ const next = [...official, ...userBlocks];
+ const prev = JSON.stringify(body.system ?? null);
+ body.system = next;
+ return prev !== JSON.stringify(next);
+}
diff --git a/src/proxy/upstream.ts b/src/proxy/upstream.ts
index 97cb46d..b35ab33 100644
--- a/src/proxy/upstream.ts
+++ b/src/proxy/upstream.ts
@@ -51,7 +51,11 @@ export function buildAuthHeaders(format: Format, cred: Credential, identity: Pro
};
if (format === "anthropic") {
- base["x-api-key"] = credStr;
+ if (plan === "start-plan" && cred.jwt) {
+ base["authorization"] = `Bearer ${cred.jwt}`;
+ } else {
+ base["x-api-key"] = credStr;
+ }
base["anthropic-version"] = ANTHROPIC_VERSION;
} else {
base["authorization"] = `Bearer ${credStr}`;
diff --git a/src/proxy/zcode_system.json b/src/proxy/zcode_system.json
new file mode 100644
index 0000000..0f33dc0
--- /dev/null
+++ b/src/proxy/zcode_system.json
@@ -0,0 +1,16 @@
+[
+ {
+ "type": "text",
+ "text": "You are ZCode, an interactive coding agent",
+ "cache_control": {
+ "type": "ephemeral"
+ }
+ },
+ {
+ "type": "text",
+ "text": "\nYou are an interactive ZCode agent that helps users with software engineering tasks.\n\nIMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n# Harness\n- Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.\n- Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don't retry verbatim.\n- `` tags in messages and tool results are injected by the harness, not the user. Hooks may intercept tool calls; treat hook output as user feedback.\n- Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.\n- Reference code as `file_path:line_number` — it's clickable.",
+ "cache_control": {
+ "type": "ephemeral"
+ }
+ }
+]