Skip to content

Commit 0329b30

Browse files
committed
bump版本,并且修复headers合集
1 parent 0e0968a commit 0329b30

17 files changed

Lines changed: 569 additions & 479 deletions

‎PROMPT.md‎

Lines changed: 107 additions & 118 deletions
Large diffs are not rendered by default.

‎src/auth/oauth.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ describe("ZaiOAuthClient (server-mediated cli login)", () => {
175175
expect(interstitial).toStartWith("https://zcode.z.ai/app/oauth/login?");
176176
const inner = new URL(interstitial);
177177
expect(inner.searchParams.get("redirect")).toBe("zcode://oauth/callback");
178-
expect(inner.searchParams.get("app_version")).toBe("3.16.3");
178+
expect(inner.searchParams.get("app_version")).toBe("3.17.1");
179179
} finally {
180180
await client.close();
181181
}
@@ -256,7 +256,7 @@ describe("BigmodelPollOAuthClient (server-mediated cli login)", () => {
256256
expect(url.origin + url.pathname).toBe("https://bigmodel.cn/login");
257257
const interstitial = url.searchParams.get("redirect") ?? "";
258258
expect(interstitial).toStartWith("https://zcode.z.ai/app/oauth/login?");
259-
expect(new URL(interstitial).searchParams.get("app_version")).toBe("3.16.3");
259+
expect(new URL(interstitial).searchParams.get("app_version")).toBe("3.17.1");
260260
expect(url.searchParams.get("redirect_uri")).toBeNull();
261261
expect(started.callbackUrl).toBe("");
262262
} finally {

‎src/claim/client.test.ts‎

Lines changed: 113 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,13 +96,123 @@ describe("createClaimClient — getPreviews", () => {
9696
expect(auths[1]).toBeNull();
9797
});
9898

99-
it("throws on non-zero biz code and missing data", async () => {
99+
it("throws on non-zero biz code; code 0 + missing data enumerates as empty (wk-1030 shape)", async () => {
100100
const fetchImpl = makeMockFetch(() => Promise.resolve(jsonResp({ code: 1002, msg: "campaign ended" })));
101101
const client = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.11.2", platform: "win32-x64", fetchImpl });
102102
await expect(client.getPreviews()).rejects.toThrow("1002");
103-
const fetchNoData = makeMockFetch(() => Promise.resolve(jsonResp({ code: 0 })));
103+
// 2026-10-30 live shape: the billing preview returns code 0 with NO data
104+
// field when the campaign is banner-distributed — the desktop client
105+
// throws `manual_claim_preview_missing_data`, we enumerate it as empty so
106+
// the marketing fallback can supply the plans (see getMarketingPlans).
107+
const fetchNoData = makeMockFetch(() => Promise.resolve(jsonResp({ code: 0, msg: "", logid: "x" })));
104108
const client2 = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.11.2", platform: "win32-x64", fetchImpl: fetchNoData });
105-
await expect(client2.getPreviews()).rejects.toThrow("preview failed");
109+
expect(await client2.getPreviews()).toEqual([]);
110+
});
111+
});
112+
113+
describe("createClaimClient — marketing/touch enumeration (wk-1030)", () => {
114+
const MARKETING_BODY = {
115+
code: 0,
116+
msg: "",
117+
data: {
118+
server_time: 1793364305,
119+
deliveries: [
120+
{
121+
campaign_id: "2101141259813175296",
122+
resource_position: "banner",
123+
banner: {
124+
buttons: [
125+
{ text: { content: "" }, action: { type: "close", args: null } },
126+
{ text: { content: "" }, action: { type: "claim_zcode_plan", args: { plan_id: "zcode-v3-start-plan-1030-wk" } } },
127+
],
128+
background: {
129+
type: "bundle",
130+
bundle: { bundle: { src: "https://cdn-zcode.z.ai/x.zip", sha256: "aa" }, entry: "index.html" },
131+
args: {
132+
zcode_plan: {
133+
plan_id: "zcode-v3-start-plan-1030-wk",
134+
name: "ZCODE WEEKEND BUILD",
135+
priority: 101,
136+
starts_at: 1793358000,
137+
ends_at: 1793581200,
138+
entitlements: [
139+
{ entitlement_id: "ent-1", show_name: "GLM-5.3-Flash", meter: "model_usage", unit_type: "requests", capabilities: ["chat"], grant_units: 500000000, period: "weekly", priority: 1 },
140+
],
141+
},
142+
},
143+
},
144+
},
145+
},
146+
{
147+
campaign_id: "other",
148+
resource_position: "popup",
149+
popup: { buttons: [{ action: { type: "open_url", args: { url: "https://x" } } }] },
150+
},
151+
],
152+
},
153+
};
154+
155+
it("surfaces claim_zcode_plan banners with the enriched zcode_plan payload", async () => {
156+
const seen: Array<{ path: string; seq: string | null; dm: string | null; lang: string | null; ver: string | null; auth: string | null }> = [];
157+
const fetchImpl = makeMockFetch((req) => {
158+
const u = new URL(req.url);
159+
seen.push({ path: u.pathname, seq: u.searchParams.get("seq"), dm: req.headers.get("x-device-mid"), lang: req.headers.get("x-client-language"), ver: req.headers.get("x-zcode-app-version"), auth: req.headers.get("authorization") });
160+
return Promise.resolve(jsonResp(MARKETING_BODY));
161+
});
162+
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "jwt-9", appVersion: "3.17.1", platform: "win32-x64", marketingDeviceMid: "11111111-2222-4333-8444-555555555555", fetchImpl });
163+
const plans = await client.getMarketingPlans();
164+
165+
expect(seen[0].path).toBe("/api/v1/marketing/touch");
166+
expect(seen[0].seq).toBe("0"); // seq counter starts at 0
167+
expect(seen[0].dm).toBe("11111111-2222-4333-8444-555555555555");
168+
expect(seen[0].lang).toBe("zh-CN");
169+
expect(seen[0].ver).toBe("3.17.1");
170+
expect(seen[0].auth).toBe("Bearer jwt-9");
171+
172+
expect(plans).toHaveLength(1);
173+
const p = plans[0];
174+
expect(p.planId).toBe("zcode-v3-start-plan-1030-wk");
175+
expect(p.name).toBe("ZCODE WEEKEND BUILD");
176+
expect(p.source).toBe("banner");
177+
expect(p.campaignId).toBe("2101141259813175296");
178+
expect(p.startsAt).toBe(1793358000);
179+
expect(p.entitlements[0].grantUnits).toBe(500000000);
180+
});
181+
182+
it("returns [] without marketingDeviceMid and swallows marketing errors", async () => {
183+
const fetchImpl = makeMockFetch(() => Promise.resolve(new Response("{}", { status: 500 })));
184+
const client = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.17.1", platform: "win32-x64", fetchImpl });
185+
expect(await client.getMarketingPlans()).toEqual([]);
186+
const errClient = createClaimClient({ origin: "https://zcode.z.ai", appVersion: "3.17.1", platform: "win32-x64", marketingDeviceMid: "11111111-2222-4333-8444-555555555555", fetchImpl });
187+
expect(await errClient.getMarketingPlans()).toEqual([]);
188+
});
189+
190+
it("listPlans merges preview + banner, deduped by planId (preview wins)", async () => {
191+
const fetchImpl = makeMockFetch((req) => {
192+
const path = new URL(req.url).pathname;
193+
if (path.endsWith("/billing/preview")) {
194+
return Promise.resolve(jsonResp({ code: 0, data: { plans: [{ plan_id: "preview-plan", name: "Preview Plan", priority: 5 }] } }));
195+
}
196+
return Promise.resolve(jsonResp(MARKETING_BODY));
197+
});
198+
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "j", appVersion: "3.17.1", platform: "win32-x64", marketingDeviceMid: "11111111-2222-4333-8444-555555555555", fetchImpl });
199+
const plans = await client.listPlans();
200+
expect(plans.map((p) => p.planId)).toEqual(["preview-plan", "zcode-v3-start-plan-1030-wk"]);
201+
expect(plans[0].source ?? "preview").toBe("preview");
202+
expect(plans[1].source).toBe("banner");
203+
});
204+
205+
it("listPlans falls back to banner plans when preview is empty-no-data", async () => {
206+
const fetchImpl = makeMockFetch((req) => {
207+
const path = new URL(req.url).pathname;
208+
if (path.endsWith("/billing/preview")) {
209+
return Promise.resolve(jsonResp({ code: 0, msg: "", logid: "l" })); // wk-1030 live shape
210+
}
211+
return Promise.resolve(jsonResp(MARKETING_BODY));
212+
});
213+
const client = createClaimClient({ origin: "https://zcode.z.ai", jwt: "j", appVersion: "3.17.1", platform: "win32-x64", marketingDeviceMid: "11111111-2222-4333-8444-555555555555", fetchImpl });
214+
const plans = await client.listPlans();
215+
expect(plans.map((p) => p.planId)).toEqual(["zcode-v3-start-plan-1030-wk"]);
106216
});
107217
});
108218

