@@ -118050,27 +118050,121 @@ var import_node_http3 = require("node:http");
118050118050// src/auth/oauth.ts
118051118051var import_node_http2 = require("node:http");
118052118052var 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`;
118054118055var BIGMODEL_HOST = "https://bigmodel.cn";
118055118056var 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- };
118223118301var 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};
118237118309var 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+ }
118245118320function 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 {
0 commit comments