Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): xAI 订阅 OAuth 回调支持 consent 页跨源 fetch,修复登录卡死 (#501)

Chris Zhang05a04c1cb5ce
diff --git a/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts
new file mode 100644
index 0000000000..0c05be9a3a
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/grokOauthCallbackListener.test.ts
@@ -0,0 +1,330 @@
+/**
+ * CallbackListener(xAI OAuth loopback 回调)回归单测 —— issue #491。
+ *
+ * xAI 新版 consent 页(accounts.x.ai)授权后不再 302 重定向,而是页面 JS 跨源
+ * fetch http://127.0.0.1:56121/callback 投递 code。回归点:
+ * - CORS/PNA preflight(OPTIONS)必须 204 放行且不得终止登录流 —— 修复前它落进
+ * 缺 code 分支直接 reject,整个登录被 preflight 杀死;
+ * - 回执必须带 CORS 头(白名单限 xAI auth 域),否则 consent 页 fetch 读不到结果;
+ * - 无 code 无 error 的杂请求不得终止等待中的登录;
+ * - 首个终态结果落定后,重试回调不得覆盖 pendingRes / 登录结果。
+ */
+
+import { request as httpRequest } from 'node:http';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ shell: { openExternal: vi.fn() },
+ app: {
+ getPath: vi.fn(() => '/tmp/xdt-maker-test'),
+ getAppPath: vi.fn(() => '/tmp/xdt-maker-test/app'),
+ isPackaged: false,
+ },
+ safeStorage: { isEncryptionAvailable: vi.fn(() => false) },
+}));
+
+import { CallbackListener, xaiCallbackCorsHeaders } from '../grok-oauth-login.js';
+
+const PORT = 56121;
+const XAI_ORIGIN = 'https://accounts.x.ai';
+
+interface HttpResult {
+ status: number;
+ headers: Record<string, string | string[] | undefined>;
+ body: string;
+}
+
+/** 用 node:http 直发请求(fetch 不允许自定义 Origin 这类受管头)。 */
+function send(
+ method: string,
+ path: string,
+ headers: Record<string, string> = {},
+): Promise<HttpResult> {
+ return new Promise((resolve, reject) => {
+ const req = httpRequest(
+ // agent:false —— 每请求独立连接。全局 agent 的 keep-alive 会把上一个用例
+ // 已关闭 server 的死 socket 复用给下一个用例,产生假 ECONNRESET。
+ { host: '127.0.0.1', port: PORT, method, path, headers, agent: false },
+ (res) => {
+ let body = '';
+ res.on('data', (chunk: Buffer) => (body += chunk.toString('utf-8')));
+ res.on('end', () =>
+ resolve({ status: res.statusCode ?? 0, headers: res.headers, body }),
+ );
+ },
+ );
+ req.on('error', reject);
+ req.end();
+ });
+}
+
+/** 断言 promise 在 wait 毫秒内保持 pending(登录流未被终止)。 */
+async function expectStillPending(p: Promise<unknown>, wait = 50): Promise<void> {
+ const outcome = await Promise.race([
+ p.then(
+ () => 'settled',
+ () => 'settled',
+ ),
+ new Promise<string>((r) => setTimeout(() => r('pending'), wait)),
+ ]);
+ expect(outcome).toBe('pending');
+}
+
+describe('xaiCallbackCorsHeaders', () => {
+ it('白名单 origin(accounts.x.ai / auth.x.ai)返回完整 CORS + PNA 头', () => {
+ for (const origin of ['https://accounts.x.ai', 'https://auth.x.ai']) {
+ const h = xaiCallbackCorsHeaders(origin);
+ expect(h['Access-Control-Allow-Origin']).toBe(origin);
+ expect(h['Access-Control-Allow-Methods']).toBe('GET, OPTIONS');
+ expect(h['Access-Control-Allow-Private-Network']).toBe('true');
+ expect(h.Vary).toBe('Origin');
+ }
+ });
+
+ it('非白名单 / 缺失 origin 不放行', () => {
+ expect(xaiCallbackCorsHeaders('https://evil.example')).toEqual({});
+ expect(xaiCallbackCorsHeaders('http://accounts.x.ai')).toEqual({});
+ expect(xaiCallbackCorsHeaders(undefined)).toEqual({});
+ });
+});
+
+describe('CallbackListener(xAI loopback 回调)', () => {
+ let listener: CallbackListener;
+
+ beforeEach(async () => {
+ listener = new CallbackListener();
+ await listener.start();
+ });
+
+ afterEach(() => {
+ listener.close();
+ });
+
+ it('OPTIONS preflight 回 204 + CORS/PNA 头,且不终止登录流', async () => {
+ const codePromise = listener.waitForCode('state-1');
+ codePromise.catch(() => undefined);
+
+ const res = await send('OPTIONS', '/callback', {
+ origin: XAI_ORIGIN,
+ 'access-control-request-method': 'GET',
+ 'access-control-request-private-network': 'true',
+ });
+ expect(res.status).toBe(204);
+ expect(res.headers['access-control-allow-origin']).toBe(XAI_ORIGIN);
+ expect(res.headers['access-control-allow-private-network']).toBe('true');
+
+ // 修复前:preflight 落进缺 code 分支,登录流被 reject 杀死。
+ await expectStillPending(codePromise);
+
+ // preflight 后正式 GET 仍能完成登录。
+ const getPromise = send('GET', '/callback?code=abc123&state=state-1', {
+ origin: XAI_ORIGIN,
+ });
+ await expect(codePromise).resolves.toBe('abc123');
+ listener.succeed();
+ const getRes = await getPromise;
+ expect(getRes.status).toBe(200);
+ expect(getRes.headers['access-control-allow-origin']).toBe(XAI_ORIGIN);
+ });
+
+ it('无 code 无 error 的杂请求回 400 但登录继续等待', async () => {
+ const codePromise = listener.waitForCode('state-2');
+ codePromise.catch(() => undefined);
+
+ // 完全无参数(走 state-mismatch 拒绝)与 state 匹配但缺 code(走缺 code 分支)
+ // 两条路径都不得终止登录。
+ const res = await send('GET', '/callback');
+ expect(res.status).toBe(400);
+ const matchedNoCode = await send('GET', '/callback?state=state-2');
+ expect(matchedNoCode.status).toBe(400);
+ await expectStillPending(codePromise);
+
+ const getPromise = send('GET', '/callback?code=xyz&state=state-2');
+ await expect(codePromise).resolves.toBe('xyz');
+ listener.succeed();
+ await getPromise;
+ });
+
+ it('state 匹配的 error 回调终止登录并透出 error_description', async () => {
+ const codePromise = listener.waitForCode('state-3');
+ // 与生产 runGrokOAuthLogin 同模式预挂 no-op catch:reject 可能先于下方
+ // rejects 断言挂载,避免被记成 unhandled rejection。
+ codePromise.catch(() => undefined);
+ const res = await send(
+ 'GET',
+ '/callback?error=access_denied&error_description=user%20denied&state=state-3',
+ { origin: XAI_ORIGIN },
+ );
+ expect(res.status).toBe(400);
+ expect(res.headers['access-control-allow-origin']).toBe(XAI_ORIGIN);
+ await expect(codePromise).rejects.toThrow('No authorization code received');
+ });
+
+ it('state 不匹配的回调(旧登录 tab 滞留重试)回 400 但不终止当前登录', async () => {
+ const codePromise = listener.waitForCode('expected-state');
+
+ // 旧 tab 带旧 state 的 code 重试与 error 回调都只被拒,不得 settle 当前登录。
+ const staleCode = await send('GET', '/callback?code=abc&state=wrong-state', {
+ origin: XAI_ORIGIN,
+ });
+ expect(staleCode.status).toBe(400);
+ const staleError = await send(
+ 'GET',
+ '/callback?error=access_denied&state=wrong-state',
+ { origin: XAI_ORIGIN },
+ );
+ expect(staleError.status).toBe(400);
+ await expectStillPending(codePromise);
+
+ // 当前登录自己的回调随后到达,仍正常完成。
+ const getPromise = send('GET', '/callback?code=real&state=expected-state', {
+ origin: XAI_ORIGIN,
+ });
+ await expect(codePromise).resolves.toBe('real');
+ listener.succeed();
+ await getPromise;
+ });
+
+ it('exchange 进行中的重试回调挂起同候,succeed() 后与首个一起收到 200', async () => {
+ const codePromise = listener.waitForCode('state-5');
+
+ const firstGet = send('GET', '/callback?code=first&state=state-5', {
+ origin: XAI_ORIGIN,
+ });
+ await expect(codePromise).resolves.toBe('first');
+
+ // token 交换进行中,页面重试 fetch —— 不能提前拿到 200(交换随后可能失败),
+ // 必须与首个连接一起等 succeed()/fail() 收口。
+ const retry = send('GET', '/callback?code=first&state=state-5', {
+ origin: XAI_ORIGIN,
+ });
+ await expectStillPending(retry);
+
+ // exchange 挂起窗口内 state 不匹配的请求立即 400 拒绝,不得入 pending 挂起
+ // (否则不知道 state 的本机进程可囤积任意多连接)。
+ const staleDuringExchange = await send('GET', '/callback?code=x&state=wrong', {
+ origin: XAI_ORIGIN,
+ });
+ expect(staleDuringExchange.status).toBe(400);
+
+ listener.succeed();
+ const [first, second] = await Promise.all([firstGet, retry]);
+ for (const r of [first, second]) {
+ expect(r.status).toBe(200);
+ expect(r.headers['access-control-allow-origin']).toBe(XAI_ORIGIN);
+ expect(r.body).toContain('html');
+ }
+
+ // 成功收口后的迟到回调直接重放成功回执;state 不匹配的迟到请求仍被 400 拒绝,
+ // 不得吃到成功重放。
+ const late = await send('GET', '/callback?code=first&state=state-5', {
+ origin: XAI_ORIGIN,
+ });
+ expect(late.status).toBe(200);
+ const staleAfterSuccess = await send('GET', '/callback?code=x&state=wrong', {
+ origin: XAI_ORIGIN,
+ });
+ expect(staleAfterSuccess.status).toBe(400);
+ });
+
+ it('exchange 失败后挂起的重试与首个一起收到 500,迟到回调重放 400', async () => {
+ const codePromise = listener.waitForCode('state-5b');
+ const firstGet = send('GET', '/callback?code=bad&state=state-5b', {
+ origin: XAI_ORIGIN,
+ });
+ await expect(codePromise).resolves.toBe('bad');
+ const retry = send('GET', '/callback?code=bad&state=state-5b', {
+ origin: XAI_ORIGIN,
+ });
+ await expectStillPending(retry);
+
+ listener.fail('exchange exploded');
+ const [first, second] = await Promise.all([firstGet, retry]);
+ expect(first.status).toBe(500);
+ expect(second.status).toBe(500);
+
+ const late = await send('GET', '/callback?code=bad&state=state-5b', {
+ origin: XAI_ORIGIN,
+ });
+ expect(late.status).toBe(400);
+ });
+
+ it('error 终态后的重试回调重放 4xx,不得误报成功', async () => {
+ const codePromise = listener.waitForCode('state-5c');
+ codePromise.catch(() => undefined);
+ // state 必须匹配:否则请求走 state-mismatch 分支被拒,终态从未建立,
+ // 本用例就测不到「error 终态后的重放」路径(3f98a3f 曾漏改此处)。
+ const first = await send('GET', '/callback?error=access_denied&state=state-5c', {
+ origin: XAI_ORIGIN,
+ });
+ expect(first.status).toBe(400);
+ await expect(codePromise).rejects.toThrow('No authorization code received');
+
+ const retry = await send('GET', '/callback?error=access_denied&state=state-5c', {
+ origin: XAI_ORIGIN,
+ });
+ expect(retry.status).toBe(400);
+ expect(retry.headers['access-control-allow-origin']).toBe(XAI_ORIGIN);
+ });
+
+ it('非白名单 origin 的响应不带 CORS 放行头', async () => {
+ const codePromise = listener.waitForCode('state-6');
+ const getPromise = send('GET', '/callback?code=ok&state=state-6', {
+ origin: 'https://evil.example',
+ });
+ await expect(codePromise).resolves.toBe('ok');
+ listener.succeed();
+ const res = await getPromise;
+ expect(res.status).toBe(200);
+ expect(res.headers['access-control-allow-origin']).toBeUndefined();
+ });
+
+ it('挂起连接被客户端中止后 succeed() 不抛错,状态机不受影响', async () => {
+ const codePromise = listener.waitForCode('state-7');
+
+ // 发起回调后立刻掐断客户端连接(用户在 exchange 期间关掉授权页)。
+ const aborted = await new Promise<void>((resolve, reject) => {
+ const req = httpRequest(
+ {
+ host: '127.0.0.1',
+ port: PORT,
+ method: 'GET',
+ path: '/callback?code=abort-me&state=state-7',
+ headers: { origin: XAI_ORIGIN },
+ agent: false,
+ },
+ () => resolve(),
+ );
+ req.on('error', reject);
+ req.end();
+ // code 被消费(连接进入 pending hold)后销毁 socket。
+ void codePromise.then(() => {
+ setTimeout(() => {
+ req.destroy();
+ resolve();
+ }, 30);
+ });
+ }).then(
+ () => true,
+ () => true,
+ );
+ expect(aborted).toBe(true);
+ await expect(codePromise).resolves.toBe('abort-me');
+
+ // 凭证已落盘场景:succeed() 面对已中止的连接不得抛错。
+ expect(() => listener.succeed()).not.toThrow();
+
+ // 状态机仍是成功终态:迟到回调拿到成功重放。
+ const late = await send('GET', '/callback?code=abort-me&state=state-7', {
+ origin: XAI_ORIGIN,
+ });
+ expect(late.status).toBe(200);
+ });
+
+ it('回调端口被占用时 start() 报可读错误', async () => {
+ const blocker = new CallbackListener();
+ // beforeEach 已占 56121,新实例 start 应失败。
+ await expect(blocker.start()).rejects.toThrow('56121');
+ blocker.close();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
index 44b828e7e0..cff2f1c34e 100644
--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts
+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
@@ -4,6 +4,8 @@
* 参数取自 xAI 的 grok-cli OAuth 公共配置(client_id / OIDC issuer / scope / 固定回调端口)。
* 与 Claude 登录的关键差异:
* - 回调端口**固定 56121**(xAI 注册的 redirect_uri 是 http://127.0.0.1:56121/callback,不可随机);
+ * - code 由 consent 页(accounts.x.ai)的**页面 JS 跨源 fetch** 投递到 loopback(新版流程,
+ * 不再 302 重定向)——回调服务器必须应答 CORS preflight + Chrome PNA 头,见 CallbackListener;
* - endpoints 走 OIDC discovery(auth.x.ai/.well-known/openid-configuration),校验必须在 *.x.ai over https;
* - token 交换是 **form-encoded**,且 PKCE 的 code_challenge/method 在交换时**再发一次**(该 client 会二次校验);
* - token 由**本模块自管**(存 safeStorage 的 provider secret 'xai',JSON blob),过期自己用 refresh_token 刷新
@@ -222,12 +224,41 @@ function blobFromTokenResponse(t: TokenResponse, prev?: GrokTokenBlob | null): G
};
}
+// ── 回调 CORS ──────────────────────────────────────────────────────────────────
+// xAI 新版 consent 页(accounts.x.ai)授权完成后不再 302 重定向到 loopback,而是由
+// 页面 JS 跨源 fetch 本回调地址投递 code(页面同时显示授权码供官方 CLI 手动粘贴兜底)。
+// 跨源 fetch 要求本服务器正确应答 CORS preflight;Chrome 对「公网 https 页面 →
+// 127.0.0.1」还要求 Private Network Access 头。来源只放行 xAI 自己的 auth 域。
+const CALLBACK_CORS_ALLOWED_ORIGINS = new Set(['https://accounts.x.ai', 'https://auth.x.ai']);
+
+/** origin 在白名单内时返回回调响应应附带的 CORS 头;否则为空(不放行)。 */
+export function xaiCallbackCorsHeaders(origin: string | undefined): Record<string, string> {
+ if (!origin || !CALLBACK_CORS_ALLOWED_ORIGINS.has(origin)) return {};
+ return {
+ 'Access-Control-Allow-Origin': origin,
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type',
+ 'Access-Control-Allow-Private-Network': 'true',
+ Vary: 'Origin',
+ };
+}
+
// ── 回调监听(固定端口 56121)────────────────────────────────────────────────────
-class CallbackListener {
+// 导出仅供单测(runGrokOAuthLogin 是唯一运行期使用方)。
+export class CallbackListener {
private server: Server;
private expectedState = '';
- private pendingRes: ServerResponse | null = null;
+ /** code 已收到、等待 token exchange 收口的全部连接(consent 页可能重试 fetch)。 */
+ private pending: Array<{ res: ServerResponse; cors: Record<string, string> }> = [];
private callbackLang: OAuthResultPageLang = 'en';
+ /**
+ * 登录结果状态机,仅由 state 已匹配的回调驱动:收到 code → 'exchanging',
+ * succeed()/fail() 收口为 'success'/'failed'(state 匹配的 error 回调直接
+ * 'failed')。重放/迟到的回调按它回执:成功重放 200、失败重放 400、exchanging
+ * 挂起同候(挂起连接在 fail() 时收 500)。state 不匹配的请求一律 400 拒绝,
+ * 不进入状态机也不入 pending。
+ */
+ private outcome: 'exchanging' | 'success' | 'failed' | null = null;
private resolve: ((code: string) => void) | null = null;
private reject: ((err: Error) => void) | null = null;
@@ -261,6 +292,16 @@ class CallbackListener {
}
private onRequest(req: IncomingMessage, res: ServerResponse): void {
+ const cors = xaiCallbackCorsHeaders(
+ typeof req.headers.origin === 'string' ? req.headers.origin : undefined,
+ );
+ // CORS/PNA preflight 必须 204 放行且不触碰登录流状态 —— 它没有 code 参数,
+ // 落进下方缺 code 分支会直接终止整个登录(issue #491 的卡死根因之一)。
+ if (req.method === 'OPTIONS') {
+ res.writeHead(204, cors);
+ res.end();
+ return;
+ }
const parsed = new URL(req.url || '', `http://127.0.0.1:${REDIRECT_PORT}`);
if (parsed.pathname !== '/callback') {
res.writeHead(404);
@@ -277,81 +318,133 @@ class CallbackListener {
const action = buildOAuthReturnAction(lang, 'xai-oauth', BRAND_NAME);
const code = parsed.searchParams.get('code') ?? undefined;
const state = parsed.searchParams.get('state') ?? undefined;
- if (!code) {
- res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' });
+ const oauthError =
+ parsed.searchParams.get('error_description') ?? parsed.searchParams.get('error') ?? undefined;
+ // state 是回调真实性的唯一凭证,最先校验。固定端口 + fetch 重试的新流程下,
+ // 上一次登录尝试的 consent 页 tab 可能仍在带旧 state 重试 —— 凡 state 不匹配
+ // 的请求(无论携带 code 还是 error、无论登录处于何种阶段)一律 400 拒绝:
+ // 不 settle 当前登录(旧 tab 一次滞留重试不能杀死新发起的登录)、不入 pending
+ // 挂起(否则不知道 state 的本机进程可在 exchange 窗口内囤积任意多连接)、
+ // 不吃成功重放(避免旧 tab 白显成功)。
+ if (state !== this.expectedState) {
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8', ...cors });
res.end(
renderOAuthResultPage({
htmlLang: OAUTH_RESULT_HTML_LANG[lang],
variant: 'error',
title: copy.errorTitle,
- body: copy.missingCodeBody,
- detail:
- parsed.searchParams.get('error_description') ??
- parsed.searchParams.get('error') ??
- undefined,
+ body: copy.invalidStateBody,
action,
}),
);
- this.reject?.(new Error('No authorization code received'));
return;
}
- if (state !== this.expectedState) {
- res.writeHead(400, { 'content-type': 'text/html; charset=utf-8' });
+ // 已有终态结果后网页侧可能重试 fetch(超时重发/用户手动访问)—— 不改写登录结果,
+ // 按状态机回执:成功 200 / 失败 400;exchange 未收口时挂起同候(与首个连接一起在
+ // succeed()/fail() 回执),不能提前发 200 —— exchange 随后失败会让页面白显成功。
+ // 能走到这里的都已通过 state 校验,pending 只会积累同一 consent 页的合法重试。
+ if (this.outcome !== null) {
+ if (this.outcome === 'exchanging') {
+ this.pending.push({ res, cors });
+ return;
+ }
+ const replayStatus = this.outcome === 'success' ? 200 : 400;
+ res.writeHead(replayStatus, { 'content-type': 'text/plain; charset=utf-8', ...cors });
+ res.end(this.outcome === 'success' ? 'OK' : 'login failed');
+ return;
+ }
+ if (!code) {
+ // 无 code 也无 error:健康检查、预取等杂请求,回 400 但保持登录流继续等待,
+ // 不能让任意本机请求终止一次进行中的登录。
+ if (!oauthError) {
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8', ...cors });
+ res.end(
+ renderOAuthResultPage({
+ htmlLang: OAUTH_RESULT_HTML_LANG[lang],
+ variant: 'error',
+ title: copy.errorTitle,
+ body: copy.missingCodeBody,
+ action,
+ }),
+ );
+ return;
+ }
+ // state 已匹配的 error 回调 = 当前这次授权被真实拒绝/失败,终止登录。
+ this.outcome = 'failed';
+ res.writeHead(400, { 'content-type': 'text/html; charset=utf-8', ...cors });
res.end(
renderOAuthResultPage({
htmlLang: OAUTH_RESULT_HTML_LANG[lang],
variant: 'error',
title: copy.errorTitle,
- body: copy.invalidStateBody,
+ body: copy.missingCodeBody,
+ detail: oauthError,
action,
}),
);
- this.reject?.(new Error('Invalid state parameter'));
+ this.reject?.(new Error('No authorization code received'));
return;
}
- this.pendingRes = res;
+ this.outcome = 'exchanging';
+ this.pending.push({ res, cors });
this.resolve?.(code);
}
succeed(): void {
- if (!this.pendingRes) return;
+ this.outcome = 'success';
+ const held = this.pending;
+ this.pending = [];
const copy = getProviderOAuthResultCopy(this.callbackLang, 'xAI', BRAND_NAME);
- this.pendingRes.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
- this.pendingRes.end(
- renderOAuthResultPage({
- htmlLang: OAUTH_RESULT_HTML_LANG[this.callbackLang],
- variant: 'success',
- title: copy.successTitle,
- body: copy.successBody,
- action: buildOAuthReturnAction(this.callbackLang, 'xai-oauth', BRAND_NAME),
- }),
- );
- this.pendingRes = null;
+ for (const { res, cors } of held) {
+ try {
+ // 回执必须带上对应请求的 CORS 头:没有它,consent 页的 fetch 读不到响应,
+ // 页面停在「等待检测」;302 导航场景 cors 为空对象,无影响。
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...cors });
+ res.end(
+ renderOAuthResultPage({
+ htmlLang: OAUTH_RESULT_HTML_LANG[this.callbackLang],
+ variant: 'success',
+ title: copy.successTitle,
+ body: copy.successBody,
+ action: buildOAuthReturnAction(this.callbackLang, 'xai-oauth', BRAND_NAME),
+ }),
+ );
+ } catch {
+ // 连接可能已被客户端中止(如用户在 exchange 期间关掉授权页)——凭证此刻
+ // 已成功落盘,单个回执通道抛错不得把成功登录翻转成失败(调用方在 catch
+ // 里会返回 ok:false),也不得影响其余挂起连接的回执。
+ }
+ }
}
fail(detail?: string): void {
- if (!this.pendingRes) return;
- try {
- const copy = getProviderOAuthResultCopy(this.callbackLang, 'xAI', BRAND_NAME);
- this.pendingRes.writeHead(500, { 'content-type': 'text/html; charset=utf-8' });
- this.pendingRes.end(
- renderOAuthResultPage({
- htmlLang: OAUTH_RESULT_HTML_LANG[this.callbackLang],
- variant: 'error',
- title: copy.errorTitle,
- body: copy.exchangeFailedBody,
- detail,
- action: buildOAuthReturnAction(this.callbackLang, 'xai-oauth', BRAND_NAME),
- }),
- );
- } catch {
- /* 回执通道已关闭,登录结果仍由调用链决定 */
+ // exchange 失败也是失败终态;code 尚未收到(pending 为空)时不改写 outcome,
+ // 留给 onRequest 的分支自行定性。
+ if (this.outcome === 'exchanging') this.outcome = 'failed';
+ const held = this.pending;
+ this.pending = [];
+ for (const { res, cors } of held) {
+ try {
+ const copy = getProviderOAuthResultCopy(this.callbackLang, 'xAI', BRAND_NAME);
+ res.writeHead(500, { 'content-type': 'text/html; charset=utf-8', ...cors });
+ res.end(
+ renderOAuthResultPage({
+ htmlLang: OAUTH_RESULT_HTML_LANG[this.callbackLang],
+ variant: 'error',
+ title: copy.errorTitle,
+ body: copy.exchangeFailedBody,
+ detail,
+ action: buildOAuthReturnAction(this.callbackLang, 'xai-oauth', BRAND_NAME),
+ }),
+ );
+ } catch {
+ /* 回执通道已关闭,登录结果仍由调用链决定 */
+ }
}
- this.pendingRes = null;
}
close(): void {
- if (this.pendingRes) {
+ if (this.pending.length > 0) {
this.fail();
}
try {