Skip to content

Commit ea25409

Browse files
committed
接入云控,避免被指纹识别
1 parent 4cbafef commit ea25409

7 files changed

Lines changed: 320 additions & 20 deletions

File tree

‎src/claim/client.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,10 @@ describe("createClaimClient — minimal claim-plane header set (3.12.3 verbatim)
139139

140140
it("claim sends exactly the bundle's 6 headers (Authorization, Content-Type, captcha param, [region], version, platform)", async () => {
141141
let req: Request | undefined;
142-
const fetchImpl = makeMockFetch((r) => {
142+
let sentHeaders: Record<string, string> | undefined;
143+
const fetchImpl = makeMockFetch((r, init) => {
143144
req = r;
145+
sentHeaders = init?.headers as Record<string, string>;
144146
return Promise.resolve(jsonResp({ code: 0, data: { plan: { plan_id: "weekend-free-1024", starts_at: 1, ends_at: 2 } } }));
145147
});
146148
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "jwt-1", appVersion: "3.12.3", platform: "win32-x64", fetchImpl });
@@ -159,6 +161,40 @@ describe("createClaimClient — minimal claim-plane header set (3.12.3 verbatim)
159161
expect(req!.headers.get("http-referer")).toBeNull();
160162
expect(req!.headers.get("x-device-mid")).toBeNull();
161163
expect(req!.headers.get("x-zcode-agent")).toBeNull();
164+
// Wire-order contract, pinned on the pre-Headers Record (Bun's Headers
165+
// re-normalizes key order).
166+
expect(Object.keys(sentHeaders!)).toEqual([
167+
"Authorization",
168+
"Content-Type",
169+
"X-Aliyun-Captcha-Verify-Param",
170+
"X-Aliyun-Captcha-Verify-Region",
171+
"X-ZCode-App-Version",
172+
"X-Platform",
173+
]);
174+
});
175+
176+
it("claim without a captcha token omits both captcha headers (3.16.3 switch off)", async () => {
177+
let req: Request | undefined;
178+
let sentHeaders: Record<string, string> | undefined;
179+
const fetchImpl = makeMockFetch((r, init) => {
180+
req = r;
181+
sentHeaders = init?.headers as Record<string, string>;
182+
return Promise.resolve(jsonResp({ code: 0, data: { plan: { plan_id: "weekend-free-1024" } } }));
183+
});
184+
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "jwt-1", appVersion: "3.16.3", platform: "win32-x64", fetchImpl });
185+
186+
await client.claim("weekend-free-1024");
187+
188+
expect(req!.headers.get("authorization")).toBe("Bearer jwt-1");
189+
expect(req!.headers.get("content-type")).toBe("application/json");
190+
expect(req!.headers.get("x-aliyun-captcha-verify-param")).toBeNull();
191+
expect(req!.headers.get("x-aliyun-captcha-verify-region")).toBeNull();
192+
expect(req!.headers.get("x-zcode-app-version")).toBe("3.16.3");
193+
expect(req!.headers.get("x-platform")).toBe("win32-x64");
194+
// The captcha pair vanishes from its slot; everything else keeps its
195+
// position (asserted on the pre-Headers Record — Bun's Headers
196+
// re-normalizes key order).
197+
expect(Object.keys(sentHeaders!)).toEqual(["Authorization", "Content-Type", "X-ZCode-App-Version", "X-Platform"]);
162198
});
163199
});
164200

‎src/claim/client.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
* anonymous — no Content-Type, no Accept)
1111
* - `POST {origin}/api/v1/zcode-plan/billing/claim` body `{plan_id}`
1212
* headers (bundle order): Authorization, Content-Type,
13-
* X-Aliyun-Captcha-Verify-Param, [X-Aliyun-Captcha-Verify-Region],
13+
* [X-Aliyun-Captcha-Verify-Param, [X-Aliyun-Captcha-Verify-Region]]
14+
* (omitted when the 3.16.3 configs.captcha gate is off),
1415
* X-ZCode-App-Version, X-Platform
1516
*
1617
* NOTE: an earlier revision sent the full identity set with X-Device-Mid
@@ -52,7 +53,7 @@ export interface ClaimClientOptions {
5253

5354
export interface ClaimClient {
5455
getPreviews(signal?: AbortSignal): Promise<ClaimablePlan[]>;
55-
claim(planId: string, captcha: { verifyParam: string; region?: string }, signal?: AbortSignal): Promise<ClaimOutcome>;
56+
claim(planId: string, captcha?: { verifyParam: string; region?: string }, signal?: AbortSignal): Promise<ClaimOutcome>;
5657
}
5758

5859
const DEFAULT_TIMEOUT_MS = 15_000;
@@ -193,17 +194,21 @@ export function createClaimClient(opts: ClaimClientOptions): ClaimClient {
193194
});
194195
},
195196

