fix(cursor): resolve review feedback and harden edge cases

This commit is contained in:
Tam Nhu Tran committed 2026-02-17 16:33:21 +07:00
1 parent c639cefa7b
commit 4798741a99
13 files changed
+746 -114

No files matched your search

+13 -1
View File
@@ -21,12 +21,24 @@ import * as os from 'os';
import type { CursorCredentials, CursorAuthStatus, AutoDetectResult } from './types';
import { getCcsDir } from '../utils/config-manager';
/**
* Resolve home directory from environment first for deterministic testability,
* then fall back to os.homedir() when env vars are unavailable.
*/
function resolveHomeDir(): string {
if (process.platform === 'win32') {
return process.env.USERPROFILE || process.env.HOME || os.homedir();
}
return process.env.HOME || os.homedir();
}
/**
* Get platform-specific path to Cursor's state.vscdb
*/
export function getTokenStoragePath(): string {
const platform = process.platform;
const home = os.homedir();
const home = resolveHomeDir();
if (platform === 'win32') {
const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
+9 -4
View File
@@ -5,7 +5,7 @@
*/
import * as crypto from 'crypto';
import type { CursorCredentials } from './cursor-protobuf-schema';
import type { CursorApiCredentials } from './cursor-protobuf-schema';
export const CURSOR_CLIENT_VERSION = '2.3.41';
export const CURSOR_USER_AGENT = 'connect-es/1.6.1';
@@ -33,6 +33,7 @@ export function generateCursorChecksum(machineId: string, nowMs: number = Date.n
throw new Error('Machine ID is required for Cursor API');
}
// Convert milliseconds to coarse ~1000-second units required by Cursor's checksum routine.
const timestamp = Math.floor(nowMs / 1000000);
// JS bitwise shifts wrap modulo 32, so >>40 and >>32 give wrong results.
// Use Math.trunc division for upper bytes that exceed 32-bit range.
@@ -73,7 +74,7 @@ export function generateCursorChecksum(machineId: string, nowMs: number = Date.n
return `${encoded}${machineId}`;
}
function buildCursorBaseHeaders(credentials: CursorCredentials): Record<string, string> {
function buildCursorBaseHeaders(credentials: CursorApiCredentials): Record<string, string> {
const cleanToken = normalizeCursorAccessToken(credentials.accessToken);
if (!cleanToken) {
@@ -105,7 +106,9 @@ function buildCursorBaseHeaders(credentials: CursorCredentials): Record<string,
};
}
export function buildCursorConnectHeaders(credentials: CursorCredentials): Record<string, string> {
export function buildCursorConnectHeaders(
credentials: CursorApiCredentials
): Record<string, string> {
return {
...buildCursorBaseHeaders(credentials),
'connect-accept-encoding': 'gzip',
@@ -115,7 +118,9 @@ export function buildCursorConnectHeaders(credentials: CursorCredentials): Recor
};
}
export function buildCursorModelsHeaders(credentials: CursorCredentials): Record<string, string> {
export function buildCursorModelsHeaders(
credentials: CursorApiCredentials
): Record<string, string> {
return {
...buildCursorBaseHeaders(credentials),
accept: 'application/json',
+31 -10
View File
@@ -59,12 +59,26 @@ function readJsonBody(req: http.IncomingMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
let settled = false;
const resolveOnce = (payload: unknown) => {
if (settled) return;
settled = true;
resolve(payload);
};
const rejectOnce = (error: Error) => {
if (settled) return;
settled = true;
reject(error);
};
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > MAX_BODY_SIZE) {
req.destroy();
reject(new Error('Request body too large (max 10MB)'));
// Stop processing body, but avoid force-closing socket so caller can return 413 cleanly.
req.pause();
rejectOnce(new Error('Request body too large (max 10MB)'));
return;
}
chunks.push(chunk);
@@ -73,17 +87,19 @@ function readJsonBody(req: http.IncomingMessage): Promise<unknown> {
req.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8').trim();
if (!raw) {
resolve({});
resolveOnce({});
return;
}
try {
resolve(JSON.parse(raw));
resolveOnce(JSON.parse(raw));
} catch {
reject(new Error('Invalid JSON in request body'));
rejectOnce(new Error('Invalid JSON in request body'));
}
});
req.on('error', reject);
req.on('error', (error) => {
rejectOnce(error instanceof Error ? error : new Error(String(error)));
});
});
}
@@ -241,11 +257,15 @@ export function startCursorDaemonServer(options: DaemonRuntimeOptions): http.Ser
}
const abortController = new AbortController();
req.on('close', () => {
if (!res.writableEnded) {
const abortOnDisconnect = () => {
if (!abortController.signal.aborted && !res.writableEnded) {
abortController.abort();
}
});
};
req.on('aborted', abortOnDisconnect);
req.on('close', abortOnDisconnect);
res.on('close', abortOnDisconnect);
const result = await executor.execute({
model,
@@ -269,7 +289,8 @@ export function startCursorDaemonServer(options: DaemonRuntimeOptions): http.Ser
await pipeWebResponseToNode(result.response, res);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
writeJson(res, 400, {
const isPayloadTooLarge = message.includes('Request body too large');
writeJson(res, isPayloadTooLarge ? 413 : 400, {
error: {
type: 'invalid_request_error',
message,
+26 -10
View File
@@ -6,7 +6,7 @@
import type { IncomingHttpHeaders } from 'http';
import { generateCursorBody, extractTextFromResponse } from './cursor-protobuf.js';
import { buildCursorRequest } from './cursor-translator.js';
import type { CursorTool, CursorCredentials } from './cursor-protobuf-schema.js';
import type { CursorTool, CursorApiCredentials } from './cursor-protobuf-schema.js';
import { buildCursorConnectHeaders, generateCursorChecksum } from './cursor-client-policy.js';
import { StreamingFrameParser, decompressPayload } from './cursor-stream-parser.js';
@@ -30,7 +30,7 @@ interface ExecutorParams {
reasoning_effort?: string;
};
stream: boolean;
credentials: CursorCredentials;
credentials: CursorApiCredentials;
signal?: AbortSignal;
}
@@ -104,7 +104,7 @@ export class CursorExecutor {
return generateCursorChecksum(machineId);
}
buildHeaders(credentials: CursorCredentials): Record<string, string> {
buildHeaders(credentials: CursorApiCredentials): Record<string, string> {
return buildCursorConnectHeaders(credentials);
}
@@ -112,7 +112,7 @@ export class CursorExecutor {
model: string,
body: ExecutorParams['body'],
stream: boolean,
credentials: CursorCredentials
credentials: CursorApiCredentials
): Uint8Array {
const translatedBody = buildCursorRequest(model, body, stream, credentials);
const messages = translatedBody.messages || [];
@@ -320,12 +320,24 @@ export class CursorExecutor {
const created = Math.floor(Date.now() / 1000);
return new Promise((resolve, reject) => {
let settled = false;
const resolveOnce = (response: Response) => {
if (settled) return;
settled = true;
resolve(response);
};
const rejectOnce = (error: Error) => {
if (settled) return;
settled = true;
reject(error);
};
const urlObj = new URL(url);
const client = http2.connect(`https://${urlObj.host}`);
client.on('error', (err) => {
client.close();
reject(err);
rejectOnce(err instanceof Error ? err : new Error(String(err)));
});
const req = client.request({
@@ -342,7 +354,8 @@ export class CursorExecutor {
if (signal) {
const onAbort = () => {
streamClosed = true;
// Close the ReadableStream controller so consumers don't hang on reader.read()
// If stream already started, close readable to unblock consumers.
if (streamController) {
try {
streamController.close();
@@ -350,9 +363,12 @@ export class CursorExecutor {
/* already closed */
}
}
req.close();
client.close();
rejectOnce(new Error('Request aborted'));
};
signal.addEventListener('abort', onAbort, { once: true });
const cleanup = () => signal.removeEventListener('abort', onAbort);
req.on('end', cleanup);
@@ -368,12 +384,12 @@ export class CursorExecutor {
req.on('end', () => {
client.close();
const errorText = Buffer.concat(errorChunks).toString();
resolve(
resolveOnce(
new Response(
JSON.stringify({
error: {
message: `[${status}]: ${errorText}`,
type: 'invalid_request_error',
type: status === 429 ? 'rate_limit_error' : 'invalid_request_error',
code: '',
},
}),
@@ -561,7 +577,7 @@ export class CursorExecutor {
},
});
resolve(
resolveOnce(
new Response(readable, {
status: 200,
headers: {
@@ -575,7 +591,7 @@ export class CursorExecutor {
req.on('error', (err) => {
client.close();
reject(err);
rejectOnce(err instanceof Error ? err : new Error(String(err)));
});
req.write(body);
+43 -15
View File
@@ -6,7 +6,7 @@
import * as http from 'http';
import type { CursorModel } from './types';
import type { CursorCredentials } from './cursor-protobuf-schema';
import type { CursorApiCredentials } from './cursor-protobuf-schema';
import { isDaemonRunning } from './cursor-daemon';
import { buildCursorModelsHeaders } from './cursor-client-policy';
import {
@@ -34,6 +34,15 @@ interface CursorModelsApiResponse {
models?: Array<{ id?: unknown; name?: unknown; provider?: unknown }>;
}
function debugLog(message: string, error?: unknown): void {
if (!process.env.CCS_DEBUG) return;
if (error) {
console.error(`[cursor] ${message}`, error);
return;
}
console.error(`[cursor] ${message}`);
}
function normalizeModelRecords(
records: Array<{ id?: unknown; name?: unknown; provider?: unknown }>
): CursorModel[] {
@@ -93,7 +102,7 @@ export function clearCursorModelsCache(): void {
}
export async function fetchModelsFromCursorApi(
credentials: CursorCredentials,
credentials: CursorApiCredentials,
options: {
endpoint?: string;
timeoutMs?: number;
@@ -116,12 +125,21 @@ export async function fetchModelsFromCursorApi(
});
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
clearCursorModelsCache();
}
debugLog(`Cursor models API returned ${response.status} (${endpoint})`);
return null;
}
const payload = (await response.json()) as unknown;
return parseApiModelsResponse(payload);
} catch {
const parsed = parseApiModelsResponse(payload);
if (!parsed) {
debugLog(`Cursor models API payload shape invalid (${endpoint})`);
}
return parsed;
} catch (error) {
debugLog(`Cursor models API fetch failed (${endpoint})`, error);
return null;
} finally {
clearTimeout(timeout);
@@ -130,7 +148,7 @@ export async function fetchModelsFromCursorApi(
export async function getModelsForDaemon(
options: {
credentials?: CursorCredentials | null;
credentials?: CursorApiCredentials | null;
endpoint?: string;
timeoutMs?: number;
} = {}
@@ -186,6 +204,7 @@ export async function fetchModelsFromDaemon(port: number): Promise<CursorModel[]
res.on('data', (chunk) => {
data += chunk;
if (data.length > MAX_BODY_SIZE) {
debugLog('Cursor daemon /v1/models body exceeded 1MB; falling back to defaults');
req.destroy();
safeResolve(DEFAULT_CURSOR_MODELS);
}
@@ -193,30 +212,39 @@ export async function fetchModelsFromDaemon(port: number): Promise<CursorModel[]
res.on('end', () => {
try {
const response = JSON.parse(data) as { data?: Array<{ id: string }> };
if (response.data && Array.isArray(response.data)) {
const models: CursorModel[] = response.data.map((m) => ({
id: m.id,
name: formatModelName(m.id),
provider: detectProvider(m.id),
isDefault: m.id === DEFAULT_CURSOR_MODEL,
}));
const response = JSON.parse(data) as { data?: Array<{ id?: unknown }> };
if (Array.isArray(response.data)) {
const models: CursorModel[] = response.data
.filter((m) => m && typeof m.id === 'string' && m.id.length > 0)
.map((m) => ({
id: m.id as string,
name: formatModelName(m.id as string),
provider: detectProvider(m.id as string),
isDefault: m.id === DEFAULT_CURSOR_MODEL,
}));
safeResolve(models.length > 0 ? models : DEFAULT_CURSOR_MODELS);
} else {
debugLog('Cursor daemon /v1/models payload missing data[]; falling back to defaults');
safeResolve(DEFAULT_CURSOR_MODELS);
}
} catch {
} catch (error) {
debugLog(
'Cursor daemon /v1/models returned invalid JSON; falling back to defaults',
error
);
safeResolve(DEFAULT_CURSOR_MODELS);
}
});
}
);
req.on('error', () => {
req.on('error', (error) => {
debugLog('Cursor daemon /v1/models request failed; falling back to defaults', error);
safeResolve(DEFAULT_CURSOR_MODELS);
});
req.on('timeout', () => {
debugLog('Cursor daemon /v1/models request timed out; falling back to defaults');
req.destroy();
safeResolve(DEFAULT_CURSOR_MODELS);
});
+5 -1
View File
@@ -326,11 +326,15 @@ export function extractTextFromResponse(payload: Uint8Array): {
}
}
if (payload.length > 0) {
return { text: null, error: 'Malformed protobuf response', toolCall: null, thinking: null };
}
return { text: null, error: null, toolCall: null, thinking: null };
} catch (err) {
if (process.env.CCS_DEBUG) {
console.error('[cursor] extractTextFromResponse parsing failed:', err);
}
return { text: null, error: null, toolCall: null, thinking: null };
return { text: null, error: 'Malformed protobuf response', toolCall: null, thinking: null };
}
}
+1 -1
View File
@@ -135,7 +135,7 @@ export type UnifiedModeType = (typeof UNIFIED_MODE)[keyof typeof UNIFIED_MODE];
export type ThinkingLevelType = (typeof THINKING_LEVEL)[keyof typeof THINKING_LEVEL];
/** Cursor credentials structure */
export interface CursorCredentials {
export interface CursorApiCredentials {
accessToken: string;
machineId: string;
ghostMode?: boolean;