Skip to content

Commit 54893ca

Browse files
committed
fix(cursor): harden HTTP/1.1 failure handling
1 parent d4de195 commit 54893ca

4 files changed

Lines changed: 170 additions & 26 deletions

File tree

‎src/adapters/cursor/http1-bidi.ts‎

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { TranslatorBudget } from "../../lib/translator-budget";
33
import { CURSOR_MAX_EFFECTIVE_CONNECT_PAYLOAD_BYTES } from "../../lib/translator-budget";
44
import { readBoundedResponseBytes } from "../../lib/bounded-body";
55
import { withUpstreamHttpVersionValue } from "../../lib/upstream-http-version";
6+
import { isPreConnectReachabilityError } from "../../lib/upstream-reachability";
67
import { BidiRequestIdSchema } from "./gen/agent_pb";
78
import { consumeConnectFrames, encodeConnectFrame } from "./framing";
89

@@ -212,13 +213,23 @@ export class CursorHttp1BidiConnection {
212213
}
213214

214215
private requestUrl(path: string): string {
215-
return new URL(path, this.options.baseUrl).toString();
216+
const url = new URL(path, this.options.baseUrl);
217+
if (url.protocol !== "https:") {
218+
throw new Error("Cursor HTTP/1.1 transport requires an HTTPS base URL");
219+
}
220+
return url.toString();
216221
}
217222

218223
private http1Init(url: string, init: RequestInit): RequestInit {
219224
return withUpstreamHttpVersionValue(url, init, "http1.1") ?? init;
220225
}
221226

