fix(qoder): address review findings

Correctness:
- testUtils: drop checkExpiry so the userinfo URL probe actually runs (revoked
  tokens used to look "active" until local 30-day expiry passed)
- auth.parseExpiry: handle numeric expiresAt, swap parseInt before Date.parse
  so "2026" doesn't get interpreted as year-2026, treat expires_in:0 as
  already-expired instead of fabricating a 30-day default
- providers.mapTokens: synthesize email from userId when fetchUserInfo fails
  so OAuth dedup works (re-logins no longer accumulate "Account N" rows)

SSE wrapper:
- wrapQoderSSE: add !doneEmitted guard on success branch (chunks could leak
  past [DONE] when an error envelope shared a TCP packet with a valid one)
- flush(): finalize TextDecoder + drain trailing buffer so the chunk carrying
  finish_reason is delivered when upstream closes without a final \n
- sanitize literal \n inside inner OpenAI body so SSE framing stays intact

Robustness:
- executor: wrap buildCosyHeaders in try/catch so a missing accessToken
  returns 401 (re-auth) instead of bubbling as 500
- executor: short-circuit on missing accessToken before signing
- executor: plumb proxyOptions/signal through buildQoderRequestBody so
  proxy-only networks can fetch the model_config catalog
- qoderModels: dedupe concurrent first-time misses with an in-flight Promise
  map (parallel chat windows now do 1 upstream fetch instead of N)
- qoderModels: check signal.aborted before addEventListener so a pre-aborted
  parent signal cancels the inner fetch immediately
- auth: AbortController + 15s timeout on pollDeviceToken / fetchUserInfo to
  prevent hung sockets when openapi.qoder.sh stalls mid-response

UX:
- OAuthModal: derive polling deadline from device-code expires_in (qoder
  publishes 300s; the previous fixed 120s caused timeouts when users took
  more than 2 minutes on the consent page)

Cleanup:
- delete src/lib/oauth/services/qoder.js — referenced removed config fields
  (clientId/clientSecret/tokenUrl/authorizeUrl) and was re-exported from
  services/index.js, so any future caller would TypeError on first use
