Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,18 @@ repos:
entry: cargo clippy --workspace --all-targets -- -D warnings
language: system
types: [rust]
pass_filenames: false
pass_filenames: false

- id: surge-check
name: Surge script format and lint
entry: biome check biome.json integrations/surge
language: system
files: ^(biome\.json|integrations/surge/.*\.(js|mjs))$
pass_filenames: false

- id: surge-test
name: Surge module tests
entry: node --test integrations/surge/codex-hide-usage-banner.test.mjs
language: system
files: ^integrations/surge/.*\.(js|mjs|sgmodule)$
pass_filenames: false
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ With Nix and [devenv](https://devenv.sh/) installed, run:
devenv shell
```

The environment provides Rust, Cargo, Clippy, rustfmt, rust-analyzer, a C compiler, and `protoc`. Commit `devenv.lock` to keep the tool versions reproducible. Run `devenv update` to update the pinned inputs.
The environment provides Rust, Cargo, Clippy, rustfmt, rust-analyzer, a C compiler, and `protoc`. It also provides Node.js and Biome for the [optional Surge integration](integrations/surge/README.md#development-checks). Commit `devenv.lock` to keep the tool versions reproducible. Run `devenv update` to update the pinned inputs.

To run one command without opening a shell:

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ The default is `false`, which preserves upstream reviewer metadata. When enabled

Codex still supplies its approval policy, read-only reviewer tools and structured-output schema. The selected model must support these requests; its review quality may differ from the official reviewer, and review requests consume that provider's quota. BYOKEY does not convert review failures into approvals or retry them through ChatGPT. Multi-agent V2 metadata, actual quota data and error responses remain unchanged. This setting does not hide the desktop client's official-account quota banner.

**Optional: hide the Codex Desktop quota banner.** The [Surge for Mac module](integrations/surge/README.md) hides the workspace-member usage-limit banner for all models, including official ChatGPT models, without changing real quotas or errors. It requires HTTPS interception; Surge Logbook can retain authentication headers even with debugging disabled. Read the security and installation instructions before enabling it. BYOKEY does not install or enable the module.

Copilot can change an output item's ID between stream events. BYOKEY retains the first ID for each output index so Codex updates one message instead of displaying a duplicate. Response IDs and tool `call_id` values remain unchanged. ChatGPT and custom providers retain their original stream payloads.

The catalog borrows actual ChatGPT model metadata, including instructions and capabilities. When `model_messages.instructions_template` is present, BYOKEY omits the ignored legacy `base_instructions` copy to reduce catalog size. Each routed model needs a ChatGPT catalog entry with its ID or its `catalog_model`, or a complete Codex ModelInfo object in `model_overrides.<model>.catalog`. A missing match is an error. A custom default with complete catalog objects, no `models_url`, and no enabled Copilot credentials or routes needs no ChatGPT catalog access; otherwise catalog discovery needs the client's ChatGPT login. Alias upgrades are disabled so the client does not migrate an alias to a different route. The existing `/v1/models`, `byokey route`, and TUI route list remain Anthropic-only.
Expand Down
12 changes: 12 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"files": {
"includes": ["biome.json", "integrations/surge/**"]
},
"formatter": {
"indentStyle": "space",
"indentWidth": 2
},
"javascript": {
"globals": ["$request", "$response", "$done"]
}
}
6 changes: 5 additions & 1 deletion devenv.nix
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@

{
languages.rust.enable = true;
packages = [ pkgs.protobuf ];
packages = [
pkgs.protobuf
pkgs.nodejs
pkgs.biome
];
}
2 changes: 2 additions & 0 deletions docs/README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ responses:

保持监听地址为 `127.0.0.1`,且只配置可信的上游地址。BYOKEY 不为已存储的 Copilot 或自定义上游凭据提供入站鉴权,不要向不可信网络暴露端口。

[可选的 Surge for Mac 模块](../integrations/surge/README.md)可以隐藏 Codex Desktop 的工作区成员额度耗尽横幅,不修改真实额度或错误。模块对所有模型生效,包括官方 ChatGPT 模型。模块需要 HTTPS 解密;即使关闭调试,Surge Logbook 仍可能保存认证请求头。启用前必须阅读安全说明和安装步骤。BYOKEY 不会自动安装或启用模块。

### Claude Code / Claude Desktop

```sh
Expand Down
47 changes: 47 additions & 0 deletions integrations/surge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Codex Desktop usage banner (Surge for Mac)

This optional module hides the workspace-member usage-limit banner in Codex Desktop, including the Codex interface in ChatGPT.app. It is useful when BYOKEY routes inference to another provider but Desktop still displays the official account's quota warning. BYOKEY does not install or enable this module.

The script removes `rate_limit_upsell` only when its `banner_type` is `workspace_member_usage_limit_reached`. It processes HTTP 200 JSON responses for these endpoints:

- `GET https://chatgpt.com/backend-api/wham/usage`
- `POST https://chatgpt.com/backend-api/wham/usage/subscriptions`

Query strings are allowed. Requests must identify as `CodexBrowser …` or `Codex Desktop/…` in `User-Agent`. Other clients, other banners, non-JSON responses, and error responses remain unchanged. Real quotas, reset times, and other response fields remain unchanged. The module does not modify `app.asar`, inference requests, or approval requests.

**This is not a quota bypass.** Usage data is account-wide and does not identify the selected model or provider. The banner is hidden for every model, including official ChatGPT models. Actual quota errors still apply. These are private client endpoints; client updates can stop the module from working.

## Security and scope

- **MITM decrypts HTTPS traffic for the whole `chatgpt.com` hostname**, not just the two script endpoints. The script's response-matching conditions do not restrict the TLS decryption scope.
- **Surge Logbook can retain authentication headers.** During local validation, script input records contained authentication headers even with `debug` disabled. The script's own messages do not print credentials or response bodies, but disabling script debugging does not prevent Surge's input recording. Do not export or share those records. Do not enable this module if that retention is unacceptable.
- The module uses `hostname = %APPEND% chatgpt.com` to preserve existing MITM hostnames. Before enabling MITM, review the complete effective hostname list, including other modules. Enabling the global switch also enables decryption for those existing entries. Do not add a wildcard or disable server certificate verification to make this module work.
- Trust only your own Surge CA. Review both source files before installing. This module uses a local script and does not download script updates automatically.

## Install

1. Download [codex-hide-usage-banner.sgmodule](codex-hide-usage-banner.sgmodule) and [codex-hide-usage-banner.js](codex-hide-usage-banner.js) from the same repository revision. Use the raw file contents, not the GitHub HTML pages.
2. Open Surge's profile directory. Place both files beside the active profile, without an extra subdirectory. The module's relative `script-path` expects the JavaScript file there. Back up any existing files with these names before replacing them.
3. Enable **Codex Desktop Usage Banner** in Surge's module list. Enable the **Scripting** switch.
4. Configure and trust your own Surge MITM CA if you have not already done so. Reuse an existing trusted CA. Keep server certificate verification enabled.
5. Review the effective MITM hostname list, then enable the **MITM** switch. Confirm `chatgpt.com` is included and is not excluded by another hostname rule. Do not add `debug=true`.
6. After active tasks finish, fully quit Codex Desktop or ChatGPT.app with `⌘Q`, then reopen it to refresh usage data and HTTPS connections.

The target banner should disappear while the composer and model, effort, and approval controls remain available. An absent banner does not prove that inference works or that the account has quota. Check real provider errors separately. If TLS errors appear, disable the module; do not turn off server certificate verification.

## Remove

Disable **Codex Desktop Usage Banner**, then fully quit and reopen the client. Delete the two installed files if no longer needed. Disabling the module does not delete Surge's existing Logbook records or remove its trusted CA.

If MITM was enabled only for this module, turn off the global MITM switch. Otherwise, review the effective hostnames: another profile entry or module may still include `chatgpt.com`.

## Development checks

From the repository root, use the tools provided by `devenv shell`:

```sh
devenv shell biome check integrations/surge
devenv shell node --test integrations/surge/codex-hide-usage-banner.test.mjs
```

The tests execute the script with synthetic Surge request and response objects through its `$done` interface. They check both endpoint forms, quota preservation, and unchanged responses outside the intended scope. They require no credentials or network access. They do not validate TLS interception or the current Desktop UI; check those separately on a Mac before changing client-matching behavior.
52 changes: 52 additions & 0 deletions integrations/surge/codex-hide-usage-banner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Hide one account-wide presentation field; preserve quotas and upstream errors.
function rewriteUsageBanner() {
const route =
/^https:\/\/chatgpt\.com\/backend-api\/wham\/usage(\/subscriptions)?(?:\?.*)?$/.exec(
$request.url,
);
if (
!route ||
$request.method !== (route[1] ? "POST" : "GET") ||
$response.status !== 200
) {
console.log(
`Codex usage banner: skipped; route=${Boolean(route)}, method=${Boolean(route && $request.method === (route[1] ? "POST" : "GET"))}, status=${$response.status} (${typeof $response.status}).`,
);
return {};
}

const userAgent = Object.entries($request.headers ?? {}).find(
([name]) => name.toLowerCase() === "user-agent",
)?.[1];
if (
!userAgent?.startsWith("Codex Desktop/") &&
!userAgent?.startsWith("CodexBrowser ")
) {
console.log(
`Codex usage banner: skipped; Desktop identity not matched, User-Agent present=${userAgent !== undefined}.`,
);
return {};
}

let usage;
try {
usage = JSON.parse($response.body);
} catch {
// A changed upstream format must not interrupt quota updates.
console.log("Codex usage banner: non-JSON response left unchanged.");
return {};
}
if (
usage?.rate_limit_upsell?.banner_type !==
"workspace_member_usage_limit_reached"
) {
console.log("Codex usage banner: skipped; target banner absent.");
return {};
}

delete usage.rate_limit_upsell;
console.log("Codex usage banner: removed target banner; quotas unchanged.");
return { body: JSON.stringify(usage) };
}

$done(rewriteUsageBanner());
9 changes: 9 additions & 0 deletions integrations/surge/codex-hide-usage-banner.sgmodule
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!name=Codex Desktop Usage Banner
#!desc=Hide the workspace member usage-limit banner in Codex Desktop for every model. Preserve real quotas and errors. Append chatgpt.com to MITM; review all effective hostnames before enabling MITM. Surge Logbook may retain authentication headers even without debug. Requires a trusted Surge CA and MITM enabled separately.
#!system=mac

[Script]
codex-hide-usage-banner = type=http-response, pattern=^https://chatgpt\.com/backend-api/wham/usage(?:/subscriptions)?(?:\?.*)?$, script-path=codex-hide-usage-banner.js, requires-body=true, max-size=262144, timeout=5, engine=jsc

[MITM]
hostname = %APPEND% chatgpt.com
102 changes: 102 additions & 0 deletions integrations/surge/codex-hide-usage-banner.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { runInNewContext } from "node:vm";

const script = readFileSync(
new URL("./codex-hide-usage-banner.js", import.meta.url),
"utf8",
);
const module = readFileSync(
new URL("./codex-hide-usage-banner.sgmodule", import.meta.url),
"utf8",
);
const pattern = new RegExp(module.match(/\bpattern=([^,\s]+)/)[1]);
const url = "https://chatgpt.com/backend-api/wham/usage";
const quota = {
rate_limit: {
allowed: false,
limit_reached: true,
primary_window: { used_percent: 100, reset_at: 1900000123 },
secondary_window: { used_percent: 37, reset_at: 1900080456 },
},
credits: { has_credits: false, unlimited: false, balance: "0" },
spend_control: { limit: 42, used: 17 },
future_field: { preserve: [null, false, "unchanged"] },
};
const body = JSON.stringify({
...quota,
rate_limit_upsell: {
banner_type: "workspace_member_usage_limit_reached",
message: "Contact your admin to increase your usage limit",
},
});

function rewrite(request = {}, response = {}) {
let result;
runInNewContext(script, {
$request: {
url,
method: "GET",
headers: { "User-Agent": "CodexBrowser Mozilla/5.0" },
...request,
},
$response: { status: 200, body, ...response },
console: { log() {} },
$done(value) {
result = value;
},
});
// Surge receives a plain object, not the VM's realm-specific prototype.
return JSON.parse(JSON.stringify(result));
}

for (const request of [
{ url, method: "GET", headers: { "User-Agent": "CodexBrowser Mozilla/5.0" } },
{
url: `${url}/subscriptions?source=desktop`,
method: "POST",
headers: { "user-agent": "Codex Desktop/1.0" },
},
]) {
test(`${request.method} ${request.url} removes only the target upsell`, () => {
assert.equal(pattern.test(request.url), true);
const result = rewrite(request);
assert.deepEqual(
{ ...result, body: JSON.parse(result.body) },
{ body: quota },
);
});
}

for (const otherUrl of [
"https://chatgpt.com/backend-api/codex/responses",
"https://chatgpt.com.example.org/backend-api/wham/usage",
`${url}/other`,
]) {
test(`does not intercept ${otherUrl}`, () => {
assert.equal(pattern.test(otherUrl), false);
assert.deepEqual(rewrite({ url: otherUrl }), {});
});
}

for (const [name, request, response] of [
["ordinary browser", { headers: { "User-Agent": "Mozilla/5.0" } }, {}],
["CLI client", { headers: { "User-Agent": "codex_cli_rs/1.0" } }, {}],
["missing client identity", { headers: {} }, {}],
["POST on usage", { method: "POST" }, {}],
["GET on subscriptions", { url: `${url}/subscriptions` }, {}],
["quota rejection", {}, { status: 429 }],
["authentication failure", {}, { status: 401 }],
["non-JSON response", {}, { body: "<html>upstream failure</html>" }],
["missing banner", {}, { body: JSON.stringify(quota) }],
[
"different banner",
{},
{ body: '{"rate_limit_upsell":{"banner_type":"other_banner"}}' },
],
]) {
test(`leaves the response unchanged for ${name}`, () => {
assert.deepEqual(rewrite(request, response), {});
});
}
Loading