Skip to content

feat(proxies): read CLIProxyAPI upstream accounts in the gateway - #727

Merged
nixuuu merged 3 commits into
devfrom
feat/proxy-accounts-gateway
Nov 14, 2026
Merged

nixuuu merged 3 commits into
devfrom
feat/proxy-accounts-gateway

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Stage 1 of 2: the gateway reads a CLIProxyAPI proxy's upstream accounts through its management API. Base: dev (#725 merged, 0143 on dev). Migration 0145 (0144_thread_html is on dev).

  • Credential: an optional management key per CLIProxyAPI proxy (SaveProxyRequest.management_key). Omitted keeps it, empty removes it. It's encrypted like the proxy secret (proxies.management_secret_id, migration 0145_proxy_management).
    • Only Proxy.management_key_set is returned.
    • The key never reaches workers, models, logs, linked-computer sync or the audit (proxy.management_key_replaced/removed, no values).
  • Read: GET <root>/v0/management/auth-files (CLIProxyAPI v8.0.x) with a Bearer header, redirect: "error", a 10 s timeout, a 4 MiB body cap and a 200-account cap. The response is decoded with a schema at the boundary, and entries with the wrong type are skipped.
    • Text is sanitized: control characters and <> removed, credentials redacted, length capped.
    • Status (active, cooling_down, disabled, sign_in, error), cooldown end, success/failure counts.
    • Passive limit windows come from the Codex x-codex-* and Claude anthropic-ratelimit-unified-* headers the proxy saw.
    • usage-queue is not used, because it pops records from the queue.
  • States: ok, no_key, unauthorized, remote_disabled, unavailable, unreachable, invalid_response. The proxy itself keeps working in every state.
  • Polling (ProxyAccountsMonitor, in memory):
    • RefreshProxyAccounts on view open reuses a read under 60 s old. force (Refresh button) reads at most every 5 s.
    • Proxies that have a key and are used by a profile are checked every 5 min, backing off to 1 h after failures.
    • A new key or URL reads again.
    • CLIProxyAPI bans an address for 30 min after five wrong keys, so unauthorized, remote_disabled and no_key are never retried automatically.
  • Delivery: OverviewUpdate.proxy_accounts = 831 carries one proxy's accounts. OverviewInvalidation patches the shared ListProxies cache in place on web and mobile. BFF: POST /api/proxies/accounts.
  • Proto (additive only): ProxyAccount, ProxyAccounts, RefreshProxyAccountsRequest, Proxy.management_key_set = 9, Proxy.accounts = 10, SaveProxyRequest.management_key = 8, rpc RefreshProxyAccounts.
  • Docs: docs/proxies.md (Konta upstream), docs/ui-api.md.

Tests

tests/integration/proxy-accounts.test.ts runs against a fake management server. It covers:

  • parsed and sanitized accounts (including hostile HTML, control characters and tokens), plus an incremental push;
  • no repeat request within the fresh window;
  • the key absent from RPC responses, the database (ciphertext) and the audit;
  • a wrong key read once and never retried on its own;
  • remote management turned off, an oversized body, a non-JSON body and an unreachable host;
  • no key;
  • owner scoping;
  • the periodic check reading only proxies in use.

Also run: proxies.test.ts, schema.test.ts, gen:check, typecheck, lint, format:check.

Security review fixes

  • Echoed secrets: the exact management key and proxy secret are redacted from every account text field before truncation, raw, URL-encoded, base64 and base64url. A proxy that echoes a key in email, label, status_message or id cannot hand it to clients. Tested with a fake server echoing each form in each field.
  • Bounded bodies: every body, including a 403, goes through a bounded reader. Only a 512-byte prefix of an error is read and the rest is cancelled. Tested with an endless 403 body.
  • Persisted state: the last read is stored with the proxy (management_status) together with the key/URL identity it used (<key secret id>|<url>). A rejected key stays rejected across restarts and gateway processes until the key changes or Refresh is pressed.
  • Cross-process lease: a lease in the same row (management_read_at, management_read_identity) lets one process start a read of an identity at most once per 60 s, or 5 s for Refresh. Tested with fresh monitors (a restart and a second process) after a rejection, and with two monitors racing for one read.
  • Other processes: proxies_changed now also reflects reads made by another gateway process.