‎src/claim/client.ts‎

Lines changed: 137 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,18 @@
2828
* `deviceMid` is provided both calls append `X-Device-Mid` (last position,
2929
* matching its slot in the endpoint-routing `TV` identity set).
3030
*
31-
* @see _reverse/NOTEPAD.md "claim/billing 平面"
31+
* MARKETING ENUMERATION (2026-10-30, wk-1030 campaign): the weekend plan
32+
* was distributed via the marketing banner (`createMarketingTouchService`,
33+
* present since ≤3.16.3 in the host bundle) instead of the billing preview —
34+
* `GET {origin}/api/v1/marketing/touch?seq=N` with X-Device-Mid (required,
35+
* UUID-parsed) / X-Client-Language / X-ZCode-App-Version / [Authorization].
36+
* The banner button action `claim_zcode_plan` carries the plan_id (and the
37+
* banner background args carry the full `zcode_plan` object); the desktop
38+
* renderer then calls the SAME `claimManualPlan` billing endpoint with that
39+
* plan_id. `getMarketingPlans` mirrors the snapshot parse; `listPlans`
40+
* merges both faces (billing preview first, banner plans appended).
41+
*
42+
* @see _reverse/NOTEPAD.md "claim/billing 平面" + "3.17.1 增补"五轮
3243
*/
3344
import type { ClaimablePlan, ClaimOutcome, PlanEntitlement } from "./types.js";
3445
import { classifyClaimCode } from "./types.js";
@@ -45,6 +56,14 @@ export interface ClaimClientOptions {
4556
* `X-Device-Mid`. When omitted no device header is sent.
4657
*/
4758
deviceMid?: string;
59+
/**
60+
* Marketing-face device id (`marketing/touch` uuid.parse's it — required
61+
* there even when the billing campaign gate is off). The caller supplies
62+
* a stable value (config `identity.deviceMid` or a derived fallback).
63+
*/
64+
marketingDeviceMid?: string;
65+
/** Marketing-face locale header. Default `zh-CN` (client enum zh-CN|en-US). */
66+
language?: string;
4867
/** Per-call timeout in ms. Default `15000` (bundle `ss`). */
4968
timeoutMs?: number;
5069
/** DI seam for tests. Default `globalThis.fetch`. */
@@ -53,6 +72,10 @@ export interface ClaimClientOptions {
5372

5473
export interface ClaimClient {
5574
getPreviews(signal?: AbortSignal): Promise<ClaimablePlan[]>;
75+
/** Banner-distributed plans from `marketing/touch` (wk-1030 shape). */
76+
getMarketingPlans(signal?: AbortSignal): Promise<ClaimablePlan[]>;
77+
/** Preview + banner merged, deduped by planId (preview wins). */
78+
listPlans(signal?: AbortSignal): Promise<ClaimablePlan[]>;
5679
claim(planId: string, captcha?: { verifyParam: string; region?: string }, signal?: AbortSignal): Promise<ClaimOutcome>;
5780
}
5881

@@ -96,8 +119,13 @@ export function createClaimClient(opts: ClaimClientOptions): ClaimClient {
96119
const origin = opts.origin.replace(/\/+$/, "");
97120
const jwt = opts.jwt?.trim() || undefined;
98121
const deviceMid = opts.deviceMid?.trim() || undefined;
122+
const marketingDeviceMid = opts.marketingDeviceMid?.trim() || undefined;
123+
const language = opts.language?.trim() || "zh-CN";
99124
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
100125
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
126+
// Marketing snapshot sequence — the client keeps a module-level counter
127+
// (`Xde++`); a per-client counter from 0 is equivalent per session.
128+
let marketingSeq = 0;
101129

102130
function parseEntitlement(c: RawEntitlement): PlanEntitlement | null {
103131
const entitlementId = c.entitlement_id?.trim() ?? "";
@@ -134,6 +162,64 @@ export function createClaimClient(opts: ClaimClientOptions): ClaimClient {
134162
return plan;
135163
}
136164

165+
/** Marketing snapshot delivery (wk-1030 shape, parsed defensively). */
166+
interface MarketingNode {
167+
action?: { type?: unknown; args?: { plan_id?: unknown } };
168+
buttons?: MarketingNode[];
169+
}
170+
interface MarketingDelivery {
171+
campaign_id?: unknown;
172+
banner?: MarketingNode & { background?: { args?: Record<string, unknown> } };
173+
popup?: MarketingNode & { background?: { args?: Record<string, unknown> } };
174+
}
175+
176+
/** Collect `zcode_plan` RawPlan objects anywhere inside a delivery (depth-limited). */
177+
function collectZcodePlans(node: unknown, out: RawPlan[], depth = 0): void {
178+
if (depth > 4 || node === null || typeof node !== "object") return;
179+
if (Array.isArray(node)) {
180+
for (const item of node) collectZcodePlans(item, out, depth + 1);
181+
return;
182+
}
183+
const rec = node as Record<string, unknown>;
184+
const zp = rec.zcode_plan;
185+
if (zp && typeof zp === "object" && !Array.isArray(zp)) out.push(zp as RawPlan);
186+
for (const value of Object.values(rec)) collectZcodePlans(value, out, depth + 1);
187+
}
188+
189+
/**
190+
* deliveries → claimable plans: button action `claim_zcode_plan` supplies
191+
* the plan_id (schema-conformant minimal args); the banner background args
192+
* carry the full `zcode_plan` object for enrichment when the ids match.
193+
*/
194+
function parseMarketingDeliveries(deliveries: unknown[]): ClaimablePlan[] {
195+
const plans: ClaimablePlan[] = [];
196+
const seen = new Set<string>();
197+
for (const d of deliveries) {
198+
if (d === null || typeof d !== "object") continue;
199+
const delivery = d as MarketingDelivery;
200+
const campaignId = typeof delivery.campaign_id === "string" ? delivery.campaign_id : undefined;
201+
const richPlans: RawPlan[] = [];
202+
collectZcodePlans(delivery, richPlans);
203+
const richById = new Map(richPlans.map((p) => [p.plan_id?.trim() ?? "", p]));
204+
const buttonHosts = [delivery.banner, delivery.popup];
205+
for (const host of buttonHosts) {
206+
for (const button of host?.buttons ?? []) {
207+
if (button?.action?.type !== "claim_zcode_plan") continue;
208+
const planId = typeof button.action.args?.plan_id === "string" ? button.action.args.plan_id.trim() : "";
209+
if (!planId || seen.has(planId)) continue;
210+
const raw = richById.get(planId) ?? { plan_id: planId };
211+
const plan = parsePlan(raw);
212+
if (!plan) continue;
213+
seen.add(planId);
214+
plan.source = "banner";
215+
if (campaignId) plan.campaignId = campaignId;
216+
plans.push(plan);
217+
}
218+
}
219+
}
220+
return plans;
221+
}
222+
137223
async function request(
138224
method: string,
139225
path: string,
@@ -183,17 +269,66 @@ export function createClaimClient(opts: ClaimClientOptions): ClaimClient {
183269
const headers: Record<string, string> = jwt ? { Authorization: `Bearer ${jwt}` } : {};
184270
if (deviceMid) headers["X-Device-Mid"] = deviceMid;
185271
const { status, json, text } = await request("GET", url, { headers, signal });
272+
// code 0 + NO data field (observed 2026-10-30, wk-1030): the billing
273+
// preview simply has no manual campaigns for this account — the
274+
// desktop client throws `manual_claim_preview_missing_data` here, but
275+
// its banner flow never calls preview. For enumeration we treat it as
276+
// an empty list so the marketing fallback can supply the plans.
277+
if (status >= 200 && status < 300 && json?.code === 0 && json?.data === undefined) {
278+
return [];
279+
}
186280
if (status < 200 || status >= 300 || (json?.code !== undefined && json.code !== 0) || json?.data === undefined) {
187281
const { code, message } = unwrapError(json, status, text);
188282
throw new ClaimPreviewError(`claim preview failed (${code}): ${message}`, status, code);
189283
}
190284
const data = json.data as { plans?: RawPlan[] };
191-
return (data.plans ?? []).flatMap((p) => {
285+
return ((data.plans ?? []) as RawPlan[]).flatMap((p) => {
192286
const plan = parsePlan(p);
193287
return plan ? [plan] : [];
194288
});
195289
},
196290

291+
async getMarketingPlans(signal?: AbortSignal): Promise<ClaimablePlan[]> {
292+
if (!marketingDeviceMid) return [];
293+
const headers: Record<string, string> = {
294+
"X-Device-Mid": marketingDeviceMid,
295+
"X-Client-Language": language,
296+
"X-ZCode-App-Version": opts.appVersion,
297+
};
298+
if (jwt) headers["Authorization"] = `Bearer ${jwt}`;
299+
const path = `/api/v1/marketing/touch?seq=${marketingSeq++}`;
300+
const { status, json, text } = await request("GET", path, { headers, signal });
301+
if (status < 200 || status >= 300 || (json?.code !== undefined && json.code !== 0)) {
302+
// Marketing failures never block enumeration — log-free empty result
303+
// (the billing face stays authoritative when both are alive).
304+
void text;
305+
return [];
306+
}
307+
const deliveries = (json?.data as { deliveries?: unknown[] } | undefined)?.deliveries ?? [];
308+
return parseMarketingDeliveries(deliveries);
309+
},
310+
311+
async listPlans(signal?: AbortSignal): Promise<ClaimablePlan[]> {
312+
const [preview, banner] = await Promise.all([
313+
this.getPreviews(signal).catch((err: unknown) => {
314+
// 404 = campaign endpoint not deployed (pre-launch state) — keep
315+
// polling semantics to the caller by surfacing an EMPTY list here
316+
// only for that case; real errors propagate.
317+
if (err instanceof ClaimPreviewError && err.status === 404) return [];
318+
throw err;
319+
}),
320+
this.getMarketingPlans(signal),
321+
]);
322+
const seen = new Set(preview.map((p) => p.planId));
323+
const merged = [...preview];
324+
for (const p of banner) {
325+
if (seen.has(p.planId)) continue;
326+
seen.add(p.planId);
327+
merged.push(p);
328+
}
329+
return merged;
330+
},
331+
197332
async claim(planId: string, captcha?: { verifyParam: string; region?: string }, signal?: AbortSignal): Promise<ClaimOutcome> {
198333
if (!jwt) return { ok: false, planId, failureKind: "login_required", code: 401, message: "manual_claim_login_required" };
199334
// Bundle `claimManualPlan` header order: Authorization, Content-Type,

0 commit comments

Comments
 (0)