From ecf0089ee94d382e73fcfbd52b1c5b52cecec5ce Mon Sep 17 00:00:00 2001 From: Diego Rodrigues de Sa e Souza <8016841+diegosouzapw@users.noreply.github.com> Date: Wed, 17 Jun 2026 14:57:07 -0300 Subject: [PATCH] feat(sse): port Claude Code quota-probe bypass + command meta-request helpers (#4083) Integrated into release/v3.8.28 --- open-sse/utils/bypassHandler.ts | 12 +++ open-sse/utils/claudeCodeMetaRequests.ts | 87 ++++++++++++++++++++ tests/unit/bypass-handler.test.ts | 15 ++++ tests/unit/claude-code-meta-requests.test.ts | 53 ++++++++++++ 4 files changed, 167 insertions(+) create mode 100644 open-sse/utils/claudeCodeMetaRequests.ts create mode 100644 tests/unit/claude-code-meta-requests.test.ts diff --git a/open-sse/utils/bypassHandler.ts b/open-sse/utils/bypassHandler.ts index 4e1ba7b527..618d1f4db5 100644 --- a/open-sse/utils/bypassHandler.ts +++ b/open-sse/utils/bypassHandler.ts @@ -69,6 +69,18 @@ export function handleBypassRequest(body, model, userAgent = "") { } } + // Pattern 5: Quota probe — max_tokens=1 + "quota" keyword (FCC try_quota_mock). + if (!shouldBypass && body.max_tokens === 1) { + const userText = messages + .filter((m) => m.role === "user") + .map((m) => getText(m.content)) + .join(" ") + .toLowerCase(); + if (userText.includes("quota")) { + shouldBypass = true; + } + } + if (!shouldBypass) return null; const sourceFormat = detectFormat(body); diff --git a/open-sse/utils/claudeCodeMetaRequests.ts b/open-sse/utils/claudeCodeMetaRequests.ts new file mode 100644 index 0000000000..2c765b8490 --- /dev/null +++ b/open-sse/utils/claudeCodeMetaRequests.ts @@ -0,0 +1,87 @@ +// Tools whose meaningful prefix is two words (verb + subcommand). +const TWO_WORD_TOOLS = new Set([ + "git", "npm", "docker", "kubectl", "cargo", "go", "pip", "yarn", "pnpm", "bun", +]); + +const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/; +// Command-injection signals: ; | & ` $( (newline handled separately) +const INJECTION_RE = /[;|&`]|\$\(/; + +/** Tokenize a shell command on whitespace, respecting simple single/double quotes. */ +function tokenize(command: string): string[] { + const tokens: string[] = []; + let current = ""; + let quote: string | null = null; + for (const ch of command) { + if (quote) { + if (ch === quote) quote = null; + else current += ch; + } else if (ch === '"' || ch === "'") { + quote = ch; + } else if (/\s/.test(ch)) { + if (current) { tokens.push(current); current = ""; } + } else { + current += ch; + } + } + if (current) tokens.push(current); + return tokens; +} + +export function extractCommandPrefix(command: string): string { + if (typeof command !== "string" || !command.trim()) return ""; + if (INJECTION_RE.test(command) || command.includes("\n")) { + return "command_injection_detected"; + } + let tokens = tokenize(command); + // Strip leading FOO=bar env assignments. + while (tokens.length && ENV_ASSIGNMENT_RE.test(tokens[0])) tokens = tokens.slice(1); + if (!tokens.length) return ""; + const head = tokens[0]; + // Only form a two-word prefix when the second token is an actual subcommand, + // not a flag. We intentionally do not parse flag-arguments (e.g. `git -C `); + // for those we fall back to the single-word head (conservative, never wrong). + if (TWO_WORD_TOOLS.has(head) && tokens.length > 1 && !tokens[1].startsWith("-")) { + return `${head} ${tokens[1]}`; + } + return head; +} + +const READ_COMMANDS = new Set(["cat", "head", "tail", "less", "more", "bat", "type"]); +const LISTING_COMMANDS = new Set(["ls", "dir", "find", "tree"]); +// grep flags that consume the NEXT arg (so it is not a filepath). +const GREP_ARG_FLAGS = new Set(["-e", "-f", "-m", "-A", "-B", "-C"]); + +export function extractFilepathsFromCommand(command: string, _output = ""): string[] { + if (typeof command !== "string" || !command.trim()) return []; + const tokens = tokenize(command); + if (!tokens.length) return []; + const head = tokens[0]; + + if (LISTING_COMMANDS.has(head)) return []; + + if (head === "grep") { + const files: string[] = []; + let patternConsumed = false; + for (let i = 1; i < tokens.length; i++) { + const tok = tokens[i]; + if (tok.startsWith("-")) { + if (GREP_ARG_FLAGS.has(tok)) { + i++; // skip this flag's argument + // -e/-f supply the pattern itself, so the positional pattern is already consumed. + if (tok === "-e" || tok === "-f") patternConsumed = true; + } + continue; + } + if (!patternConsumed) { patternConsumed = true; continue; } // first non-flag = pattern + files.push(tok); + } + return files; + } + + if (READ_COMMANDS.has(head)) { + return tokens.slice(1).filter((t) => !t.startsWith("-")); + } + + return []; +} diff --git a/tests/unit/bypass-handler.test.ts b/tests/unit/bypass-handler.test.ts index 28eeeb7394..e97cad0440 100644 --- a/tests/unit/bypass-handler.test.ts +++ b/tests/unit/bypass-handler.test.ts @@ -83,3 +83,18 @@ test("handleBypassRequest bypasses single-message count probes", async () => { assert.equal(payload.usage.total_tokens, 2); assert.equal(payload.choices[0].finish_reason, "stop"); }); + +test("bypass returns quota response for max_tokens=1 quota probe", () => { + const body = { + max_tokens: 1, + stream: false, + messages: [{ role: "user", content: "Please check the quota for this key" }], + }; + const result = handleBypassRequest(body, "x", "claude-cli/2.1.0"); + assert.ok(result?.success, "should bypass quota probe"); +}); + +test("bypass does NOT trigger for normal requests", () => { + const body = { messages: [{ role: "user", content: "write a function" }] }; + assert.equal(handleBypassRequest(body, "x", "claude-cli/2.1.0"), null); +}); diff --git a/tests/unit/claude-code-meta-requests.test.ts b/tests/unit/claude-code-meta-requests.test.ts new file mode 100644 index 0000000000..ab7dabb095 --- /dev/null +++ b/tests/unit/claude-code-meta-requests.test.ts @@ -0,0 +1,53 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { extractCommandPrefix } from "../../open-sse/utils/claudeCodeMetaRequests.ts"; +import { extractFilepathsFromCommand } from "../../open-sse/utils/claudeCodeMetaRequests.ts"; + +test("extractCommandPrefix returns two-word prefix for known multi-verb tools", () => { + assert.equal(extractCommandPrefix("git commit -m 'x'"), "git commit"); + assert.equal(extractCommandPrefix("npm install lodash"), "npm install"); + assert.equal(extractCommandPrefix("docker build ."), "docker build"); +}); + +test("extractCommandPrefix returns single word for simple commands", () => { + assert.equal(extractCommandPrefix("ls -la"), "ls"); + assert.equal(extractCommandPrefix("cat file.txt"), "cat"); +}); + +test("extractCommandPrefix strips leading env assignments", () => { + assert.equal(extractCommandPrefix("FOO=bar npm run build"), "npm run"); +}); + +test("extractCommandPrefix detects command injection", () => { + assert.equal(extractCommandPrefix("ls; rm -rf /"), "command_injection_detected"); + assert.equal(extractCommandPrefix("echo $(whoami)"), "command_injection_detected"); + assert.equal(extractCommandPrefix("cat `id`"), "command_injection_detected"); +}); + +test("extractFilepathsFromCommand returns read files for read commands", () => { + assert.deepEqual(extractFilepathsFromCommand("cat src/a.ts src/b.ts", ""), ["src/a.ts", "src/b.ts"]); + assert.deepEqual(extractFilepathsFromCommand("head -n5 README.md", ""), ["README.md"]); +}); + +test("extractFilepathsFromCommand returns empty for listing commands", () => { + assert.deepEqual(extractFilepathsFromCommand("ls -la src/", ""), []); + assert.deepEqual(extractFilepathsFromCommand("find . -name '*.ts'", ""), []); +}); + +test("extractFilepathsFromCommand skips the grep pattern arg", () => { + assert.deepEqual(extractFilepathsFromCommand("grep -n foo src/a.ts", ""), ["src/a.ts"]); +}); + +test("extractCommandPrefix stays conservative when a flag precedes the subcommand", () => { + // -C takes a path arg; we don't parse flag-args, so fall back to the head + // (never emit a wrong two-word prefix like "git -C" or "git /x"). + assert.equal(extractCommandPrefix("git -C /x commit"), "git"); +}); + +test("extractFilepathsFromCommand handles grep -e pattern then file", () => { + assert.deepEqual(extractFilepathsFromCommand("grep -e pattern a.ts", ""), ["a.ts"]); +}); + +test("extractFilepathsFromCommand handles grep -f patternfile then file", () => { + assert.deepEqual(extractFilepathsFromCommand("grep -f pats.txt a.ts", ""), ["a.ts"]); +});