@nixuuu
nixuuu force-pushed the fix/proxy-usage-limits branch from 61e07e8 to 8f0902c Compare November 14, 2026 15:10
@nixuuu
nixuuu force-pushed the feat/proxy-accounts-gateway branch from 0e902de to f456d2a Compare November 14, 2026 15:17
Base automatically changed from fix/proxy-usage-limits to dev November 14, 2026 15:22
@nixuuu
nixuuu force-pushed the feat/proxy-accounts-gateway branch from f456d2a to dbbcb43 Compare November 14, 2026 15:40
An optional management key per CLIProxyAPI proxy, stored encrypted like the
proxy secret, lets the gateway read the proxy's upstream accounts from its
management API. Responses are parsed and sanitized at the boundary, kept in
memory, read on demand and every few minutes for proxies in use, and pushed
to clients per proxy. A rejected key is never retried on its own.
Account text drops the exact management key and proxy secret, raw and
encoded. Every response body, including 403s, is read through a bounded
reader. The last read is stored with the proxy and the key identity it
used, and a lease in the same row spaces reads across gateway processes,
so a rejected key is never retried automatically after a restart or from
another process. The migration moves to 0145.
@nixuuu
nixuuu force-pushed the feat/proxy-accounts-gateway branch from dbbcb43 to 48b1c63 Compare November 14, 2026 16:09
@nixuuu
nixuuu marked this pull request as ready for review November 14, 2026 16:09
@nixuuu
nixuuu merged commit 552e90b into dev Nov 14, 2026
13 checks passed
@nixuuu
nixuuu deleted the feat/proxy-accounts-gateway branch November 14, 2026 16:22
nixuuu added a commit that referenced this pull request Nov 14, 2026
Stage 2 of 2, on #727. UI for CLIProxyAPI upstream accounts on web and
mobile.

- **Settings → Proxies (web):**
- A **Management key** field for CLIProxyAPI proxies (optional;
Replace/Clear like other secrets).
- **Accounts** on the proxy card: compact rows with the provider mark,
account (truncated), status badge, the limits the proxy last saw (the
same meters as plan limits), cooldown end and last message (two lines at
most), **Refresh** and "Checked …".
- Without a key, or in an error state, one short hint instead of the
list. Texts render as text only.
- **Settings → Providers (web):** a proxy-backed instance shows "Through
<proxy> · 2 Codex accounts · 1 cooling down", with a link to the proxy
card. It replaces the plan meters #725 removed.
- **Mobile, read-only:**
- The proxy row lists accounts with status, limits and message, plus
Refresh accounts.
  - Provider instance rows add the "Through …" line.
  - JS only, so the OTA fingerprint is unchanged.
- Shared labels, hints and summary: `@canopy/domain/proxy-accounts`.
- The view reads once on open (the gateway answers from a read under 60
s old). Changes arrive incrementally through
`OverviewUpdate.proxy_accounts`.
- Docs: `docs/proxies.md` (UI), `docs/copy.md` glossary (`proxy
account`, `management key`).

## Browser review
Reviewed on a separate review machine, with a fake CLIProxyAPI giving 6
accounts:
- typical and very long emails, a long cooldown message, HTML and a
token in a message;
- Codex and Claude limit headers;
- Gemini and Grok accounts.

Checked in light and dark, at 1280 px and a 390 px phone width:
- no horizontal scroll;
- long names truncate;
- messages clamp;
- the badge stays on the right without shifting rows;
- Refresh shows progress only when pressed.

