Skip to content

Commit d5d6df1

Browse files
committed
Fix: oauth login call back url
修复了{"detail":"Redirect URI not registered for this client"}错误
1 parent 84c4059 commit d5d6df1

6 files changed

Lines changed: 599 additions & 223 deletions

File tree

‎Android-APP/app/src/main/assets/server_bundle/server.cjs‎

Lines changed: 121 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -118050,27 +118050,121 @@ var import_node_http3 = require("node:http");
118050118050
// src/auth/oauth.ts
118051118051
var import_node_http2 = require("node:http");
118052118052
var import_node_crypto3 = require("node:crypto");
118053-
var ZCODE_TOKEN_ENDPOINT = "https://zcode.z.ai/api/v1/oauth/token";
118053+
var ZCODE_API_BASE = "https://zcode.z.ai/api/v1";
118054+
var ZCODE_TOKEN_ENDPOINT = `${ZCODE_API_BASE}/oauth/token`;
118054118055
var BIGMODEL_HOST = "https://bigmodel.cn";
118055118056
var BIGMODEL_APP_ID = "zcode";
118056-
var AuthCodeOAuthClient = class {
118057-
constructor(config, fetchImpl = fetch) {
118058-
this.config = config;
118057+
var LOGIN_TIMEOUT_MS = 3e5;
118058+
var OAuthFlowClient = class {
118059+
constructor(provider, fetchImpl) {
118060+
this.provider = provider;
118059118061
this.fetchImpl = fetchImpl;
118060118062
}
118061-
config;
118063+
provider;
118062118064
fetchImpl;
118065+
/** Run the full flow end-to-end: surface authorize URL, wait, close. */
118066+
async authorize(onAuthorizeUrl, timeoutMs = LOGIN_TIMEOUT_MS) {
118067+
const started = await this.start();
118068+
onAuthorizeUrl?.(started.authorizeUrl);
118069+
try {
118070+
const tokens = await this.complete(started, timeoutMs);
118071+
return { accessToken: tokens.accessToken, provider: this.provider, userId: tokens.userId, jwt: tokens.jwt };
118072+
} finally {
118073+
await this.close();
118074+
}
118075+
}
118076+
};
118077+
async function requestZcodeEnvelope(fetchImpl, url2, init, label2) {
118078+
const resp = await fetchImpl(url2, init);
118079+
const raw = safeJsonParse(await resp.text());
118080+
if (!raw || typeof raw.code !== "number") {
118081+
throw new Error(`${label2}: invalid response envelope (status=${resp.status})`);
118082+
}
118083+
if (!resp.ok || raw.code !== 0) {
118084+
throw new Error(`${label2} failed: status=${resp.status} msg=${raw.msg ?? "(none)"}`);
118085+
}
118086+
return raw.data;
118087+
}
118088+
var ZaiOAuthClient = class extends OAuthFlowClient {
118089+
constructor(fetchImpl = fetch, sleep2 = defaultSleep) {
118090+
super("zai", fetchImpl);
118091+
this.sleep = sleep2;
118092+
}
118093+
sleep;
118094+
flow = null;
118095+
pollToken = "";
118096+
start() {
118097+
this.flow = null;
118098+
this.pollToken = (0, import_node_crypto3.randomBytes)(32).toString("hex");
118099+
return (async () => {
118100+
const data2 = await requestZcodeEnvelope(
118101+
this.fetchImpl,
118102+
`${ZCODE_API_BASE}/oauth/cli/init`,
118103+
{
118104+
method: "POST",
118105+
headers: { authorization: `Bearer ${this.pollToken}`, "content-type": "application/json" },
118106+
body: JSON.stringify({ provider: this.provider })
118107+
},
118108+
"Z.AI login init"
118109+
);
118110+
if (!data2 || typeof data2.flow_id !== "string" || typeof data2.authorize_url !== "string" || typeof data2.expires_at !== "number" || typeof data2.poll_interval_sec !== "number") {
118111+
throw new Error("Z.AI login init: invalid response data");
118112+
}
118113+
this.flow = data2;
118114+
return { authorizeUrl: this.flow.authorize_url, callbackUrl: "", state: this.flow.flow_id };
118115+
})();
118116+
}
118117+
async complete(_started, timeoutMs = LOGIN_TIMEOUT_MS) {
118118+
const flow = this.flow;
118119+
if (!flow) throw new Error("Z.AI login not started");
118120+
const deadlineMs = Math.min(Date.now() + timeoutMs, flow.expires_at * 1e3);
118121+
const intervalMs = Math.max(1e3, flow.poll_interval_sec * 1e3);
118122+
for (; ; ) {
118123+
if (Date.now() >= deadlineMs) {
118124+
throw new Error("Authorization timed out. Please retry login.");
118125+
}
118126+
const data2 = await requestZcodeEnvelope(
118127+
this.fetchImpl,
118128+
`${ZCODE_API_BASE}/oauth/cli/poll/${encodeURIComponent(flow.flow_id)}`,
118129+
{ method: "GET", headers: { authorization: `Bearer ${this.pollToken}` } },
118130+
"Z.AI login poll"
118131+
);
118132+
if (data2?.status === "ready") {
118133+
const accessToken = typeof data2.zai?.access_token === "string" ? data2.zai.access_token.trim() : "";
118134+
if (!accessToken) {
118135+
throw new Error("Z.AI login poll: response missing data.zai.access_token");
118136+
}
118137+
return {
118138+
accessToken,
118139+
jwt: typeof data2.token === "string" ? data2.token.trim() : void 0,
118140+
userId: typeof data2.user?.user_id === "string" ? data2.user.user_id : void 0
118141+
};
118142+
}
118143+
if (data2?.status === "failed") {
118144+
throw new Error("Authorization failed. Please retry login.");
118145+
}
118146+
if (data2?.status !== "pending") {
118147+
throw new Error(`Z.AI login poll: unexpected status ${String(data2?.status ?? "(none)")}`);
118148+
}
118149+
await this.sleep(Math.min(intervalMs, Math.max(0, deadlineMs - Date.now())));
118150+
}
118151+
}
118152+
async close() {
118153+
this.flow = null;
118154+
}
118155+
};
118156+
var AuthCodeOAuthClient = class extends OAuthFlowClient {
118063118157
server = null;
118064118158
callbackResult = null;
118065118159
callbackWaiters = [];
118160+
constructor(config, fetchImpl = fetch) {
118161+
super(config.provider, fetchImpl);
118162+
this.config = config;
118163+
}
118164+
config;
118066118165
/** Build the provider authorize URL with the localhost redirect + state. */
118067118166
buildAuthorizeUrl(callbackUrl, state2) {
118068-
const params = this.config.authorizeParamStyle === "oauth2" ? new URLSearchParams({
118069-
redirect_uri: callbackUrl,
118070-
response_type: "code",
118071-
client_id: this.config.appId,
118072-
state: state2
118073-
}) : new URLSearchParams({
118167+
const params = new URLSearchParams({
118074118168
appId: this.config.appId,
118075118169
redirect: callbackUrl,
118076118170
state: state2
@@ -118083,7 +118177,7 @@ var AuthCodeOAuthClient = class {
118083118177
*
118084118178
* The bind port is `0` (OS-assigned random) unless the env var
118085118179
* `ZCODE_OAUTH_CALLBACK_PORT` is set, in which case that exact port is used.
118086-
* The Android entry sets the env var so the WebView redirect URL is
118180+
* The Android entry sets the env var so the Custom Tabs redirect URL is
118087118181
* predictable across launches.
118088118182
*/
118089118183
start() {
@@ -118135,7 +118229,7 @@ var AuthCodeOAuthClient = class {
118135118229
}
118136118230
}
118137118231
/** Wait for the OAuth callback redirect. Resolves with the auth code. */
118138-
waitForCallback(timeoutMs = 3e5) {
118232+
waitForCallback(timeoutMs = LOGIN_TIMEOUT_MS) {
118139118233
if (this.callbackResult?.code) {
118140118234
return Promise.resolve(this.callbackResult.code);
118141118235
}
@@ -118188,17 +118282,10 @@ var AuthCodeOAuthClient = class {
118188118282
const jwt = raw?.data?.token?.trim() ?? void 0;
118189118283
return { accessToken, userId: typeof userId === "string" ? userId : void 0, jwt };
118190118284
}
118191-
/** Run the full flow: start server, surface authorize URL, exchange code. */
118192-
async authorize(onAuthorizeUrl, timeoutMs = 3e5) {
118193-
const { authorizeUrl, callbackUrl, state: state2 } = await this.start();
118194-
onAuthorizeUrl?.(authorizeUrl);
118195-
try {
118196-
const authCode = await this.waitForCallback(timeoutMs);
118197-
const { accessToken, userId, jwt } = await this.exchangeCode(authCode, callbackUrl, state2);
118198-
return { accessToken, provider: this.config.provider, userId, jwt };
118199-
} finally {
118200-
await this.close();
118201-
}
118285+
/** Wait for the browser callback, then exchange the code. */
118286+
async complete(started, timeoutMs = LOGIN_TIMEOUT_MS) {
118287+
const code = await this.waitForCallback(timeoutMs);
118288+
return this.exchangeCode(code, started.callbackUrl, started.state);
118202118289
}
118203118290
async close() {
118204118291
if (this.server) {
@@ -118211,28 +118298,13 @@ var AuthCodeOAuthClient = class {
118211118298
}
118212118299
}
118213118300
};
118214-
var ZAI_AUTH_CODE_CONFIG = {
118215-
provider: "zai",
118216-
authorizeUrl: "https://chat.z.ai/api/oauth/authorize",
118217-
appId: "client_P8X5CMWmlaRO9gyO-KSqtg",
118218-
tokenUrl: ZCODE_TOKEN_ENDPOINT,
118219-
callbackPath: "/oauth/callback/zai",
118220-
accessTokenField: "zai",
118221-
authorizeParamStyle: "oauth2"
118222-
};
118223118301
var BIGMODEL_AUTH_CODE_CONFIG = {
118224118302
provider: "bigmodel",
118225118303
authorizeUrl: `${BIGMODEL_HOST}/login`,
118226118304
appId: BIGMODEL_APP_ID,
118227118305
tokenUrl: ZCODE_TOKEN_ENDPOINT,
118228118306
callbackPath: "/oauth/callback/bigmodel",
118229-
accessTokenField: "bigmodel",
118230-
authorizeParamStyle: "zcode"
118231-
};
118232-
var ZaiOAuthClient = class extends AuthCodeOAuthClient {
118233-
constructor(fetchImpl = fetch) {
118234-
super(ZAI_AUTH_CODE_CONFIG, fetchImpl);
118235-
}
118307+
accessTokenField: "bigmodel"
118236118308
};
118237118309
var BigmodelOAuthClient = class extends AuthCodeOAuthClient {
118238118310
constructor(fetchImpl = fetch, host2 = BIGMODEL_HOST, appId = BIGMODEL_APP_ID) {
@@ -118242,6 +118314,9 @@ var BigmodelOAuthClient = class extends AuthCodeOAuthClient {
118242118314
);
118243118315
}
118244118316
};
118317+
function defaultSleep(ms) {
118318+
return new Promise((resolve) => setTimeout(resolve, ms));
118319+
}
118245118320
function safeJsonParse(text) {
118246118321
try {
118247118322
return JSON.parse(text);
@@ -118467,20 +118542,18 @@ async function dispatch(cmd, state2, ctx) {
118467118542
}
118468118543
const client = cmd.provider === "bigmodel" ? new BigmodelOAuthClient() : new ZaiOAuthClient();
118469118544
const started = await client.start();
118470-
const callbackUrlObj = new URL(started.callbackUrl);
118471-
const callbackPort = callbackUrlObj.port ? Number(callbackUrlObj.port) : 80;
118545+
const callbackPort = started.callbackUrl ? Number(new URL(started.callbackUrl).port) || 80 : 0;
118472118546
state2.activeOauth = {
118473118547
client,
118474118548
callbackUrl: started.callbackUrl,
118475118549
state: started.state
118476118550
};
118477-
client.waitForCallback().then(async (code) => {
118478-
const { accessToken, userId, jwt } = await client.exchangeCode(code, started.callbackUrl, started.state);
118551+
client.complete(started).then(async (tokens) => {
118479118552
const resolver = new KeyResolver();
118480-
const cred = await resolver.resolveCodingPlanCredential(accessToken, cmd.provider, userId);
118481-
if (jwt) cred.jwt = jwt;
118553+
const cred = await resolver.resolveCodingPlanCredential(tokens.accessToken, cmd.provider, tokens.userId);
118554+
if (tokens.jwt) cred.jwt = tokens.jwt;
118482118555
await saveCredential(cred);
118483-
console.log(`OAuth completed for ${cmd.provider} via browser callback`);
118556+
console.log(`OAuth completed for ${cmd.provider}`);
118484118557
}).catch((err) => {
118485118558
console.error(`OAuth flow ended without success: ${err?.message ?? String(err)}`);
118486118559
}).finally(() => {
@@ -118497,7 +118570,7 @@ async function dispatch(cmd, state2, ctx) {
118497118570
}
118498118571
case "deliverOAuthCode": {
118499118572
const active = state2.activeOauth;
118500-
if (!active || active.state !== cmd.state) {
118573+
if (!(active?.client instanceof AuthCodeOAuthClient) || active.state !== cmd.state) {
118501118574
return { ok: false, error: "no_matching_oauth_flow" };
118502118575
}
118503118576
try {

‎README.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,16 @@ provider: zai # or bigmodel
3838
### Option 2: OAuth Login (browser-based, both providers)
3939
4040
```bash
41-
# Z.AI auth-code flow (chat.z.ai authorize → zcode.z.ai token exchange)
41+
# Z.AI server-mediated CLI login (3.10 parity: init/poll at zcode.z.ai, no local callback)
4242
bun run src/index.ts auth login zai
4343

44-
# Bigmodel auth-code flow (bigmodel.cn authorize → zcode.z.ai token exchange)
44+
# Bigmodel auth-code flow (bigmodel.cn authorize → localhost callback → zcode.z.ai token exchange)
4545
bun run src/index.ts auth login bigmodel
4646

4747
# This will:
4848
# 1. Print an authorize URL and open your browser
49-
# 2. Exchange the auth code for upstream credentials
49+
# 2. Z.AI: poll the server until authorization completes;
50+
# Bigmodel: receive the browser callback and exchange the auth code
5051
# 3. Resolve your coding-plan API key automatically
5152
# 4. Save encrypted credentials to ~/.zcode-proxy/credentials.json
5253

‎src/android/control.test.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -277,15 +277,17 @@ describe("android control startOAuth callback-port lifecycle", () => {
277277
it("releases the callback port when the flow is rejected (abandoned login)", async () => {
278278
const port = await freePort();
279279
process.env.ZCODE_OAUTH_CALLBACK_PORT = String(port);
280-
const state: ControlState = { provider: "zai", plan: "coding-plan", proxyPort: 0 };
280+
// bigmodel is the provider with a local callback server (zai's cli login
281+
// flow completes via server polling and binds nothing).
282+
const state: ControlState = { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 };
281283

282-
const started = await post({ cmd: "startOAuth", provider: "zai" }, state);
284+
const started = await post({ cmd: "startOAuth", provider: "bigmodel" }, state);
283285
expect(started.body.ok).toBe(true);
284286
expect(state.activeOauth).toBeDefined();
285287

286288
// Simulate the user abandoning the flow: a callback with a bad state
287289
// rejects every waitForCallback waiter.
288-
const resp = await fetch(`http://127.0.0.1:${port}/oauth/callback/zai?state=bad&code=x`);
290+
const resp = await fetch(`http://127.0.0.1:${port}/oauth/callback/bigmodel?state=bad&code=x`);
289291
expect(resp.status).toBe(400);
290292
await Bun.sleep(50);
291293

@@ -296,14 +298,14 @@ describe("android control startOAuth callback-port lifecycle", () => {
296298
it("a second startOAuth tears down the previous flow instead of hitting EADDRINUSE", async () => {
297299
const port = await freePort();
298300
process.env.ZCODE_OAUTH_CALLBACK_PORT = String(port);
299-
const state: ControlState = { provider: "zai", plan: "coding-plan", proxyPort: 0 };
301+
const state: ControlState = { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 };
300302

301-
const first = await post({ cmd: "startOAuth", provider: "zai" }, state);
303+
const first = await post({ cmd: "startOAuth", provider: "bigmodel" }, state);
302304
expect(first.body.ok).toBe(true);
303305

304306
// Previously this threw EADDRINUSE (500) because the first flow still
305307
// held the fixed callback port.
306-
const second = await post({ cmd: "startOAuth", provider: "zai" }, state);
308+
const second = await post({ cmd: "startOAuth", provider: "bigmodel" }, state);
307309
expect(second.body.ok).toBe(true);
308310

309311
// Clean up the flow started by the second command.

‎src/android/control.ts‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,12 @@
1818
import { createServer, type Server, type IncomingMessage, type ServerResponse } from "node:http";
1919
import type { ProviderId } from "../provider/types.js";
2020
import type { Credential } from "../auth/types.js";
21-
import { ZaiOAuthClient, BigmodelOAuthClient } from "../auth/oauth.js";
21+
import {
22+
ZaiOAuthClient,
23+
BigmodelOAuthClient,
24+
AuthCodeOAuthClient,
25+
type OAuthFlowClient,
26+
} from "../auth/oauth.js";
2227
import { KeyResolver } from "../auth/resolver.js";
2328
import { saveCredential, clearCredential, loadCredential } from "../auth/store.js";
2429

@@ -75,7 +80,7 @@ export interface ControlState {
7580
proxyPort: number;
7681
/** Active OAuth client while a flow is in flight; nulled on completion. */
7782
activeOauth?: {
78-
client: ZaiOAuthClient | BigmodelOAuthClient;
83+
client: OAuthFlowClient;
7984
callbackUrl: string;
8085
state: string;
8186
};
@@ -251,25 +256,28 @@ async function dispatch(
251256
await state.activeOauth.client.close().catch(() => {});
252257
state.activeOauth = undefined;
253258
}
254-
const client = cmd.provider === "bigmodel" ? new BigmodelOAuthClient() : new ZaiOAuthClient();
259+
// Z.AI uses the server-mediated cli login (no local callback); bigmodel
260+
// keeps the classic localhost auth-code callback server.
261+
const client: OAuthFlowClient =
262+
cmd.provider === "bigmodel" ? new BigmodelOAuthClient() : new ZaiOAuthClient();
255263
const started = await client.start();
256-
const callbackUrlObj = new URL(started.callbackUrl);
257-
const callbackPort = callbackUrlObj.port ? Number(callbackUrlObj.port) : 80;
264+
const callbackPort = started.callbackUrl
265+
? Number(new URL(started.callbackUrl).port) || 80
266+
: 0;
258267
state.activeOauth = {
259268
client,
260269
callbackUrl: started.callbackUrl,
261270
state: started.state,
262271
};
263-
client.waitForCallback().then(async (code) => {
264-
const { accessToken, userId, jwt } = await client.exchangeCode(code, started.callbackUrl, started.state);
272+
client.complete(started).then(async (tokens) => {
265273
const resolver = new KeyResolver();
266-
const cred: Credential = await resolver.resolveCodingPlanCredential(accessToken, cmd.provider, userId);
267-
if (jwt) cred.jwt = jwt;
274+
const cred: Credential = await resolver.resolveCodingPlanCredential(tokens.accessToken, cmd.provider, tokens.userId);
275+
if (tokens.jwt) cred.jwt = tokens.jwt;
268276
await saveCredential(cred);
269-
console.log(`OAuth completed for ${cmd.provider} via browser callback`);
277+
console.log(`OAuth completed for ${cmd.provider}`);
270278
}).catch((err: unknown) => {
271-
// Timeouts / callback rejections are expected when the user abandons
272-
// the browser; nothing to surface beyond the log buffer.
279+
// Timeouts / rejections are expected when the user abandons the
280+
// browser; nothing to surface beyond the log buffer.
273281
console.error(`OAuth flow ended without success: ${(err as Error)?.message ?? String(err)}`);
274282
}).finally(() => {
275283
// MUST run on rejection too — otherwise the callback port leaks until
@@ -287,7 +295,9 @@ async function dispatch(
287295

288296
case "deliverOAuthCode": {
289297
const active = state.activeOauth;
290-
if (!active || active.state !== cmd.state) {
298+
// Code delivery only applies to callback-based (auth-code) flows — the
299+
// Z.AI cli login completes via server polling and has no code to deliver.
300+
if (!(active?.client instanceof AuthCodeOAuthClient) || active.state !== cmd.state) {
291301
return { ok: false, error: "no_matching_oauth_flow" };
292302
}
293303
try {

0 commit comments

Comments
 (0)