Files
OmniRoute/tests/unit/cursor-version-detector.test.mjs
payne 0594af6a6c feat(cursor): vision (image_url) input + tool-commit/output-constraint enhancements (#3104)
* feat(cursor): vision (image_url) input + tool-commit/output-constraint enhancements

Add image/vision input to the Cursor provider's agent.v1 endpoint, plus the
supporting prompt-engineering and resilience work developed alongside it.

Vision input
- Decode OpenAI `image_url` parts (base64 `data:` URIs and remote `http(s)` URLs)
  and inline them as `SelectedContext.selected_images[]` — field numbers pinned
  from the cursor-agent agent.v1 protobuf descriptor (SelectedImage.data oneof,
  uuid, optional Dimension, mime_type). Cross-checked against composer-api's shape.
- New `resolveCursorImages` helper: SSRF-guarded remote fetches via the repo's
  canonical `parseAndValidatePublicUrl` (always public-only for client URLs),
  <=1 MiB per image (pre-decode + streaming cap), `image/*` enforced, max 12
  images, sanitized `CursorImageError` (no stack/path leakage).
- `openai-to-cursor` translator now preserves `image_url` parts instead of
  dropping them; executor `buildRequest` resolves images and attaches them to
  the user turn. The no-image path is byte-identical to before (test-asserted).

Supporting cursor enhancements
- Tool-commit directive (raises composer-2.5 tool-call rate ~53% -> ~88%),
  `tool_choice` none/required/specific handling, and output constraints
  (`response_format` / `max_tokens` / `stop` surfaced as prompt instructions).
- `cursorSessionManager`: clear pending tool-call mappings on session close.
- `cursorVersionDetector`: export `FALLBACK_VERSION` as a single source of truth.

Tests & docs
- New unit suite for the image encoder + resolver (field layout, byte-identical
  no-image path, SSRF / oversize / bad-base64 / too-many rejections, sanitized
  error body), translator image-preservation tests, and live e2e tests
  (base64 + remote URL, gated on `CURSOR_E2E_TOKEN`).
- Documented `CURSOR_TOOL_DIRECTIVE` and `CURSOR_IMAGE_FETCH_TIMEOUT_MS` in
  `.env.example` and `docs/reference/ENVIRONMENT.md`.

* fix(cursor): address review — redirect SSRF, large-payload guard, stream OOM, case/NaN nits

Resolves the gemini-code-assist review on #3104:
- SSRF via redirect (critical): fetchImageBytes now uses redirect:"manual" and
  re-validates every hop through parseAndValidatePublicUrl, so a public URL can't
  30x-redirect to a private/link-local address. Bounded to 3 redirects.
- Large data URL (high): reject on raw payload length before the whitespace-strip
  regex, so an oversized data URL can't burn CPU.
- Stream read (high): readCapped consumes the body as an async iterable (Node
  Readable + Web Streams) or via getReader, capping mid-read; uncapped
  arrayBuffer() is only a last resort.
- data: scheme (medium): match case-insensitively (RFC 2397) while preserving the
  original payload.
- NaN timeouts (medium): CURSOR_IMAGE_FETCH_TIMEOUT_MS and CURSOR_STREAM_TIMEOUT_MS
  fall back to defaults when the env value isn't a positive integer.

Adds tests: redirect-to-private blocked, redirect-to-public followed, too-many-
redirects rejected, uppercase DATA: accepted.

* fix(cursor): defend image fetch against DNS-rebinding SSRF

Address the @codex review on #3104: parseAndValidatePublicUrl only checks the
hostname string, so a public-looking host that (re)resolves to a private /
link-local / metadata IP would still be fetched. Each hop now resolves the host
via dns.lookup({all:true}) and rejects if ANY answer is private (isPrivateHost),
before connecting. IP literals are skipped (already validated by the URL guard).

This narrows but doesn't fully close the TOCTOU window vs fetch's own
resolution; a connection-time IP filter on the shared outbound guard would
close it for every caller. Adds unit tests for the IP gate and a mocked
DNS-rebinding case (public host -> 127.0.0.1, fetch never reached).
2026-06-03 18:24:41 -03:00

122 lines
4.1 KiB
JavaScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const Database = (await import("better-sqlite3")).default;
const { getCursorVersion, resetCursorVersionCache, FALLBACK_VERSION } =
await import("../../open-sse/utils/cursorVersionDetector.ts");
function createStateDb(dir, version) {
const dbPath = path.join(dir, "state.vscdb");
const db = new Database(dbPath);
db.exec("CREATE TABLE itemTable (key TEXT PRIMARY KEY, value TEXT)");
if (version) {
db.prepare("INSERT INTO itemTable (key, value) VALUES (?, ?)").run(
"cursorupdate.lastUpdatedAndShown.version",
version
);
}
db.close();
return dbPath;
}
test("getCursorVersion reads version from state.vscdb", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-ver-"));
const dbPath = createStateDb(tmpDir, "99.0.1");
const origEnv = process.env.CURSOR_STATE_DB_PATH;
process.env.CURSOR_STATE_DB_PATH = dbPath;
try {
resetCursorVersionCache();
assert.equal(getCursorVersion(), "99.0.1");
} finally {
if (origEnv === undefined) delete process.env.CURSOR_STATE_DB_PATH;
else process.env.CURSOR_STATE_DB_PATH = origEnv;
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test("getCursorVersion returns fallback when DB does not exist", () => {
const origEnv = process.env.CURSOR_STATE_DB_PATH;
process.env.CURSOR_STATE_DB_PATH = "/nonexistent/path/state.vscdb";
try {
resetCursorVersionCache();
assert.equal(getCursorVersion(), FALLBACK_VERSION);
} finally {
if (origEnv === undefined) delete process.env.CURSOR_STATE_DB_PATH;
else process.env.CURSOR_STATE_DB_PATH = origEnv;
}
});
test("getCursorVersion returns fallback when DB has no version key", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-ver-nokey-"));
const dbPath = createStateDb(tmpDir, null);
const origEnv = process.env.CURSOR_STATE_DB_PATH;
process.env.CURSOR_STATE_DB_PATH = dbPath;
try {
resetCursorVersionCache();
assert.equal(getCursorVersion(), FALLBACK_VERSION);
} finally {
if (origEnv === undefined) delete process.env.CURSOR_STATE_DB_PATH;
else process.env.CURSOR_STATE_DB_PATH = origEnv;
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test("getCursorVersion caches the result across calls", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-ver-cache-"));
const dbPath = createStateDb(tmpDir, "10.0.0");
const origEnv = process.env.CURSOR_STATE_DB_PATH;
process.env.CURSOR_STATE_DB_PATH = dbPath;
try {
resetCursorVersionCache();
assert.equal(getCursorVersion(), "10.0.0");
// Update the DB — cache should still return old value
const db = new Database(dbPath);
db.prepare("UPDATE itemTable SET value = ? WHERE key = ?").run(
"20.0.0",
"cursorupdate.lastUpdatedAndShown.version"
);
db.close();
assert.equal(getCursorVersion(), "10.0.0", "cached value should be returned");
} finally {
if (origEnv === undefined) delete process.env.CURSOR_STATE_DB_PATH;
else process.env.CURSOR_STATE_DB_PATH = origEnv;
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
test("resetCursorVersionCache forces re-read from DB", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cursor-ver-reset-"));
const dbPath = createStateDb(tmpDir, "5.0.0");
const origEnv = process.env.CURSOR_STATE_DB_PATH;
process.env.CURSOR_STATE_DB_PATH = dbPath;
try {
resetCursorVersionCache();
assert.equal(getCursorVersion(), "5.0.0");
const db = new Database(dbPath);
db.prepare("UPDATE itemTable SET value = ? WHERE key = ?").run(
"6.0.0",
"cursorupdate.lastUpdatedAndShown.version"
);
db.close();
resetCursorVersionCache();
assert.equal(getCursorVersion(), "6.0.0", "should re-read after cache reset");
} finally {
if (origEnv === undefined) delete process.env.CURSOR_STATE_DB_PATH;
else process.env.CURSOR_STATE_DB_PATH = origEnv;
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});