196-
async claim(planId: string, captcha: { verifyParam: string; region?: string }, signal?: AbortSignal): Promise<ClaimOutcome> {
197+
async claim(planId: string, captcha?: { verifyParam: string; region?: string }, signal?: AbortSignal): Promise<ClaimOutcome> {
197198
if (!jwt) return { ok: false, planId, failureKind: "login_required", code: 401, message: "manual_claim_login_required" };
198199
// Bundle `claimManualPlan` header order: Authorization, Content-Type,
199-
// captcha param, [captcha region], X-ZCode-App-Version, X-Platform,
200-
// [X-Device-Mid] (campaign-gated deviation, same as preview).
200+
// [captcha param, [captcha region]] (omitted entirely when the 3.16.3
201+
// configs.captcha gate is off — captcha arg undefined),
202+
// X-ZCode-App-Version, X-Platform, [X-Device-Mid] (campaign-gated
203+
// deviation, same as preview).
201204
const headers: Record<string, string> = {
202205
Authorization: `Bearer ${jwt}`,
203206
"Content-Type": "application/json",
204-
"X-Aliyun-Captcha-Verify-Param": captcha.verifyParam,
205207
};
206-
if (captcha.region) headers["X-Aliyun-Captcha-Verify-Region"] = captcha.region;
208+
if (captcha) {
209+
headers["X-Aliyun-Captcha-Verify-Param"] = captcha.verifyParam;
210+
if (captcha.region) headers["X-Aliyun-Captcha-Verify-Region"] = captcha.region;
211+
}
207212
headers["X-ZCode-App-Version"] = opts.appVersion;
208213
headers["X-Platform"] = opts.platform;
209214
if (deviceMid) headers["X-Device-Mid"] = deviceMid;

‎src/claim/runtime.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,28 @@
66
import type { AuthManager } from "../auth/manager.js";
77
import type { ProxyConfig } from "../config/types.js";
88
import type { ClaimablePlan, ClaimOutcome } from "./types.js";
9+
import type { Credential } from "../auth/types.js";
10+
import { credentialString } from "../auth/types.js";
911
import { createClaimClient, ClaimPreviewError } from "./client.js";
1012
import { ClaimScheduler } from "./scheduler.js";
1113
import { getCaptchaToken } from "../proxy/captcha.js";
1214
import { loadCredential } from "../auth/store.js";
15+
import { getDefaultEndpointRouting, requiresClaimCaptcha } from "../proxy/endpoint-routing.js";
1316

1417
/** `${process.platform}-${process.arch}` — mirrors the client's `TH()`. */
1518
function claimPlatform(): string {
1619
return `${process.platform}-${process.arch}`;
1720
}
1821

22+
function claimCaptchaRequired(config: ProxyConfig, resolveCredential: () => Promise<Credential | null>): Promise<boolean> {
23+
const routing = getDefaultEndpointRouting(config);
24+
if (!routing) return Promise.resolve(true);
25+
return resolveCredential()
26+
.then((cred) => routing.getRequestVerificationConfig(cred ? credentialString(cred) : undefined))
27+
.then((cfg) => requiresClaimCaptcha(cfg))
28+
.catch(() => true);
29+
}
30+
1931
export function startAutoClaim(config: ProxyConfig, auth: AuthManager): ClaimScheduler {
2032
const scheduler = new ClaimScheduler({
2133
// AuthManager first (fresh), then the encrypted store — on Android the
@@ -40,6 +52,14 @@ export function startAutoClaim(config: ProxyConfig, auth: AuthManager): ClaimSch
4052
const { verifyParam, region } = await getCaptchaToken(config.identity.appVersion);
4153
return { verifyParam, region: region || undefined };
4254
},
55+
captchaRequired: () =>
56+
claimCaptchaRequired(config, async () => {
57+
try {
58+
return await auth.getCredential();
59+
} catch {
60+
return await loadCredential().catch(() => null);
61+
}
62+
}),
4363
config: {
4464
planId: config.claim.planId || undefined,
4565
pollIntervalMs: config.claim.pollIntervalMs,
@@ -108,8 +128,13 @@ export async function runClaimCli(config: ProxyConfig, mode: "list" | "now"): Pr
108128
}
109129
if (target.planId !== plans[0].planId) console.log(`Claiming configured plan: ${target.planId}`);
110130

111-
const captcha = await getCaptchaToken(config.identity.appVersion);
112-
const outcome = await client.claim(target.planId, { verifyParam: captcha.verifyParam, region: captcha.region || undefined });
131+
const captchaRequired = await claimCaptchaRequired(config, async () => cred);
132+
let captcha: { verifyParam: string; region?: string } | undefined;
133+
if (captchaRequired) {
134+
const token = await getCaptchaToken(config.identity.appVersion);
135+
captcha = { verifyParam: token.verifyParam, region: token.region || undefined };
136+
}
137+
const outcome = await client.claim(target.planId, captcha);
113138
printOutcome(outcome);
114139
if (!outcome.ok) process.exit(1);
115140
}

‎src/claim/scheduler.test.ts‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ type HarnessFields = {
1515
claimOutcome: ClaimOutcome | Error;
1616
captchaResult: { verifyParam: string; region?: string } | Error;
1717
captchaCalls: number;
18-
claimCalls: Array<{ planId: string; captcha: { verifyParam: string; region?: string } }>;
18+
claimCalls: Array<{ planId: string; captcha: { verifyParam: string; region?: string } | undefined }>;
1919
nowMs: number;
2020
logs: string[];
2121
config: ClaimSchedulerDeps["config"];
@@ -217,3 +217,81 @@ describe("ClaimScheduler lifecycle", () => {
217217
expect(await h.scheduler.tick()).toEqual({ action: "stopped" });
218218
});
219219
});
220+
221+
describe("ClaimScheduler — 3.16.3 configs.captcha gate", () => {
222+
const plans: ClaimablePlan[] = [{ planId: "weekend-1", name: "Weekend", description: "", priority: 1, entitlements: [] }];
223+
224+
function gateHarness(captchaRequired: ClaimSchedulerDeps["captchaRequired"]) {
225+
const h = {
226+
captchaCalls: 0,
227+
claimCalls: [] as Array<{ planId: string; captcha: { verifyParam: string; region?: string } | undefined }>,
228+
};
229+
const scheduler = new ClaimScheduler({
230+
getJwt: () => Promise.resolve("jwt-1"),
231+
createClient: () => ({
232+
getPreviews: () => Promise.resolve(plans),
233+
claim: (planId, captcha) => {
234+
h.claimCalls.push({ planId, captcha });
235+
return Promise.resolve({ ok: true, planId } as ClaimOutcome);
236+
},
237+
}),
238+
getCaptcha: () => {
239+
h.captchaCalls += 1;
240+
return Promise.resolve({ verifyParam: "cap", region: "cn" });
241+
},
242+
captchaRequired,
243+
config: { pollIntervalMs: 300_000, cooldownMs: 600_000 },
244+
log: () => {},
245+
now: () => 1_000_000,
246+
});
247+
return { h, scheduler };
248+
}
249+
250+
it("skips the solve and claims without captcha when the (async) gate returns false", async () => {
251+
const { h, scheduler } = gateHarness(async () => false);
252+
const result = await scheduler.tick();
253+
expect(result.action).toBe("claimed");
254+
expect(h.captchaCalls).toBe(0);
255+
expect(h.claimCalls).toEqual([{ planId: "weekend-1", captcha: undefined }]);
256+
});
257+
258+
it("fails open — a throwing gate keeps the pre-3.16.3 wire (solve + captcha headers)", async () => {
259+
const { h, scheduler } = gateHarness(() => {
260+
throw new Error("config fetch exploded");
261+
});
262+
const result = await scheduler.tick();
263+
expect(result.action).toBe("claimed");
264+
expect(h.captchaCalls).toBe(1);
265+
expect(h.claimCalls).toEqual([{ planId: "weekend-1", captcha: { verifyParam: "cap", region: "cn" } }]);
266+
});
267+
});
268+
269+
describe("ClaimScheduler — 3.16.3 gate true keeps the solve (default-equivalent)", () => {
270+
it("a gate returning true solves and claims with the captcha pair", async () => {
271+
const plans: ClaimablePlan[] = [{ planId: "weekend-1", name: "Weekend", description: "", priority: 1, entitlements: [] }];
272+
let captchaCalls = 0;
273+
const claimCalls: Array<{ planId: string; captcha: { verifyParam: string; region?: string } | undefined }> = [];
274+
const scheduler = new ClaimScheduler({
275+
getJwt: () => Promise.resolve("jwt-1"),
276+
createClient: () => ({
277+
getPreviews: () => Promise.resolve(plans),
278+
claim: (planId, captcha) => {
279+
claimCalls.push({ planId, captcha });
280+
return Promise.resolve({ ok: true, planId } as ClaimOutcome);
281+
},
282+
}),
283+
getCaptcha: () => {
284+
captchaCalls += 1;
285+
return Promise.resolve({ verifyParam: "cap" });
286+
},
287+
captchaRequired: async () => true,
288+
config: { pollIntervalMs: 300_000, cooldownMs: 600_000 },
289+
log: () => {},
290+
now: () => 1_000_000,
291+
});
292+
const result = await scheduler.tick();
293+
expect(result.action).toBe("claimed");
294+
expect(captchaCalls).toBe(1);
295+
expect(claimCalls).toEqual([{ planId: "weekend-1", captcha: { verifyParam: "cap" } }]);
296+
});
297+
});

‎src/claim/scheduler.ts‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ import { ClaimPreviewError } from "./client.js";
1818

1919
interface ClaimGateway {
2020
getPreviews(): Promise<ClaimablePlan[]>;
21-
claim(planId: string, captcha: { verifyParam: string; region?: string }): Promise<ClaimOutcome>;
21+
/** `captcha` omitted → claim without captcha headers (3.16.3 switch off). */
22+
claim(planId: string, captcha?: { verifyParam: string; region?: string }): Promise<ClaimOutcome>;
2223
}
2324

2425
interface ClaimSchedulerConfig {
@@ -118,11 +119,22 @@ export class ClaimScheduler {
118119
return { action: "idle" };
119120
}
120121

121-
let captcha: { verifyParam: string; region?: string };
122-
try {
123-
captcha = await this.deps.getCaptcha();
124-
} catch (err) {
125-
return this.errorBackoff(`captcha token failed: ${(err as Error).message}`);
122+
let captchaRequired = true;
123+
if (this.deps.captchaRequired) {
124+
try {
125+
captchaRequired = await this.deps.captchaRequired();
126+
} catch {
127+
captchaRequired = true;
128+
}
129+
}
130+
131+
let captcha: { verifyParam: string; region?: string } | undefined;
132+
if (captchaRequired) {
133+
try {
134+
captcha = await this.deps.getCaptcha();
135+
} catch (err) {
136+
return this.errorBackoff(`captcha token failed: ${(err as Error).message}`);
137+
}
126138
}
127139

128140
let outcome: ClaimOutcome;

‎src/proxy/endpoint-routing.test.ts‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "bun:test";
2-
import { EndpointRoutingService } from "./endpoint-routing.js";
2+
import { EndpointRoutingService, requiresClaimCaptcha } from "./endpoint-routing.js";
33
import type { ProxyIdentity } from "../config/types.js";
44

55
const identity: ProxyIdentity = { appVersion: "3.8.1", sourceTitle: "cli", refererOrigin: "https://zcode.z.ai" };
@@ -282,3 +282,92 @@ describe("EndpointRoutingService", () => {
282282
});
283283
});
284284
});
285+
286+
describe("3.16.3 configs.captcha request-verification switch", () => {
287+
function configFetchWith(captcha: unknown): typeof fetch {
288+
return (async () => new Response(JSON.stringify({
289+
code: 0,
290+
data: { proxyEndpoint: { mapping: [{ from: ZAI_ANTHROPIC, to: ZAI_ULTRA }] }, configs: { captcha } },
291+
}), { status: 200 })) as unknown as typeof fetch;
292+
}
293+
294+
it("parses data.configs.captcha (snake_case → camelCase) on the same snapshot", async () => {
295+
const svc = new EndpointRoutingService({
296+
identity,
297+
fetchImpl: configFetchWith({ enabled: true, skip_model_request: false }),
298+
});
299+
expect(await svc.getRequestVerificationConfig()).toEqual({ enabled: true, skipModelRequest: false });
300+
});
301+
302+
it("returns null while the server has not shipped the block (live state 2026-10-23)", async () => {
303+
const svc = new EndpointRoutingService({
304+
identity,
305+
fetchImpl: (async () => new Response(JSON.stringify({
306+
code: 0,
307+
data: { proxyEndpoint: { mapping: [] }, configs: {} },
308+
}), { status: 200 })) as unknown as typeof fetch,
309+
});
310+
expect(await svc.getRequestVerificationConfig()).toBeNull();
311+
});
312+
313+
it("records only the decisive booleans; non-boolean/garbage values degrade neutrally", async () => {
314+
const neutral = new EndpointRoutingService({
315+
identity,
316+
fetchImpl: configFetchWith({ enabled: "false", skip_model_request: "true" }),
317+
});
318+
expect(await neutral.getRequestVerificationConfig()).toEqual({});
319+
const garbage = new EndpointRoutingService({ identity, fetchImpl: configFetchWith("not-an-object") });
320+
expect(await garbage.getRequestVerificationConfig()).toBeNull();
321+
});
322+
323+
it("a malformed captcha block never fails the mapping refresh", async () => {
324+
const svc = new EndpointRoutingService({ identity, fetchImpl: configFetchWith([1, 2]) });
325+
const resolved = await svc.resolve(ZAI_ANTHROPIC);
326+
expect(resolved.routed).toBeTrue();
327+
expect(await svc.getRequestVerificationConfig()).toBeNull();
328+
});
329+
330+
it("fails open on fetch errors (null → captcha stays required)", async () => {
331+
const svc = new EndpointRoutingService({
332+
identity,
333+
fetchImpl: (async () => {
334+
throw new Error("network down");
335+
}) as unknown as typeof fetch,
336+
});
337+
expect(await svc.getRequestVerificationConfig()).toBeNull();
338+
});
339+
340+
it("honors the snapshot TTL: a fresh cache does not refetch for the config read", async () => {
341+
let clock = 0;
342+
let calls = 0;
343+
const svc = new EndpointRoutingService({
344+
identity,
345+
now: () => clock,
346+
fetchImpl: (async () => {
347+
calls++;
348+
return new Response(JSON.stringify({
349+
code: 0,
350+
data: { proxyEndpoint: { mapping: [] }, configs: { captcha: { skip_model_request: true } } },
351+
}), { status: 200 });
352+
}) as unknown as typeof fetch,
353+
});
354+
expect(await svc.getRequestVerificationConfig()).toEqual({ skipModelRequest: true });
355+
expect(await svc.getRequestVerificationConfig()).toEqual({ skipModelRequest: true });
356+
expect(calls).toBe(1);
357+
clock = 301_000;
358+
expect(await svc.getRequestVerificationConfig()).toEqual({ skipModelRequest: true });
359+
expect(calls).toBe(2);
360+
});
361+
362+
it("requiresClaimCaptcha mirrors requiresRequestVerification's defaults", () => {
363+
// absent / null / neutral → required (pre-3.16.3 wire)
364+
expect(requiresClaimCaptcha(undefined)).toBeTrue();
365+
expect(requiresClaimCaptcha(null)).toBeTrue();
366+
expect(requiresClaimCaptcha({})).toBeTrue();
367+
expect(requiresClaimCaptcha({ enabled: true, skipModelRequest: false })).toBeTrue();
368+
// explicit server switches → skipped
369+
expect(requiresClaimCaptcha({ enabled: false })).toBeFalse();
370+
expect(requiresClaimCaptcha({ skipModelRequest: true })).toBeFalse();
371+
expect(requiresClaimCaptcha({ enabled: false, skipModelRequest: true })).toBeFalse();
372+
});
373+
});

0 commit comments

Comments
 (0)