This commit is contained in:
Simon Shi
2026-05-29 17:36:27 +07:00
committed by decolua
parent a6fd84691b
commit 620b59ca0b
8 changed files with 219 additions and 318 deletions
+8 -2
View File
@@ -671,8 +671,14 @@ const PROVIDERS = {
};
},
mapTokens: (tokens) => {
const email = (tokens._qoderEmail || "").trim() || null;
const rawEmail = (tokens._qoderEmail || "").trim();
const displayName = (tokens._qoderName || "").trim() || null;
const userId = tokens._qoderUserId || "";
// Dedup in createProviderConnection requires a non-empty email. When
// fetchUserInfo silently fails (returns ""), fall back to a stable
// synthetic identifier derived from userId so re-logins update the
// existing row instead of accumulating "Account N" duplicates.
const email = rawEmail || (userId ? `qoder-user-${userId}` : null);
return {
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token || null,
@@ -681,7 +687,7 @@ const PROVIDERS = {
displayName,
providerSpecificData: {
authMethod: "device",
userId: tokens._qoderUserId || "",
userId,
machineId: tokens._qoderMachineId || "",
organizationId: tokens._qoderOrganizationId || "",
},
-1
View File
@@ -8,7 +8,6 @@ export { CodexService } from "./codex.js";
export { GeminiCLIService } from "./gemini.js";
export { QwenService } from "./qwen.js";
export { IFlowService } from "./iflow.js";
export { QoderService } from "./qoder.js";
export { AntigravityService } from "./antigravity.js";
export { OpenAIService } from "./openai.js";
export { GitHubService } from "./github.js";
-232
View File
@@ -1,232 +0,0 @@
import crypto from "crypto";
import open from "open";
import { QODER_CONFIG } from "../constants/oauth.js";
import { getServerCredentials } from "../config/index.js";
import { startLocalServer } from "../utils/server.js";
import { spinner as createSpinner } from "../utils/ui.js";
/**
* Qoder OAuth Service
* Uses Authorization Code flow with Basic Auth
*/
export class QoderService {
constructor() {
this.config = QODER_CONFIG;
}
/**
* Build Qoder authorization URL
*/
buildAuthUrl(redirectUri, state) {
const params = new URLSearchParams({
client_id: this.config.clientId,
response_type: "code",
redirect_uri: redirectUri,
state: state,
});
return `${this.config.authorizeUrl}?${params.toString()}`;
}
/**
* Exchange authorization code for tokens
*/
async exchangeCode(code, redirectUri) {
const basicAuth = Buffer.from(
`${this.config.clientId}:${this.config.clientSecret}`
).toString("base64");
const response = await fetch(this.config.tokenUrl, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
Authorization: `Basic ${basicAuth}`,
},
body: new URLSearchParams({
grant_type: "authorization_code",
code: code,
redirect_uri: redirectUri,
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Token exchange failed: ${error}`);
}
return await response.json();
}
/**
* Refresh access token using refresh token
*/
async refreshToken(refreshToken) {
const basicAuth = Buffer.from(
`${this.config.clientId}:${this.config.clientSecret}`
).toString("base64");
const response = await fetch(this.config.tokenUrl, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
Authorization: `Basic ${basicAuth}`,
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Token refresh failed: ${error}`);
}
return await response.json();
}
/**
* Get user info from Qoder
*/
async getUserInfo(accessToken) {
const response = await fetch(
`${this.config.userInfoUrl}?accessToken=${encodeURIComponent(accessToken)}`,
{ headers: { Accept: "application/json" } }
);
if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to get user info: ${error}`);
}
const result = await response.json();
if (!result.success) {
throw new Error("Failed to get user info");
}
return result.data;
}
/**
* Save Qoder tokens to server
*/
async saveTokens(tokens, userInfo) {
const { server, token, userId } = getServerCredentials();
const response = await fetch(`${server}/api/cli/providers/qoder`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"X-User-Id": userId,
},
body: JSON.stringify({
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
expiresIn: tokens.expires_in,
apiKey: userInfo.apiKey,
email: userInfo.email || userInfo.phone,
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || "Failed to save tokens");
}
return await response.json();
}
/**
* Refresh and update tokens on server
*/
async refreshAndSave(existingRefreshToken) {
const spinner = createSpinner("Refreshing Qoder token...").start();
try {
const tokens = await this.refreshToken(existingRefreshToken);
const userInfo = await this.getUserInfo(tokens.access_token);
await this.saveTokens(tokens, userInfo);
spinner.succeed("Qoder token refreshed successfully");
return tokens;
} catch (error) {
spinner.fail(`Token refresh failed: ${error.message}`);
throw error;
}
}
/**
* Complete Qoder OAuth flow
*/
async connect() {
const spinner = createSpinner("Starting Qoder OAuth...").start();
try {
spinner.text = "Starting local server...";
let callbackParams = null;
const { port, close } = await startLocalServer((params) => {
callbackParams = params;
});
const redirectUri = `http://localhost:${port}/callback`;
spinner.succeed(`Local server started on port ${port}`);
const state = crypto.randomBytes(32).toString("base64url");
const authUrl = this.buildAuthUrl(redirectUri, state);
console.log("\nOpening browser for Qoder authentication...");
console.log(`If browser doesn't open, visit:\n${authUrl}\n`);
await open(authUrl);
spinner.start("Waiting for Qoder authorization...");
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error("Authentication timeout (5 minutes)"));
}, 300000);
const checkInterval = setInterval(() => {
if (callbackParams) {
clearInterval(checkInterval);
clearTimeout(timeout);
resolve();
}
}, 100);
});
close();
if (callbackParams.error) {
throw new Error(callbackParams.error_description || callbackParams.error);
}
if (!callbackParams.code) {
throw new Error("No authorization code received");
}
spinner.start("Exchanging code for tokens...");
const tokens = await this.exchangeCode(callbackParams.code, redirectUri);
spinner.text = "Fetching user info...";
const userInfo = await this.getUserInfo(tokens.access_token);
spinner.text = "Saving tokens to server...";
await this.saveTokens(tokens, userInfo);
spinner.succeed(`Qoder connected successfully! (${userInfo.email || userInfo.phone})`);
return true;
} catch (error) {
spinner.fail(`Failed: ${error.message}`);
throw error;
}
}
}
+45 -7
View File
@@ -63,6 +63,26 @@ export function initiateDeviceFlow() {
};
}
// Timeout for OAuth helper calls. The OAuth modal polls every 2s for up to
// 5 minutes; an individual request that stalls beyond this is treated as a
// failed poll attempt and the next poll iteration retries.
const FETCH_TIMEOUT_MS = 15_000;
/**
* Wrap fetch with an AbortController-based timeout. Without this, a stalled
* upstream socket hangs on Node's default keepalive timeout (minutes) and
* abandoned polls accumulate hung sockets.
*/
async function fetchWithTimeout(url, init = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort("timeout"), FETCH_TIMEOUT_MS);
try {
return await fetch(url, { ...init, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
/**
* Single poll attempt. Returns one of:
* { status: "pending" } — keep polling
@@ -77,7 +97,7 @@ export async function pollDeviceToken({ nonce, codeVerifier }) {
}
const url = `${QODER_DEVICE_TOKEN_URL}?nonce=${encodeURIComponent(nonce)}&verifier=${encodeURIComponent(codeVerifier)}&challenge_method=S256`;
const response = await fetch(url, {
const response = await fetchWithTimeout(url, {
method: "GET",
headers: {
Accept: "application/json",
@@ -132,7 +152,7 @@ export async function pollDeviceToken({ nonce, codeVerifier }) {
*/
export async function fetchUserInfo(accessToken) {
try {
const response = await fetch(QODER_USERINFO_URL, {
const response = await fetchWithTimeout(QODER_USERINFO_URL, {
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
@@ -154,18 +174,36 @@ export async function fetchUserInfo(accessToken) {
/**
* Convert the upstream's expiry hint into a Unix-millisecond timestamp.
* Accepts RFC3339 strings, ms-epoch integer strings, or seconds-from-now
* (`expires_in`). Falls back to "now + 30 days" when both are missing.
* Accepts:
* - numeric (ms-epoch): returned as-is
* - numeric string of ms-epoch: e.g. "1781594470000"
* - RFC3339 string: e.g. "2026-06-16T07:15:04Z"
* - seconds-from-now via expiresInSeconds (>= 0)
* Falls back to "now + 30 days" when both are missing.
*
* Order matters: try numeric (string or number) before Date.parse, since
* Date.parse accepts short numeric strings like "2026" as years and would
* otherwise return a misleading year-2026 timestamp instead of falling
* through to the integer branch.
*/
function parseExpiry(expiresAt, expiresInSeconds) {
if (typeof expiresAt === "number" && Number.isFinite(expiresAt) && expiresAt > 0) {
return expiresAt;
}
const trimmed = typeof expiresAt === "string" ? expiresAt.trim() : "";
if (trimmed) {
// Pure numeric string → ms-epoch (don't let Date.parse swallow short
// numerics as years).
if (/^\d+$/.test(trimmed)) {
const ms = Number.parseInt(trimmed, 10);
if (Number.isFinite(ms) && ms > 0) return ms;
}
const parsed = Date.parse(trimmed);
if (!Number.isNaN(parsed)) return parsed;
const ms = Number.parseInt(trimmed, 10);
if (!Number.isNaN(ms) && ms > 0) return ms;
}
if (typeof expiresInSeconds === "number" && expiresInSeconds > 0) {
// expiresInSeconds === 0 means "already expired"; honor that by returning
// the current time rather than fabricating a 30-day default.
if (typeof expiresInSeconds === "number" && Number.isFinite(expiresInSeconds) && expiresInSeconds >= 0) {
return Date.now() + expiresInSeconds * 1000;
}
return Date.now() + 30 * 24 * 60 * 60 * 1000;