227+
private markCommitted(): void {
228+
if (this.committed) return;
229+
this.committed = true;
230+
this.options.callbacks.onCommitted();
231+
}
232+
222233
private async runSse(): Promise<void> {
223234
const url = this.requestUrl(CURSOR_RUN_SSE_PATH);
224235
const requestId = toBinary(BidiRequestIdSchema, create(BidiRequestIdSchema, {
@@ -270,22 +281,27 @@ export class CursorHttp1BidiConnection {
270281
pending.rawBytesCharged = false;
271282
this.options.translatorBudget.releaseRetained(pending.payload.byteLength, { kind: "request_copies" });
272283
}
273-
if (!this.committed) {
274-
this.committed = true;
275-
this.options.callbacks.onCommitted();
276-
}
277-
278-
const url = this.requestUrl(CURSOR_BIDI_APPEND_PATH);
279-
const timeout = AbortSignal.timeout(CURSOR_HTTP1_APPEND_TIMEOUT_MS);
280-
const signal = AbortSignal.any([this.abortController.signal, timeout]);
281284
try {
282-
const response = await this.fetchImpl(url, this.http1Init(url, {
283-
method: "POST",
284-
headers: this.commonHeaders("application/proto"),
285-
body: bunFetchBody(body),
286-
redirect: "manual",
287-
signal,
288-
}));
285+
const url = this.requestUrl(CURSOR_BIDI_APPEND_PATH);
286+
const timeout = AbortSignal.timeout(CURSOR_HTTP1_APPEND_TIMEOUT_MS);
287+
const signal = AbortSignal.any([this.abortController.signal, timeout]);
288+
let response: Response;
289+
try {
290+
response = await this.fetchImpl(url, this.http1Init(url, {
291+
method: "POST",
292+
headers: this.commonHeaders("application/proto"),
293+
body: bunFetchBody(body),
294+
redirect: "manual",
295+
signal,
296+
}));
297+
} catch (error) {
298+
// A proven DNS/TCP pre-connect failure means no append bytes reached Cursor and replay is
299+
// safe. Every ambiguous rejection stays conservative: the server may have accepted the
300+
// append before the response path failed, so suppress replay exactly as the h2 path does.
301+
if (!isPreConnectReachabilityError(error)) this.markCommitted();
302+
throw error;
303+
}
304+
this.markCommitted();
289305
if (response.status !== 200) {
290306
void response.body?.cancel().catch(() => undefined);
291307
throw cursorHttp1Error("BidiAppend", response.status);

‎src/adapters/cursor/live-models.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,16 @@ function decodeCursorUsableModels(bytes: Uint8Array): CursorUsableModelsResult {
9595
}
9696

9797
async function fetchCursorUsableModelsHttp1Once(opts: CursorUsableModelsOptions): Promise<CursorUsableModelsResult> {
98-
const baseUrl = (opts.baseUrl ?? "https://api2.cursor.sh").replace(/\/+$/, "");
99-
const requestUrl = `${baseUrl}${CURSOR_GET_USABLE_MODELS_PATH}`;
98+
let requestUrl: string;
99+
try {
100+
const parsed = new URL(CURSOR_GET_USABLE_MODELS_PATH, opts.baseUrl ?? "https://api2.cursor.sh");
101+
if (parsed.protocol !== "https:") {
102+
return { ok: false, error: "transport", detail: "Cursor HTTP/1.1 discovery requires HTTPS" };
103+
}
104+
requestUrl = parsed.toString();
105+
} catch {
106+
return { ok: false, error: "transport", detail: "Cursor HTTP/1.1 discovery base URL is invalid" };
107+
}
100108
const timeoutMs = opts.timeoutMs ?? 8000;
101109
const controller = new AbortController();
102110
let timedOut = false;

‎tests/cursor-hardening.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,24 @@ describe("Cursor live-model discovery hardening", () => {
101101
expect(new Headers(seenInit?.headers).get("authorization")).toBe("Bearer test-token");
102102
});
103103

104+
test("HTTP/1.1 discovery rejects cleartext before exposing the Bearer token", async () => {
105+
let fetchCalls = 0;
106+
const fetchImpl = (async () => {
107+
fetchCalls += 1;
108+
return new Response(new Uint8Array(), { status: 200 });
109+
}) as typeof fetch;
110+
111+
const result = await fetchCursorUsableModels({
112+
apiKey: "must-not-leave-process",
113+
baseUrl: "http://api2.cursor.sh",
114+
upstreamHttpVersion: "http1.1",
115+
fetch: fetchImpl,
116+
});
117+
118+
expect(result).toMatchObject({ ok: false, error: "transport", detail: expect.stringContaining("requires HTTPS") });
119+
expect(fetchCalls).toBe(0);
120+
});
121+
104122
test("Cursor catalog propagates the provider HTTP/1.1 pin to discovery", async () => {
105123
const providerName = "cursor-http1-discovery";
106124
const body = toBinary(GetUsableModelsResponseSchema, create(GetUsableModelsResponseSchema, {

‎tests/cursor-http1-transport.test.ts‎

Lines changed: 110 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,33 @@ function hexBytes(value: string): Uint8Array {
7575
Number.parseInt(value.slice(index * 2, index * 2 + 2), 16));
7676
}
7777

78+
function cursorProvider(
79+
fetchImpl: typeof fetch,
80+
baseUrl = "https://api2.cursor.sh",
81+
): OcxProviderConfig & { fetch: typeof fetch } {
82+
return {
83+
adapter: "cursor",
84+
baseUrl,
85+
apiKey: "test-token",
86+
upstreamHttpVersion: "http1.1",
87+
fetch: fetchImpl,
88+
};
89+
}
90+
91+
function heldRunSseResponse(signal: AbortSignal | null | undefined): Response {
92+
const body = new ReadableStream<Uint8Array>({
93+
start(controller) {
94+
const abort = () => controller.error(signal?.reason ?? new DOMException("aborted", "AbortError"));
95+
if (signal?.aborted) abort();
96+
else signal?.addEventListener("abort", abort, { once: true });
97+
},
98+
});
99+
return new Response(body, {
100+
status: 200,
101+
headers: { "content-type": "application/connect+proto" },
102+
});
103+
}
104+
78105
describe("Cursor HTTP/1.1 compatibility transport", () => {
79106
test("encodes the Cursor BidiAppend hex fallback wire shape", () => {
80107
const payload = Uint8Array.of(0xde, 0xad, 0xbe, 0xef);
@@ -126,15 +153,8 @@ describe("Cursor HTTP/1.1 compatibility transport", () => {
126153
throw new Error(`unexpected Cursor compatibility endpoint ${url.pathname}`);
127154
}) as typeof fetch;
128155

129-
const provider = {
130-
adapter: "cursor",
131-
baseUrl: "https://api2.cursor.sh",
132-
apiKey: "test-token",
133-
upstreamHttpVersion: "http1.1",
134-
fetch: fetchImpl,
135-
} as OcxProviderConfig & { fetch: typeof fetch };
136156
const transport = createLiveCursorTransport({
137-
provider,
157+
provider: cursorProvider(fetchImpl),
138158
translatorBudget: createTestTranslatorBudget(),
139159
firstFrameTimeoutMs: 2_000,
140160
});
@@ -166,6 +186,88 @@ describe("Cursor HTTP/1.1 compatibility transport", () => {
166186
expect(transport.requestCommitted?.()).toBe(true);
167187
});
168188

189+
test("keeps a proven pre-connect BidiAppend failure uncommitted", async () => {
190+
const fetchImpl = (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
191+
const url = new URL(String(input));
192+
if (url.pathname === "/agent.v1.AgentService/RunSSE") return heldRunSseResponse(init?.signal);
193+
throw Object.assign(new Error("fixture append connect failed"), { code: "ECONNREFUSED" });
194+
}) as typeof fetch;
195+
const transport = createLiveCursorTransport({
196+
provider: cursorProvider(fetchImpl),
197+
translatorBudget: createTestTranslatorBudget(),
198+
firstFrameTimeoutMs: 2_000,
199+
});
200+
201+
try {
202+
await expect((async () => {
203+
for await (const _message of transport.run({
204+
modelId: "claude-opus-5",
205+
conversationId: "cursor_http1_preconnect_failure",
206+
system: [],
207+
messages: [{ role: "user", content: "hello" }],
208+
})) { /* drain */ }
209+
})()).rejects.toThrow("fixture append connect failed");
210+
expect(transport.requestCommitted?.()).toBe(false);
211+
} finally {
212+
await transport.close?.();
213+
}
214+
});
215+
216+
test("keeps ambiguous BidiAppend failures committed to prevent replay", async () => {
217+
const fetchImpl = (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
218+
const url = new URL(String(input));
219+
if (url.pathname === "/agent.v1.AgentService/RunSSE") return heldRunSseResponse(init?.signal);
220+
throw new Error("fixture ambiguous append failure");
221+
}) as typeof fetch;
222+
const transport = createLiveCursorTransport({
223+
provider: cursorProvider(fetchImpl),
224+
translatorBudget: createTestTranslatorBudget(),
225+
firstFrameTimeoutMs: 2_000,
226+
});
227+
228+
try {
229+
await expect((async () => {
230+
for await (const _message of transport.run({
231+
modelId: "claude-opus-5",
232+
conversationId: "cursor_http1_ambiguous_failure",
233+
system: [],
234+
messages: [{ role: "user", content: "hello" }],
235+
})) { /* drain */ }
236+
})()).rejects.toThrow("fixture ambiguous append failure");
237+
expect(transport.requestCommitted?.()).toBe(true);
238+
} finally {
239+
await transport.close?.();
240+
}
241+
});
242+
243+
test("rejects a cleartext HTTP/1.1 transport before invoking fetch", async () => {
244+
let fetchCalls = 0;
245+
const fetchImpl = (async () => {
246+
fetchCalls += 1;
247+
throw new Error("fetch must not run");
248+
}) as typeof fetch;
249+
const transport = createLiveCursorTransport({
250+
provider: cursorProvider(fetchImpl, "http://api2.cursor.sh"),
251+
translatorBudget: createTestTranslatorBudget(),
252+
firstFrameTimeoutMs: 2_000,
253+
});
254+
255+
try {
256+
await expect((async () => {
257+
for await (const _message of transport.run({
258+
modelId: "claude-opus-5",
259+
conversationId: "cursor_http1_cleartext",
260+
system: [],
261+
messages: [{ role: "user", content: "hello" }],
262+
})) { /* drain */ }
263+
})()).rejects.toThrow("requires an HTTPS base URL");
264+
expect(fetchCalls).toBe(0);
265+
expect(transport.requestCommitted?.()).toBe(false);
266+
} finally {
267+
await transport.close?.();
268+
}
269+
});
270+
169271
test("preserves the proto3 zero and later append sequence values", () => {
170272
const payload = Uint8Array.of(1, 2, 3);
171273
expect(decodeAppend(encodeCursorBidiAppendRequest(payload, "req", 0n)).appendSeqno).toBe(0n);

0 commit comments

Comments
 (0)