The review found two problems, both fixed in this stack:
- The on-open read re-fired when its own result updated the proxy
object. It's now keyed on a primitive; one request per open, verified
with resource timing.
- Proxy messages showed tag remnants. The gateway now strips whole tags
(#727).

## Checks
gen:check, typecheck, lint, format:check, web build, `expo export`
(android, ios). Tests: `proxy-accounts`, `proxies`, `provider-usage`,
`provider-usage-bots`, `schema`, domain and worker unit tests. No UI
tests, per policy.

## Copy audit (§8)
| Before | After | Reason |
| --- | --- | --- |
| (none) | Field "Management key": "Optional. Lets Canopy show the
proxy's accounts and their status. Encrypted in the gateway." | Says
what it does, then where it's kept. New glossary term. |
| (none) | "Accounts · 6", "Checked just now", "Showing 20 of 240.",
"The proxy has no accounts yet." | Short; no repeated facts. |
| (none) | Badges: Active, Cooling down, Off, Sign in again, Error |
Sentence case. Each badge has text, so color is never the only cue. |
| (none) | "Add a management key to see this proxy's accounts." | What
to do, in one sentence. |
| (none) | "The proxy rejected the management key. Replace it, then
refresh." | What happened, then what to do. |
| (none) | "The proxy allows management only from its own computer. Turn
on remote management there." | Plain words instead of
`allow-remote-management`. |
| (none) | "The proxy's management API is off or unavailable." / "Canopy
could not reach the proxy's management API." / "The proxy sent an
account list Canopy cannot read." | Errors without raw bodies. |
| Plan meter on a proxy instance | "Through Team proxy · 2 Codex
accounts · 1 cooling down" | Names the proxy; the counts are about its
accounts, not the user's plan. |

Glossary: added `proxy account` (not "auth file" or "credential") and
`management key` (not "admin key").

## Also
- Mobile bot-chat failure card gets the proxy wording for proxy
instances (web already had it).
nixuuu added a commit that referenced this pull request Nov 14, 2026
Saving a management key starts a background accounts read. A concurrent
`RefreshProxyAccounts` could lose the database lease and return an empty
account state in two orderings: while the winner was acquiring its
lease, or after a stale target lookup outlived the completed winner.
Register the shared promise before claiming the lease and reload the
committed snapshot after a refused claim. Keep cached and forced refresh
decisions unchanged.

The original proxy test and its assertions are unchanged. Add a
regression with explicit target/lease gates that holds a stale lookup
until the winning refresh has committed. Restoring the stale-snapshot
fallback makes this regression fail deterministically with an empty
account state; restoring the fix makes it pass.

For the Claude usage test, coordinate the fake CLI and WatchThread
explicitly: the CLI announces turn admission, then waits for the watch's
initial snapshot before emitting the existing limit events and result.
The existing 10-second watch budget and 60-second test budget are
unchanged, as are all five assertions. Include the caller's proxy
credential variable in fixture environment isolation so native plan
reporting remains enabled in developer/agent shells.

### Repeated focused runs

All runs used `nice -n 10`, with temporary files under a private
directory in `/var/tmp`. Each 200-run sample consists of four batches of
50 using `--rerun-each=50` and the exact test-name filter.

| Test | Before | After |
| --- | --- | --- |
| Encrypted management key / proxy accounts | 152 passed, 48 failed /
200 | 200 passed, 0 failed / 200 |
| Claude reached window / paid-usage notice | 200 passed, 0 failed / 200
| 200 passed, 0 failed / 200 |

The proxy baseline failures returned `state: ""`, `total: 0` rather than
the sanitized account snapshot, matching the fast CI failure. The Claude
cancellation in Release run 43622538704 was not reproduced locally; ten
additional runs with the preceding gateway-restart test also passed. Its
change removes scheduling of CLI startup and stream subscription from
the timed event-observation phase; it does not claim a provider product
fix.

Standalone Docker-per-iteration baselines also encountered 12 proxy and
4 Claude teardown-hook timeouts, separate from the test-body counts
above. Final repeated runs and focused files use the repository's
`check:tmp` runner, which shares PostgreSQL across iterations and checks
cleanup.

### Validation

- `nice -n 10 bun install`
- `nice -n 10 bun run typecheck`
- `nice -n 10 bun run lint`
- `nice -n 10 bun run format:check`
- `nice -n 10 bun run check:tmp tests/integration/proxy-accounts.test.ts
tests/integration/provider-usage.test.ts
tests/integration/provider-usage-bots.test.ts` — 16 passed, 0 failed; no
temp directories left

Fixes: #727
Related: #697
nixuuu added a commit that referenced this pull request Nov 15, 2026
## Change

Claude quota could show 45% remaining while the provider reported 17%,
because Canopy only read passive response headers cached by CLIProxyAPI.
Read current Claude OAuth usage through the management API, with the
proxy substituting the account token internally. A valid provider
response takes precedence; unavailable or invalid active reads retain
the passive fallback.

Resolve passive windows from credential and model observations by
observation time, keeping each window's percentage, reset and status
together. Keep exhausted Opus/Sonnet allowances scoped to their model
instead of zeroing the shared weekly balance. Update `docs/proxies.md`
with the behavior and limits.

## Verification

- Targeted `check:tmp` runs: proxy account usage, existing management
integration, observation parsing and capacity projection (25 tests
passed across the affected files).
- Gateway and domain package typechecks; lint and formatting on edited
files; test shard coverage check.
- Live check against the configured CLIProxyAPI: passive weekly balance
45%, current provider response 17%, corrected reader 17%. Management and
provider requests returned HTTP 200. No credentials or account
identities are included here.
- Full repository checks and builds are left to CI. No UI text changed.

Fixes: #727
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant