mirror of
https://github.com/Finesssee/ProxyPilot.git
synced 2026-11-20 20:34:36 +00:00
Compare commits
373
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0241c3e6b | ||
|
|
d8b1ade0ea | ||
|
|
0b04915694 | ||
|
|
40cb8329e6 | ||
|
|
d88d3a7829 | ||
|
|
646ceef400 | ||
|
|
b741c439e9 | ||
|
|
a29917297b | ||
|
|
d3f61fc925 | ||
|
|
e3302b694c | ||
|
|
c8b7e2b8d6 | ||
|
|
cad45ffa33 | ||
|
|
6a27bceec0 | ||
|
|
163d68318f | ||
|
|
0ea768011b | ||
|
|
9f5bdfaa31 | ||
|
|
9eabdd09db | ||
|
|
c3f8dc362e | ||
|
|
b85120873b | ||
|
|
6f58518c69 | ||
|
|
000fcb15fa | ||
|
|
ea43361492 | ||
|
|
c1818f197b | ||
|
|
a7ea27d047 | ||
|
|
53be957861 | ||
|
|
e6ec1fd86a | ||
|
|
b0653cec7b | ||
|
|
08065bd061 | ||
|
|
159a3b218e | ||
|
|
46758c9787 | ||
|
|
91fe656204 | ||
|
|
67c79b9dc5 | ||
|
|
53f6f99433 | ||
|
|
cea7a0f4e3 | ||
|
|
f4ae033c97 | ||
|
|
22a1a24cf5 | ||
|
|
1c2396bb52 | ||
|
|
3da810d19a | ||
|
|
1b3542d77c | ||
|
|
1c3edd9f4a | ||
|
|
c603b98c2b | ||
|
|
fbc6545d85 | ||
|
|
20fda28fb4 | ||
|
|
469fd38420 | ||
|
|
0b80a392e7 | ||
|
|
f9da6dcb0a | ||
|
|
16a0799176 | ||
|
|
ff5fa96583 | ||
|
|
3e205f7335 | ||
|
|
056e4d8edf | ||
|
|
fcdcbfc174 | ||
|
|
85687a4ab7 | ||
|
|
388a7a127d | ||
|
|
e040fdb330 | ||
|
|
ada8e2905e | ||
|
|
4ba10531da | ||
|
|
81929c06da | ||
|
|
3774b56e9f | ||
|
|
c2d4137fb9 | ||
|
|
2ee938acaf | ||
|
|
8d5e470e1f | ||
|
|
65e9e892a4 | ||
|
|
8430b28cfa | ||
|
|
f3ab8f4bc5 | ||
|
|
0e4f189c2e | ||
|
|
754b126944 | ||
|
|
ae37ccffbf | ||
|
|
d548446ce8 | ||
|
|
852642d5ee | ||
|
|
371bfc3528 | ||
|
|
9cf230cc40 | ||
|
|
42c062bb5b | ||
|
|
f389667ec3 | ||
|
|
29dba0399b | ||
|
|
a824e7cd0b | ||
|
|
adb580b344 | ||
|
|
06405f2129 | ||
|
|
d1fd2c4ad4 | ||
|
|
b6c6379bfa | ||
|
|
8f0e66b72e | ||
|
|
f63cf6ff7a | ||
|
|
de8d8cc432 | ||
|
|
3d853cb295 | ||
|
|
d2419ed49d | ||
|
|
9b5ce8c64f | ||
|
|
058793c73a | ||
|
|
ab9ebea592 | ||
|
|
7ee37ee4b9 | ||
|
|
3171d524f0 | ||
|
|
3e78a8d500 | ||
|
|
fcba912cc4 | ||
|
|
7170eeea5f | ||
|
|
e3eb048c7a | ||
|
|
a59e92435b | ||
|
|
108895fc04 | ||
|
|
abc293c642 | ||
|
|
da3a498a28 | ||
|
|
bb44671845 | ||
|
|
09e480036a | ||
|
|
249f969110 | ||
|
|
4f8acec2d8 | ||
|
|
34339f61ee | ||
|
|
4045378cb4 | ||
|
|
4f99bc54f1 | ||
|
|
913f4a9c5f | ||
|
|
25d1c18a3f | ||
|
|
d09dd4d0b2 | ||
|
|
474fb042da | ||
|
|
8435c3d7be | ||
|
|
e783d0a62e | ||
|
|
b05f575e9b | ||
|
|
f5e9f01811 | ||
|
|
ff7dbb5867 | ||
|
|
e34b2b4f1d | ||
|
|
15c2f274ea | ||
|
|
37249339ac | ||
|
|
c422d16beb | ||
|
|
66cd50f603 | ||
|
|
caa529c282 | ||
|
|
51a4379bf4 | ||
|
|
acf98ed10e | ||
|
|
d1c07a091e | ||
|
|
105a21548f | ||
|
|
1734aa1664 | ||
|
|
ca11b236a7 | ||
|
|
6fdff8227d | ||
|
|
330e12d3c2 | ||
|
|
8fc58e0806 | ||
|
|
b468ca79c3 | ||
|
|
d2c7e4e96a | ||
|
|
1c7003ff68 | ||
|
|
1b44364e78 | ||
|
|
ec77f4a4f5 | ||
|
|
f611dd6e96 | ||
|
|
07b7c1a1e0 | ||
|
|
51fd58d74f | ||
|
|
faae9c2f7c | ||
|
|
bc3a6e4646 | ||
|
|
b09b03e35e | ||
|
|
16231947e7 | ||
|
|
39b9a38fbc | ||
|
|
bd855abec9 | ||
|
|
7c3c2e9f64 | ||
|
|
c10f8ae2e2 | ||
|
|
a0bf33eca6 | ||
|
|
88dd9c715d | ||
|
|
a3e21df814 | ||
|
|
d3b94c9241 | ||
|
|
c1d7599829 | ||
|
|
d11936f292 | ||
|
|
17363edf25 | ||
|
|
279cbbbb8a | ||
|
|
486cd4c343 | ||
|
|
25feceb783 | ||
|
|
d26752250d | ||
|
|
b15453c369 | ||
|
|
04ba8c8bc3 | ||
|
|
6570692291 | ||
|
|
f73d55ddaa | ||
|
|
13aa5b3375 | ||
|
|
0fcc02fbea | ||
|
|
c03883ccf0 | ||
|
|
134a9eac9d | ||
|
|
1e4ba8f4c7 | ||
|
|
950e484af6 | ||
|
|
9167f0a416 | ||
|
|
3af8992d23 | ||
|
|
9332a5eac8 | ||
|
|
9fddf15d2a | ||
|
|
f793af5a12 | ||
|
|
1436721c3e | ||
|
|
5f48b13144 | ||
|
|
6d8de0ade4 | ||
|
|
1587ff5e74 | ||
|
|
f033d3a6df | ||
|
|
145e0e0b5d | ||
|
|
9b7d7021af | ||
|
|
e41c22ef44 | ||
|
|
5fc2bd393e | ||
|
|
55271403fb | ||
|
|
36fba66619 | ||
|
|
66eb12294a | ||
|
|
73b22ec29b | ||
|
|
c31ae2f3b5 | ||
|
|
76b53d6b5b | ||
|
|
a34dfed378 | ||
|
|
b9b127a7ea | ||
|
|
2741e7b7b3 | ||
|
|
1767a56d4f | ||
|
|
779e6c2d2f | ||
|
|
73c831747b | ||
|
|
10b824fcac | ||
|
|
e5d3541b5a | ||
|
|
79755e76ea | ||
|
|
35f158d526 | ||
|
|
6962e09dd9 | ||
|
|
4c4cbd44da | ||
|
|
26eca8b6ba | ||
|
|
62b17f40a1 | ||
|
|
511b8a992e | ||
|
|
7dccc7ba2f | ||
|
|
70c90687fd | ||
|
|
8144ffd5c8 | ||
|
|
0ab977c236 | ||
|
|
224f0de353 | ||
|
|
6b45d311ec | ||
|
|
d54de441d3 | ||
|
|
1821bf7051 | ||
|
|
d42b5d4e78 | ||
|
|
754f3bcbc3 | ||
|
|
36973d4a6f | ||
|
|
c89d19b300 | ||
|
|
fc9616026b | ||
|
|
1e6bc81cfd | ||
|
|
1a149475e0 | ||
|
|
e5166841db | ||
|
|
bb9b2d1758 | ||
|
|
76c064c729 | ||
|
|
d2f652f436 | ||
|
|
6a452a54d5 | ||
|
|
9e5693e74f | ||
|
|
528b1a2307 | ||
|
|
0cc978ec1d | ||
|
|
d312422ab4 | ||
|
|
fee736933b | ||
|
|
09c92aa0b5 | ||
|
|
8c67b3ae64 | ||
|
|
000e4ceb4e | ||
|
|
a2a4fba626 | ||
|
|
5c99846ecf | ||
|
|
cc32f5ff61 | ||
|
|
fbff68b9e0 | ||
|
|
7e1a543b79 | ||
|
|
d475aaba96 | ||
|
|
96f55570f7 | ||
|
|
0906aeca87 | ||
|
|
7333619f15 | ||
|
|
97c0487add | ||
|
|
74b862d8b8 | ||
|
|
2db8df8e38 | ||
|
|
a576088d5f | ||
|
|
66ff916838 | ||
|
|
7b0453074e | ||
|
|
a000eb523d | ||
|
|
18a4fedc7f | ||
|
|
5d6cdccda0 | ||
|
|
1b7f4ac3e1 | ||
|
|
afc1a5b814 | ||
|
|
7ed38db54f | ||
|
|
28c10f4e69 | ||
|
|
6e12441a3b | ||
|
|
65c439c18d | ||
|
|
0ed2d16596 | ||
|
|
db335ac616 | ||
|
|
e8bb350467 | ||
|
|
5331d51f27 | ||
|
|
755ca75879 | ||
|
|
2398ebad55 | ||
|
|
c1bf298216 | ||
|
|
e005208d76 | ||
|
|
d1df70d02f | ||
|
|
f81acd0760 | ||
|
|
636da4c932 | ||
|
|
cccb77b552 | ||
|
|
2bd646ad70 | ||
|
|
52c1fa025e | ||
|
|
680105f84d | ||
|
|
f7069e9548 | ||
|
|
793840cdb4 | ||
|
|
8f421de532 | ||
|
|
be2dd60ee7 | ||
|
|
ea3e0b713e | ||
|
|
8179d5a8a4 | ||
|
|
6fa7abe434 | ||
|
|
5135c22cd6 | ||
|
|
1e27990561 | ||
|
|
e1e9fc43c1 | ||
|
|
b2921518ac | ||
|
|
dd64adbeeb | ||
|
|
616d41c06a | ||
|
|
e0e337aeb9 | ||
|
|
d52839fced | ||
|
|
56073ded69 | ||
|
|
9738a53f49 | ||
|
|
be3f8dbf7e | ||
|
|
9c6c3612a8 | ||
|
|
19e1a4447a | ||
|
|
36efcc6e28 | ||
|
|
a337ecf35c | ||
|
|
3595d47a9d | ||
|
|
82a00093b6 | ||
|
|
fb95813fbf | ||
|
|
db63f9b5d6 | ||
|
|
25f6c4a250 | ||
|
|
b24ae74216 | ||
|
|
59ad8f40dc | ||
|
|
ff03dc6a2c | ||
|
|
dc7187ca5b | ||
|
|
b1dcff778c | ||
|
|
198b3f4a40 | ||
|
|
9fee7f488e | ||
|
|
c1241a98e2 | ||
|
|
8d8f5970ee | ||
|
|
f90120f846 | ||
|
|
0b94d36c4a | ||
|
|
152c310bb7 | ||
|
|
f6bbca35ab | ||
|
|
c8cee6a209 | ||
|
|
b5701f416b | ||
|
|
4b1a404fcb | ||
|
|
67669196ed | ||
|
|
5c817a9b42 | ||
|
|
e08f68ed7c | ||
|
|
f09ed25fd3 | ||
|
|
58fd9bf964 | ||
|
|
7b3dfc67bc | ||
|
|
cdd24052d3 | ||
|
|
733fd8edab | ||
|
|
af27f2b8bc | ||
|
|
2e1925d762 | ||
|
|
77254bd074 | ||
|
|
5b6342e6ac | ||
|
|
e166e56249 | ||
|
|
560c020477 | ||
|
|
aec65e3be3 | ||
|
|
f44f0702f8 | ||
|
|
b76b79068f | ||
|
|
1db23979e8 | ||
|
|
c3d5dbe96f | ||
|
|
3a828bb14c | ||
|
|
c93f57a02a | ||
|
|
dd0d99e64b | ||
|
|
96f28fc5d5 | ||
|
|
85f6a29477 | ||
|
|
13a1fbe946 | ||
|
|
1f82eedbef | ||
|
|
d9e5506949 | ||
|
|
6628e20d8c | ||
|
|
64e2a43259 | ||
|
|
febd409cca | ||
|
|
5484489406 | ||
|
|
0ac52da460 | ||
|
|
817cebb321 | ||
|
|
683f3709d6 | ||
|
|
dbd42a42b2 | ||
|
|
ec24baf757 | ||
|
|
dea3e74d35 | ||
|
|
a6c3042e34 | ||
|
|
861537c9bd | ||
|
|
8c92cb0883 | ||
|
|
89d7be9525 | ||
|
|
2b79d7f22f | ||
|
|
163fe287ce | ||
|
|
70988d387b | ||
|
|
ddaa9d2436 | ||
|
|
7b7b258c38 | ||
|
|
cf74ed2f0c | ||
|
|
c3762328a5 | ||
|
|
e333fbea3d | ||
|
|
efbe36d1d4 | ||
|
|
8553cfa40e | ||
|
|
30d5c95b26 | ||
|
|
d1e3195e6f | ||
|
|
ce53d3a287 | ||
|
|
5f58248016 | ||
|
|
4cc99e7449 | ||
|
|
71773fe032 | ||
|
|
a1e0fa0f39 | ||
|
|
fc2f0b6983 | ||
|
|
5c9997cdac | ||
|
|
07d6689d87 | ||
|
|
14cb2b95c6 | ||
|
|
fdeef48498 |
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
cargo fetch --manifest-path rust/Cargo.toml
|
||||
if [ ! -f rust/proxypilot-rs.toml ]; then
|
||||
cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- init --config rust/proxypilot-rs.toml
|
||||
fi
|
||||
@@ -0,0 +1,86 @@
|
||||
# Architecture
|
||||
|
||||
High-level system guidance for the Rust terminal operator-console slice.
|
||||
|
||||
**What belongs here:** module boundaries, state ownership, data flow, invariants, and where workers should add new behavior.
|
||||
**What does not belong here:** low-level implementation diffs or line-by-line rewrite plans.
|
||||
|
||||
---
|
||||
|
||||
## Current Rust Entry Points
|
||||
|
||||
- `rust/proxypilot-rs/src/main.rs` wires CLI entrypoints.
|
||||
- `cli.rs` defines command surfaces.
|
||||
- `accounts.rs` handles CLI account operations against disk-backed account state.
|
||||
- `config.rs` loads TOML config and resolves the state-file path.
|
||||
- `state.rs` owns persisted local account state.
|
||||
- `codex.rs` owns Codex device login and refresh-token exchange logic.
|
||||
- `proxy.rs` owns the local HTTP proxy process and current in-memory proxy state.
|
||||
- `tui.rs` owns the terminal operator console.
|
||||
|
||||
## State Layers
|
||||
|
||||
There are three distinct state layers in this mission. Workers must keep them separate and truthful:
|
||||
|
||||
1. **Config state**
|
||||
- Loaded from TOML via `config.rs`
|
||||
- Includes bind address, state-file path, upstream base URL, and fallback API key
|
||||
|
||||
2. **Saved local account state**
|
||||
- Loaded and saved through `state.rs`
|
||||
- Used by CLI account commands and by the TUI for disk-backed account visibility and local actions
|
||||
|
||||
3. **Live runtime state**
|
||||
- Lives inside the running proxy process
|
||||
- Includes the adopted active credential, request counters, refresh attempts/results, and any runtime-auth summary shown by `/v0/runtime/stats`
|
||||
- Must not silently re-read disk on every stats request and pretend disk changes already altered runtime memory
|
||||
|
||||
## Desired Shared Domain for This Mission
|
||||
|
||||
This milestone should create a small shared auth/runtime domain used by both proxy and TUI-facing logic. It should own:
|
||||
|
||||
- RFC3339 parsing / clock helpers
|
||||
- auth-health classification with the shared vocabulary:
|
||||
- `valid`
|
||||
- `expiring_soon`
|
||||
- `expired`
|
||||
- `static`
|
||||
- `unknown`
|
||||
- refresh outcome/status types
|
||||
- runtime stats snapshot types for `/v0/runtime/stats`
|
||||
|
||||
The goal is to remove duplicated auth/time decision logic currently spread across `proxy.rs` and `tui.rs`.
|
||||
|
||||
## Runtime Stats Surface
|
||||
|
||||
`GET /v0/runtime/stats` is a read-only local operator endpoint.
|
||||
|
||||
It should expose runtime-memory state for:
|
||||
- bind address
|
||||
- upstream base URL
|
||||
- active account name
|
||||
- account count
|
||||
- auth-health summary
|
||||
- request counters
|
||||
- last runtime refresh status
|
||||
- last runtime refresh timestamp
|
||||
|
||||
This endpoint is the runtime source of truth for the TUI's operator-health panels.
|
||||
|
||||
## TUI Composition Model
|
||||
|
||||
The TUI should combine two inputs:
|
||||
|
||||
- **Disk-backed local state** for account list, selected-account details, and local account actions
|
||||
- **Runtime stats HTTP data** for live auth/runtime visibility
|
||||
|
||||
This split is intentional. The UI must stay truthful if local saved state and running runtime state diverge.
|
||||
|
||||
## Mission Invariants
|
||||
|
||||
- The branch remains Codex-only for this mission.
|
||||
- The TUI remains terminal-first and should become more operator-console-like, not more dashboard-like.
|
||||
- Runtime counters are in-memory only and reset when the proxy process restarts.
|
||||
- `R` targets the active account runtime action; `f` targets the selected saved account action.
|
||||
- `r` reloads local/disk and runtime surfaces; `c` clears transient feedback only.
|
||||
- Empty states and failures must stay readable and operator-meaningful.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Environment
|
||||
|
||||
Environment variables, external dependencies, and setup notes.
|
||||
|
||||
**What belongs here:** required env vars, local setup notes, external dependency expectations, and fixture guidance.
|
||||
**What does not belong here:** service start/stop commands or fixed ports outside explanatory notes.
|
||||
|
||||
---
|
||||
|
||||
## External Dependencies
|
||||
|
||||
- No external database, cache, or queue is required for this mission.
|
||||
- No live Codex/OpenAI credentials are required for baseline automated validation.
|
||||
- Use mocked local HTTP fixtures for upstream proxy and refresh-token flows unless the user explicitly expands scope to live credentials.
|
||||
|
||||
## Local Config Notes
|
||||
|
||||
- The Rust slice uses a TOML config and a separate state file.
|
||||
- Run `./.factory/init.sh` to fetch Rust dependencies and create `rust/proxypilot-rs.toml` if it is missing before local smoke validation.
|
||||
- Workers may generate temporary local configs for smoke validation.
|
||||
- Relative state-file paths resolve relative to the chosen config file path.
|
||||
|
||||
## Local Runtime Notes
|
||||
|
||||
- The default Rust bind is `127.0.0.1:8318`.
|
||||
- Keep runtime observability surfaces on the same local Rust proxy process.
|
||||
- Avoid unrelated busy ports already present on the machine.
|
||||
@@ -0,0 +1,97 @@
|
||||
# User Testing
|
||||
|
||||
Validation guidance for the Rust terminal operator-console mission.
|
||||
|
||||
**What belongs here:** validation surfaces, tools, setup notes, and concurrency guidance.
|
||||
**What does not belong here:** service command definitions (use `.factory/services.yaml`).
|
||||
|
||||
---
|
||||
|
||||
## Validation Surface
|
||||
|
||||
### HTTP runtime surface
|
||||
- Endpoints:
|
||||
- `GET /healthz`
|
||||
- `GET /v0/runtime/stats`
|
||||
- supported local Codex proxy routes touched by runtime tracking
|
||||
- Primary tools:
|
||||
- `curl`
|
||||
- Rust mocked endpoint tests
|
||||
- Validation focus:
|
||||
- local health identity
|
||||
- runtime stats schema and semantics
|
||||
- request counters
|
||||
- proactive refresh
|
||||
- 401 retry refresh
|
||||
- refresh failure tracking
|
||||
|
||||
### TUI surface
|
||||
- Command:
|
||||
- `cargo run -p proxypilot-rs -- tui --config <path>`
|
||||
- Primary tools:
|
||||
- `tuistory`
|
||||
- manual local smoke when needed
|
||||
- Validation focus:
|
||||
- runtime/auth visibility
|
||||
- truthful footer/help text
|
||||
- local account visibility when runtime is down
|
||||
- reload, clear feedback, selected refresh, active refresh-now
|
||||
- readable empty/error states
|
||||
|
||||
### CLI/account surface
|
||||
- Commands:
|
||||
- `init`
|
||||
- `account add-codex`
|
||||
- `account list`
|
||||
- `account activate`
|
||||
- `account remove`
|
||||
- `account refresh-codex`
|
||||
- Primary tools:
|
||||
- shell
|
||||
- Validation focus:
|
||||
- config creation semantics
|
||||
- disk-backed account lifecycle semantics
|
||||
- refreshable vs static-account behavior
|
||||
|
||||
## Validation Concurrency
|
||||
|
||||
- Automated Rust validation activities: max `2` concurrent
|
||||
- rationale: machine has ample memory/CPU, but Rust tests plus local mocked listener flows should stay conservative
|
||||
- Manual TUI validation: max `1` at a time
|
||||
- rationale: interactive terminal verification is not realistically parallel and should not overlap with another heavy manual runtime smoke
|
||||
|
||||
## Setup Notes
|
||||
|
||||
- Baseline automated validation does not require live external credentials.
|
||||
- Prefer mocked local upstream and refresh fixtures for HTTP/runtime tests.
|
||||
- TUI validation requires a local config file and usually a running local Rust proxy for runtime-visible scenarios.
|
||||
- Proxy-down scenarios are also required: validators should verify local disk-backed account visibility when runtime is unreachable.
|
||||
|
||||
## Flow Validator Guidance: shell
|
||||
- Use only `.factory/validation/terminal-operator-console/user-testing/fixtures/cli-shell/` plus `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/`.
|
||||
- Use temporary config/state files inside that fixture directory; do not modify repo-root default configs.
|
||||
- Stay on CLI/account flows only; do not start long-lived proxy services from this fixture.
|
||||
- Do not use live device-login. Prefer `init`, `account add-codex`, `account list`, `account activate`, `account remove`, and negative-path `account refresh-codex` checks against local fixture state.
|
||||
- If refresh-success validation cannot be isolated without live OpenAI OAuth, record it as blocked with concrete evidence rather than using private credentials.
|
||||
|
||||
|
||||
## Flow Validator Guidance: curl
|
||||
- Use only `.factory/validation/terminal-operator-console/user-testing/fixtures/http-runtime/` plus `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/`.
|
||||
- Own ports `18318-18339` for this validator only. Keep the proxy on `127.0.0.1:18318` unless a collision forces another port in that range.
|
||||
- Mock the Codex upstream locally; never send `/v1/*` validation traffic to the real OpenAI upstream.
|
||||
- Auth-refresh success paths may be blocked if the running binary cannot be pointed at a local OAuth token stub. Failure-path validation with intentionally invalid refresh tokens is allowed if it stays within the assigned fixture.
|
||||
- Capture before/after `curl` output for stats-changing requests so counter deltas are explicit.
|
||||
|
||||
|
||||
## Flow Validator Guidance: tuistory
|
||||
- Use only `.factory/validation/terminal-operator-console/user-testing/fixtures/tui-console/` plus `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/`.
|
||||
- Run only one TUI session at a time.
|
||||
- Own ports `18418-18439` for proxy/mock services used by this validator. Keep runtime-down scenarios fully local by stopping those fixture services instead of touching shared ports.
|
||||
- Keep disk-backed state isolated to the assigned fixture config/state files so reload, activate, delete, and refresh actions are attributable to this validator alone.
|
||||
- Capture snapshots before and after each key flow (`r`, `a`, `d`, `f`, `R`, `c`) and note whether feedback came from local disk state or live runtime stats.
|
||||
|
||||
## Discovered Validation Quirks
|
||||
|
||||
- CLI `account refresh-codex` and runtime-triggered refresh paths now honor `codex.refresh_token_url` when set, so validators can redirect refresh success to a local stub from the real user surface while still relying on the built-in OpenAI OAuth endpoint when the override is unset.
|
||||
- `tuistory` sessions should be closed explicitly after the TUI exits with `q`; the PTY can remain allocated even after the binary terminates.
|
||||
- In runtime-down TUI scenarios, selected-account refresh (`f`) still attempts the hardwired OAuth refresh exchange for refreshable saved accounts and surfaces that remote failure text. Treat that as truthful runtime-dependent behavior, not as loss of local disk state.
|
||||
@@ -0,0 +1,16 @@
|
||||
commands:
|
||||
install: cargo fetch --manifest-path rust/Cargo.toml
|
||||
init: ./.factory/init.sh
|
||||
fmt: cargo fmt --all --manifest-path rust/Cargo.toml
|
||||
test: cargo test --manifest-path rust/Cargo.toml
|
||||
typecheck: cargo check --manifest-path rust/Cargo.toml
|
||||
lint: cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings
|
||||
tui-help: cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- tui --help
|
||||
|
||||
services:
|
||||
proxypilot-rs:
|
||||
start: cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- run --config rust/proxypilot-rs.toml
|
||||
stop: lsof -ti :8318 | xargs -r kill
|
||||
healthcheck: curl -sf http://127.0.0.1:8318/healthz
|
||||
port: 8318
|
||||
depends_on: []
|
||||
@@ -0,0 +1,89 @@
|
||||
---
|
||||
name: rust-operator-worker
|
||||
description: Implement Rust terminal-operator-console features for proxypilot-rs with test-first discipline and truthful runtime/TUI verification.
|
||||
---
|
||||
|
||||
# Rust Operator Worker
|
||||
|
||||
NOTE: Startup and cleanup are handled by `worker-base`. This skill defines the WORK PROCEDURE.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use for features in the Rust replatform slice that touch `proxypilot-rs` runtime/auth logic, local HTTP observability, CLI/account coherence, or the terminal operator console.
|
||||
|
||||
## Required Skills
|
||||
|
||||
- `tdd` — invoke before implementation to drive failing tests first for new runtime/auth/TUI helper behavior.
|
||||
- `tuistory` — invoke when manually validating terminal operator-console behavior.
|
||||
- `verification-before-completion` — invoke before claiming the feature is complete so evidence matches the actual commands and outputs.
|
||||
|
||||
## Work Procedure
|
||||
|
||||
1. Read `mission.md`, `validation-contract.md`, mission `AGENTS.md`, and `.factory/library/*.md` relevant to the feature before editing.
|
||||
2. Confirm which validation assertions the feature fulfills and restate them in your notes.
|
||||
3. Write or update failing Rust tests first (red) for the feature's intended behavior before changing implementation.
|
||||
4. Implement the smallest Rust changes needed to make those tests pass while preserving the mission boundaries:
|
||||
- keep the work inside the Rust replatform slice unless docs are explicitly part of the feature
|
||||
- prefer shared auth/runtime helpers over duplicating logic
|
||||
- keep runtime-memory state distinct from disk-backed saved state
|
||||
5. Run focused checks during iteration, then the required final validators:
|
||||
- `cargo fmt --all --manifest-path rust/Cargo.toml`
|
||||
- `cargo test --manifest-path rust/Cargo.toml`
|
||||
6. If the feature affects the TUI or runtime observability surface, perform manual verification with `tuistory` or equivalent local smoke and capture what changed on screen or via local HTTP output.
|
||||
7. Review the changed files for truthfulness of operator-visible wording, especially where runtime state and disk state can diverge.
|
||||
8. Produce a handoff that cites exact commands, tests added, interactive checks, and any discovered gaps.
|
||||
|
||||
## Example Handoff
|
||||
|
||||
```json
|
||||
{
|
||||
"salientSummary": "Added a shared auth-health/runtime model plus `/v0/runtime/stats`, then wired the TUI runtime panel to the new stats surface. Ran fmt/tests successfully and manually verified runtime counters plus active-account refresh feedback in the terminal UI.",
|
||||
"whatWasImplemented": "Created a shared runtime/auth module for auth-health classification and refresh status, extended proxy state with in-memory counters and last refresh metadata, added GET /v0/runtime/stats with stable fields, and updated the TUI to render runtime stats while keeping disk-backed account controls separate.",
|
||||
"whatWasLeftUndone": "",
|
||||
"verification": {
|
||||
"commandsRun": [
|
||||
{
|
||||
"command": "cargo fmt --all --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0,
|
||||
"observation": "Formatting completed without changes needed after final pass."
|
||||
},
|
||||
{
|
||||
"command": "cargo test --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0,
|
||||
"observation": "Workspace tests passed, including new runtime stats and auth-health cases."
|
||||
}
|
||||
],
|
||||
"interactiveChecks": [
|
||||
{
|
||||
"action": "Launched proxypilot-rs TUI against a local fixture config, pressed `r`, `R`, and `c`, and inspected the runtime/auth panel.",
|
||||
"observed": "Runtime counters and last refresh outcome became visible, active-account refresh targeted the active account even when another row was selected, and clear-feedback only cleared the transient status line."
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": {
|
||||
"added": [
|
||||
{
|
||||
"file": "rust/proxypilot-rs/src/proxy.rs",
|
||||
"cases": [
|
||||
{
|
||||
"name": "runtime_stats_reset_after_restart",
|
||||
"verifies": "In-memory runtime stats start empty on fresh process start and do not persist across restarts."
|
||||
},
|
||||
{
|
||||
"name": "runtime_stats_reports_401_refresh_path_once",
|
||||
"verifies": "A single client request that triggers 401 and retry increments upstream 401 and refresh counters without double-counting total proxied requests."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"discoveredIssues": []
|
||||
}
|
||||
```
|
||||
|
||||
## When to Return to Orchestrator
|
||||
|
||||
- The feature requires changing mission boundaries or touching non-Rust product surfaces outside the approved scope.
|
||||
- The intended behavior cannot be implemented truthfully without clarifying runtime-vs-disk ownership semantics.
|
||||
- A required local validation path cannot be exercised because config/fixtures/runtime setup is missing or broken.
|
||||
- The feature reveals a larger refactor is needed than fits a single worker session.
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"featureId": "cli-state-runtime-truthfulness-and-docs",
|
||||
"reviewedAt": "2026-04-05T10:54:50.137470Z",
|
||||
"commitId": "1c2396bb",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "fail",
|
||||
"codeReview": {
|
||||
"summary": "Reviewed feature commit 1c2396bb together with the directly relevant follow-up fixes f4ae033c and cea7a0f4. CLI wording, docs alignment, static-account refresh errors, and runtime-vs-disk refresh targeting are much clearer after those changes, but the TUI footer layout still prevents the new explanatory copy from being visible.",
|
||||
"issues": [
|
||||
{
|
||||
"file": "rust/proxypilot-rs/src/tui.rs",
|
||||
"line": 389,
|
||||
"severity": "blocking",
|
||||
"description": "The footer block is still allocated `Constraint::Length(3)` even though it now renders four content lines (feedback, selected-account hint, runtime status hint, and key help) inside a bordered paragraph at lines 523-534. In ratatui that height leaves room for only a single inner text row, so the newly added runtime/disk guidance and keybinding help are clipped off-screen. That means the feature does not actually make the cross-surface behavior explicit to operators, and docs/tests now describe footer copy that users cannot see."
|
||||
}
|
||||
]
|
||||
},
|
||||
"sharedStateObservations": [
|
||||
{
|
||||
"area": "skills",
|
||||
"observation": "TUI copy changes in this mission need a visibility check, not just string-helper tests. The current worker skill and tests verified footer text helpers, but they did not verify that the fixed-height footer block can actually render the added lines.",
|
||||
"evidence": "rust/proxypilot-rs/src/tui.rs:389 keeps the footer at `Constraint::Length(3)` while rust/proxypilot-rs/src/tui.rs:523-534 renders four lines; the added tests at rust/proxypilot-rs/src/tui.rs:770-842 assert string content only and do not exercise visible layout fit."
|
||||
}
|
||||
],
|
||||
"addressesFailureFrom": null,
|
||||
"summary": "Fail: the reviewed feature and its direct follow-up fixes improved CLI/runtime truthfulness, but the TUI footer's fixed height still clips the newly added selected-account/runtime hints and key help, so an operator cannot see the copy intended to explain runtime-vs-disk divergence."
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"featureId": "fix-runtime-account-count-semantics",
|
||||
"reviewedAt": "2026-04-05T11:36:06.651055Z",
|
||||
"commitId": "91fe6562",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "pass",
|
||||
"codeReview": {
|
||||
"summary": "Reviewed the original runtime-stats feature (`1b3542d7`), the prior scrutiny finding, and the fix commit (`91fe6562`). The fix resolves the remaining non-blocking truthfulness issue: `/v0/runtime/stats.account_count` now counts only runtime-usable Codex accounts, mixed-provider and blank-key entries no longer inflate that value, and the TUI wording matches the runtime semantics.",
|
||||
"issues": []
|
||||
},
|
||||
"sharedStateObservations": [
|
||||
{
|
||||
"area": "skills",
|
||||
"observation": "The worker skipped the rust-operator-worker skill's required manual `tuistory` verification even though the feature touched TUI-visible runtime wording. For this fix the unit-level wording assertion was likely sufficient, but the skill currently leaves that lightweight label-only case undocumented.",
|
||||
"evidence": "Skill procedure step 6 requires manual verification with `tuistory` when the feature affects the TUI or runtime observability surface (`/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/skills/rust-operator-worker/SKILL.md`). The handoff for session `38bb865f-5bfd-4b20-8a75-281170e69c06` records `followedProcedure: false` and says manual TUI verification was skipped in favor of unit tests because the change was only label alignment."
|
||||
}
|
||||
],
|
||||
"addressesFailureFrom": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/proxy-runtime-stats-surface.json",
|
||||
"summary": "Pass. The follow-up fix closes the prior `account_count` truthfulness gap and I found no new code issues in the scoped change."
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"featureId": "fix-runtime-auth-health-and-date-validation",
|
||||
"reviewedAt": "2026-04-05T10:53:54.938311Z",
|
||||
"commitId": "f4ae033c97c0912c03c0a0eaa9b14a2aeb696f8f",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "pass",
|
||||
"codeReview": {
|
||||
"summary": "Reviewed commit `f4ae033c97c0912c03c0a0eaa9b14a2aeb696f8f` against the feature requirements and worker handoff. The implementation now rejects impossible RFC3339 calendar dates in `auth_runtime::parse_rfc3339_z`, classifies malformed impossible expiry metadata as `unknown`, and recomputes `/v0/runtime/stats` auth health from the live in-memory account state after proactive and 401-triggered refresh mutations. The targeted regressions in `auth_runtime.rs` and `proxy.rs` cover invalid leap-day/month-end inputs plus successful and failed refresh paths, and I found no remaining high-confidence correctness issues in scope.",
|
||||
"issues": []
|
||||
},
|
||||
"sharedStateObservations": [],
|
||||
"addressesFailureFrom": null,
|
||||
"summary": "Pass. The reviewed fix closes the two reported blockers: impossible RFC3339 calendar dates no longer parse as valid expiries, and proxy runtime stats now report refreshed auth health truthfully after runtime credential mutations."
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"featureId": "fix-tui-footer-and-passive-polling",
|
||||
"reviewedAt": "2026-04-05T11:36:55Z",
|
||||
"commitId": "67c79b9dc5755305448c33df5cb1d761f150bece",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "fail",
|
||||
"codeReview": {
|
||||
"summary": "Reviewed the fix commit together with both prior failed reviews (`terminal-tui-operator-console` and `cli-state-runtime-truthfulness-and-docs`). The passive-polling blocker is resolved: idle polling now stays on `/healthz` + `/v0/runtime/stats`, and the new regression test proves it no longer calls `/v1/models`. However, the footer visibility blocker is only partially fixed: the panel now fits the four nominal footer lines, but realistic long feedback still wraps and pushes the help text back out of view.",
|
||||
"issues": [
|
||||
{
|
||||
"file": "rust/proxypilot-rs/src/tui.rs",
|
||||
"line": 396,
|
||||
"severity": "blocking",
|
||||
"description": "The footer still has a fixed height of `Constraint::Length(6)`, which leaves only four inner text rows once the bordered `Keys` block is rendered (`tui.rs:530-543`). That is enough only when the feedback line stays on a single row. But routine operator messages in this same file are much longer\u2014for example the `runtime_refresh_target` failure text at `tui.rs:701-708` is 131 characters before account-name variation, so in the worker's own 120-column verification geometry it wraps to two rows. When that happens, one of the status/help lines is clipped again, so the feature does not fully satisfy the prior blocker of keeping all footer/help guidance visible. The added snapshot test (`tui.rs:943-975`) only exercises a short `Feedback line`, so it misses this realistic wrapped-feedback path."
|
||||
}
|
||||
]
|
||||
},
|
||||
"sharedStateObservations": [
|
||||
{
|
||||
"area": "skills",
|
||||
"observation": "The shared Rust operator-worker guidance still does not tell workers to exercise long, wrapped operator feedback when validating fixed-height TUI regions. That omission helped this fix reintroduce a footer-visibility edge case even though the worker followed the documented procedure and added a snapshot test.",
|
||||
"evidence": "`rust-operator-worker` step 6/7 asks for manual TUI verification and truthful operator-visible wording review, but it does not call out wrap/line-budget checks for fixed-height panels (`/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/skills/rust-operator-worker/SKILL.md`). In this fix, the new regression test in `rust/proxypilot-rs/src/tui.rs:943-975` only uses a one-line `Feedback line`, while the production footer can render much longer routine messages such as `runtime_refresh_target` at `tui.rs:701-708`."
|
||||
}
|
||||
],
|
||||
"addressesFailureFrom": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/terminal-tui-operator-console.json; /home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/cli-state-runtime-truthfulness-and-docs.json",
|
||||
"summary": "Fail. The fix successfully stops passive idle polling from contaminating runtime telemetry, but the footer/help blocker is not fully resolved because long, routine feedback messages can still wrap and hide guidance in the fixed-height footer."
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"featureId": "fix-tui-footer-wrap-visibility",
|
||||
"reviewedAt": "2026-04-05T12:02:30Z",
|
||||
"commitId": "159a3b21",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "pass",
|
||||
"codeReview": {
|
||||
"summary": "Reviewed the prior failed fix (`fix-tui-footer-and-passive-polling`) alongside the rerun fix commit `159a3b21`, the worker handoff, and the transcript skeleton. This rerun fully addresses the remaining footer-wrap blocker: the TUI now sizes the footer from its wrapped content instead of a fixed six-row region, and the regression test was updated to use the same long runtime-active-account failure wording that previously exposed clipping.",
|
||||
"issues": []
|
||||
},
|
||||
"sharedStateObservations": [],
|
||||
"addressesFailureFrom": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/reviews/fix-tui-footer-and-passive-polling.json",
|
||||
"summary": "Pass. The rerun replaces the fixed-height footer with content-based sizing and adds realistic long-message regression coverage, so the prior footer-wrap visibility failure is adequately resolved."
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"featureId": "fix-tui-runtime-truthfulness",
|
||||
"reviewedAt": "2026-04-05T10:51:50.745826Z",
|
||||
"commitId": "cea7a0f4",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "pass",
|
||||
"codeReview": {
|
||||
"summary": "The TUI change now drives `R` from the runtime stats active account, preserves truthful runtime-unavailable and missing-runtime-active feedback, and relabels runtime-memory account counts so they are no longer presented as disk state. The scoped tests cover the new runtime-vs-disk selection logic and wording, and I found no high-confidence correctness issues in the reviewed change.",
|
||||
"issues": []
|
||||
},
|
||||
"sharedStateObservations": [
|
||||
{
|
||||
"area": "skills",
|
||||
"observation": "Mission worker guidance does not explain that mission artifacts may live outside the repo under `/home/fsos/.factory/missions/<id>`. The reviewed worker initially tried repo-relative mission paths and hit ENOENT before switching to the absolute mission directory.",
|
||||
"evidence": "The transcript skeleton for worker session `da34164d-4575-44bf-b059-608a68652407` shows failed reads of `/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/{mission.md,validation-contract.md,AGENTS.md}` followed by successful reads from `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/...`; `rust-operator-worker` step 1 requires reading mission artifacts but does not document this path fallback."
|
||||
}
|
||||
],
|
||||
"addressesFailureFrom": null,
|
||||
"summary": "Pass. Commit `cea7a0f4` resolves the reviewed TUI truthfulness blockers: `R` now follows runtime-active state from `/v0/runtime/stats`, runtime-unavailable cases remain explicit without hiding disk-backed state, and the runtime count label no longer claims to be disk-backed."
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"featureId": "proxy-runtime-stats-surface",
|
||||
"reviewedAt": "2026-04-05T10:57:26.499831Z",
|
||||
"commitId": "1b3542d77c125df31d091f052ca872237c5932c6",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "pass",
|
||||
"codeReview": {
|
||||
"summary": "Reviewed the original runtime-stats implementation commit (`1b3542d7`) plus the directly relevant follow-up fix commit (`f4ae033c`). The feature now satisfies the core HTTP contract: `/v0/runtime/stats` is local-only, counters stay in memory and reset on restart, supported proxied requests are counted once per client request, proactive and 401-triggered refresh outcomes are surfaced, and post-refresh auth health is recomputed truthfully. I found one remaining non-blocking truthfulness gap in mixed-provider saved state.",
|
||||
"issues": [
|
||||
{
|
||||
"file": "rust/proxypilot-rs/src/proxy.rs",
|
||||
"line": 105,
|
||||
"severity": "non_blocking",
|
||||
"description": "`account_count` reports `accounts.accounts.len()`, which counts every saved entry loaded into memory, not just runtime-usable Codex accounts. That becomes untruthful in mixed-provider state because `AccountState` only treats `provider == \"codex\"` entries as active/refreshable (`rust/proxypilot-rs/src/state.rs:153`, `rust/proxypilot-rs/src/state.rs:170`, `rust/proxypilot-rs/src/state.rs:300`), while imported auth preserves arbitrary `provider_type` values from disk (`rust/proxypilot-rs/src/state.rs:232`). A non-Codex imported entry will inflate `/v0/runtime/stats.account_count` even though the runtime cannot actually use it."
|
||||
}
|
||||
]
|
||||
},
|
||||
"sharedStateObservations": [
|
||||
{
|
||||
"area": "conventions",
|
||||
"observation": "This feature updated `docs/rust-replatform.md` even though the mission guidance says only docs-alignment work should touch that file. The rule exists, but the worker still crossed it in the runtime-stats feature commit.",
|
||||
"evidence": "Mission AGENTS says `Docs ownership: only features explicitly scoped to docs alignment should update docs/rust-replatform.md or README.md` (`/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/AGENTS.md:59`), while commit `1b3542d7` changes `docs/rust-replatform.md` alongside `rust/proxypilot-rs/src/proxy.rs`."
|
||||
},
|
||||
{
|
||||
"area": "services",
|
||||
"observation": "Runtime-surface smoke verification depends on setup that is not represented in `.factory/services.yaml`: generating a config file and standing up a local mock upstream/refresh server. Workers had to do this ad hoc in the transcript instead of using shared service metadata.",
|
||||
"evidence": "`.factory/services.yaml:8-12` only defines `proxypilot-rs` start/stop/healthcheck. The reviewed worker transcript for session `f8120536-90d3-4124-9b6f-a84412e716f4` shows manual `.factory/init.sh`, temporary config creation, and a background mock HTTP server before the `curl` smoke documented in the handoff `2026-04-05T09-14-14-581Z__proxy-runtime-stats-surface__f8120536-90d3-4124-9b6f-a84412e716f4.json`."
|
||||
}
|
||||
],
|
||||
"addressesFailureFrom": null,
|
||||
"summary": "Pass with one non-blocking issue. The runtime stats surface works as intended after the direct follow-up fix, but `account_count` still overstates runtime-usable accounts when saved state contains non-Codex imported entries."
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"featureId": "shared-auth-runtime-domain",
|
||||
"reviewedAt": "2026-04-05T10:52:53.771197Z",
|
||||
"commitId": "1c3edd9f4a2493a2dcd27931a680c359c14c9f43",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "pass",
|
||||
"codeReview": {
|
||||
"summary": "The feature successfully extracted shared auth/runtime primitives into `auth_runtime.rs` and both proxy and TUI consumers were moved onto the shared RFC3339 parsing, auth-health classification, and runtime snapshot types. The only blocking correctness gap from the original commit (impossible calendar dates being accepted, plus stale runtime auth-health after refresh) was addressed by the directly relevant follow-up fix `f4ae033c`, so there are no remaining high-confidence issues in this review scope.",
|
||||
"issues": []
|
||||
},
|
||||
"sharedStateObservations": [
|
||||
{
|
||||
"area": "skills",
|
||||
"observation": "The worker had to deviate because the mission/bootstrap path guidance pointed at a repo-relative mission directory that did not exist; the recoverable fallback to `/home/fsos/.factory/missions/...` is not captured in the Rust worker guidance.",
|
||||
"evidence": "Handoff `2026-04-05T08-56-54-173Z__shared-auth-runtime-domain__132757c8-6967-4cb2-b929-a387c3429b02.json`: lines 100-115 record `followedProcedure: false` and explicitly ask to clarify handling when bootstrap paths point to a repo-relative mission directory that does not exist."
|
||||
},
|
||||
{
|
||||
"area": "services",
|
||||
"observation": "Local smoke/runtime setup depends on generating `rust/proxypilot-rs.toml` first, but the services manifest only advertises a start command that assumes that file already exists. The canonical setup helper is discoverable only via `.factory/init.sh` rather than the shared service metadata.",
|
||||
"evidence": "`.factory/services.yaml:9` starts proxypilot-rs with `--config rust/proxypilot-rs.toml`, while `.factory/init.sh:6-7` creates that file on demand before smoke validation."
|
||||
}
|
||||
],
|
||||
"addressesFailureFrom": null,
|
||||
"summary": "Reviewed the shared auth/runtime domain commit (`1c3edd9f4a2493a2dcd27931a680c359c14c9f43`), its transcript/handoff, and the directly relevant follow-up fix (`f4ae033c`). Result: pass, with no remaining actionable code defects in scope after the follow-up fix, plus two shared-state observations about mission path guidance and init/service discoverability."
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"featureId": "terminal-tui-operator-console",
|
||||
"reviewedAt": "2026-04-05T18:06:00Z",
|
||||
"commitId": "3da810d19a174aa439f079db9b4fb9ad3a15461e",
|
||||
"transcriptSkeletonReviewed": true,
|
||||
"diffReviewed": true,
|
||||
"status": "fail",
|
||||
"codeReview": {
|
||||
"summary": "Reviewed the original TUI feature commit `3da810d1` plus the directly relevant follow-up fix `cea7a0f4`. The console now shows runtime stats, handles runtime-unavailable cases more explicitly, and `R` now targets the runtime-reported active account, but two blocking truthfulness issues remain in the live console: the footer/help region is clipped by the fixed layout height, and the TUI's own background model polling mutates the runtime counters and refresh state it is supposed to observe.",
|
||||
"issues": [
|
||||
{
|
||||
"file": "rust/proxypilot-rs/src/tui.rs",
|
||||
"line": 389,
|
||||
"severity": "blocking",
|
||||
"description": "The footer block is still allocated `Constraint::Length(3)` while the `Keys` paragraph renders four separate content lines (`feedback`, selected-account hint, runtime hint, and key help at lines 525-532). With a bordered ratatui block that leaves only one inner text row, so the newly added help/runtime guidance is clipped off-screen. The feature therefore does not actually deliver readable, truthful footer/help text in the running console."
|
||||
},
|
||||
{
|
||||
"file": "rust/proxypilot-rs/src/tui.rs",
|
||||
"line": 113,
|
||||
"severity": "blocking",
|
||||
"description": "The idle poll path still calls `refresh_models()` whenever `/healthz` succeeds (`tui.rs:49-50`, `tui.rs:113-121`, `tui.rs:218-220`). That performs a real `GET /v1/models` through the local proxy, and the proxy counts every supported request and may trigger proactive refresh before forwarding (`proxy.rs:143-145`, `proxy.rs:264-267`). As a result, merely leaving the operator console open inflates `total_proxied_requests`/`successful_upstream_responses` and can change `last_refresh`, so the runtime counters and refresh outcome are not a truthful view of external runtime activity."
|
||||
}
|
||||
]
|
||||
},
|
||||
"sharedStateObservations": [
|
||||
{
|
||||
"area": "conventions",
|
||||
"observation": "Mission guidance says only docs-scoped features should edit `docs/rust-replatform.md`, but this TUI feature commit changed that file anyway.",
|
||||
"evidence": "Mission AGENTS `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/AGENTS.md:59` says `Docs ownership: only features explicitly scoped to docs alignment should update docs/rust-replatform.md or README.md`, while commit `3da810d1` changes `docs/rust-replatform.md` alongside `rust/proxypilot-rs/src/tui.rs`."
|
||||
},
|
||||
{
|
||||
"area": "skills",
|
||||
"observation": "For TUI work, helper-string tests are not enough; shared guidance should explicitly require a layout-fit check for any new multi-line regions.",
|
||||
"evidence": "`rust/proxypilot-rs/src/tui.rs:743-840` tests helper string content, but no test or skill step verifies that those lines fit inside the fixed-height footer/runtime blocks (`tui.rs:387-389`, `tui.rs:523-534`). The worker handoff for session `b1f2df79-2748-4890-a74a-2cb5e38b416c` reported footer/help validation even though the clipped layout remained."
|
||||
}
|
||||
],
|
||||
"addressesFailureFrom": null,
|
||||
"summary": "Fail. The feature and direct `cea7a0f4` follow-up improved runtime visibility and `R` targeting, but the live TUI still hides much of the footer/help copy and its own background polling contaminates the runtime counters and refresh status it displays."
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"milestone": "terminal-operator-console",
|
||||
"round": 3,
|
||||
"status": "pass",
|
||||
"validatorsRun": {
|
||||
"format": {
|
||||
"passed": true,
|
||||
"command": "cargo fmt --all --manifest-path rust/Cargo.toml -- --check",
|
||||
"exitCode": 0
|
||||
},
|
||||
"test": {
|
||||
"passed": true,
|
||||
"command": "cargo test --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0
|
||||
},
|
||||
"typecheck": {
|
||||
"passed": true,
|
||||
"command": "cargo check --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0
|
||||
},
|
||||
"lint": {
|
||||
"passed": true,
|
||||
"command": "cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings",
|
||||
"exitCode": 0
|
||||
}
|
||||
},
|
||||
"reviewsSummary": {
|
||||
"total": 1,
|
||||
"passed": 1,
|
||||
"failed": 0,
|
||||
"failedFeatures": []
|
||||
},
|
||||
"blockingIssues": [],
|
||||
"nonBlockingIssues": [],
|
||||
"appliedUpdates": [],
|
||||
"suggestedGuidanceUpdates": [],
|
||||
"rejectedObservations": [],
|
||||
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/synthesis.round2.json"
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
{
|
||||
"milestone": "terminal-operator-console",
|
||||
"round": 1,
|
||||
"status": "fail",
|
||||
"validatorsRun": {
|
||||
"format": {
|
||||
"passed": true,
|
||||
"command": "cargo fmt --all --manifest-path rust/Cargo.toml -- --check",
|
||||
"exitCode": 0
|
||||
},
|
||||
"test": {
|
||||
"passed": true,
|
||||
"command": "cargo test --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0
|
||||
},
|
||||
"typecheck": {
|
||||
"passed": true,
|
||||
"command": "cargo check --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0
|
||||
},
|
||||
"lint": {
|
||||
"passed": true,
|
||||
"command": "cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings",
|
||||
"exitCode": 0
|
||||
}
|
||||
},
|
||||
"reviewsSummary": {
|
||||
"total": 6,
|
||||
"passed": 4,
|
||||
"failed": 2,
|
||||
"failedFeatures": [
|
||||
"terminal-tui-operator-console",
|
||||
"cli-state-runtime-truthfulness-and-docs"
|
||||
]
|
||||
},
|
||||
"blockingIssues": [
|
||||
{
|
||||
"featureId": "terminal-tui-operator-console",
|
||||
"severity": "blocking",
|
||||
"description": "The TUI footer/help block still uses Constraint::Length(3) while rendering four content lines inside a bordered block, so the selected-account/runtime divergence copy and key help are clipped off-screen. This makes the console fail both the TUI readability contract and the CLI/runtime-truthfulness feature's operator-facing explanation goals."
|
||||
},
|
||||
{
|
||||
"featureId": "terminal-tui-operator-console",
|
||||
"severity": "blocking",
|
||||
"description": "The TUI background polling path still calls GET /v1/models whenever /healthz succeeds, which goes through the proxy and mutates total_proxied_requests, successful_upstream_responses, and potentially last_refresh/auth state. Leaving the console open therefore contaminates the runtime stats it is supposed to observe."
|
||||
}
|
||||
],
|
||||
"nonBlockingIssues": [
|
||||
{
|
||||
"featureId": "proxy-runtime-stats-surface",
|
||||
"severity": "non_blocking",
|
||||
"description": "runtime_stats.account_count currently reports all saved state entries rather than only runtime-usable Codex accounts, so mixed-provider saved state can overstate runtime-usable account count."
|
||||
}
|
||||
],
|
||||
"appliedUpdates": [
|
||||
{
|
||||
"target": "services.yaml",
|
||||
"description": "Added `init`, `typecheck`, and `lint` commands so scrutiny/user-testing workers can bootstrap the Rust slice and run the full validator suite from shared service metadata.",
|
||||
"sourceFeature": "scrutiny-validator-terminal-operator-console"
|
||||
},
|
||||
{
|
||||
"target": "library",
|
||||
"description": "Documented in `.factory/library/environment.md` that `./.factory/init.sh` fetches Rust dependencies and creates `rust/proxypilot-rs.toml` when missing before smoke validation.",
|
||||
"sourceFeature": "shared-auth-runtime-domain"
|
||||
}
|
||||
],
|
||||
"suggestedGuidanceUpdates": [
|
||||
{
|
||||
"target": "rust-operator-worker",
|
||||
"suggestion": "Clarify that mission artifacts may live under `/home/fsos/.factory/missions/<id>` even when repo-relative `.factory/missions/...` paths are absent, and instruct workers to fall back to the absolute mission directory before treating missing files as blockers.",
|
||||
"evidence": "Review reports for `shared-auth-runtime-domain` and `fix-tui-runtime-truthfulness` both recorded ENOENT attempts against repo-relative mission paths before successfully reading `/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/...`.",
|
||||
"isSystemic": true
|
||||
},
|
||||
{
|
||||
"target": "rust-operator-worker",
|
||||
"suggestion": "For TUI features that change visible copy or layout, require a layout-fit visibility check (render/snapshot or terminal smoke) in addition to helper-string assertions so multi-line regions are proven visible.",
|
||||
"evidence": "Both `terminal-tui-operator-console` and `cli-state-runtime-truthfulness-and-docs` failed review because the footer stayed at `Constraint::Length(3)` while rendering four lines, yet the worker tests only asserted helper-string content.",
|
||||
"isSystemic": true
|
||||
},
|
||||
{
|
||||
"target": "rust-operator-worker",
|
||||
"suggestion": "Reinforce the mission boundary that only docs-scoped features may edit `docs/rust-replatform.md` or `README.md`, and direct workers to defer such changes to the explicit docs-alignment feature when possible.",
|
||||
"evidence": "Review reports for `proxy-runtime-stats-surface` and `terminal-tui-operator-console` both recorded edits to `docs/rust-replatform.md` despite mission AGENTS guidance reserving docs changes for docs-alignment work.",
|
||||
"isSystemic": true
|
||||
}
|
||||
],
|
||||
"rejectedObservations": [
|
||||
{
|
||||
"observation": "Add a dedicated mock upstream/refresh service definition to `.factory/services.yaml` for runtime smoke validation.",
|
||||
"reason": "ambiguous: the reviewed mock servers were scenario-specific one-off fixtures with ad hoc ports and behavior, so a generic shared service entry would risk encoding the wrong workflow. The concrete bootstrap/config discovery gap was handled instead via additive command/library updates."
|
||||
}
|
||||
],
|
||||
"previousRound": null
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"milestone": "terminal-operator-console",
|
||||
"round": 2,
|
||||
"status": "fail",
|
||||
"validatorsRun": {
|
||||
"format": {
|
||||
"passed": true,
|
||||
"command": "cargo fmt --all --manifest-path rust/Cargo.toml -- --check",
|
||||
"exitCode": 0
|
||||
},
|
||||
"test": {
|
||||
"passed": true,
|
||||
"command": "cargo test --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0
|
||||
},
|
||||
"typecheck": {
|
||||
"passed": true,
|
||||
"command": "cargo check --manifest-path rust/Cargo.toml",
|
||||
"exitCode": 0
|
||||
},
|
||||
"lint": {
|
||||
"passed": true,
|
||||
"command": "cargo clippy --manifest-path rust/Cargo.toml --all-targets -- -D warnings",
|
||||
"exitCode": 0
|
||||
}
|
||||
},
|
||||
"reviewsSummary": {
|
||||
"total": 2,
|
||||
"passed": 1,
|
||||
"failed": 1,
|
||||
"failedFeatures": [
|
||||
"fix-tui-footer-and-passive-polling"
|
||||
]
|
||||
},
|
||||
"blockingIssues": [
|
||||
{
|
||||
"featureId": "fix-tui-footer-and-passive-polling",
|
||||
"severity": "blocking",
|
||||
"description": "The TUI footer still has a fixed six-row outer height, which leaves only four inner text rows inside the bordered keys block. Long routine feedback such as the runtime-active-account failure copy wraps at the validated terminal width, so one of the footer status/help lines becomes clipped again and the operator console still fails the footer-visibility contract."
|
||||
}
|
||||
],
|
||||
"nonBlockingIssues": [],
|
||||
"appliedUpdates": [],
|
||||
"suggestedGuidanceUpdates": [
|
||||
{
|
||||
"target": "rust-operator-worker",
|
||||
"suggestion": "When validating fixed-height TUI regions, explicitly exercise long wrapped operator feedback (not just short placeholder strings) so layout-fit checks prove realistic messages remain visible.",
|
||||
"evidence": "The follow-up review for `fix-tui-footer-and-passive-polling` found the new snapshot test only covered a short `Feedback line`, while real footer messages in `rust/proxypilot-rs/src/tui.rs` are long enough to wrap and clip help text again within the fixed six-row footer.",
|
||||
"isSystemic": true
|
||||
},
|
||||
{
|
||||
"target": "rust-operator-worker",
|
||||
"suggestion": "Document when label-only TUI/runtime wording changes may use lightweight non-interactive verification instead of full `tuistory` validation, so narrow observability fixes can follow a clear exception path.",
|
||||
"evidence": "The pass review for `fix-runtime-account-count-semantics` noted the worker intentionally skipped manual `tuistory` verification because the change only aligned runtime/TUI labels, but the current skill does not describe that small-change exception.",
|
||||
"isSystemic": false
|
||||
}
|
||||
],
|
||||
"rejectedObservations": [],
|
||||
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/scrutiny/synthesis.round1.json"
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
active_account = "refreshable-local"
|
||||
|
||||
[[accounts]]
|
||||
name = "refreshable-local"
|
||||
provider = "codex"
|
||||
api_key = "refreshed-access-token"
|
||||
refresh_token = "refreshed-refresh-token"
|
||||
id_token = "TEST_ID_TOKEN_PLACEHOLDER"
|
||||
email = "rerun@example.com"
|
||||
account_id = "acct_refresh_rerun"
|
||||
plan_type = "pro"
|
||||
expires_at = "2030-01-01T00:00:00Z"
|
||||
source = "import:/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/refreshable-auth.json"
|
||||
|
||||
[[accounts]]
|
||||
name = "static-local"
|
||||
provider = "codex"
|
||||
api_key = "sk-static-local"
|
||||
source = "manual"
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# isolated CLI refresh rerun config
|
||||
[server]
|
||||
bind = "127.0.0.1:8318"
|
||||
|
||||
[state]
|
||||
path = "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/proxypilot-rs.state.toml"
|
||||
|
||||
[codex]
|
||||
upstream_base_url = "https://api.openai.com"
|
||||
api_key = ""
|
||||
refresh_token_url = "http://127.0.0.1:34051/oauth/token"
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"access_token": "seed-access-token",
|
||||
"refresh_token": "seed-refresh-token",
|
||||
"email": "seed@example.com",
|
||||
"account_id": "acct_seed",
|
||||
"expired": "2020-01-01T00:00:00Z",
|
||||
"type": "codex"
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
active_account = "preemptive-account"
|
||||
|
||||
[[accounts]]
|
||||
name = "preemptive-account"
|
||||
provider = "codex"
|
||||
api_key = "expired-preemptive-token"
|
||||
refresh_token = "preemptive-refresh-token"
|
||||
id_token = "header.payload.sig"
|
||||
email = "refresh@example.com"
|
||||
account_id = "acct_seed"
|
||||
plan_type = "seed"
|
||||
expires_at = "1970-01-01T00:00:00Z"
|
||||
source = "fixture"
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
[server]
|
||||
bind = "127.0.0.1:18318"
|
||||
|
||||
[state]
|
||||
path = "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/http-refresh-rerun/VAL-HTTP-007.state.toml"
|
||||
|
||||
[codex]
|
||||
upstream_base_url = "http://127.0.0.1:18319"
|
||||
api_key = ""
|
||||
refresh_token_url = "http://127.0.0.1:18319/oauth/token"
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
active_account = "retry-account"
|
||||
|
||||
[[accounts]]
|
||||
name = "retry-account"
|
||||
provider = "codex"
|
||||
api_key = "stale-401-token"
|
||||
refresh_token = "retry-refresh-token"
|
||||
id_token = "header.payload.sig"
|
||||
email = "refresh@example.com"
|
||||
account_id = "acct_seed"
|
||||
plan_type = "seed"
|
||||
expires_at = "2035-01-01T00:00:00Z"
|
||||
source = "fixture"
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
[server]
|
||||
bind = "127.0.0.1:18318"
|
||||
|
||||
[state]
|
||||
path = "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/http-refresh-rerun/VAL-HTTP-008.state.toml"
|
||||
|
||||
[codex]
|
||||
upstream_base_url = "http://127.0.0.1:18319"
|
||||
api_key = ""
|
||||
refresh_token_url = "http://127.0.0.1:18319/oauth/token"
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
|
||||
def encode_claims(exp, email, account_id, plan_type):
|
||||
payload = {
|
||||
"email": email,
|
||||
"exp": exp,
|
||||
"https://api.openai.com/auth": {
|
||||
"chatgpt_account_id": account_id,
|
||||
"chatgpt_plan_type": plan_type,
|
||||
},
|
||||
}
|
||||
raw = json.dumps(payload, separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||
|
||||
|
||||
class ReusableServer(ThreadingHTTPServer):
|
||||
allow_reuse_address = True
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
scenario = "preemptive"
|
||||
log_path = None
|
||||
state = {"model_calls": 0}
|
||||
|
||||
def log_message(self, format, *args):
|
||||
return
|
||||
|
||||
def _write_json(self, status, payload):
|
||||
body = json.dumps(payload).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return body
|
||||
|
||||
def _record(self, *, response_status, response_body, request_body=""):
|
||||
entry = {
|
||||
"ts": time.time(),
|
||||
"scenario": self.scenario,
|
||||
"method": self.command,
|
||||
"path": self.path,
|
||||
"headers": {k: v for k, v in self.headers.items()},
|
||||
"request_body": request_body,
|
||||
"response_status": response_status,
|
||||
"response_body": response_body,
|
||||
"model_call_index": self.state["model_calls"],
|
||||
}
|
||||
with open(self.log_path, "a", encoding="utf-8") as fh:
|
||||
fh.write(json.dumps(entry) + "\n")
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/__health":
|
||||
body = b"ok"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
|
||||
if self.path == "/v1/models":
|
||||
auth = self.headers.get("Authorization", "")
|
||||
self.state["model_calls"] += 1
|
||||
if self.scenario == "retry401" and self.state["model_calls"] == 1:
|
||||
payload = {
|
||||
"error": "expired token",
|
||||
"received_authorization": auth,
|
||||
"attempt": 1,
|
||||
}
|
||||
self._record(response_status=401, response_body=payload)
|
||||
self._write_json(401, payload)
|
||||
return
|
||||
payload = {
|
||||
"object": "list",
|
||||
"data": [{"id": "gpt-5.2-codex", "object": "model"}],
|
||||
"received_authorization": auth,
|
||||
"attempt": self.state["model_calls"],
|
||||
"scenario": self.scenario,
|
||||
}
|
||||
self._record(response_status=200, response_body=payload)
|
||||
self._write_json(200, payload)
|
||||
return
|
||||
|
||||
payload = {"error": "not found", "path": self.path}
|
||||
self._record(response_status=404, response_body=payload)
|
||||
self._write_json(404, payload)
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
raw_body = self.rfile.read(length).decode()
|
||||
if self.path == "/oauth/token":
|
||||
form = parse_qs(raw_body)
|
||||
refresh_token = form.get("refresh_token", [""])[0]
|
||||
if self.scenario == "preemptive":
|
||||
payload = {
|
||||
"access_token": "preemptive-fresh-token",
|
||||
"refresh_token": "preemptive-fresh-refresh-token",
|
||||
"id_token": f"header.{encode_claims(1893456000, 'refresh@example.com', 'acct_preemptive', 'team')}.sig",
|
||||
"expires_in": 3600,
|
||||
"seen_refresh_token": refresh_token,
|
||||
}
|
||||
else:
|
||||
payload = {
|
||||
"access_token": "retry-fresh-token",
|
||||
"refresh_token": "retry-fresh-refresh-token",
|
||||
"id_token": f"header.{encode_claims(1893456000, 'refresh@example.com', 'acct_retry401', 'pro')}.sig",
|
||||
"expires_in": 3600,
|
||||
"seen_refresh_token": refresh_token,
|
||||
}
|
||||
self._record(response_status=200, response_body=payload, request_body=raw_body)
|
||||
self._write_json(200, payload)
|
||||
return
|
||||
|
||||
payload = {"error": "not found", "path": self.path}
|
||||
self._record(response_status=404, response_body=payload, request_body=raw_body)
|
||||
self._write_json(404, payload)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--scenario", required=True, choices=["preemptive", "retry401"])
|
||||
parser.add_argument("--port", required=True, type=int)
|
||||
parser.add_argument("--log", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
Handler.scenario = args.scenario
|
||||
Handler.log_path = args.log
|
||||
Handler.state = {"model_calls": 0}
|
||||
server = ReusableServer(("127.0.0.1", args.port), Handler)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"groupId": "cli-refresh-rerun",
|
||||
"testedAt": "2026-04-05T13:32:26Z",
|
||||
"isolation": {
|
||||
"surface": "shell",
|
||||
"fixtureDirectory": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun",
|
||||
"evidenceDirectory": "/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-refresh-rerun",
|
||||
"configPath": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/proxypilot-rs.toml",
|
||||
"statePath": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-refresh-rerun/proxypilot-rs.state.toml",
|
||||
"refreshTokenUrl": "http://127.0.0.1:34051/oauth/token"
|
||||
},
|
||||
"toolsUsed": [
|
||||
"shell"
|
||||
],
|
||||
"assertions": [
|
||||
{
|
||||
"id": "VAL-CLI-003",
|
||||
"title": "Refresh commands handle both refreshable and static accounts clearly",
|
||||
"status": "pass",
|
||||
"steps": [
|
||||
{
|
||||
"action": "Import a refreshable saved Codex account into isolated state and add a static account",
|
||||
"expected": "Fixture state contains one active refreshable account and one static account",
|
||||
"observed": "account list showed `refreshable-local` active with `refresh=refreshable` and `static-local` present with `refresh=static`"
|
||||
},
|
||||
{
|
||||
"action": "Run `account refresh-codex` with no `--name` while the refreshable account is active",
|
||||
"expected": "Refresh succeeds through the configured local refresh endpoint and updates saved account metadata",
|
||||
"observed": "Command printed `refreshed saved Codex account `refreshable-local` in local state`; the local stub received one POST to `/oauth/token`; state updated access token, refresh token, email, account id, plan, and expiry"
|
||||
},
|
||||
{
|
||||
"action": "Run `account refresh-codex --name static-local`",
|
||||
"expected": "Static account refresh is rejected with a clear operator-readable error and no state corruption",
|
||||
"observed": "Command exited non-zero with `account `static-local` is static and has no refresh token`; follow-up state snapshot matched the post-success state byte-for-byte"
|
||||
},
|
||||
{
|
||||
"action": "Run `account refresh-codex --name missing-local`",
|
||||
"expected": "Missing account refresh is rejected with a clear operator-readable error and no state corruption",
|
||||
"observed": "Command exited non-zero with `no saved Codex account named missing-local`; follow-up state snapshot remained unchanged and list output still showed the same active/static accounts"
|
||||
}
|
||||
],
|
||||
"evidence": {
|
||||
"commandOutputs": [
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-import-refreshable.txt",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-add-static.txt",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-list-before-refresh.txt",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-success.txt",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-list-after-success.txt",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-static-fails.txt",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-missing-fails.txt",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-list-after-failures.txt"
|
||||
],
|
||||
"stateSnapshots": [
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-state-before-refresh.toml",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-state-after-success.toml",
|
||||
"terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-state-after-failures.toml"
|
||||
],
|
||||
"network": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-stub-requests.json",
|
||||
"config": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-config.toml",
|
||||
"fixtureImport": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-import-auth.json",
|
||||
"validator": "terminal-operator-console/cli-refresh-rerun/VAL-CLI-003-refresh-related-tests.txt"
|
||||
},
|
||||
"issues": null
|
||||
}
|
||||
],
|
||||
"frictions": [],
|
||||
"blockers": [],
|
||||
"summary": "VAL-CLI-003 passed: refresh succeeded for the active refreshable Codex account through `codex.refresh_token_url`, static and missing account refreshes failed clearly, and saved state stayed coherent after all runs."
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"groupId": "cli-shell",
|
||||
"surface": "shell",
|
||||
"toolsUsed": [
|
||||
"shell"
|
||||
],
|
||||
"assertions": [
|
||||
{
|
||||
"id": "VAL-CLI-001",
|
||||
"status": "pass",
|
||||
"summary": "init wrote an example config at the requested fixture path and a second run without --force refused to overwrite it with a clear error.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-001-init-success.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-001-init-refused-overwrite.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-001-config.toml"
|
||||
],
|
||||
"details": "Used isolated fixture config /home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/cli-shell/20260405T121714Z/proxypilot-rs.toml. Successful init printed the written path. Re-running init returned exit code 1 with \"config already exists ... (pass --force to overwrite)\". The captured config file includes server.bind=127.0.0.1:8318, state.path=proxypilot-rs.state.toml, and codex.upstream_base_url=https://api.openai.com."
|
||||
},
|
||||
{
|
||||
"id": "VAL-CLI-002",
|
||||
"status": "pass",
|
||||
"summary": "Add, list, activate, and remove commands kept saved active-account state coherent, including promotion back to the remaining account and explicit empty-state output after removing the final account.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-add-primary.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-add-backup.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-add.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-activate-backup.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-activate.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-remove-backup.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-remove-backup.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-remove-primary.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-list-after-remove-primary.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-state-after-activate-backup.toml",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-state-after-remove-backup.toml",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-002-state-after-remove-primary.toml"
|
||||
],
|
||||
"details": "primary became active when first added; list output marked it with `*`. After activating backup, list output switched the marker to backup and the saved state snapshot shows active_account=\"backup\". Removing backup reported \"local active account is now `primary`\" and the next state snapshot shows active_account=\"primary\". Removing primary reported \"no local active account remains\" and follow-up list output showed \"No local Rust accounts saved yet.\" with an empty accounts snapshot."
|
||||
},
|
||||
{
|
||||
"id": "VAL-CLI-003",
|
||||
"status": "blocked",
|
||||
"summary": "Negative refresh paths behaved clearly for static and missing accounts, but the required refresh-success path could not be exercised within the isolated fixture because refresh-codex is hardwired to the live OpenAI OAuth refresh endpoint.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-state-with-static-and-refreshable.toml",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-list-pre-refresh.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-refresh-static-fails.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-refresh-missing-fails.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-list-after-failures.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-state-after-failures.toml",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/cli-shell/20260405T121714Z/VAL-CLI-003-refresh-success-blocked.txt"
|
||||
],
|
||||
"details": "Imported a refreshable local fixture account and added a static account inside the assigned fixture state. Refreshing the static account failed cleanly with \"account `static-local` is static and has no refresh token\"; refreshing a missing account failed with \"no saved Codex account named missing-local\". Follow-up list/state evidence shows saved state remained unchanged after both failures. The assertion remains blocked because the CLI refresh path uses the built-in OpenAI OAuth refresh endpoint and the supported config surface does not expose a way to redirect refresh-codex to a local mock endpoint without live credentials."
|
||||
}
|
||||
],
|
||||
"frictions": [],
|
||||
"blockers": [
|
||||
"VAL-CLI-003 success-path refresh is not isolatable in this shell fixture: refresh-codex uses the built-in live OpenAI OAuth refresh endpoint, and the allowed CLI/config surface provides no local mock override. Live device-login/private credentials were explicitly disallowed, so the refresh-success portion of the assertion was recorded as blocked with evidence."
|
||||
],
|
||||
"overallSummary": "Validated 3 CLI shell assertions for terminal-operator-console: VAL-CLI-001 pass, VAL-CLI-002 pass, VAL-CLI-003 blocked due to non-mockable live refresh dependency. Report and evidence were written under the requested flow-report and mission evidence paths."
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"groupId": "http-refresh-rerun",
|
||||
"testedAt": "2026-04-05T13:34:49Z",
|
||||
"isolation": {
|
||||
"surface": "curl",
|
||||
"fixtureDirectory": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/fixtures/http-refresh-rerun",
|
||||
"evidenceDirectory": "/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-refresh-rerun",
|
||||
"proxyBind": "127.0.0.1:18318",
|
||||
"stubBind": "127.0.0.1:18319",
|
||||
"refreshTokenUrl": "http://127.0.0.1:18319/oauth/token"
|
||||
},
|
||||
"toolsUsed": [
|
||||
"curl"
|
||||
],
|
||||
"assertions": [
|
||||
{
|
||||
"id": "VAL-HTTP-007",
|
||||
"title": "Proactive refresh is visible before forwarding expired or near-expiry requests",
|
||||
"status": "pass",
|
||||
"steps": [
|
||||
{
|
||||
"action": "Start proxypilot-rs with an expired refreshable active account plus a local OAuth/upstream stub",
|
||||
"expected": "Runtime stats start with expired auth health and zero counters",
|
||||
"observed": "/v0/runtime/stats reported auth_health.state=expired with total_proxied_requests=0 and auth_refresh_attempts=0"
|
||||
},
|
||||
{
|
||||
"action": "Send GET /v1/models through the proxy",
|
||||
"expected": "Proxy refreshes before forwarding and the client request succeeds with the refreshed token",
|
||||
"observed": "Client received 200 JSON showing received_authorization=Bearer preemptive-fresh-token"
|
||||
},
|
||||
{
|
||||
"action": "Inspect runtime stats and stub traffic after the request",
|
||||
"expected": "Stats show one refresh attempt/success and upstream sees only refreshed-token traffic",
|
||||
"observed": "Stats showed total_proxied_requests=1, successful_upstream_responses=1, auth_refresh_attempts=1, upstream_401_count=0, last_refresh.kind=success; stub log recorded POST /oauth/token before GET /v1/models with Bearer preemptive-fresh-token"
|
||||
}
|
||||
],
|
||||
"evidence": {
|
||||
"statsBefore": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stats-before.json",
|
||||
"requestHeaders": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-request.headers.txt",
|
||||
"requestBody": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-request-body.json",
|
||||
"statsAfter": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stats-after.json",
|
||||
"stubLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stub-log.jsonl",
|
||||
"proxyLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-proxy.log",
|
||||
"stubStdout": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-007-stub.log"
|
||||
},
|
||||
"issues": null
|
||||
},
|
||||
{
|
||||
"id": "VAL-HTTP-008",
|
||||
"title": "Upstream 401 retry refresh is visible and counted exactly once",
|
||||
"status": "pass",
|
||||
"steps": [
|
||||
{
|
||||
"action": "Start proxypilot-rs with a refreshable active account and a local stub that returns 401 on the first /v1/models request",
|
||||
"expected": "Initial stats are zeroed and the first upstream attempt uses the stale token",
|
||||
"observed": "Stub log recorded the first GET /v1/models with Bearer stale-401-token and response_status=401"
|
||||
},
|
||||
{
|
||||
"action": "Let the proxy handle the 401-triggered refresh-and-retry path for one GET /v1/models client request",
|
||||
"expected": "Proxy refreshes once, retries once, and the client sees the retried success result",
|
||||
"observed": "Client received 200 JSON showing received_authorization=Bearer retry-fresh-token on attempt=2"
|
||||
},
|
||||
{
|
||||
"action": "Inspect runtime stats and stub traffic after the request",
|
||||
"expected": "Stats count one proxied request, one upstream 401, one refresh success, and mock upstream shows 401 then refresh then retry",
|
||||
"observed": "Stats showed total_proxied_requests=1, successful_upstream_responses=1, auth_refresh_attempts=1, upstream_401_count=1, last_refresh.kind=success; stub log showed GET 401 -> POST /oauth/token -> GET 200 with Bearer retry-fresh-token"
|
||||
}
|
||||
],
|
||||
"evidence": {
|
||||
"statsBefore": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stats-before.json",
|
||||
"requestHeaders": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-request.headers.txt",
|
||||
"requestBody": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-request-body.json",
|
||||
"statsAfter": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stats-after.json",
|
||||
"stubLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stub-log.jsonl",
|
||||
"proxyLog": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-proxy.log",
|
||||
"stubStdout": "terminal-operator-console/http-refresh-rerun/VAL-HTTP-008-stub.log"
|
||||
},
|
||||
"issues": null
|
||||
}
|
||||
],
|
||||
"frictions": [],
|
||||
"blockers": [],
|
||||
"summary": "Retested 2 assertions: VAL-HTTP-007 passed with proactive refresh before forwarding, and VAL-HTTP-008 passed with one 401-triggered refresh-and-retry path counted exactly once."
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
{
|
||||
"assertions": [
|
||||
{
|
||||
"details": "Observed status=ok, provider=codex, listen=127.0.0.1:18318, upstream=http://127.0.0.1:18319 on the reachable fixture and the same local health response with upstream=http://127.0.0.1:18339.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-001-healthz-reachable.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-001-healthz-unreachable.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-fallback.toml",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-unreachable.toml"
|
||||
],
|
||||
"id": "VAL-HTTP-001",
|
||||
"status": "pass",
|
||||
"summary": "Health checks returned 200 with local proxy identity fields both with the mock upstream and with an unreachable local upstream port."
|
||||
},
|
||||
{
|
||||
"details": "The stats call returned HTTP 200 with a JSON payload and the mock log remained empty (request_count=0), confirming the operator surface is read-only and local.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-002-runtime-stats.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-002-mock-log.json"
|
||||
],
|
||||
"id": "VAL-HTTP-002",
|
||||
"status": "pass",
|
||||
"summary": "The local /v0/runtime/stats surface returned 200 without auth and did not create any upstream mock traffic."
|
||||
},
|
||||
{
|
||||
"details": "Before and after mutating the state file on disk, /v0/runtime/stats continued to report active_account_name=runtime-valid and auth_health.state=valid for the running process while exposing bind_address, upstream_base_url, account_count, auth_health, request_counters, and last_refresh.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-stats-before-disk-mutation.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-stats-after-disk-mutation.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-state-before.toml",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-003-state-mutated.toml"
|
||||
],
|
||||
"id": "VAL-HTTP-003",
|
||||
"status": "pass",
|
||||
"summary": "The runtime stats payload exposed the expected stable schema and stayed pinned to runtime-memory state after the disk state file was mutated externally."
|
||||
},
|
||||
{
|
||||
"details": "Observed auth_health.state values: fallback-key -> static with source=config_fallback_key and no active_account_name; static saved account -> static with source=active_account; valid fixture -> valid; expiring fixture -> expiring_soon; expired fixture -> expired; malformed expiry fixture -> unknown with metadata_state=malformed.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-fallback-key.json",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-static-saved.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-valid.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-expiring.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-expired.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-004-malformed.txt"
|
||||
],
|
||||
"id": "VAL-HTTP-004",
|
||||
"status": "pass",
|
||||
"summary": "Representative fixtures produced explicit auth-health states for fallback static, saved static, valid, expiring_soon, expired, and malformed unknown cases."
|
||||
},
|
||||
{
|
||||
"details": "Initial stats showed all request counters at 0 and last_refresh.kind=unknown with null timestamps; after two successful requests the counters rose; after restarting the proxy with the same fixture they reset to zero again.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-002-runtime-stats.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-stats-after-success.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-005-stats-after-restart.txt"
|
||||
],
|
||||
"id": "VAL-HTTP-005",
|
||||
"status": "pass",
|
||||
"summary": "Fresh runtime counters started at zero, last-refresh metadata was null-like before any attempt, and a restart cleared in-memory stats after traffic."
|
||||
},
|
||||
{
|
||||
"details": "Starting from zero, one GET /v1/models and one POST /v1/chat/completions produced total_proxied_requests=2 and successful_upstream_responses=2, with two corresponding mock upstream calls.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-models-success.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-chat-success.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-stats-after-success.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-006-mock-log.json"
|
||||
],
|
||||
"id": "VAL-HTTP-006",
|
||||
"status": "pass",
|
||||
"summary": "Successful supported proxy requests incremented both total_proxied_requests and successful_upstream_responses."
|
||||
},
|
||||
{
|
||||
"details": "With an expired refreshable account, the next proxied request returned 502, auth_refresh_attempts/auth_refresh_failures incremented, last_refresh.kind became failure, and the local upstream mock saw zero calls. This confirms the pre-forward refresh attempt, but successful local stubbed refresh remains blocked because the available config surface has no OAuth token endpoint override.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-stats-before.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-proactive-refresh-attempt.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-stats-after.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-007-mock-log.json",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-expired.toml"
|
||||
],
|
||||
"id": "VAL-HTTP-007",
|
||||
"status": "blocked",
|
||||
"summary": "A proactive refresh attempt was observable before forwarding, but the success path could not be validated because the runtime cannot be redirected from the user surface to a local OAuth token stub."
|
||||
},
|
||||
{
|
||||
"details": "The local mock forced one upstream 401 and the proxy recorded upstream_401_count=1 with a single proxied request, but the refresh attempt failed with a 502 response and the mock saw no /oauth/token call. A successful refresh-and-retry path therefore remains blocked under the current user-surface configuration.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-stats-before.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-401-refresh-attempt.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-stats-after.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-mock-log.json",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/fixture-config-401-retry.toml"
|
||||
],
|
||||
"id": "VAL-HTTP-008",
|
||||
"status": "blocked",
|
||||
"summary": "The 401-triggered refresh path is visible, but the success retry case cannot be validated locally because the runtime cannot point refresh traffic at a local OAuth token stub from the user surface."
|
||||
},
|
||||
{
|
||||
"details": "The client received HTTP 502 with a local JSON error after the mock upstream returned 401, while /v0/runtime/stats showed total_proxied_requests=1, upstream_401_count=1, auth_refresh_attempts=1, auth_refresh_failures=1, and last_refresh.kind=failure with a failure timestamp/message.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-401-refresh-attempt.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-stats-after.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-008-009-mock-log.json"
|
||||
],
|
||||
"id": "VAL-HTTP-009",
|
||||
"status": "pass",
|
||||
"summary": "A 401-triggered refresh failure remained visible to the operator surface and did not masquerade as success."
|
||||
},
|
||||
{
|
||||
"details": "POST /v1/files returned HTTP 404 with an error naming /v1/files and the supported routes list; successful_upstream_responses and total_proxied_requests stayed unchanged across the before/after stats captures.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-010-stats-before.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-010-unsupported-route.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/http-runtime/val-http-010-stats-after.txt"
|
||||
],
|
||||
"id": "VAL-HTTP-010",
|
||||
"status": "pass",
|
||||
"summary": "Unsupported /v1/* routes returned a clear 404 JSON error and did not change success counters."
|
||||
}
|
||||
],
|
||||
"blockers": [
|
||||
"VAL-HTTP-007 and VAL-HTTP-008 remain blocked for success-path validation because proxypilot-rs exposes no user-surface config knob to redirect refresh token exchange from the hardwired OAuth endpoint to a local stub."
|
||||
],
|
||||
"frictions": [],
|
||||
"groupId": "http-runtime",
|
||||
"overallSummary": "Validated 10 HTTP runtime assertions: 8 passed and 2 were blocked (refresh-success paths VAL-HTTP-007 and VAL-HTTP-008).",
|
||||
"surface": "curl",
|
||||
"toolsUsed": [
|
||||
"curl"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
{
|
||||
"groupId": "tui-console",
|
||||
"surface": "tuistory",
|
||||
"toolsUsed": [
|
||||
"tuistory",
|
||||
"shell",
|
||||
"curl"
|
||||
],
|
||||
"assertions": [
|
||||
{
|
||||
"id": "VAL-TUI-001",
|
||||
"status": "pass",
|
||||
"summary": "The TUI opened as a readable Codex operator console with overview, runtime, runtime-stats, models, accounts, selected-account, feedback, and key-help regions visible.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.png"
|
||||
],
|
||||
"details": "Launching `cargo run --manifest-path rust/Cargo.toml -p proxypilot-rs -- tui --config .../config-live.toml` rendered the Codex Operator Console immediately. The initial surface showed readable runtime health, live runtime stats, a disk-backed account list, selected-account details, and footer/help text rather than a blank or cryptic screen."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-002",
|
||||
"status": "pass",
|
||||
"summary": "The footer/help text matched the shipped key bindings, and each listed action was exercised through the TUI during validation.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-activate-alpha.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-delete-beta.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-clear-feedback.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-after-q-snapshot.txt"
|
||||
],
|
||||
"details": "Visible help text listed `q`, `r`, arrows, `a`, `f`, `R`, `d`, and `c`. Those bindings were exercised across the live, runtime-down, and auth-trouble sessions: reload/poll updated state, arrows changed selection, activate/delete changed local state, selected refresh and active refresh produced targeted feedback, clear removed feedback, and `q` exited the TUI process back to the launcher shell."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-003",
|
||||
"status": "pass",
|
||||
"summary": "With no proxy running on the configured port, the TUI explicitly showed runtime unavailability while keeping the local disk-backed account list and selected-account details visible.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-initial.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-initial.png"
|
||||
],
|
||||
"details": "Using the isolated runtime-down fixture on 127.0.0.1:18430 without starting a proxy produced `Health: proxy not running yet` and `Runtime unavailable` copy, while still rendering six saved accounts and full selected-account details from the local fixture state file."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-004",
|
||||
"status": "pass",
|
||||
"summary": "Pressing `r` refreshed both disk-backed state and runtime-observed data without restarting the TUI.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/cli-activate-beta.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-activate-reload.txt"
|
||||
],
|
||||
"details": "After changing the saved active account externally through the CLI and generating runtime traffic through `/v1/models`, pressing `r` in the live TUI updated the disk active account from `alpha` to `beta`, loaded the model list, and refreshed runtime counters to `total=1 success=1` while still truthfully showing the runtime active account as `alpha`."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-005",
|
||||
"status": "pass",
|
||||
"summary": "The activate action updated active markers, selected-account details, and feedback coherently.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-before-activate.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-activate-alpha.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-activate-alpha.png"
|
||||
],
|
||||
"details": "Before pressing `a`, the selected row was `alpha` while the disk active marker was on `beta`. After `a`, the footer reported `Activated account \\`alpha\\`.` and the active marker moved to `alpha` without corrupting selection or the selected-account panel."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-006",
|
||||
"status": "pass",
|
||||
"summary": "The delete action removed the selected account, kept selection in bounds, and updated visible account state coherently.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-clear-feedback.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-delete-beta.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-delete-beta.png"
|
||||
],
|
||||
"details": "With `beta` selected, pressing `d` removed that row, reduced the saved-account count from two to one, moved selection to the remaining `alpha` row, and showed `Deleted account \\`beta\\`.` in the footer without leaving stale details on screen."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-007",
|
||||
"status": "pass",
|
||||
"summary": "Selected-account refresh targeted the selected row and named that account clearly in feedback.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-select-beta.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-refresh-selected-beta.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-selected-soon.txt"
|
||||
],
|
||||
"details": "On the live fixture, `beta` was selected while `alpha` remained active; pressing `f` produced `Failed to refresh account \\`beta\\`: account \\`beta\\` is static and has no refresh token`. In the runtime-down fixture, selecting `soon` and pressing `f` produced feedback naming `soon`, confirming the action targets the selected row rather than the active row."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-008",
|
||||
"status": "pass",
|
||||
"summary": "Active-account refresh-now targeted the active account even when another row was selected.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-select-beta.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-refresh-active-alpha.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-select-valid-while-active-soon.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-active-runtime-down.txt"
|
||||
],
|
||||
"details": "In the live fixture, `beta` was selected while `alpha` was the active disk/runtime account; pressing `R` produced feedback naming `alpha`, not `beta`. In the runtime-down fixture, `valid` was selected while disk active remained `soon`, and `R` reported `Disk active account remains \\`soon\\``, again proving the action targeted the active account rather than the selected row."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-009",
|
||||
"status": "pass",
|
||||
"summary": "Clear-feedback removed transient status text without altering selection or account state.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-refresh-active-alpha.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-clear-feedback.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-clear-feedback.txt"
|
||||
],
|
||||
"details": "After visible failure feedback in both live and runtime-down sessions, pressing `c` cleared the footer message back to blank while keeping the selected row, disk active account, runtime panel, and counters unchanged."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-010",
|
||||
"status": "pass",
|
||||
"summary": "The TUI used explicit operator-readable auth labels for valid, expiring soon, expired, static, and unknown, with distinct missing-vs-malformed expiry details.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-valid.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-expiring-soon.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-expired.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-static.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-unknown-missing.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-labels-unknown-malformed.txt"
|
||||
],
|
||||
"details": "A dedicated auth-label fixture showed `Auth health: valid`, `expiring soon`, `expired`, `static`, and `unknown` in the selected-account panel. The `unknown-missing` account showed `Expiry: expiry metadata missing`, while `unknown-malformed` showed `Expiry: malformed expiry metadata (not-a-timestamp)`, which truthfully distinguishes the two unknown states."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-011",
|
||||
"status": "pass",
|
||||
"summary": "When runtime stats were available, the TUI surfaced request counters and the last refresh outcome/timestamp in the runtime panel.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-initial.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-activate-reload.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-after-reload.txt"
|
||||
],
|
||||
"details": "The idle live fixture showed zeroed counters and `Last refresh: unknown`. After proxied traffic, the live runtime panel updated to `total=1 success=1`. After a proxy-triggered refresh failure, the auth-trouble TUI showed `refresh_attempts=1 refresh_failures=1` and `Last refresh: failure for \\`refresh-fail\\` at ...`, making runtime refresh outcome visible without reading files or logs."
|
||||
},
|
||||
{
|
||||
"id": "VAL-TUI-012",
|
||||
"status": "pass",
|
||||
"summary": "When runtime was down, local disk-backed actions still worked where feasible and runtime-dependent refresh paths failed with readable copy while local state stayed visible.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-activate-soon.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-selected-soon.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-active-runtime-down.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-delete-valid.txt"
|
||||
],
|
||||
"details": "With runtime unavailable, pressing `a` still updated the local disk active account from `valid` to `soon`; `f` failed with readable refresh-token-exchange copy naming the selected account; `R` failed with explicit `runtime stats unavailable` copy while preserving the disk active account label; and `d` still deleted a locally saved account without hiding the local account list."
|
||||
},
|
||||
{
|
||||
"id": "VAL-CROSS-001",
|
||||
"status": "pass",
|
||||
"summary": "CLI active-account changes became visible in the TUI after reload while runtime state remained truthfully separate.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/cli-activate-beta.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-activate-reload.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/cli-remove-alpha.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/live-after-cli-remove-alpha-reload.txt"
|
||||
],
|
||||
"details": "After CLI activation changed the saved active account to `beta`, TUI reload showed `Local disk active account: beta` while still showing `Runtime active account: alpha`. After CLI removal of `alpha`, reload again showed the saved state change (`beta` on disk, one saved account left) while runtime stats still truthfully reported the still-running proxy's runtime state as `alpha`."
|
||||
},
|
||||
{
|
||||
"id": "VAL-CROSS-002",
|
||||
"status": "pass",
|
||||
"summary": "A proxy-triggered refresh attempt became visible across runtime surfaces without reading the state file manually.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-proxy-request.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-stats-after.json",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/auth-trouble-after-reload.txt"
|
||||
],
|
||||
"details": "A proxied `GET /v1/models` against the auth-trouble fixture triggered an expired-account refresh attempt and returned a local 502. `/v0/runtime/stats` then showed `auth_refresh_attempts=1`, `auth_refresh_failures=1`, and a failed `last_refresh`, and the auth-trouble TUI showed the same failed refresh outcome in its runtime panel after reload."
|
||||
},
|
||||
{
|
||||
"id": "VAL-CROSS-003",
|
||||
"status": "pass",
|
||||
"summary": "When runtime was down, reload and feedback clearing preserved local state while keeping runtime failures separate from local actions.",
|
||||
"evidence": [
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-refresh-active-runtime-down.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-clear-feedback.txt",
|
||||
"/home/fsos/.factory/missions/7e6968f8-b3d3-4772-9518-ca3a93ea1374/evidence/terminal-operator-console/tui-console/runtime-down-clean-after-reload.txt"
|
||||
],
|
||||
"details": "In the runtime-down fixture, local actions changed disk state, `R` surfaced runtime unavailability separately from that local state, `c` cleared only the transient footer message, and `r` reloaded the current disk-backed account list without hiding local accounts or collapsing the separate `Runtime unavailable` messaging."
|
||||
}
|
||||
],
|
||||
"frictions": [
|
||||
"tuistory keeps the PTY session alive after `q` exits the TUI binary, so explicit `tuistory close` cleanup was still required even though the application quit successfully.",
|
||||
"With runtime down, `f` still attempts the hardwired Codex OAuth refresh exchange and surfaces the resulting OAuth 401 text instead of a pure local runtime-unavailable message; this was truthful but not called out in user-testing guidance."
|
||||
],
|
||||
"blockers": [],
|
||||
"overallSummary": "Validated 15 assigned TUI/cross-surface assertions for terminal-operator-console: 15 passed, 0 failed, 0 blocked. Evidence and the flow report were written under the requested mission and validation paths."
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"milestone": "terminal-operator-console",
|
||||
"round": 2,
|
||||
"status": "pass",
|
||||
"assertionsSummary": {
|
||||
"total": 3,
|
||||
"passed": 3,
|
||||
"failed": 0,
|
||||
"blocked": 0
|
||||
},
|
||||
"passedAssertions": [
|
||||
"VAL-CLI-003",
|
||||
"VAL-HTTP-007",
|
||||
"VAL-HTTP-008"
|
||||
],
|
||||
"failedAssertions": [],
|
||||
"blockedAssertions": [],
|
||||
"appliedUpdates": [],
|
||||
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/synthesis.round1.json"
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"milestone": "terminal-operator-console",
|
||||
"round": 1,
|
||||
"status": "fail",
|
||||
"assertionsSummary": {
|
||||
"total": 28,
|
||||
"passed": 25,
|
||||
"failed": 0,
|
||||
"blocked": 3
|
||||
},
|
||||
"passedAssertions": [
|
||||
"VAL-CLI-001",
|
||||
"VAL-CLI-002",
|
||||
"VAL-HTTP-001",
|
||||
"VAL-HTTP-002",
|
||||
"VAL-HTTP-003",
|
||||
"VAL-HTTP-004",
|
||||
"VAL-HTTP-005",
|
||||
"VAL-HTTP-006",
|
||||
"VAL-HTTP-009",
|
||||
"VAL-HTTP-010",
|
||||
"VAL-TUI-001",
|
||||
"VAL-TUI-002",
|
||||
"VAL-TUI-003",
|
||||
"VAL-TUI-004",
|
||||
"VAL-TUI-005",
|
||||
"VAL-TUI-006",
|
||||
"VAL-TUI-007",
|
||||
"VAL-TUI-008",
|
||||
"VAL-TUI-009",
|
||||
"VAL-TUI-010",
|
||||
"VAL-TUI-011",
|
||||
"VAL-TUI-012",
|
||||
"VAL-CROSS-001",
|
||||
"VAL-CROSS-002",
|
||||
"VAL-CROSS-003"
|
||||
],
|
||||
"failedAssertions": [],
|
||||
"blockedAssertions": [
|
||||
{
|
||||
"id": "VAL-CLI-003",
|
||||
"blockedBy": "Negative refresh paths behaved clearly for static and missing accounts, but the required refresh-success path could not be exercised within the isolated fixture because refresh-codex is hardwired to the live OpenAI OAuth refresh endpoint."
|
||||
},
|
||||
{
|
||||
"id": "VAL-HTTP-007",
|
||||
"blockedBy": "A proactive refresh attempt was observable before forwarding, but the success path could not be validated because the runtime cannot be redirected from the user surface to a local OAuth token stub."
|
||||
},
|
||||
{
|
||||
"id": "VAL-HTTP-008",
|
||||
"blockedBy": "The 401-triggered refresh path is visible, but the success retry case cannot be validated locally because the runtime cannot point refresh traffic at a local OAuth token stub from the user surface."
|
||||
}
|
||||
],
|
||||
"appliedUpdates": [
|
||||
{
|
||||
"target": "user-testing.md",
|
||||
"description": "Added flow validator guidance for shell, curl, and tuistory surfaces plus isolated fixture/evidence boundaries for terminal-operator-console validation.",
|
||||
"source": "setup"
|
||||
},
|
||||
{
|
||||
"target": "user-testing.md",
|
||||
"description": "Documented discovered validation quirks: hardwired OAuth refresh paths block local success-path refresh testing, tuistory PTYs need explicit close, and runtime-down selected refresh still surfaces remote OAuth failure text.",
|
||||
"source": "flow-report"
|
||||
}
|
||||
],
|
||||
"previousRound": null
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"milestone": "terminal-operator-console",
|
||||
"round": 2,
|
||||
"status": "pass",
|
||||
"assertionsSummary": {
|
||||
"total": 3,
|
||||
"passed": 3,
|
||||
"failed": 0,
|
||||
"blocked": 0
|
||||
},
|
||||
"passedAssertions": [
|
||||
"VAL-CLI-003",
|
||||
"VAL-HTTP-007",
|
||||
"VAL-HTTP-008"
|
||||
],
|
||||
"failedAssertions": [],
|
||||
"blockedAssertions": [],
|
||||
"appliedUpdates": [],
|
||||
"previousRound": "/home/fsos/code-lean/ai-tools/ProxyPilot/.factory/validation/terminal-operator-console/user-testing/synthesis.round1.json"
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
name: docker-image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
APP_NAME: ProxyPilot
|
||||
@@ -28,6 +26,9 @@ jobs:
|
||||
- name: Checkout
|
||||
if: steps.check-secrets.outputs.skip != 'true'
|
||||
uses: actions/checkout@v4
|
||||
- name: Refresh models catalog
|
||||
if: steps.check-secrets.outputs.skip != 'true'
|
||||
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
|
||||
- name: Set up QEMU
|
||||
if: steps.check-secrets.outputs.skip != 'true'
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
@@ -12,6 +12,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Refresh models catalog
|
||||
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
name: ProxyPilot Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -16,6 +16,8 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Refresh models catalog
|
||||
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
|
||||
- run: git fetch --force --tags
|
||||
- uses: actions/setup-go@v4
|
||||
with:
|
||||
|
||||
@@ -40,35 +40,6 @@ jobs:
|
||||
# Build tray app (includes embedded dashboard)
|
||||
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot.exe ./cmd/proxypilot-tray
|
||||
|
||||
- name: Build Installer UI
|
||||
run: |
|
||||
cd installer-ui
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
- name: Copy Installer UI to cmd/installer
|
||||
run: |
|
||||
# Ensure target directory exists
|
||||
New-Item -ItemType Directory -Force -Path cmd/installer/ui | Out-Null
|
||||
# Copy built UI files
|
||||
Copy-Item -Path installer-ui/dist/* -Destination cmd/installer/ui/ -Recurse -Force
|
||||
shell: pwsh
|
||||
|
||||
- name: Create bundle for installer
|
||||
run: |
|
||||
# Create bundle directory
|
||||
New-Item -ItemType Directory -Force -Path cmd/installer/bundle | Out-Null
|
||||
# Copy files for embedding
|
||||
Copy-Item -Path dist/ProxyPilot.exe -Destination cmd/installer/bundle/
|
||||
Copy-Item -Path config.example.yaml -Destination cmd/installer/bundle/
|
||||
Copy-Item -Path static/icon.ico -Destination cmd/installer/bundle/
|
||||
Copy-Item -Path static/icon.png -Destination cmd/installer/bundle/
|
||||
shell: pwsh
|
||||
|
||||
- name: Build Custom Installer
|
||||
run: |
|
||||
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot-Installer.exe ./cmd/installer
|
||||
|
||||
- name: Install Inno Setup
|
||||
run: |
|
||||
choco install innosetup -y
|
||||
@@ -82,16 +53,18 @@ jobs:
|
||||
id: version
|
||||
run: |
|
||||
if ("${{ github.event.inputs.version }}" -ne "") {
|
||||
echo "VERSION=${{ github.event.inputs.version }}" >> $env:GITHUB_OUTPUT
|
||||
$version = "${{ github.event.inputs.version }}"
|
||||
} else {
|
||||
$tag = "${{ github.ref_name }}"
|
||||
$version = $tag -replace '^v', ''
|
||||
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
|
||||
}
|
||||
$versionInfo = $version -replace '^v', '' -replace '-dev-0\.', '.' -replace '-dev-', '.'
|
||||
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
|
||||
echo "VERSION_INFO=$versionInfo" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: Build Inno Setup Installer
|
||||
run: |
|
||||
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /DAppVersion="${{ steps.version.outputs.VERSION }}" installer\proxypilot.iss
|
||||
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /DAppVersion="${{ steps.version.outputs.VERSION }}" /DVersionInfoVersion="${{ steps.version.outputs.VERSION_INFO }}" installer\proxypilot.iss
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -99,7 +72,6 @@ jobs:
|
||||
name: windows-release
|
||||
path: |
|
||||
dist/ProxyPilot.exe
|
||||
dist/ProxyPilot-Installer.exe
|
||||
dist/ProxyPilot-*-Setup.exe
|
||||
|
||||
- name: Upload to Release
|
||||
@@ -108,6 +80,4 @@ jobs:
|
||||
with:
|
||||
files: |
|
||||
dist/ProxyPilot.exe
|
||||
dist/ProxyPilot-Installer.exe
|
||||
dist/ProxyPilot-${{ steps.version.outputs.VERSION }}-Setup.exe
|
||||
config.example.yaml
|
||||
|
||||
@@ -49,12 +49,14 @@ docs/*
|
||||
!docs/long-context-features.md
|
||||
!docs/desktop-app-build-process.md
|
||||
!docs/cli.md
|
||||
!docs/rust-replatform.md
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
GEMINI.md
|
||||
|
||||
# Tooling metadata
|
||||
.vscode/*
|
||||
.worktrees/
|
||||
.codex/*
|
||||
.claude/*
|
||||
.gemini/*
|
||||
@@ -74,6 +76,7 @@ claude-progress.txt
|
||||
feature_list.json
|
||||
tui-snapshot*.txt
|
||||
tui-ttyd.png
|
||||
rust/target/
|
||||
|
||||
# Local settings (user-specific)
|
||||
*.local.json
|
||||
@@ -118,3 +121,9 @@ config-debug.yaml
|
||||
test_results.txt
|
||||
test_results_full.txt
|
||||
tmpclaude-*
|
||||
|
||||
# Opencode
|
||||
.beads/
|
||||
.opencode/
|
||||
.cli-proxy-api/
|
||||
.venv/
|
||||
|
||||
@@ -12,6 +12,7 @@ builds:
|
||||
- linux
|
||||
- windows
|
||||
- darwin
|
||||
- freebsd
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
Built in Go, it handles OAuth authentication, token management, and API translation automatically. One server to route them all.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
An experimental Rust replatform now lives on the <code>rust-replatform</code> branch with a terminal-first <code>proxypilot-rs</code> binary under <code>rust/</code>.
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
> [!TIP]
|
||||
@@ -92,10 +96,11 @@ go build -o proxypilot ./cmd/server
|
||||
|
||||
### First Launch
|
||||
|
||||
1. Copy config: `cp config.example.yaml config.yaml`
|
||||
2. Run: `./proxypilot`
|
||||
3. Server starts on `http://localhost:8317`
|
||||
4. Open dashboard: `http://localhost:8317/management.html`
|
||||
1. Packaged installs create `config.yaml` automatically on first start when `config.example.yaml` is bundled next to the executable.
|
||||
2. If you're running from source, copy config: `cp config.example.yaml config.yaml`
|
||||
3. Run: `./proxypilot`
|
||||
4. Server starts on `http://localhost:8317`
|
||||
5. Open dashboard: `http://localhost:8317/management.html`
|
||||
|
||||
### Authentication
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
v6.8.49
|
||||
v6.9.16
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
// Command fetch_antigravity_models connects to the Antigravity API using the
|
||||
// stored auth credentials and saves the dynamically fetched model list to a
|
||||
// JSON file for inspection or offline use.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// go run ./cmd/fetch_antigravity_models [flags]
|
||||
//
|
||||
// Flags:
|
||||
//
|
||||
// --auths-dir <path> Directory containing auth JSON files (default: "auths")
|
||||
// --output <path> Output JSON file path (default: "antigravity_models.json")
|
||||
// --pretty Pretty-print the output JSON (default: true)
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
sdkauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
const (
|
||||
antigravityBaseURLDaily = "https://daily-cloudcode-pa.googleapis.com"
|
||||
antigravitySandboxBaseURLDaily = "https://daily-cloudcode-pa.sandbox.googleapis.com"
|
||||
antigravityBaseURLProd = "https://cloudcode-pa.googleapis.com"
|
||||
antigravityModelsPath = "/v1internal:fetchAvailableModels"
|
||||
)
|
||||
|
||||
func init() {
|
||||
logging.SetupBaseLogger()
|
||||
log.SetLevel(log.InfoLevel)
|
||||
}
|
||||
|
||||
// modelOutput wraps the fetched model list with fetch metadata.
|
||||
type modelOutput struct {
|
||||
Models []modelEntry `json:"models"`
|
||||
}
|
||||
|
||||
// modelEntry contains only the fields we want to keep for static model definitions.
|
||||
type modelEntry struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
OwnedBy string `json:"owned_by"`
|
||||
Type string `json:"type"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
ContextLength int `json:"context_length,omitempty"`
|
||||
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
var authsDir string
|
||||
var outputPath string
|
||||
var pretty bool
|
||||
|
||||
flag.StringVar(&authsDir, "auths-dir", "auths", "Directory containing auth JSON files")
|
||||
flag.StringVar(&outputPath, "output", "antigravity_models.json", "Output JSON file path")
|
||||
flag.BoolVar(&pretty, "pretty", true, "Pretty-print the output JSON")
|
||||
flag.Parse()
|
||||
|
||||
// Resolve relative paths against the working directory.
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: cannot get working directory: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if !filepath.IsAbs(authsDir) {
|
||||
authsDir = filepath.Join(wd, authsDir)
|
||||
}
|
||||
if !filepath.IsAbs(outputPath) {
|
||||
outputPath = filepath.Join(wd, outputPath)
|
||||
}
|
||||
|
||||
fmt.Printf("Scanning auth files in: %s\n", authsDir)
|
||||
|
||||
// Load all auth records from the directory.
|
||||
fileStore := sdkauth.NewFileTokenStore()
|
||||
fileStore.SetBaseDir(authsDir)
|
||||
|
||||
ctx := context.Background()
|
||||
auths, err := fileStore.List(ctx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: failed to list auth files: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if len(auths) == 0 {
|
||||
fmt.Fprintf(os.Stderr, "error: no auth files found in %s\n", authsDir)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Find the first enabled antigravity auth.
|
||||
var chosen *coreauth.Auth
|
||||
for _, a := range auths {
|
||||
if a == nil || a.Disabled {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(a.Provider), "antigravity") {
|
||||
chosen = a
|
||||
break
|
||||
}
|
||||
}
|
||||
if chosen == nil {
|
||||
fmt.Fprintf(os.Stderr, "error: no enabled antigravity auth found in %s\n", authsDir)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Printf("Using auth: id=%s label=%s\n", chosen.ID, chosen.Label)
|
||||
|
||||
// Fetch models from the upstream Antigravity API.
|
||||
fmt.Println("Fetching Antigravity model list from upstream...")
|
||||
|
||||
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
models := fetchModels(fetchCtx, chosen)
|
||||
if len(models) == 0 {
|
||||
fmt.Fprintln(os.Stderr, "warning: no models returned (API may be unavailable or token expired)")
|
||||
} else {
|
||||
fmt.Printf("Fetched %d models.\n", len(models))
|
||||
}
|
||||
|
||||
// Build the output payload.
|
||||
out := modelOutput{
|
||||
Models: models,
|
||||
}
|
||||
|
||||
// Marshal to JSON.
|
||||
var raw []byte
|
||||
if pretty {
|
||||
raw, err = json.MarshalIndent(out, "", " ")
|
||||
} else {
|
||||
raw, err = json.Marshal(out)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: failed to marshal JSON: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err = os.WriteFile(outputPath, raw, 0o644); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error: failed to write output file %s: %v\n", outputPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Printf("Model list saved to: %s\n", outputPath)
|
||||
}
|
||||
|
||||
func fetchModels(ctx context.Context, auth *coreauth.Auth) []modelEntry {
|
||||
accessToken := metaStringValue(auth.Metadata, "access_token")
|
||||
if accessToken == "" {
|
||||
fmt.Fprintln(os.Stderr, "error: no access token found in auth")
|
||||
return nil
|
||||
}
|
||||
|
||||
baseURLs := []string{antigravityBaseURLProd, antigravityBaseURLDaily, antigravitySandboxBaseURLDaily}
|
||||
|
||||
for _, baseURL := range baseURLs {
|
||||
modelsURL := baseURL + antigravityModelsPath
|
||||
|
||||
var payload []byte
|
||||
if auth != nil && auth.Metadata != nil {
|
||||
if pid, ok := auth.Metadata["project_id"].(string); ok && strings.TrimSpace(pid) != "" {
|
||||
payload = []byte(fmt.Sprintf(`{"project": "%s"}`, strings.TrimSpace(pid)))
|
||||
}
|
||||
}
|
||||
if len(payload) == 0 {
|
||||
payload = []byte(`{}`)
|
||||
}
|
||||
|
||||
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, modelsURL, strings.NewReader(string(payload)))
|
||||
if errReq != nil {
|
||||
continue
|
||||
}
|
||||
httpReq.Close = true
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
httpReq.Header.Set("User-Agent", misc.AntigravityUserAgent())
|
||||
|
||||
httpClient := &http.Client{Timeout: 30 * time.Second}
|
||||
if transport, _, errProxy := proxyutil.BuildHTTPTransport(auth.ProxyURL); errProxy == nil && transport != nil {
|
||||
httpClient.Transport = transport
|
||||
}
|
||||
httpResp, errDo := httpClient.Do(httpReq)
|
||||
if errDo != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
bodyBytes, errRead := io.ReadAll(httpResp.Body)
|
||||
httpResp.Body.Close()
|
||||
if errRead != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
|
||||
continue
|
||||
}
|
||||
|
||||
result := gjson.GetBytes(bodyBytes, "models")
|
||||
if !result.Exists() {
|
||||
continue
|
||||
}
|
||||
|
||||
var models []modelEntry
|
||||
|
||||
for originalName, modelData := range result.Map() {
|
||||
modelID := strings.TrimSpace(originalName)
|
||||
if modelID == "" {
|
||||
continue
|
||||
}
|
||||
// Skip internal/experimental models
|
||||
switch modelID {
|
||||
case "chat_20706", "chat_23310", "tab_flash_lite_preview", "tab_jump_flash_lite_preview", "gemini-2.5-flash-thinking", "gemini-2.5-pro":
|
||||
continue
|
||||
}
|
||||
|
||||
displayName := modelData.Get("displayName").String()
|
||||
if displayName == "" {
|
||||
displayName = modelID
|
||||
}
|
||||
|
||||
entry := modelEntry{
|
||||
ID: modelID,
|
||||
Object: "model",
|
||||
OwnedBy: "antigravity",
|
||||
Type: "antigravity",
|
||||
DisplayName: displayName,
|
||||
Name: modelID,
|
||||
Description: displayName,
|
||||
}
|
||||
|
||||
if maxTok := modelData.Get("maxTokens").Int(); maxTok > 0 {
|
||||
entry.ContextLength = int(maxTok)
|
||||
}
|
||||
if maxOut := modelData.Get("maxOutputTokens").Int(); maxOut > 0 {
|
||||
entry.MaxCompletionTokens = int(maxOut)
|
||||
}
|
||||
|
||||
models = append(models, entry)
|
||||
}
|
||||
|
||||
return models
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func metaStringValue(m map[string]interface{}, key string) string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
v, ok := m[key]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
return val
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
+115
-16
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -24,6 +25,8 @@ import (
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/managementasset"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/startupconfig"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/store"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/tui"
|
||||
@@ -103,6 +106,7 @@ func main() {
|
||||
var switchMode string
|
||||
var projectID string
|
||||
var vertexImport string
|
||||
var vertexImportPrefix string
|
||||
var configPath string
|
||||
var password string
|
||||
var noIncognito bool
|
||||
@@ -138,6 +142,7 @@ func main() {
|
||||
// TUI flag
|
||||
var launchTUI bool
|
||||
var standalone bool
|
||||
var localModel bool
|
||||
|
||||
// Define command-line flags for different operation modes.
|
||||
flag.BoolVar(&login, "login", false, "Login Google Account")
|
||||
@@ -177,9 +182,11 @@ func main() {
|
||||
flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
|
||||
flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path")
|
||||
flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file")
|
||||
flag.StringVar(&vertexImportPrefix, "vertex-import-prefix", "", "Prefix for Vertex model namespacing (use with -vertex-import)")
|
||||
flag.StringVar(&password, "password", "", "")
|
||||
flag.BoolVar(&launchTUI, "tui", false, "Start with terminal management UI")
|
||||
flag.BoolVar(&standalone, "standalone", false, "In TUI mode, start an embedded local server")
|
||||
flag.BoolVar(&localModel, "local-model", false, "Use embedded model catalog only, skip remote model fetching")
|
||||
|
||||
flag.BoolVar(&showVersion, "version", false, "Show ProxyPilot version and exit")
|
||||
flag.BoolVar(&showStatus, "status", false, "Show ProxyPilot status and exit")
|
||||
@@ -305,6 +312,7 @@ func main() {
|
||||
gitStoreRemoteURL string
|
||||
gitStoreUser string
|
||||
gitStorePassword string
|
||||
gitStoreBranch string
|
||||
gitStoreLocalPath string
|
||||
gitStoreInst *store.GitTokenStore
|
||||
gitStoreRoot string
|
||||
@@ -374,6 +382,9 @@ func main() {
|
||||
if value, ok := lookupEnv("GITSTORE_LOCAL_PATH", "gitstore_local_path"); ok {
|
||||
gitStoreLocalPath = value
|
||||
}
|
||||
if value, ok := lookupEnv("GITSTORE_GIT_BRANCH", "gitstore_git_branch"); ok {
|
||||
gitStoreBranch = value
|
||||
}
|
||||
if value, ok := lookupEnv("OBJECTSTORE_ENDPOINT", "objectstore_endpoint"); ok {
|
||||
useObjectStore = true
|
||||
objectStoreEndpoint = value
|
||||
@@ -508,7 +519,7 @@ func main() {
|
||||
}
|
||||
gitStoreRoot = filepath.Join(gitStoreLocalPath, "gitstore")
|
||||
authDir := filepath.Join(gitStoreRoot, "auths")
|
||||
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword)
|
||||
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword, gitStoreBranch)
|
||||
gitStoreInst.SetBaseDir(authDir)
|
||||
if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil {
|
||||
log.Errorf("failed to prepare git token store: %v", errRepo)
|
||||
@@ -546,12 +557,18 @@ func main() {
|
||||
configFilePath = configPath
|
||||
cfg, err = config.LoadConfigOptional(configPath, isCloudDeploy)
|
||||
} else {
|
||||
wd, err = os.Getwd()
|
||||
if err != nil {
|
||||
log.Errorf("failed to get working directory: %v", err)
|
||||
return
|
||||
exePath, errExe := os.Executable()
|
||||
if errExe != nil {
|
||||
log.WithError(errExe).Debug("failed to resolve executable path for default config lookup")
|
||||
}
|
||||
configFilePath = filepath.Join(wd, "config.yaml")
|
||||
resolution := startupconfig.ResolveConfigPath("", wd, exePath)
|
||||
if created, errPrepare := startupconfig.EnsureDefaultConfig(resolution); errPrepare != nil {
|
||||
log.Errorf("failed to prepare default config: %v", errPrepare)
|
||||
return
|
||||
} else if created {
|
||||
log.Infof("default config initialized from template: %s", resolution.ConfigPath)
|
||||
}
|
||||
configFilePath = resolution.ConfigPath
|
||||
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -651,7 +668,7 @@ func main() {
|
||||
|
||||
if vertexImport != "" {
|
||||
// Handle Vertex service account import
|
||||
cmd.DoVertexImport(cfg, vertexImport)
|
||||
cmd.DoVertexImport(cfg, vertexImport, vertexImportPrefix)
|
||||
} else if showVersion {
|
||||
// Version already printed at startup, just exit
|
||||
return
|
||||
@@ -812,9 +829,13 @@ func main() {
|
||||
cmd.WaitForCloudDeploy()
|
||||
return
|
||||
}
|
||||
// Start the main proxy service
|
||||
// Auto-generate management password if not provided
|
||||
// This enables browser-based webui access without requiring the -password flag
|
||||
|
||||
if localModel && (!launchTUI || standalone) {
|
||||
log.Info("Local model mode: using embedded model catalog, remote model updates disabled")
|
||||
}
|
||||
|
||||
// Auto-generate management password if not provided.
|
||||
// This enables browser-based webui access without requiring the -password flag.
|
||||
autoGenPassword := false
|
||||
if password == "" {
|
||||
if pw, err := desktopctl.GetManagementPassword(); err == nil {
|
||||
@@ -825,13 +846,91 @@ func main() {
|
||||
log.Warnf("failed to get management password: %v (webui may require manual authentication)", err)
|
||||
}
|
||||
}
|
||||
// Use standalone mode (no keep-alive shutdown) when password was auto-generated
|
||||
// Keep-alive shutdown is only needed when the tray app spawns the server as subprocess
|
||||
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
||||
if autoGenPassword {
|
||||
cmd.StartServiceStandalone(cfg, configFilePath, password)
|
||||
|
||||
if launchTUI {
|
||||
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", cfg.Port)
|
||||
if standalone {
|
||||
// Standalone mode: start an embedded local server and connect TUI client to it.
|
||||
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
||||
misc.StartAntigravityVersionUpdater(context.Background())
|
||||
if !localModel {
|
||||
registry.StartModelsUpdater(context.Background())
|
||||
}
|
||||
origStdout := os.Stdout
|
||||
origStderr := os.Stderr
|
||||
origLogOutput := log.StandardLogger().Out
|
||||
log.SetOutput(io.Discard)
|
||||
|
||||
devNull, errOpenDevNull := os.Open(os.DevNull)
|
||||
if errOpenDevNull == nil {
|
||||
os.Stdout = devNull
|
||||
os.Stderr = devNull
|
||||
}
|
||||
|
||||
restoreIO := func() {
|
||||
os.Stdout = origStdout
|
||||
os.Stderr = origStderr
|
||||
log.SetOutput(origLogOutput)
|
||||
if devNull != nil {
|
||||
_ = devNull.Close()
|
||||
}
|
||||
}
|
||||
|
||||
if password == "" {
|
||||
password = fmt.Sprintf("tui-%d-%d", os.Getpid(), time.Now().UnixNano())
|
||||
}
|
||||
|
||||
cancel, done := cmd.StartServiceBackground(cfg, configFilePath, password)
|
||||
|
||||
client := tui.NewClient(proxyURL, password)
|
||||
ready := false
|
||||
backoff := 100 * time.Millisecond
|
||||
for i := 0; i < 30; i++ {
|
||||
if _, errFetchStatus := client.FetchStatus(); errFetchStatus == nil {
|
||||
ready = true
|
||||
break
|
||||
}
|
||||
time.Sleep(backoff)
|
||||
if backoff < time.Second {
|
||||
backoff = time.Duration(float64(backoff) * 1.5)
|
||||
}
|
||||
}
|
||||
|
||||
if !ready {
|
||||
restoreIO()
|
||||
cancel()
|
||||
<-done
|
||||
fmt.Fprintf(os.Stderr, "TUI error: embedded server is not ready\n")
|
||||
return
|
||||
}
|
||||
|
||||
if errRun := tui.RunWithStdio(proxyURL, password, os.Stdin, origStdout); errRun != nil {
|
||||
restoreIO()
|
||||
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
|
||||
} else {
|
||||
restoreIO()
|
||||
}
|
||||
|
||||
cancel()
|
||||
<-done
|
||||
} else {
|
||||
// Default TUI mode: pure management client.
|
||||
// The proxy server must already be running.
|
||||
if errRun := tui.Run(proxyURL, password); errRun != nil {
|
||||
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cmd.StartService(cfg, configFilePath, password)
|
||||
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
||||
misc.StartAntigravityVersionUpdater(context.Background())
|
||||
if !localModel {
|
||||
registry.StartModelsUpdater(context.Background())
|
||||
}
|
||||
if autoGenPassword {
|
||||
cmd.StartServiceStandalone(cfg, configFilePath, password)
|
||||
} else {
|
||||
cmd.StartService(cfg, configFilePath, password)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+45
-4
@@ -25,6 +25,10 @@ remote-management:
|
||||
# Disable the bundled management control panel asset download and HTTP route when true.
|
||||
disable-control-panel: false
|
||||
|
||||
# Disable automatic periodic background updates of the management panel from GitHub (default: false).
|
||||
# When enabled, the panel is only downloaded on first access if missing, and never auto-updated afterward.
|
||||
# disable-auto-update-panel: false
|
||||
|
||||
# GitHub repository for the management control panel. Accepts a repository URL or releases API URL.
|
||||
panel-github-repository: "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
|
||||
|
||||
@@ -63,6 +67,7 @@ error-logs-max-files: 10
|
||||
usage-statistics-enabled: false
|
||||
|
||||
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/
|
||||
# Per-entry proxy-url also supports "direct" or "none" to bypass both the global proxy-url and environment proxies explicitly.
|
||||
proxy-url: ""
|
||||
|
||||
# When true, unprefixed model requests only use credentials without a prefix (except when prefix == model name).
|
||||
@@ -82,10 +87,14 @@ max-retry-credentials: 0
|
||||
# Maximum wait time in seconds for a cooled-down credential before triggering a retry.
|
||||
max-retry-interval: 30
|
||||
|
||||
# When true, disable auth/model cooldown scheduling globally (prevents blackout windows after failure states).
|
||||
disable-cooling: false
|
||||
|
||||
# Quota exceeded behavior
|
||||
quota-exceeded:
|
||||
switch-project: true # Whether to automatically switch to another project when a quota is exceeded
|
||||
switch-preview-model: true # Whether to automatically switch to a preview model when a quota is exceeded
|
||||
antigravity-credits: true # Whether to retry Antigravity quota_exhausted 429s once with enabledCreditTypes=["GOOGLE_ONE_AI"]
|
||||
|
||||
# Routing strategy for selecting credentials when multiple match.
|
||||
routing:
|
||||
@@ -94,6 +103,10 @@ routing:
|
||||
# When true, enable authentication for the WebSocket API (/v1/ws).
|
||||
ws-auth: false
|
||||
|
||||
# When true, enable Gemini CLI internal endpoints (/v1internal:*).
|
||||
# Default is false for safety.
|
||||
enable-gemini-cli-endpoint: false
|
||||
|
||||
# When > 0, emit blank lines every N seconds for non-streaming responses to prevent idle timeouts.
|
||||
nonstream-keepalive-interval: 0
|
||||
|
||||
@@ -110,6 +123,7 @@ nonstream-keepalive-interval: 0
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
# proxy-url: "socks5://proxy.example.com:1080"
|
||||
# # proxy-url: "direct" # optional: explicit direct connect for this credential
|
||||
# models:
|
||||
# - name: "gemini-2.5-flash" # upstream model name
|
||||
# alias: "gemini-flash" # client alias mapped to the upstream model
|
||||
@@ -128,6 +142,7 @@ nonstream-keepalive-interval: 0
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
|
||||
# # proxy-url: "direct" # optional: explicit direct connect for this credential
|
||||
# models:
|
||||
# - name: "gpt-5-codex" # upstream model name
|
||||
# alias: "codex-latest" # client alias mapped to the upstream model
|
||||
@@ -146,6 +161,7 @@ nonstream-keepalive-interval: 0
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
|
||||
# # proxy-url: "direct" # optional: explicit direct connect for this credential
|
||||
# models:
|
||||
# - name: "claude-3-5-sonnet-20241022" # upstream model name
|
||||
# alias: "claude-sonnet-latest" # client alias mapped to the upstream model
|
||||
@@ -164,14 +180,31 @@ nonstream-keepalive-interval: 0
|
||||
# - "API"
|
||||
# - "proxy"
|
||||
# cache-user-id: true # optional: default is false; set true to reuse cached user_id per API key instead of generating a random one each request
|
||||
# experimental-cch-signing: false # optional: default is false; when true, sign the final /v1/messages body using the current Claude Code cch algorithm
|
||||
# # keep this disabled unless you explicitly need the behavior, so upstream seed changes fall back to legacy proxy behavior
|
||||
|
||||
# Default headers for Claude API requests. Update when Claude Code releases new versions.
|
||||
# These are used as fallbacks when the client does not send its own headers.
|
||||
# In legacy mode, user-agent/package-version/runtime-version/timeout are used as fallbacks
|
||||
# when the client omits them, while OS/arch remain runtime-derived. When
|
||||
# stabilize-device-profile is enabled, OS/arch stay pinned to the baseline values below,
|
||||
# while user-agent/package-version/runtime-version seed a software fingerprint that can
|
||||
# still upgrade to newer official Claude client versions.
|
||||
# claude-header-defaults:
|
||||
# user-agent: "claude-cli/2.1.44 (external, sdk-cli)"
|
||||
# package-version: "0.74.0"
|
||||
# runtime-version: "v24.3.0"
|
||||
# os: "MacOS"
|
||||
# arch: "arm64"
|
||||
# timeout: "600"
|
||||
# stabilize-device-profile: false # optional, default false; set true to enable per-auth/API-key fingerprint pinning
|
||||
|
||||
# Default headers for Codex OAuth model requests.
|
||||
# These are used only for file-backed/OAuth Codex requests when the client
|
||||
# does not send the header. `user-agent` applies to HTTP and websocket requests;
|
||||
# `beta-features` only applies to websocket requests. They do not apply to codex-api-key entries.
|
||||
# codex-header-defaults:
|
||||
# user-agent: "codex_cli_rs/0.114.0 (Mac OS 14.2.0; x86_64) vscode/1.111.0"
|
||||
# beta-features: "multi_agent"
|
||||
|
||||
# OpenAI compatibility providers
|
||||
# openai-compatibility:
|
||||
@@ -183,10 +216,13 @@ nonstream-keepalive-interval: 0
|
||||
# api-key-entries:
|
||||
# - api-key: "sk-or-v1-...b780"
|
||||
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
|
||||
# # proxy-url: "direct" # optional: explicit direct connect for this credential
|
||||
# - api-key: "sk-or-v1-...b781" # without proxy-url
|
||||
# models: # The models supported by the provider.
|
||||
# - name: "moonshotai/kimi-k2:free" # The actual model name.
|
||||
# alias: "kimi-k2" # The alias used in the API.
|
||||
# alias: "kimi-k2" # The alias used in the API.
|
||||
# thinking: # optional: omit to default to levels ["low","medium","high"]
|
||||
# levels: ["low", "medium", "high"]
|
||||
# # You may repeat the same alias to build an internal model pool.
|
||||
# # The client still sees only one alias in the model list.
|
||||
# # Requests to that alias will round-robin across the upstream names below,
|
||||
@@ -199,12 +235,13 @@ nonstream-keepalive-interval: 0
|
||||
# - name: "kimi-k2.5"
|
||||
# alias: "claude-opus-4.66"
|
||||
|
||||
# Vertex API keys (Vertex-compatible endpoints, use API key + base URL)
|
||||
# Vertex API keys (Vertex-compatible endpoints, base-url is optional)
|
||||
# vertex-api-key:
|
||||
# - api-key: "vk-123..." # x-goog-api-key header
|
||||
# prefix: "test" # optional: require calls like "test/vertex-pro" to target this credential
|
||||
# base-url: "https://example.com/api" # e.g. https://zenmux.ai/api
|
||||
# base-url: "https://example.com/api" # optional, e.g. https://zenmux.ai/api; falls back to Google Vertex when omitted
|
||||
# proxy-url: "socks5://proxy.example.com:1080" # optional per-key proxy override
|
||||
# # proxy-url: "direct" # optional: explicit direct connect for this credential
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
# models: # optional: map aliases to upstream model names
|
||||
@@ -254,6 +291,10 @@ nonstream-keepalive-interval: 0
|
||||
# These aliases rename model IDs for both model listing and request routing.
|
||||
# Supported channels: gemini-cli, vertex, aistudio, antigravity, claude, codex, qwen, iflow, kimi.
|
||||
# NOTE: Aliases do not apply to gemini-api-key, codex-api-key, claude-api-key, openai-compatibility, vertex-api-key, or ampcode.
|
||||
# NOTE: Because aliases affect the merged /v1 model list and merged request routing, overlapping
|
||||
# client-visible names can become ambiguous across providers. /api/provider/{provider}/... helps
|
||||
# you select the protocol surface, but inference backend selection can still follow the resolved
|
||||
# model/alias. For strict backend pinning, use unique aliases/prefixes or avoid overlapping names.
|
||||
# You can repeat the same name with different aliases to expose multiple client model names.
|
||||
# oauth-model-alias:
|
||||
# gemini-cli:
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# ProxyPilot Rust Replatform
|
||||
|
||||
This branch carries the Rust rewrite line for ProxyPilot.
|
||||
|
||||
## Branch contract
|
||||
|
||||
- Go `main` remains the shipping line while Rust grows.
|
||||
- Rust lives under [`rust/`](/home/fsos/code-lean/ai-tools/ProxyPilot/rust).
|
||||
- The Rust line is terminal-first and does not treat the browser dashboard as a required early target.
|
||||
- The first real milestone is a working Rust executable that can proxy a Codex-compatible request end-to-end.
|
||||
|
||||
## Current milestone
|
||||
|
||||
`proxypilot-rs` is the first Rust binary in the repo. It currently provides:
|
||||
|
||||
- a `run` command that starts a local proxy server
|
||||
- a `tui` command that opens a minimal terminal operator view
|
||||
- a TOML config model plus a separate local state file for saved accounts
|
||||
- explicit Codex-facing routes for `/v1/models`, `/v1/chat/completions`, and `/v1/responses`
|
||||
- a local `/v0/runtime/stats` operator surface for runtime-memory counters, auth-health, and last refresh status
|
||||
- CLI account commands for adding, importing, device-login, refresh, listing, activating, and removing Codex accounts; these manage saved disk state only and do not pretend a running proxy has already adopted the change
|
||||
- optional `codex.refresh_token_url` config support for redirecting Codex refresh exchanges to a local stub during validation, while preserving the live OpenAI default when unset
|
||||
- a TUI operator console that shows live runtime stats, runtime-unavailable copy, local accounts, selected-account details, token state labels, terminal actions for activate/refresh/delete, separate selected-account vs active-account refresh handling, and the `r` / `c` reload-clear controls
|
||||
- runtime credential resolution that prefers the active saved account over the config fallback key
|
||||
- proactive Codex token refresh when the active saved account is already expired or within the refresh window, plus the existing 401-retry refresh fallback
|
||||
- end-to-end tests against a mocked upstream server
|
||||
|
||||
## Design defaults
|
||||
|
||||
- Go is the behavioral reference, not a line-by-line port target.
|
||||
- The Rust branch is allowed to redesign config and management surfaces.
|
||||
- The product identity does not change: ProxyPilot still exists to be a local proxy for coding tools.
|
||||
|
||||
## Local workflow
|
||||
|
||||
From the repo root:
|
||||
|
||||
```bash
|
||||
cd rust
|
||||
cargo run -p proxypilot-rs -- init
|
||||
cargo run -p proxypilot-rs -- account add-codex --name primary --api-key sk-...
|
||||
cargo run -p proxypilot-rs -- account import-codex --file ../auths/codex-example.json --activate
|
||||
cargo run -p proxypilot-rs -- account login-codex-device --activate
|
||||
cargo run -p proxypilot-rs -- account refresh-codex
|
||||
cargo run -p proxypilot-rs -- account remove --name old-account
|
||||
cargo run -p proxypilot-rs -- run --config proxypilot-rs.toml
|
||||
```
|
||||
|
||||
Open the TUI with:
|
||||
|
||||
```bash
|
||||
cd rust
|
||||
cargo run -p proxypilot-rs -- tui --config proxypilot-rs.toml
|
||||
```
|
||||
@@ -0,0 +1,84 @@
|
||||
# Session Progress - 2026-03-12
|
||||
|
||||
## Summary
|
||||
Merged upstream CLIProxyAPI releases `v6.8.50` and `v6.8.51` directly into ProxyPilot `main`, resolved fork-specific conflicts in startup and Docker publishing paths, prepared the next dev release tag `v0.3.0-dev-0.42`, then switched release publishing to a local/manual flow and uploaded the release assets outside GitHub Actions.
|
||||
|
||||
## Upstream Releases Included
|
||||
- `v6.8.50` - preserve string-form system prompts, cap websocket body log growth, and extend scheduler / executor coverage
|
||||
- `v6.8.51` - refresh model catalog from network on startup, register Codex models by plan tier, and refresh release / workflow paths
|
||||
|
||||
## Conflict Resolution Notes
|
||||
- Kept ProxyPilot Docker publishing identity in `.github/workflows/docker-image.yml` and added the upstream models catalog refresh step before image builds.
|
||||
- Kept ProxyPilot's management-password startup flow in `cmd/server/main.go` and added `registry.StartModelsUpdater(...)` before service startup.
|
||||
- Accepted the upstream move from generated static registry data to embedded `internal/registry/models/models.json`, including deletion of `internal/registry/model_definitions_static_data.go`.
|
||||
|
||||
## Fork-Specific Follow-Ups
|
||||
- Updated `internal/cmd/list_models.go` to use the new Codex plan-tier model getters instead of the removed `registry.GetOpenAIModels`.
|
||||
- Fixed `sdk/auth/filestore.go` delete-path resolution so nested relative auth IDs delete under the configured base dir, absolute paths still work for the management API, and traversal outside the base dir is rejected.
|
||||
- Updated `UPSTREAM_VERSION` to `v6.8.51`.
|
||||
- Updated `features.json` upstream marker to `CLIProxyAPI v6.8.51`.
|
||||
- Changed `.github/workflows/proxypilot-release.yml` and `.github/workflows/docker-image.yml` from tag-triggered runs to manual dispatch so releases can be built locally and uploaded manually instead of consuming GitHub Actions minutes.
|
||||
- Built the `v0.3.0-dev-0.42` release assets locally from the tag snapshot and uploaded:
|
||||
- `proxypilot-darwin-amd64`
|
||||
- `proxypilot-darwin-arm64`
|
||||
- `proxypilot-linux-amd64`
|
||||
- `proxypilot-linux-arm64`
|
||||
- `proxypilot-windows-amd64.exe`
|
||||
- `checksums.txt`
|
||||
|
||||
## Verification
|
||||
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
|
||||
- `go vet ./...` - PASS
|
||||
- `go test ./internal/runtime/executor/...` - PASS
|
||||
- `go test ./internal/registry/...` - PASS
|
||||
- `go test ./sdk/api/handlers/openai/...` - PASS
|
||||
- `go test ./sdk/cliproxy/auth -run 'TestFileStore_Delete_(RemovesFile|NotFound|AbsolutePath|RejectsTraversalOutsideBaseDir)' -v` - PASS
|
||||
- `go test ./sdk/cliproxy/auth` - PASS
|
||||
- `go test ./sdk/cliproxy/...` - PASS
|
||||
- `go test ./...` - PASS
|
||||
|
||||
## Release Notes
|
||||
- Next dev tag: `v0.3.0-dev-0.42`
|
||||
- Latest upstream target at merge time: `CLIProxyAPI v6.8.51`
|
||||
|
||||
## Maintenance Review
|
||||
- Completed parallel findings-first review of `internal/auth/*`, `internal/translator/*`, and `internal/api/handlers/*` on 2026-03-12 12:01:40 +07.
|
||||
- Auth review findings:
|
||||
- `internal/auth/kiro/token_repository.go` only queues `auth_method` values `idc` and `builder-id` for background refresh even though `internal/auth/kiro/oauth.go` persists social logins as `auth_method: "social"` and the refresher has a default OAuth refresh path for non-SSO methods. Result: Google/GitHub Kiro tokens are skipped by auto-refresh.
|
||||
- `internal/auth/kiro/token_repository.go` walks nested token files but rewrites refreshed tokens back to `filepath.Join(baseDir, token.ID)` after truncating IDs to `filepath.Base(path)`. Result: nested Kiro token files would be rewritten into the auth root instead of their original directory.
|
||||
- Translator review findings:
|
||||
- `internal/translator/kiro/openai` can emit streamed tool-call argument deltas with the wrong OpenAI tool index.
|
||||
- `internal/translator/kiro/openai` does not actually enforce `tool_choice`; it still forwards tools when callers request `none` or pin a specific function.
|
||||
- `internal/translator/openai/openai/responses` downgrades `developer` messages to `user`.
|
||||
- `internal/translator/gemini/openai/chat-completions` reads/mapping finish reasons incorrectly for some response shapes.
|
||||
- `internal/translator/gemini/openai/responses` can send `functionResponse.name = "unknown"` on follow-up tool-output requests.
|
||||
- API handler review findings:
|
||||
- `internal/api/handlers/management/memory.go` uses raw `session` query values to build filesystem paths for delete/export/import instead of the memory store's sanitized session path helper, allowing traversal outside the memory store root.
|
||||
- `internal/api/handlers/management/generic_import.go` derives auth filenames from the first characters of imported API keys, exposing secret prefixes in filenames and management responses.
|
||||
- `internal/api/handlers/management/auth_files.go` writes uploaded auth files to disk before validation and leaves invalid files behind on registration failure.
|
||||
- `internal/api/handlers/management/config_basic.go` returns a zero-value config from `GetConfig` because it serializes `new(*h.cfg)` instead of the current config.
|
||||
- `internal/api/handlers/management/auth_priority.go` and `internal/api/handlers/management/auth_files.go` update priority in places the runtime selector does not read, so management-set auth priority does not affect routing and does not persist reliably for file-backed auths.
|
||||
- Config mutation helpers in `internal/api/handlers/management/handler.go` mutate `h.cfg` before persistence succeeds, so failed writes can leave runtime config diverged from disk until restart.
|
||||
- Review validation:
|
||||
- `go test ./internal/auth/... ./internal/translator/... ./internal/api/handlers/...` - PASS
|
||||
|
||||
## Maintenance Fixes
|
||||
- Hardened management memory delete/export/import so session names are validated before resolving filesystem paths, blocking traversal attempts outside the memory store root.
|
||||
- Changed bulk API-key import filenames to opaque `provider-import-...` names so credential prefixes are no longer exposed in filenames or management responses.
|
||||
- Changed auth upload handling to validate uploaded JSON before committing it to disk and to roll back failed registrations instead of leaving broken auth files behind.
|
||||
- Fixed `GetConfig` to return the live in-memory config and changed the simple config mutation helpers to persist cloned config state instead of mutating runtime config before the file write succeeds.
|
||||
- Fixed file-backed auth persistence so `priority`, `prefix`, and `proxy_url` survive saves, reloads, and management edits, and so runtime selection prefers `Auth.Priority` with a legacy attribute fallback.
|
||||
- Changed token writers across codex, claude, gemini, kimi, qwen, iflow, copilot, and vertex to use atomic `0600` JSON writes.
|
||||
- Fixed Kiro background refresh so blank refresh responses do not erase the existing refresh token, nested token paths refresh in place, and social auth token files participate in the refresh scan.
|
||||
- Fixed Kiro OAuth callback servers so shutdown waits on a dedicated completion signal instead of racing the login flow for the only callback result.
|
||||
- Fixed Kiro/OpenAI tool streaming to keep a stable mapping from content-block indexes to OpenAI tool ordinals.
|
||||
- Fixed Kiro/OpenAI request translation so `tool_choice=none|required|function` is enforced instead of treated as a prompt-only hint.
|
||||
- Fixed OpenAI Responses to Chat Completions conversion to preserve `developer` role messages.
|
||||
- Fixed Gemini/OpenAI finish-reason mapping so OpenAI receives valid enums while the original Gemini reason is preserved in `native_finish_reason`.
|
||||
- Added a bounded Gemini function-call name cache so `previous_response_id` follow-up tool outputs resolve the original function name and fail closed when they cannot.
|
||||
|
||||
## Maintenance Fix Verification
|
||||
- `go test ./internal/auth/... ./sdk/auth ./sdk/cliproxy/auth ./internal/translator/... ./internal/api/handlers/...` - PASS
|
||||
- `go test ./internal/api/handlers/management` - PASS
|
||||
- `go test ./...` - PASS
|
||||
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
|
||||
@@ -0,0 +1,28 @@
|
||||
# Session Progress - 2026-03-17
|
||||
|
||||
## Summary
|
||||
Merged upstream CLIProxyAPI release `v6.8.55` into ProxyPilot `main`, carrying forward the fork's workflow and branding decisions while absorbing upstream changes from `v6.8.52` through `v6.8.55`.
|
||||
Built the release assets locally and published `v0.3.0-dev-0.43` on GitHub as the latest ProxyPilot release.
|
||||
|
||||
## Upstream Releases Included
|
||||
- `v6.8.52` - Codex websocket header defaults and related compatibility updates
|
||||
- `v6.8.53` - Antigravity model refresh and proxy helper improvements
|
||||
- `v6.8.54` - auth file metadata exposure and management API test coverage
|
||||
- `v6.8.55` - auth list priority/note support, Gemini responses tool-output fixes, and proxy utility additions
|
||||
|
||||
## Conflict Resolution Notes
|
||||
- Kept the fork versions of `.github/workflows/docker-image.yml`, `.github/workflows/release.yaml`, `.github/workflows/pr-test-build.yml`, and `.goreleaser.yml` so this sync does not alter CI or release automation.
|
||||
- Kept ProxyPilot README branding and deleted the upstream `README_CN.md` revival because this fork intentionally does not ship that file.
|
||||
- Merged `internal/api/handlers/management/auth_files.go` semantically so ProxyPilot keeps its `Auth.Priority` persistence while also adding upstream `note` support and priority/note exposure in the auth-file API.
|
||||
- Kept the stricter Gemini Responses JSON validation in `internal/translator/gemini/openai/responses/gemini_openai-responses_request.go` so partial JSON strings are not embedded as structured results.
|
||||
|
||||
## Repo State Updates
|
||||
- Updated `UPSTREAM_VERSION` to `v6.8.55`.
|
||||
- Updated `features.json` upstream marker to `CLIProxyAPI v6.8.55`.
|
||||
- Published dev release: `v0.3.0-dev-0.43`.
|
||||
|
||||
## Verification
|
||||
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
|
||||
- `mise exec go@1.26.0 -- go vet ./...` - PASS
|
||||
- `mise exec go@1.26.0 -- go test ./...` - PASS
|
||||
- `gh release list -R Finesssee/ProxyPilot --limit 5` - PASS (`v0.3.0-dev-0.43` is `Latest`)
|
||||
@@ -0,0 +1,26 @@
|
||||
# Session Progress - 2026-04-01
|
||||
|
||||
## Summary
|
||||
Merged upstream CLIProxyAPI release `v6.9.7` into ProxyPilot on a dedicated sync branch, carrying forward ProxyPilot branding and local-manual release workflow choices while absorbing the upstream changes from `v6.9.6` and `v6.9.7`.
|
||||
Re-established a fully local Windows installer build path on Linux using a repo-scoped Wine prefix plus Inno Setup so the `Setup.exe` can be built without CI/CD.
|
||||
|
||||
## Upstream Releases Included
|
||||
- `v6.9.6` - intermediate upstream changes now included through the `v6.9.7` merge
|
||||
- `v6.9.7` - Codex executor/cache behavior updates, Amp response rewriting improvements, scheduler/auth updates, and related tests
|
||||
|
||||
## Conflict Resolution Notes
|
||||
- Kept the ProxyPilot README and removed upstream `README_CN.md` and `README_JA.md` revivals because this fork intentionally does not ship those translation files.
|
||||
- Followed upstream on the Codex continuity revert by deleting `internal/runtime/executor/codex_continuity.go` and aligning the Codex cache tests with `v6.9.7`, since upstream explicitly reverted that helper rather than evolving it.
|
||||
- Preserved the existing fork policy of local/manual releases instead of changing CI or workflow behavior as part of this sync.
|
||||
|
||||
## Repo State Updates
|
||||
- Updated `UPSTREAM_VERSION` to `v6.9.7`.
|
||||
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.7`.
|
||||
- Prepared a local Windows installer toolchain using Wine + Inno Setup for the upcoming `v0.3.0-dev-0.47` release build.
|
||||
|
||||
## Pending Verification
|
||||
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
|
||||
- `mise exec go@1.26.0 -- go vet ./...`
|
||||
- `mise exec go@1.26.0 -- go test ./...`
|
||||
- full local release asset build for `v0.3.0-dev-0.47`
|
||||
- `gh release list -R Finesssee/ProxyPilot --limit 5`
|
||||
@@ -0,0 +1,28 @@
|
||||
# Session Progress - 2026-04-03
|
||||
|
||||
## Summary
|
||||
Merged upstream CLIProxyAPI release `v6.9.10` into ProxyPilot on a dedicated sync branch and preserved the fork's local/manual release workflow.
|
||||
Reconciled upstream's executor helper-package move with ProxyPilot's existing executor call sites by keeping the new `internal/runtime/executor/helps/` layout while restoring compatibility entrypoints in `internal/runtime/executor/`.
|
||||
|
||||
## Upstream Releases Included
|
||||
- `v6.9.8` - intermediate upstream changes now included through the `v6.9.10` merge
|
||||
- `v6.9.9` - intermediate upstream changes now included through the `v6.9.10` merge
|
||||
- `v6.9.10` - latest upstream sync target for this release cycle
|
||||
|
||||
## Conflict Resolution Notes
|
||||
- Kept the ProxyPilot README and continued to omit upstream `README_CN.md` and `README_JA.md` revivals because this fork does not ship those translation files.
|
||||
- Preserved ProxyPilot's auth-file persistence behavior, including `prefix`, `proxy_url`, `priority`, and last-refresh handling, while also bringing in upstream custom-header hydration and patch support.
|
||||
- Kept upstream's `internal/runtime/executor/helps/` reorganization, but restored executor-package compatibility wrappers/files so existing fork-specific executors still compile without a larger refactor in the same release pass.
|
||||
- Continued to omit the upstream TUI translation/usage-tab files because ProxyPilot's current TUI surface does not carry those forked files.
|
||||
|
||||
## Repo State Updates
|
||||
- Updated `UPSTREAM_VERSION` to `v6.9.10`.
|
||||
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.10`.
|
||||
- Recorded the merge commit `chore: merge upstream CLIProxyAPI v6.9.10` before starting validation and release assembly.
|
||||
|
||||
## Pending Verification
|
||||
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
|
||||
- `mise exec go@1.26.0 -- go vet ./...`
|
||||
- `mise exec go@1.26.0 -- go test ./...`
|
||||
- full local release asset build for `v0.3.0-dev-0.48`
|
||||
- `gh release list -R Finesssee/ProxyPilot --limit 5`
|
||||
@@ -0,0 +1,26 @@
|
||||
# Session Progress - 2026-04-04
|
||||
|
||||
## Summary
|
||||
Merged upstream CLIProxyAPI release `v6.9.12` into ProxyPilot on a dedicated sync branch and kept the existing local/manual release workflow unchanged.
|
||||
This catch-up pull included the upstream delta from `v6.9.11` through `v6.9.12` and merged cleanly without any fork-specific conflict resolution work.
|
||||
|
||||
## Upstream Releases Included
|
||||
- `v6.9.11` - intermediate upstream changes now included through the `v6.9.12` merge
|
||||
- `v6.9.12` - latest upstream sync target for this release cycle
|
||||
|
||||
## Merge Notes
|
||||
- The merge applied cleanly with upstream changes concentrated in `config.example.yaml`, `internal/config/sdk_config.go`, `internal/runtime/executor/qwen_executor.go`, and `sdk/api/handlers/gemini/gemini-cli_handlers.go`.
|
||||
- No additional ProxyPilot compatibility shims were needed beyond the executor-wrapper structure restored in the prior sync.
|
||||
- ProxyPilot branding, release routing, and local-build release flow remain unchanged.
|
||||
|
||||
## Repo State Updates
|
||||
- Updated `UPSTREAM_VERSION` to `v6.9.12`.
|
||||
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.12`.
|
||||
- Prepared the repo for the next local/manual release: `v0.3.0-dev-0.49`.
|
||||
|
||||
## Pending Verification
|
||||
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
|
||||
- `mise exec go@1.26.0 -- go vet ./...`
|
||||
- `mise exec go@1.26.0 -- go test ./...`
|
||||
- full local release asset build for `v0.3.0-dev-0.49`
|
||||
- `gh release list -R Finesssee/ProxyPilot --limit 5`
|
||||
@@ -0,0 +1,28 @@
|
||||
# Session Progress - 2026-04-05
|
||||
|
||||
## Summary
|
||||
Merged upstream CLIProxyAPI release `v6.9.15` into ProxyPilot on a dedicated sync branch based on the latest `origin/main`.
|
||||
Kept the local management-asset security fix from `origin/main`, preserved ProxyPilot branding and local/manual release workflow choices, and absorbed the upstream delta from `v6.9.13` through `v6.9.15`.
|
||||
|
||||
## Upstream Releases Included
|
||||
- `v6.9.13` - vertex credential namespacing support, websocket custom tool-call repair, and model catalog refreshes
|
||||
- `v6.9.14` - antigravity version refresh updates and additional upstream maintenance changes
|
||||
- `v6.9.15` - API-key proxy resolution improvements and stricter Qwen system-message handling
|
||||
|
||||
## Conflict Resolution Notes
|
||||
- Kept the ProxyPilot README branding and continued to omit upstream `README_CN.md` and `README_JA.md` revivals because this fork does not ship those translated files.
|
||||
- Kept the existing local/manual release workflow and combined the fork's broader `.gitignore` with upstream's additional local-tool entries.
|
||||
- Preserved the local `internal/managementasset/updater.go` security behavior that removes the unverified fallback download path while accepting the rest of the upstream sync.
|
||||
- Merged `cmd/server/main.go` semantically so ProxyPilot keeps its wider CLI surface while also adding upstream `--vertex-import-prefix` support.
|
||||
|
||||
## Repo State Updates
|
||||
- Updated `UPSTREAM_VERSION` to `v6.9.15`.
|
||||
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.15`.
|
||||
- Prepared the repo for the next clean release tag: `v0.3.0-dev-0.51`.
|
||||
|
||||
## Pending Verification
|
||||
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
|
||||
- `go vet ./...`
|
||||
- `go test ./...`
|
||||
- clean-tree packaging and release asset assembly for `v0.3.0-dev-0.51`
|
||||
- `gh release list -R Finesssee/ProxyPilot --limit 5`
|
||||
@@ -52,11 +52,11 @@ func init() {
|
||||
sdktr.Register(fOpenAI, fMyProv,
|
||||
func(model string, raw []byte, stream bool) []byte { return raw },
|
||||
sdktr.ResponseTransform{
|
||||
Stream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) []string {
|
||||
return []string{string(raw)}
|
||||
Stream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) [][]byte {
|
||||
return [][]byte{raw}
|
||||
},
|
||||
NonStream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) string {
|
||||
return string(raw)
|
||||
NonStream: func(ctx context.Context, model string, originalReq, translatedReq, raw []byte, param *any) []byte {
|
||||
return raw
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
+6
-6
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"project": "ProxyPilot",
|
||||
"version": "0.3.0",
|
||||
"upstream": "CLIProxyAPI v6.8.49",
|
||||
"upstream": "CLIProxyAPI v6.9.15",
|
||||
"features": [
|
||||
{
|
||||
"id": 1,
|
||||
@@ -103,24 +103,24 @@
|
||||
"id": 17,
|
||||
"name": "Auth packages code review",
|
||||
"description": "Codex review of internal/auth/* packages",
|
||||
"passes": false
|
||||
"passes": true
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"name": "Translator packages code review",
|
||||
"description": "Codex review of internal/translator/* packages",
|
||||
"passes": false
|
||||
"passes": true
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"name": "API handlers code review",
|
||||
"description": "Codex review of internal/api/handlers/* packages",
|
||||
"passes": false
|
||||
"passes": true
|
||||
}
|
||||
],
|
||||
"summary": {
|
||||
"total": 19,
|
||||
"passing": 16,
|
||||
"failing": 3
|
||||
"passing": 19,
|
||||
"failing": 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +96,7 @@ require (
|
||||
github.com/muesli/termenv v0.16.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
|
||||
github.com/pierrec/xxHash v0.1.5
|
||||
github.com/pjbgf/sha1cd v0.5.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
|
||||
@@ -180,6 +180,8 @@ github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgF
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pierrec/xxHash v0.1.5 h1:n/jBpwTHiER4xYvK3/CdPVnLDPchj8eTJFFLUb4QHBo=
|
||||
github.com/pierrec/xxHash v0.1.5/go.mod h1:w2waW5Zoa/Wc4Yqe0wgrIYAGKqRMf7czn2HNKXmuL+I=
|
||||
github.com/pjbgf/sha1cd v0.5.0 h1:a+UkboSi1znleCDUNT3M5YxjOnN1fz2FhN48FlwCxs0=
|
||||
github.com/pjbgf/sha1cd v0.5.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "0.1.0"
|
||||
#endif
|
||||
#ifndef VersionInfoVersion
|
||||
#define VersionInfoVersion AppVersion
|
||||
#endif
|
||||
#ifndef RepoRoot
|
||||
#define RepoRoot ".."
|
||||
#endif
|
||||
@@ -56,13 +59,13 @@ OutputBaseFilename=ProxyPilot-{#AppVersion}-Setup
|
||||
AppCopyright=MIT License - ProxyPilot Contributors
|
||||
|
||||
; --- Version Info Embedded in Installer ---
|
||||
VersionInfoVersion={#AppVersion}
|
||||
VersionInfoVersion={#VersionInfoVersion}
|
||||
VersionInfoCompany=ProxyPilot
|
||||
VersionInfoDescription=ProxyPilot Installer - Local AI Proxy
|
||||
VersionInfoTextVersion={#AppVersion}
|
||||
VersionInfoCopyright=MIT License
|
||||
VersionInfoProductName=ProxyPilot
|
||||
VersionInfoProductVersion={#AppVersion}
|
||||
VersionInfoProductVersion={#VersionInfoVersion}
|
||||
|
||||
[Languages]
|
||||
Name: "english"; MessagesFile: "compiler:Default.isl"
|
||||
|
||||
@@ -5,17 +5,17 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/runtime/geminicli"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/net/proxy"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
)
|
||||
@@ -637,6 +637,11 @@ func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper {
|
||||
if proxyStr := strings.TrimSpace(auth.ProxyURL); proxyStr != "" {
|
||||
proxyCandidates = append(proxyCandidates, proxyStr)
|
||||
}
|
||||
if h != nil && h.cfg != nil {
|
||||
if proxyStr := strings.TrimSpace(proxyURLFromAPIKeyConfig(h.cfg, auth)); proxyStr != "" {
|
||||
proxyCandidates = append(proxyCandidates, proxyStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if h != nil && h.cfg != nil {
|
||||
if proxyStr := strings.TrimSpace(h.cfg.ProxyURL); proxyStr != "" {
|
||||
@@ -659,46 +664,128 @@ func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper {
|
||||
return clone
|
||||
}
|
||||
|
||||
func buildProxyTransport(proxyStr string) *http.Transport {
|
||||
proxyStr = strings.TrimSpace(proxyStr)
|
||||
if proxyStr == "" {
|
||||
type apiKeyConfigEntry interface {
|
||||
GetAPIKey() string
|
||||
GetBaseURL() string
|
||||
}
|
||||
|
||||
func resolveAPIKeyConfig[T apiKeyConfigEntry](entries []T, auth *coreauth.Auth) *T {
|
||||
if auth == nil || len(entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
proxyURL, errParse := url.Parse(proxyStr)
|
||||
if errParse != nil {
|
||||
log.WithError(errParse).Debug("parse proxy URL failed")
|
||||
return nil
|
||||
attrKey, attrBase := "", ""
|
||||
if auth.Attributes != nil {
|
||||
attrKey = strings.TrimSpace(auth.Attributes["api_key"])
|
||||
attrBase = strings.TrimSpace(auth.Attributes["base_url"])
|
||||
}
|
||||
if proxyURL.Scheme == "" || proxyURL.Host == "" {
|
||||
log.Debug("proxy URL missing scheme/host")
|
||||
return nil
|
||||
}
|
||||
|
||||
if proxyURL.Scheme == "socks5" {
|
||||
var proxyAuth *proxy.Auth
|
||||
if proxyURL.User != nil {
|
||||
username := proxyURL.User.Username()
|
||||
password, _ := proxyURL.User.Password()
|
||||
proxyAuth = &proxy.Auth{User: username, Password: password}
|
||||
for i := range entries {
|
||||
entry := &entries[i]
|
||||
cfgKey := strings.TrimSpace((*entry).GetAPIKey())
|
||||
cfgBase := strings.TrimSpace((*entry).GetBaseURL())
|
||||
if attrKey != "" && attrBase != "" {
|
||||
if strings.EqualFold(cfgKey, attrKey) && strings.EqualFold(cfgBase, attrBase) {
|
||||
return entry
|
||||
}
|
||||
continue
|
||||
}
|
||||
dialer, errSOCKS5 := proxy.SOCKS5("tcp", proxyURL.Host, proxyAuth, proxy.Direct)
|
||||
if errSOCKS5 != nil {
|
||||
log.WithError(errSOCKS5).Debug("create SOCKS5 dialer failed")
|
||||
return nil
|
||||
if attrKey != "" && strings.EqualFold(cfgKey, attrKey) {
|
||||
if cfgBase == "" || strings.EqualFold(cfgBase, attrBase) {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
return &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return dialer.Dial(network, addr)
|
||||
},
|
||||
if attrKey == "" && attrBase != "" && strings.EqualFold(cfgBase, attrBase) {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
|
||||
if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" {
|
||||
return &http.Transport{Proxy: http.ProxyURL(proxyURL)}
|
||||
if attrKey != "" {
|
||||
for i := range entries {
|
||||
entry := &entries[i]
|
||||
if strings.EqualFold(strings.TrimSpace((*entry).GetAPIKey()), attrKey) {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.Debugf("unsupported proxy scheme: %s", proxyURL.Scheme)
|
||||
return nil
|
||||
}
|
||||
|
||||
func proxyURLFromAPIKeyConfig(cfg *config.Config, auth *coreauth.Auth) string {
|
||||
if cfg == nil || auth == nil {
|
||||
return ""
|
||||
}
|
||||
authKind, authAccount := auth.AccountInfo()
|
||||
if !strings.EqualFold(strings.TrimSpace(authKind), "api_key") {
|
||||
return ""
|
||||
}
|
||||
|
||||
attrs := auth.Attributes
|
||||
compatName := ""
|
||||
providerKey := ""
|
||||
if len(attrs) > 0 {
|
||||
compatName = strings.TrimSpace(attrs["compat_name"])
|
||||
providerKey = strings.TrimSpace(attrs["provider_key"])
|
||||
}
|
||||
if compatName != "" || strings.EqualFold(strings.TrimSpace(auth.Provider), "openai-compatibility") {
|
||||
return resolveOpenAICompatAPIKeyProxyURL(cfg, auth, strings.TrimSpace(authAccount), providerKey, compatName)
|
||||
}
|
||||
|
||||
switch strings.ToLower(strings.TrimSpace(auth.Provider)) {
|
||||
case "gemini":
|
||||
if entry := resolveAPIKeyConfig(cfg.GeminiKey, auth); entry != nil {
|
||||
return strings.TrimSpace(entry.ProxyURL)
|
||||
}
|
||||
case "claude":
|
||||
if entry := resolveAPIKeyConfig(cfg.ClaudeKey, auth); entry != nil {
|
||||
return strings.TrimSpace(entry.ProxyURL)
|
||||
}
|
||||
case "codex":
|
||||
if entry := resolveAPIKeyConfig(cfg.CodexKey, auth); entry != nil {
|
||||
return strings.TrimSpace(entry.ProxyURL)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func resolveOpenAICompatAPIKeyProxyURL(cfg *config.Config, auth *coreauth.Auth, apiKey, providerKey, compatName string) string {
|
||||
if cfg == nil || auth == nil {
|
||||
return ""
|
||||
}
|
||||
apiKey = strings.TrimSpace(apiKey)
|
||||
if apiKey == "" {
|
||||
return ""
|
||||
}
|
||||
candidates := make([]string, 0, 3)
|
||||
if v := strings.TrimSpace(compatName); v != "" {
|
||||
candidates = append(candidates, v)
|
||||
}
|
||||
if v := strings.TrimSpace(providerKey); v != "" {
|
||||
candidates = append(candidates, v)
|
||||
}
|
||||
if v := strings.TrimSpace(auth.Provider); v != "" {
|
||||
candidates = append(candidates, v)
|
||||
}
|
||||
|
||||
for i := range cfg.OpenAICompatibility {
|
||||
compat := &cfg.OpenAICompatibility[i]
|
||||
for _, candidate := range candidates {
|
||||
if candidate != "" && strings.EqualFold(strings.TrimSpace(candidate), compat.Name) {
|
||||
for j := range compat.APIKeyEntries {
|
||||
entry := &compat.APIKeyEntries[j]
|
||||
if strings.EqualFold(strings.TrimSpace(entry.APIKey), apiKey) {
|
||||
return strings.TrimSpace(entry.ProxyURL)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func buildProxyTransport(proxyStr string) *http.Transport {
|
||||
transport, _, errBuild := proxyutil.BuildHTTPTransport(proxyStr)
|
||||
if errBuild != nil {
|
||||
log.WithError(errBuild).Debug("build proxy transport failed")
|
||||
return nil
|
||||
}
|
||||
return transport
|
||||
}
|
||||
|
||||
@@ -2,172 +2,211 @@ package management
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
|
||||
)
|
||||
|
||||
type memoryAuthStore struct {
|
||||
mu sync.Mutex
|
||||
items map[string]*coreauth.Auth
|
||||
}
|
||||
func TestAPICallTransportDirectBypassesGlobalProxy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
func (s *memoryAuthStore) List(ctx context.Context) ([]*coreauth.Auth, error) {
|
||||
_ = ctx
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]*coreauth.Auth, 0, len(s.items))
|
||||
for _, a := range s.items {
|
||||
out = append(out, a.Clone())
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *memoryAuthStore) Save(ctx context.Context, auth *coreauth.Auth) (string, error) {
|
||||
_ = ctx
|
||||
if auth == nil {
|
||||
return "", nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.items == nil {
|
||||
s.items = make(map[string]*coreauth.Auth)
|
||||
}
|
||||
s.items[auth.ID] = auth.Clone()
|
||||
s.mu.Unlock()
|
||||
return auth.ID, nil
|
||||
}
|
||||
|
||||
func (s *memoryAuthStore) Delete(ctx context.Context, id string) error {
|
||||
_ = ctx
|
||||
s.mu.Lock()
|
||||
delete(s.items, id)
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestResolveTokenForAuth_Antigravity_RefreshesExpiredToken(t *testing.T) {
|
||||
var callCount int
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
callCount++
|
||||
if r.Method != http.MethodPost {
|
||||
t.Fatalf("expected POST, got %s", r.Method)
|
||||
}
|
||||
if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/x-www-form-urlencoded") {
|
||||
t.Fatalf("unexpected content-type: %s", ct)
|
||||
}
|
||||
bodyBytes, _ := io.ReadAll(r.Body)
|
||||
_ = r.Body.Close()
|
||||
values, err := url.ParseQuery(string(bodyBytes))
|
||||
if err != nil {
|
||||
t.Fatalf("parse form: %v", err)
|
||||
}
|
||||
if values.Get("grant_type") != "refresh_token" {
|
||||
t.Fatalf("unexpected grant_type: %s", values.Get("grant_type"))
|
||||
}
|
||||
if values.Get("refresh_token") != "rt" {
|
||||
t.Fatalf("unexpected refresh_token: %s", values.Get("refresh_token"))
|
||||
}
|
||||
if values.Get("client_id") != antigravityOAuthClientID {
|
||||
t.Fatalf("unexpected client_id: %s", values.Get("client_id"))
|
||||
}
|
||||
if values.Get("client_secret") != antigravityOAuthClientSecret {
|
||||
t.Fatalf("unexpected client_secret")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"access_token": "new-token",
|
||||
"refresh_token": "rt2",
|
||||
"expires_in": int64(3600),
|
||||
"token_type": "Bearer",
|
||||
})
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
originalURL := antigravityOAuthTokenURL
|
||||
antigravityOAuthTokenURL = srv.URL
|
||||
t.Cleanup(func() { antigravityOAuthTokenURL = originalURL })
|
||||
|
||||
store := &memoryAuthStore{}
|
||||
manager := coreauth.NewManager(store, nil, nil)
|
||||
|
||||
auth := &coreauth.Auth{
|
||||
ID: "antigravity-test.json",
|
||||
FileName: "antigravity-test.json",
|
||||
Provider: "antigravity",
|
||||
Metadata: map[string]any{
|
||||
"type": "antigravity",
|
||||
"access_token": "old-token",
|
||||
"refresh_token": "rt",
|
||||
"expires_in": int64(3600),
|
||||
"timestamp": time.Now().Add(-2 * time.Hour).UnixMilli(),
|
||||
"expired": time.Now().Add(-1 * time.Hour).Format(time.RFC3339),
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
|
||||
},
|
||||
}
|
||||
if _, err := manager.Register(context.Background(), auth); err != nil {
|
||||
t.Fatalf("register auth: %v", err)
|
||||
|
||||
transport := h.apiCallTransport(&coreauth.Auth{ProxyURL: "direct"})
|
||||
httpTransport, ok := transport.(*http.Transport)
|
||||
if !ok {
|
||||
t.Fatalf("transport type = %T, want *http.Transport", transport)
|
||||
}
|
||||
if httpTransport.Proxy != nil {
|
||||
t.Fatal("expected direct transport to disable proxy function")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICallTransportInvalidAuthFallsBackToGlobalProxy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
|
||||
},
|
||||
}
|
||||
|
||||
transport := h.apiCallTransport(&coreauth.Auth{ProxyURL: "bad-value"})
|
||||
httpTransport, ok := transport.(*http.Transport)
|
||||
if !ok {
|
||||
t.Fatalf("transport type = %T, want *http.Transport", transport)
|
||||
}
|
||||
|
||||
req, errRequest := http.NewRequest(http.MethodGet, "https://example.com", nil)
|
||||
if errRequest != nil {
|
||||
t.Fatalf("http.NewRequest returned error: %v", errRequest)
|
||||
}
|
||||
|
||||
proxyURL, errProxy := httpTransport.Proxy(req)
|
||||
if errProxy != nil {
|
||||
t.Fatalf("httpTransport.Proxy returned error: %v", errProxy)
|
||||
}
|
||||
if proxyURL == nil || proxyURL.String() != "http://global-proxy.example.com:8080" {
|
||||
t.Fatalf("proxy URL = %v, want http://global-proxy.example.com:8080", proxyURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICallTransportAPIKeyAuthFallsBackToConfigProxyURL(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
|
||||
GeminiKey: []config.GeminiKey{{
|
||||
APIKey: "gemini-key",
|
||||
ProxyURL: "http://gemini-proxy.example.com:8080",
|
||||
}},
|
||||
ClaudeKey: []config.ClaudeKey{{
|
||||
APIKey: "claude-key",
|
||||
ProxyURL: "http://claude-proxy.example.com:8080",
|
||||
}},
|
||||
CodexKey: []config.CodexKey{{
|
||||
APIKey: "codex-key",
|
||||
ProxyURL: "http://codex-proxy.example.com:8080",
|
||||
}},
|
||||
OpenAICompatibility: []config.OpenAICompatibility{{
|
||||
Name: "bohe",
|
||||
BaseURL: "https://bohe.example.com",
|
||||
APIKeyEntries: []config.OpenAICompatibilityAPIKey{{
|
||||
APIKey: "compat-key",
|
||||
ProxyURL: "http://compat-proxy.example.com:8080",
|
||||
}},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
auth *coreauth.Auth
|
||||
wantProxy string
|
||||
}{
|
||||
{
|
||||
name: "gemini",
|
||||
auth: &coreauth.Auth{
|
||||
Provider: "gemini",
|
||||
Attributes: map[string]string{"api_key": "gemini-key"},
|
||||
},
|
||||
wantProxy: "http://gemini-proxy.example.com:8080",
|
||||
},
|
||||
{
|
||||
name: "claude",
|
||||
auth: &coreauth.Auth{
|
||||
Provider: "claude",
|
||||
Attributes: map[string]string{"api_key": "claude-key"},
|
||||
},
|
||||
wantProxy: "http://claude-proxy.example.com:8080",
|
||||
},
|
||||
{
|
||||
name: "codex",
|
||||
auth: &coreauth.Auth{
|
||||
Provider: "codex",
|
||||
Attributes: map[string]string{"api_key": "codex-key"},
|
||||
},
|
||||
wantProxy: "http://codex-proxy.example.com:8080",
|
||||
},
|
||||
{
|
||||
name: "openai-compatibility",
|
||||
auth: &coreauth.Auth{
|
||||
Provider: "bohe",
|
||||
Attributes: map[string]string{
|
||||
"api_key": "compat-key",
|
||||
"compat_name": "bohe",
|
||||
"provider_key": "bohe",
|
||||
},
|
||||
},
|
||||
wantProxy: "http://compat-proxy.example.com:8080",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
transport := h.apiCallTransport(tc.auth)
|
||||
httpTransport, ok := transport.(*http.Transport)
|
||||
if !ok {
|
||||
t.Fatalf("transport type = %T, want *http.Transport", transport)
|
||||
}
|
||||
|
||||
req, errRequest := http.NewRequest(http.MethodGet, "https://example.com", nil)
|
||||
if errRequest != nil {
|
||||
t.Fatalf("http.NewRequest returned error: %v", errRequest)
|
||||
}
|
||||
|
||||
proxyURL, errProxy := httpTransport.Proxy(req)
|
||||
if errProxy != nil {
|
||||
t.Fatalf("httpTransport.Proxy returned error: %v", errProxy)
|
||||
}
|
||||
if proxyURL == nil || proxyURL.String() != tc.wantProxy {
|
||||
t.Fatalf("proxy URL = %v, want %s", proxyURL, tc.wantProxy)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthByIndexDistinguishesSharedAPIKeysAcrossProviders(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
geminiAuth := &coreauth.Auth{
|
||||
ID: "gemini:apikey:123",
|
||||
Provider: "gemini",
|
||||
Attributes: map[string]string{
|
||||
"api_key": "shared-key",
|
||||
},
|
||||
}
|
||||
compatAuth := &coreauth.Auth{
|
||||
ID: "openai-compatibility:bohe:456",
|
||||
Provider: "bohe",
|
||||
Label: "bohe",
|
||||
Attributes: map[string]string{
|
||||
"api_key": "shared-key",
|
||||
"compat_name": "bohe",
|
||||
"provider_key": "bohe",
|
||||
},
|
||||
}
|
||||
|
||||
if _, errRegister := manager.Register(context.Background(), geminiAuth); errRegister != nil {
|
||||
t.Fatalf("register gemini auth: %v", errRegister)
|
||||
}
|
||||
if _, errRegister := manager.Register(context.Background(), compatAuth); errRegister != nil {
|
||||
t.Fatalf("register compat auth: %v", errRegister)
|
||||
}
|
||||
|
||||
geminiIndex := geminiAuth.EnsureIndex()
|
||||
compatIndex := compatAuth.EnsureIndex()
|
||||
if geminiIndex == compatIndex {
|
||||
t.Fatalf("shared api key produced duplicate auth_index %q", geminiIndex)
|
||||
}
|
||||
|
||||
h := &Handler{authManager: manager}
|
||||
token, err := h.resolveTokenForAuth(context.Background(), auth)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTokenForAuth: %v", err)
|
||||
|
||||
gotGemini := h.authByIndex(geminiIndex)
|
||||
if gotGemini == nil {
|
||||
t.Fatal("expected gemini auth by index")
|
||||
}
|
||||
if token != "new-token" {
|
||||
t.Fatalf("expected refreshed token, got %q", token)
|
||||
}
|
||||
if callCount != 1 {
|
||||
t.Fatalf("expected 1 refresh call, got %d", callCount)
|
||||
if gotGemini.ID != geminiAuth.ID {
|
||||
t.Fatalf("authByIndex(gemini) returned %q, want %q", gotGemini.ID, geminiAuth.ID)
|
||||
}
|
||||
|
||||
updated, ok := manager.GetByID(auth.ID)
|
||||
if !ok || updated == nil {
|
||||
t.Fatalf("expected auth in manager after update")
|
||||
gotCompat := h.authByIndex(compatIndex)
|
||||
if gotCompat == nil {
|
||||
t.Fatal("expected compat auth by index")
|
||||
}
|
||||
if got := tokenValueFromMetadata(updated.Metadata); got != "new-token" {
|
||||
t.Fatalf("expected manager metadata updated, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTokenForAuth_Antigravity_SkipsRefreshWhenTokenValid(t *testing.T) {
|
||||
var callCount int
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
callCount++
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
originalURL := antigravityOAuthTokenURL
|
||||
antigravityOAuthTokenURL = srv.URL
|
||||
t.Cleanup(func() { antigravityOAuthTokenURL = originalURL })
|
||||
|
||||
auth := &coreauth.Auth{
|
||||
ID: "antigravity-valid.json",
|
||||
FileName: "antigravity-valid.json",
|
||||
Provider: "antigravity",
|
||||
Metadata: map[string]any{
|
||||
"type": "antigravity",
|
||||
"access_token": "ok-token",
|
||||
"expired": time.Now().Add(30 * time.Minute).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
h := &Handler{}
|
||||
token, err := h.resolveTokenForAuth(context.Background(), auth)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTokenForAuth: %v", err)
|
||||
}
|
||||
if token != "ok-token" {
|
||||
t.Fatalf("expected existing token, got %q", token)
|
||||
}
|
||||
if callCount != 0 {
|
||||
t.Fatalf("expected no refresh calls, got %d", callCount)
|
||||
if gotCompat.ID != compatAuth.ID {
|
||||
t.Fatalf("authByIndex(compat) returned %q, want %q", gotCompat.ID, compatAuth.ID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -57,8 +58,10 @@ type callbackForwarder struct {
|
||||
}
|
||||
|
||||
var (
|
||||
callbackForwardersMu sync.Mutex
|
||||
callbackForwarders = make(map[int]*callbackForwarder)
|
||||
callbackForwardersMu sync.Mutex
|
||||
callbackForwarders = make(map[int]*callbackForwarder)
|
||||
errAuthFileMustBeJSON = errors.New("auth file must be .json")
|
||||
errAuthFileNotFound = errors.New("auth file not found")
|
||||
)
|
||||
|
||||
func extractLastRefreshTimestamp(meta map[string]any) (time.Time, bool) {
|
||||
@@ -332,6 +335,21 @@ func (h *Handler) listAuthFilesFromDisk(c *gin.Context) {
|
||||
emailValue := gjson.GetBytes(data, "email").String()
|
||||
fileData["type"] = typeValue
|
||||
fileData["email"] = emailValue
|
||||
if pv := gjson.GetBytes(data, "priority"); pv.Exists() {
|
||||
switch pv.Type {
|
||||
case gjson.Number:
|
||||
fileData["priority"] = int(pv.Int())
|
||||
case gjson.String:
|
||||
if parsed, errAtoi := strconv.Atoi(strings.TrimSpace(pv.String())); errAtoi == nil {
|
||||
fileData["priority"] = parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
if nv := gjson.GetBytes(data, "note"); nv.Exists() && nv.Type == gjson.String {
|
||||
if trimmed := strings.TrimSpace(nv.String()); trimmed != "" {
|
||||
fileData["note"] = trimmed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
files = append(files, fileData)
|
||||
@@ -415,6 +433,37 @@ func (h *Handler) buildAuthFileEntry(auth *coreauth.Auth) gin.H {
|
||||
if claims := extractCodexIDTokenClaims(auth); claims != nil {
|
||||
entry["id_token"] = claims
|
||||
}
|
||||
// Expose priority from Attributes (set by synthesizer from JSON "priority" field).
|
||||
// Fall back to Metadata for auths registered via UploadAuthFile (no synthesizer).
|
||||
if p := strings.TrimSpace(authAttribute(auth, "priority")); p != "" {
|
||||
if parsed, err := strconv.Atoi(p); err == nil {
|
||||
entry["priority"] = parsed
|
||||
}
|
||||
} else if auth.Metadata != nil {
|
||||
if rawPriority, ok := auth.Metadata["priority"]; ok {
|
||||
switch v := rawPriority.(type) {
|
||||
case float64:
|
||||
entry["priority"] = int(v)
|
||||
case int:
|
||||
entry["priority"] = v
|
||||
case string:
|
||||
if parsed, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
|
||||
entry["priority"] = parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Expose note from Attributes (set by synthesizer from JSON "note" field).
|
||||
// Fall back to Metadata for auths registered via UploadAuthFile (no synthesizer).
|
||||
if note := strings.TrimSpace(authAttribute(auth, "note")); note != "" {
|
||||
entry["note"] = note
|
||||
} else if auth.Metadata != nil {
|
||||
if rawNote, ok := auth.Metadata["note"].(string); ok {
|
||||
if trimmed := strings.TrimSpace(rawNote); trimmed != "" {
|
||||
entry["note"] = trimmed
|
||||
}
|
||||
}
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
@@ -492,10 +541,23 @@ func isRuntimeOnlyAuth(auth *coreauth.Auth) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(auth.Attributes["runtime_only"]), "true")
|
||||
}
|
||||
|
||||
func isUnsafeAuthFileName(name string) bool {
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return true
|
||||
}
|
||||
if strings.ContainsAny(name, "/\\") {
|
||||
return true
|
||||
}
|
||||
if filepath.VolumeName(name) != "" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Download single auth file by name
|
||||
func (h *Handler) DownloadAuthFile(c *gin.Context) {
|
||||
name := c.Query("name")
|
||||
if name == "" || strings.Contains(name, string(os.PathSeparator)) {
|
||||
name := strings.TrimSpace(c.Query("name"))
|
||||
if isUnsafeAuthFileName(name) {
|
||||
c.JSON(400, gin.H{"error": "invalid name"})
|
||||
return
|
||||
}
|
||||
@@ -524,36 +586,61 @@ func (h *Handler) UploadAuthFile(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if file, err := c.FormFile("file"); err == nil && file != nil {
|
||||
name := filepath.Base(file.Filename)
|
||||
if !strings.HasSuffix(strings.ToLower(name), ".json") {
|
||||
c.JSON(400, gin.H{"error": "file must be .json"})
|
||||
return
|
||||
}
|
||||
dst := filepath.Join(h.cfg.AuthDir, name)
|
||||
if !filepath.IsAbs(dst) {
|
||||
if abs, errAbs := filepath.Abs(dst); errAbs == nil {
|
||||
dst = abs
|
||||
}
|
||||
}
|
||||
if errSave := c.SaveUploadedFile(file, dst); errSave != nil {
|
||||
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to save file: %v", errSave)})
|
||||
return
|
||||
}
|
||||
data, errRead := os.ReadFile(dst)
|
||||
if errRead != nil {
|
||||
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read saved file: %v", errRead)})
|
||||
return
|
||||
}
|
||||
if errReg := h.registerAuthFromFile(ctx, dst, data); errReg != nil {
|
||||
c.JSON(500, gin.H{"error": errReg.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
|
||||
fileHeaders, errMultipart := h.multipartAuthFileHeaders(c)
|
||||
if errMultipart != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid multipart form: %v", errMultipart)})
|
||||
return
|
||||
}
|
||||
name := c.Query("name")
|
||||
if name == "" || strings.Contains(name, string(os.PathSeparator)) {
|
||||
if len(fileHeaders) == 1 {
|
||||
if _, errUpload := h.storeUploadedAuthFile(ctx, fileHeaders[0]); errUpload != nil {
|
||||
if errors.Is(errUpload, errAuthFileMustBeJSON) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "file must be .json"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": errUpload.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
return
|
||||
}
|
||||
if len(fileHeaders) > 1 {
|
||||
uploaded := make([]string, 0, len(fileHeaders))
|
||||
failed := make([]gin.H, 0)
|
||||
for _, file := range fileHeaders {
|
||||
name, errUpload := h.storeUploadedAuthFile(ctx, file)
|
||||
if errUpload != nil {
|
||||
failureName := ""
|
||||
if file != nil {
|
||||
failureName = filepath.Base(file.Filename)
|
||||
}
|
||||
msg := errUpload.Error()
|
||||
if errors.Is(errUpload, errAuthFileMustBeJSON) {
|
||||
msg = "file must be .json"
|
||||
}
|
||||
failed = append(failed, gin.H{"name": failureName, "error": msg})
|
||||
continue
|
||||
}
|
||||
uploaded = append(uploaded, name)
|
||||
}
|
||||
if len(failed) > 0 {
|
||||
c.JSON(http.StatusMultiStatus, gin.H{
|
||||
"status": "partial",
|
||||
"uploaded": len(uploaded),
|
||||
"files": uploaded,
|
||||
"failed": failed,
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "uploaded": len(uploaded), "files": uploaded})
|
||||
return
|
||||
}
|
||||
if c.ContentType() == "multipart/form-data" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "no files uploaded"})
|
||||
return
|
||||
}
|
||||
name := strings.TrimSpace(c.Query("name"))
|
||||
if isUnsafeAuthFileName(name) {
|
||||
c.JSON(400, gin.H{"error": "invalid name"})
|
||||
return
|
||||
}
|
||||
@@ -566,17 +653,7 @@ func (h *Handler) UploadAuthFile(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "failed to read body"})
|
||||
return
|
||||
}
|
||||
dst := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
|
||||
if !filepath.IsAbs(dst) {
|
||||
if abs, errAbs := filepath.Abs(dst); errAbs == nil {
|
||||
dst = abs
|
||||
}
|
||||
}
|
||||
if errWrite := os.WriteFile(dst, data, 0o600); errWrite != nil {
|
||||
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to write file: %v", errWrite)})
|
||||
return
|
||||
}
|
||||
if err = h.registerAuthFromFile(ctx, dst, data); err != nil {
|
||||
if err = h.writeAuthFile(ctx, filepath.Base(name), data); err != nil {
|
||||
c.JSON(500, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -623,11 +700,172 @@ func (h *Handler) DeleteAuthFile(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"status": "ok", "deleted": deleted})
|
||||
return
|
||||
}
|
||||
name := c.Query("name")
|
||||
if name == "" || strings.Contains(name, string(os.PathSeparator)) {
|
||||
|
||||
names, errNames := requestedAuthFileNamesForDelete(c)
|
||||
if errNames != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": errNames.Error()})
|
||||
return
|
||||
}
|
||||
if len(names) == 0 {
|
||||
c.JSON(400, gin.H{"error": "invalid name"})
|
||||
return
|
||||
}
|
||||
if len(names) == 1 {
|
||||
if _, status, errDelete := h.deleteAuthFileByName(ctx, names[0]); errDelete != nil {
|
||||
c.JSON(status, gin.H{"error": errDelete.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
return
|
||||
}
|
||||
|
||||
deletedFiles := make([]string, 0, len(names))
|
||||
failed := make([]gin.H, 0)
|
||||
for _, name := range names {
|
||||
deletedName, _, errDelete := h.deleteAuthFileByName(ctx, name)
|
||||
if errDelete != nil {
|
||||
failed = append(failed, gin.H{"name": name, "error": errDelete.Error()})
|
||||
continue
|
||||
}
|
||||
deletedFiles = append(deletedFiles, deletedName)
|
||||
}
|
||||
if len(failed) > 0 {
|
||||
c.JSON(http.StatusMultiStatus, gin.H{
|
||||
"status": "partial",
|
||||
"deleted": len(deletedFiles),
|
||||
"files": deletedFiles,
|
||||
"failed": failed,
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "deleted": len(deletedFiles), "files": deletedFiles})
|
||||
}
|
||||
|
||||
func (h *Handler) multipartAuthFileHeaders(c *gin.Context) ([]*multipart.FileHeader, error) {
|
||||
if h == nil || c == nil || c.ContentType() != "multipart/form-data" {
|
||||
return nil, nil
|
||||
}
|
||||
form, err := c.MultipartForm()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if form == nil || len(form.File) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
keys := make([]string, 0, len(form.File))
|
||||
for key := range form.File {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
headers := make([]*multipart.FileHeader, 0)
|
||||
for _, key := range keys {
|
||||
headers = append(headers, form.File[key]...)
|
||||
}
|
||||
return headers, nil
|
||||
}
|
||||
|
||||
func (h *Handler) storeUploadedAuthFile(ctx context.Context, file *multipart.FileHeader) (string, error) {
|
||||
if file == nil {
|
||||
return "", fmt.Errorf("no file uploaded")
|
||||
}
|
||||
name := filepath.Base(strings.TrimSpace(file.Filename))
|
||||
if !strings.HasSuffix(strings.ToLower(name), ".json") {
|
||||
return "", errAuthFileMustBeJSON
|
||||
}
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to open uploaded file: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
data, err := io.ReadAll(src)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read uploaded file: %w", err)
|
||||
}
|
||||
if err := h.writeAuthFile(ctx, name, data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func (h *Handler) writeAuthFile(ctx context.Context, name string, data []byte) error {
|
||||
dst := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
|
||||
if !filepath.IsAbs(dst) {
|
||||
if abs, errAbs := filepath.Abs(dst); errAbs == nil {
|
||||
dst = abs
|
||||
}
|
||||
}
|
||||
return h.commitUploadedAuthFile(ctx, dst, data)
|
||||
}
|
||||
|
||||
func requestedAuthFileNamesForDelete(c *gin.Context) ([]string, error) {
|
||||
if c == nil {
|
||||
return nil, nil
|
||||
}
|
||||
names := uniqueAuthFileNames(c.QueryArray("name"))
|
||||
if len(names) > 0 {
|
||||
return names, nil
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read body")
|
||||
}
|
||||
body = bytes.TrimSpace(body)
|
||||
if len(body) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var objectBody struct {
|
||||
Name string `json:"name"`
|
||||
Names []string `json:"names"`
|
||||
}
|
||||
if body[0] == '[' {
|
||||
var arrayBody []string
|
||||
if err := json.Unmarshal(body, &arrayBody); err != nil {
|
||||
return nil, fmt.Errorf("invalid request body")
|
||||
}
|
||||
return uniqueAuthFileNames(arrayBody), nil
|
||||
}
|
||||
if err := json.Unmarshal(body, &objectBody); err != nil {
|
||||
return nil, fmt.Errorf("invalid request body")
|
||||
}
|
||||
|
||||
out := make([]string, 0, len(objectBody.Names)+1)
|
||||
if strings.TrimSpace(objectBody.Name) != "" {
|
||||
out = append(out, objectBody.Name)
|
||||
}
|
||||
out = append(out, objectBody.Names...)
|
||||
return uniqueAuthFileNames(out), nil
|
||||
}
|
||||
|
||||
func uniqueAuthFileNames(names []string) []string {
|
||||
if len(names) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{}, len(names))
|
||||
out := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[name]; ok {
|
||||
continue
|
||||
}
|
||||
seen[name] = struct{}{}
|
||||
out = append(out, name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Handler) deleteAuthFileByName(ctx context.Context, name string) (string, int, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if isUnsafeAuthFileName(name) {
|
||||
return "", http.StatusBadRequest, fmt.Errorf("invalid name")
|
||||
}
|
||||
|
||||
targetPath := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
|
||||
targetID := ""
|
||||
@@ -644,22 +882,19 @@ func (h *Handler) DeleteAuthFile(c *gin.Context) {
|
||||
}
|
||||
if errRemove := os.Remove(targetPath); errRemove != nil {
|
||||
if os.IsNotExist(errRemove) {
|
||||
c.JSON(404, gin.H{"error": "file not found"})
|
||||
} else {
|
||||
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to remove file: %v", errRemove)})
|
||||
return filepath.Base(name), http.StatusNotFound, errAuthFileNotFound
|
||||
}
|
||||
return
|
||||
return filepath.Base(name), http.StatusInternalServerError, fmt.Errorf("failed to remove file: %w", errRemove)
|
||||
}
|
||||
if errDeleteRecord := h.deleteTokenRecord(ctx, targetPath); errDeleteRecord != nil {
|
||||
c.JSON(500, gin.H{"error": errDeleteRecord.Error()})
|
||||
return
|
||||
return filepath.Base(name), http.StatusInternalServerError, errDeleteRecord
|
||||
}
|
||||
if targetID != "" {
|
||||
h.disableAuth(ctx, targetID)
|
||||
} else {
|
||||
h.disableAuth(ctx, targetPath)
|
||||
}
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
return filepath.Base(name), http.StatusOK, nil
|
||||
}
|
||||
|
||||
func (h *Handler) findAuthForDelete(name string) *coreauth.Auth {
|
||||
@@ -693,10 +928,25 @@ func (h *Handler) authIDForPath(path string) string {
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
path = filepath.Clean(path)
|
||||
if !filepath.IsAbs(path) {
|
||||
if abs, errAbs := filepath.Abs(path); errAbs == nil {
|
||||
path = abs
|
||||
}
|
||||
}
|
||||
id := path
|
||||
if h != nil && h.cfg != nil {
|
||||
authDir := strings.TrimSpace(h.cfg.AuthDir)
|
||||
if resolvedAuthDir, errResolve := util.ResolveAuthDir(authDir); errResolve == nil && resolvedAuthDir != "" {
|
||||
authDir = resolvedAuthDir
|
||||
}
|
||||
if authDir != "" {
|
||||
authDir = filepath.Clean(authDir)
|
||||
if !filepath.IsAbs(authDir) {
|
||||
if abs, errAbs := filepath.Abs(authDir); errAbs == nil {
|
||||
authDir = abs
|
||||
}
|
||||
}
|
||||
if rel, errRel := filepath.Rel(authDir, path); errRel == nil && rel != "" {
|
||||
id = rel
|
||||
}
|
||||
@@ -713,19 +963,53 @@ func (h *Handler) registerAuthFromFile(ctx context.Context, path string, data []
|
||||
if h.authManager == nil {
|
||||
return nil
|
||||
}
|
||||
if path == "" {
|
||||
return fmt.Errorf("auth path is empty")
|
||||
auth, hasLastRefresh, err := h.buildAuthFromFileData(path, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return h.registerManagedAuth(ctx, auth, hasLastRefresh)
|
||||
}
|
||||
|
||||
func (h *Handler) commitUploadedAuthFile(ctx context.Context, path string, data []byte) error {
|
||||
if _, _, err := h.buildAuthFromFileData(path, data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return fmt.Errorf("failed to prepare auth dir: %w", err)
|
||||
}
|
||||
previousData, errRead := os.ReadFile(path)
|
||||
hadPrevious := errRead == nil
|
||||
if errRead != nil && !os.IsNotExist(errRead) {
|
||||
return fmt.Errorf("failed to read existing auth file: %w", errRead)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
return fmt.Errorf("failed to write file: %w", err)
|
||||
}
|
||||
if err := h.registerAuthFromFile(ctx, path, data); err != nil {
|
||||
if hadPrevious {
|
||||
_ = os.WriteFile(path, previousData, 0o600)
|
||||
} else {
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Handler) buildAuthFromFileData(path string, data []byte) (*coreauth.Auth, bool, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return nil, false, fmt.Errorf("auth path is empty")
|
||||
}
|
||||
if data == nil {
|
||||
var err error
|
||||
data, err = os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read auth file: %w", err)
|
||||
return nil, false, fmt.Errorf("failed to read auth file: %w", err)
|
||||
}
|
||||
}
|
||||
metadata := make(map[string]any)
|
||||
if err := json.Unmarshal(data, &metadata); err != nil {
|
||||
return fmt.Errorf("invalid auth file: %w", err)
|
||||
return nil, false, fmt.Errorf("invalid auth file: %w", err)
|
||||
}
|
||||
provider, _ := metadata["type"].(string)
|
||||
if provider == "" {
|
||||
@@ -756,10 +1040,40 @@ func (h *Handler) registerAuthFromFile(ctx context.Context, path string, data []
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if prefix, ok := authStringMetadata(metadata["prefix"]); ok {
|
||||
auth.Prefix = prefix
|
||||
auth.Attributes["prefix"] = prefix
|
||||
}
|
||||
if proxyURL, ok := authStringMetadata(metadata["proxy_url"]); ok {
|
||||
auth.ProxyURL = proxyURL
|
||||
auth.Attributes["proxy_url"] = proxyURL
|
||||
}
|
||||
if priority, ok := authIntMetadata(metadata["priority"]); ok {
|
||||
auth.Priority = priority
|
||||
auth.Attributes["priority"] = strconv.Itoa(priority)
|
||||
}
|
||||
if hasLastRefresh {
|
||||
auth.LastRefreshedAt = lastRefresh
|
||||
}
|
||||
if existing, ok := h.authManager.GetByID(authID); ok {
|
||||
if h != nil && h.authManager != nil {
|
||||
if existing, ok := h.authManager.GetByID(authID); ok {
|
||||
auth.CreatedAt = existing.CreatedAt
|
||||
if !hasLastRefresh {
|
||||
auth.LastRefreshedAt = existing.LastRefreshedAt
|
||||
}
|
||||
auth.NextRefreshAfter = existing.NextRefreshAfter
|
||||
auth.Runtime = existing.Runtime
|
||||
}
|
||||
}
|
||||
coreauth.ApplyCustomHeadersFromMetadata(auth)
|
||||
return auth, hasLastRefresh, nil
|
||||
}
|
||||
|
||||
func (h *Handler) registerManagedAuth(ctx context.Context, auth *coreauth.Auth, hasLastRefresh bool) error {
|
||||
if h.authManager == nil {
|
||||
return nil
|
||||
}
|
||||
if existing, ok := h.authManager.GetByID(auth.ID); ok {
|
||||
auth.CreatedAt = existing.CreatedAt
|
||||
if !hasLastRefresh {
|
||||
auth.LastRefreshedAt = existing.LastRefreshedAt
|
||||
@@ -839,7 +1153,7 @@ func (h *Handler) PatchAuthFileStatus(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "disabled": *req.Disabled})
|
||||
}
|
||||
|
||||
// PatchAuthFileFields updates editable fields (prefix, proxy_url, priority) of an auth file.
|
||||
// PatchAuthFileFields updates editable fields (prefix, proxy_url, headers, priority, note) of an auth file.
|
||||
func (h *Handler) PatchAuthFileFields(c *gin.Context) {
|
||||
if h.authManager == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
||||
@@ -847,10 +1161,12 @@ func (h *Handler) PatchAuthFileFields(c *gin.Context) {
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Prefix *string `json:"prefix"`
|
||||
ProxyURL *string `json:"proxy_url"`
|
||||
Priority *int `json:"priority"`
|
||||
Name string `json:"name"`
|
||||
Prefix *string `json:"prefix"`
|
||||
ProxyURL *string `json:"proxy_url"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Priority *int `json:"priority"`
|
||||
Note *string `json:"note"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
@@ -886,21 +1202,143 @@ func (h *Handler) PatchAuthFileFields(c *gin.Context) {
|
||||
|
||||
changed := false
|
||||
if req.Prefix != nil {
|
||||
targetAuth.Prefix = *req.Prefix
|
||||
changed = true
|
||||
}
|
||||
if req.ProxyURL != nil {
|
||||
targetAuth.ProxyURL = *req.ProxyURL
|
||||
changed = true
|
||||
}
|
||||
if req.Priority != nil {
|
||||
prefix := strings.TrimSpace(*req.Prefix)
|
||||
targetAuth.Prefix = prefix
|
||||
if targetAuth.Metadata == nil {
|
||||
targetAuth.Metadata = make(map[string]any)
|
||||
}
|
||||
if *req.Priority == 0 {
|
||||
delete(targetAuth.Metadata, "priority")
|
||||
if targetAuth.Attributes == nil {
|
||||
targetAuth.Attributes = make(map[string]string)
|
||||
}
|
||||
if prefix == "" {
|
||||
delete(targetAuth.Metadata, "prefix")
|
||||
delete(targetAuth.Attributes, "prefix")
|
||||
} else {
|
||||
targetAuth.Metadata["priority"] = *req.Priority
|
||||
targetAuth.Metadata["prefix"] = prefix
|
||||
targetAuth.Attributes["prefix"] = prefix
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if req.ProxyURL != nil {
|
||||
proxyURL := strings.TrimSpace(*req.ProxyURL)
|
||||
targetAuth.ProxyURL = proxyURL
|
||||
if targetAuth.Metadata == nil {
|
||||
targetAuth.Metadata = make(map[string]any)
|
||||
}
|
||||
if targetAuth.Attributes == nil {
|
||||
targetAuth.Attributes = make(map[string]string)
|
||||
}
|
||||
if proxyURL == "" {
|
||||
delete(targetAuth.Metadata, "proxy_url")
|
||||
delete(targetAuth.Attributes, "proxy_url")
|
||||
} else {
|
||||
targetAuth.Metadata["proxy_url"] = proxyURL
|
||||
targetAuth.Attributes["proxy_url"] = proxyURL
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if len(req.Headers) > 0 {
|
||||
existingHeaders := coreauth.ExtractCustomHeadersFromMetadata(targetAuth.Metadata)
|
||||
nextHeaders := make(map[string]string, len(existingHeaders))
|
||||
for k, v := range existingHeaders {
|
||||
nextHeaders[k] = v
|
||||
}
|
||||
headerChanged := false
|
||||
|
||||
for key, value := range req.Headers {
|
||||
name := strings.TrimSpace(key)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
val := strings.TrimSpace(value)
|
||||
attrKey := "header:" + name
|
||||
if val == "" {
|
||||
if _, ok := nextHeaders[name]; ok {
|
||||
delete(nextHeaders, name)
|
||||
headerChanged = true
|
||||
}
|
||||
if targetAuth.Attributes != nil {
|
||||
if _, ok := targetAuth.Attributes[attrKey]; ok {
|
||||
headerChanged = true
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if prev, ok := nextHeaders[name]; !ok || prev != val {
|
||||
headerChanged = true
|
||||
}
|
||||
nextHeaders[name] = val
|
||||
if targetAuth.Attributes != nil {
|
||||
if prev, ok := targetAuth.Attributes[attrKey]; !ok || prev != val {
|
||||
headerChanged = true
|
||||
}
|
||||
} else {
|
||||
headerChanged = true
|
||||
}
|
||||
}
|
||||
|
||||
if headerChanged {
|
||||
if targetAuth.Metadata == nil {
|
||||
targetAuth.Metadata = make(map[string]any)
|
||||
}
|
||||
if targetAuth.Attributes == nil {
|
||||
targetAuth.Attributes = make(map[string]string)
|
||||
}
|
||||
|
||||
for key, value := range req.Headers {
|
||||
name := strings.TrimSpace(key)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
val := strings.TrimSpace(value)
|
||||
attrKey := "header:" + name
|
||||
if val == "" {
|
||||
delete(nextHeaders, name)
|
||||
delete(targetAuth.Attributes, attrKey)
|
||||
continue
|
||||
}
|
||||
nextHeaders[name] = val
|
||||
targetAuth.Attributes[attrKey] = val
|
||||
}
|
||||
|
||||
if len(nextHeaders) == 0 {
|
||||
delete(targetAuth.Metadata, "headers")
|
||||
} else {
|
||||
metaHeaders := make(map[string]any, len(nextHeaders))
|
||||
for k, v := range nextHeaders {
|
||||
metaHeaders[k] = v
|
||||
}
|
||||
targetAuth.Metadata["headers"] = metaHeaders
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if req.Priority != nil || req.Note != nil {
|
||||
if targetAuth.Metadata == nil {
|
||||
targetAuth.Metadata = make(map[string]any)
|
||||
}
|
||||
if targetAuth.Attributes == nil {
|
||||
targetAuth.Attributes = make(map[string]string)
|
||||
}
|
||||
if req.Priority != nil {
|
||||
targetAuth.Priority = *req.Priority
|
||||
if *req.Priority == 0 {
|
||||
delete(targetAuth.Metadata, "priority")
|
||||
delete(targetAuth.Attributes, "priority")
|
||||
} else {
|
||||
targetAuth.Metadata["priority"] = *req.Priority
|
||||
targetAuth.Attributes["priority"] = strconv.Itoa(*req.Priority)
|
||||
}
|
||||
}
|
||||
if req.Note != nil {
|
||||
trimmedNote := strings.TrimSpace(*req.Note)
|
||||
if trimmedNote == "" {
|
||||
delete(targetAuth.Metadata, "note")
|
||||
delete(targetAuth.Attributes, "note")
|
||||
} else {
|
||||
targetAuth.Metadata["note"] = trimmedNote
|
||||
targetAuth.Attributes["note"] = trimmedNote
|
||||
}
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
@@ -920,6 +1358,35 @@ func (h *Handler) PatchAuthFileFields(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
func authStringMetadata(value any) (string, bool) {
|
||||
s, ok := value.(string)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
return strings.TrimSpace(s), true
|
||||
}
|
||||
|
||||
func authIntMetadata(value any) (int, bool) {
|
||||
switch v := value.(type) {
|
||||
case int:
|
||||
return v, true
|
||||
case int32:
|
||||
return int(v), true
|
||||
case int64:
|
||||
return int(v), true
|
||||
case float64:
|
||||
return int(v), true
|
||||
case json.Number:
|
||||
n, err := v.Int64()
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return int(n), true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) disableAuth(ctx context.Context, id string) {
|
||||
if h == nil || h.authManager == nil {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
func TestUploadAuthFile_BatchMultipart(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
authDir := t.TempDir()
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
||||
|
||||
files := []struct {
|
||||
name string
|
||||
content string
|
||||
}{
|
||||
{name: "alpha.json", content: `{"type":"codex","email":"alpha@example.com"}`},
|
||||
{name: "beta.json", content: `{"type":"claude","email":"beta@example.com"}`},
|
||||
}
|
||||
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
for _, file := range files {
|
||||
part, err := writer.CreateFormFile("file", file.name)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create multipart file: %v", err)
|
||||
}
|
||||
if _, err = part.Write([]byte(file.content)); err != nil {
|
||||
t.Fatalf("failed to write multipart content: %v", err)
|
||||
}
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPost, "/v0/management/auth-files", &body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
ctx.Request = req
|
||||
|
||||
h.UploadAuthFile(ctx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected upload status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
if got, ok := payload["uploaded"].(float64); !ok || int(got) != len(files) {
|
||||
t.Fatalf("expected uploaded=%d, got %#v", len(files), payload["uploaded"])
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
fullPath := filepath.Join(authDir, file.name)
|
||||
data, err := os.ReadFile(fullPath)
|
||||
if err != nil {
|
||||
t.Fatalf("expected uploaded file %s to exist: %v", file.name, err)
|
||||
}
|
||||
if string(data) != file.content {
|
||||
t.Fatalf("expected file %s content %q, got %q", file.name, file.content, string(data))
|
||||
}
|
||||
}
|
||||
|
||||
auths := manager.List()
|
||||
if len(auths) != len(files) {
|
||||
t.Fatalf("expected %d auth entries, got %d", len(files), len(auths))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadAuthFile_BatchMultipart_InvalidJSONDoesNotOverwriteExistingFile(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
authDir := t.TempDir()
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
||||
|
||||
existingName := "alpha.json"
|
||||
existingContent := `{"type":"codex","email":"alpha@example.com"}`
|
||||
if err := os.WriteFile(filepath.Join(authDir, existingName), []byte(existingContent), 0o600); err != nil {
|
||||
t.Fatalf("failed to seed existing auth file: %v", err)
|
||||
}
|
||||
|
||||
files := []struct {
|
||||
name string
|
||||
content string
|
||||
}{
|
||||
{name: existingName, content: `{"type":"codex"`},
|
||||
{name: "beta.json", content: `{"type":"claude","email":"beta@example.com"}`},
|
||||
}
|
||||
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
for _, file := range files {
|
||||
part, err := writer.CreateFormFile("file", file.name)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create multipart file: %v", err)
|
||||
}
|
||||
if _, err = part.Write([]byte(file.content)); err != nil {
|
||||
t.Fatalf("failed to write multipart content: %v", err)
|
||||
}
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPost, "/v0/management/auth-files", &body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
ctx.Request = req
|
||||
|
||||
h.UploadAuthFile(ctx)
|
||||
|
||||
if rec.Code != http.StatusMultiStatus {
|
||||
t.Fatalf("expected upload status %d, got %d with body %s", http.StatusMultiStatus, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(authDir, existingName))
|
||||
if err != nil {
|
||||
t.Fatalf("expected existing auth file to remain readable: %v", err)
|
||||
}
|
||||
if string(data) != existingContent {
|
||||
t.Fatalf("expected existing auth file to remain %q, got %q", existingContent, string(data))
|
||||
}
|
||||
|
||||
betaData, err := os.ReadFile(filepath.Join(authDir, "beta.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("expected valid auth file to be created: %v", err)
|
||||
}
|
||||
if string(betaData) != files[1].content {
|
||||
t.Fatalf("expected beta auth file content %q, got %q", files[1].content, string(betaData))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAuthFile_BatchQuery(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
authDir := t.TempDir()
|
||||
files := []string{"alpha.json", "beta.json"}
|
||||
for _, name := range files {
|
||||
if err := os.WriteFile(filepath.Join(authDir, name), []byte(`{"type":"codex"}`), 0o600); err != nil {
|
||||
t.Fatalf("failed to write auth file %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
||||
h.tokenStore = &memoryAuthStore{}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(
|
||||
http.MethodDelete,
|
||||
"/v0/management/auth-files?name="+url.QueryEscape(files[0])+"&name="+url.QueryEscape(files[1]),
|
||||
nil,
|
||||
)
|
||||
ctx.Request = req
|
||||
|
||||
h.DeleteAuthFile(ctx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected delete status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
if got, ok := payload["deleted"].(float64); !ok || int(got) != len(files) {
|
||||
t.Fatalf("expected deleted=%d, got %#v", len(files), payload["deleted"])
|
||||
}
|
||||
|
||||
for _, name := range files {
|
||||
if _, err := os.Stat(filepath.Join(authDir, name)); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected auth file %s to be removed, stat err: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
)
|
||||
|
||||
func TestDownloadAuthFile_ReturnsFile(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
authDir := t.TempDir()
|
||||
fileName := "download-user.json"
|
||||
expected := []byte(`{"type":"codex"}`)
|
||||
if err := os.WriteFile(filepath.Join(authDir, fileName), expected, 0o600); err != nil {
|
||||
t.Fatalf("failed to write auth file: %v", err)
|
||||
}
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files/download?name="+url.QueryEscape(fileName), nil)
|
||||
h.DownloadAuthFile(ctx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected download status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := rec.Body.Bytes(); string(got) != string(expected) {
|
||||
t.Fatalf("unexpected download content: %q", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadAuthFile_RejectsPathSeparators(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, nil)
|
||||
|
||||
for _, name := range []string{
|
||||
"../external/secret.json",
|
||||
`..\\external\\secret.json`,
|
||||
"nested/secret.json",
|
||||
`nested\\secret.json`,
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files/download?name="+url.QueryEscape(name), nil)
|
||||
h.DownloadAuthFile(ctx)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected %d for name %q, got %d with body %s", http.StatusBadRequest, name, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//go:build windows
|
||||
|
||||
package management
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
)
|
||||
|
||||
func TestDownloadAuthFile_PreventsWindowsSlashTraversal(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
tempDir := t.TempDir()
|
||||
authDir := filepath.Join(tempDir, "auth")
|
||||
externalDir := filepath.Join(tempDir, "external")
|
||||
if err := os.MkdirAll(authDir, 0o700); err != nil {
|
||||
t.Fatalf("failed to create auth dir: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(externalDir, 0o700); err != nil {
|
||||
t.Fatalf("failed to create external dir: %v", err)
|
||||
}
|
||||
|
||||
secretName := "secret.json"
|
||||
secretPath := filepath.Join(externalDir, secretName)
|
||||
if err := os.WriteFile(secretPath, []byte(`{"secret":true}`), 0o600); err != nil {
|
||||
t.Fatalf("failed to write external file: %v", err)
|
||||
}
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
ctx.Request = httptest.NewRequest(
|
||||
http.MethodGet,
|
||||
"/v0/management/auth-files/download?name="+url.QueryEscape("../external/"+secretName),
|
||||
nil,
|
||||
)
|
||||
h.DownloadAuthFile(ctx)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status %d, got %d with body %s", http.StatusBadRequest, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
func TestPatchAuthFileFields_MergeHeadersAndDeleteEmptyValues(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
store := &memoryAuthStore{}
|
||||
manager := coreauth.NewManager(store, nil, nil)
|
||||
record := &coreauth.Auth{
|
||||
ID: "test.json",
|
||||
FileName: "test.json",
|
||||
Provider: "claude",
|
||||
Attributes: map[string]string{
|
||||
"path": "/tmp/test.json",
|
||||
"header:X-Old": "old",
|
||||
"header:X-Remove": "gone",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "claude",
|
||||
"headers": map[string]any{
|
||||
"X-Old": "old",
|
||||
"X-Remove": "gone",
|
||||
},
|
||||
},
|
||||
}
|
||||
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
||||
t.Fatalf("failed to register auth record: %v", errRegister)
|
||||
}
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
||||
|
||||
body := `{"name":"test.json","prefix":"p1","proxy_url":"http://proxy.local","headers":{"X-Old":"new","X-New":"v","X-Remove":" ","X-Nope":""}}`
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
ctx.Request = req
|
||||
h.PatchAuthFileFields(ctx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
updated, ok := manager.GetByID("test.json")
|
||||
if !ok || updated == nil {
|
||||
t.Fatalf("expected auth record to exist after patch")
|
||||
}
|
||||
|
||||
if updated.Prefix != "p1" {
|
||||
t.Fatalf("prefix = %q, want %q", updated.Prefix, "p1")
|
||||
}
|
||||
if updated.ProxyURL != "http://proxy.local" {
|
||||
t.Fatalf("proxy_url = %q, want %q", updated.ProxyURL, "http://proxy.local")
|
||||
}
|
||||
|
||||
if updated.Metadata == nil {
|
||||
t.Fatalf("expected metadata to be non-nil")
|
||||
}
|
||||
if got, _ := updated.Metadata["prefix"].(string); got != "p1" {
|
||||
t.Fatalf("metadata.prefix = %q, want %q", got, "p1")
|
||||
}
|
||||
if got, _ := updated.Metadata["proxy_url"].(string); got != "http://proxy.local" {
|
||||
t.Fatalf("metadata.proxy_url = %q, want %q", got, "http://proxy.local")
|
||||
}
|
||||
|
||||
headersMeta, ok := updated.Metadata["headers"].(map[string]any)
|
||||
if !ok {
|
||||
raw, _ := json.Marshal(updated.Metadata["headers"])
|
||||
t.Fatalf("metadata.headers = %T (%s), want map[string]any", updated.Metadata["headers"], string(raw))
|
||||
}
|
||||
if got := headersMeta["X-Old"]; got != "new" {
|
||||
t.Fatalf("metadata.headers.X-Old = %#v, want %q", got, "new")
|
||||
}
|
||||
if got := headersMeta["X-New"]; got != "v" {
|
||||
t.Fatalf("metadata.headers.X-New = %#v, want %q", got, "v")
|
||||
}
|
||||
if _, ok := headersMeta["X-Remove"]; ok {
|
||||
t.Fatalf("expected metadata.headers.X-Remove to be deleted")
|
||||
}
|
||||
if _, ok := headersMeta["X-Nope"]; ok {
|
||||
t.Fatalf("expected metadata.headers.X-Nope to be absent")
|
||||
}
|
||||
|
||||
if got := updated.Attributes["header:X-Old"]; got != "new" {
|
||||
t.Fatalf("attrs header:X-Old = %q, want %q", got, "new")
|
||||
}
|
||||
if got := updated.Attributes["header:X-New"]; got != "v" {
|
||||
t.Fatalf("attrs header:X-New = %q, want %q", got, "v")
|
||||
}
|
||||
if _, ok := updated.Attributes["header:X-Remove"]; ok {
|
||||
t.Fatalf("expected attrs header:X-Remove to be deleted")
|
||||
}
|
||||
if _, ok := updated.Attributes["header:X-Nope"]; ok {
|
||||
t.Fatalf("expected attrs header:X-Nope to be absent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAuthFileFields_HeadersEmptyMapIsNoop(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
store := &memoryAuthStore{}
|
||||
manager := coreauth.NewManager(store, nil, nil)
|
||||
record := &coreauth.Auth{
|
||||
ID: "noop.json",
|
||||
FileName: "noop.json",
|
||||
Provider: "claude",
|
||||
Attributes: map[string]string{
|
||||
"path": "/tmp/noop.json",
|
||||
"header:X-Kee": "1",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "claude",
|
||||
"headers": map[string]any{
|
||||
"X-Kee": "1",
|
||||
},
|
||||
},
|
||||
}
|
||||
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
||||
t.Fatalf("failed to register auth record: %v", errRegister)
|
||||
}
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
||||
|
||||
body := `{"name":"noop.json","note":"hello","headers":{}}`
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
ctx.Request = req
|
||||
h.PatchAuthFileFields(ctx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
updated, ok := manager.GetByID("noop.json")
|
||||
if !ok || updated == nil {
|
||||
t.Fatalf("expected auth record to exist after patch")
|
||||
}
|
||||
if got := updated.Attributes["header:X-Kee"]; got != "1" {
|
||||
t.Fatalf("attrs header:X-Kee = %q, want %q", got, "1")
|
||||
}
|
||||
headersMeta, ok := updated.Metadata["headers"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("expected metadata.headers to remain a map, got %T", updated.Metadata["headers"])
|
||||
}
|
||||
if got := headersMeta["X-Kee"]; got != "1" {
|
||||
t.Fatalf("metadata.headers.X-Kee = %#v, want %q", got, "1")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package management
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -38,6 +39,19 @@ func (h *Handler) SetAuthPriority(c *gin.Context) {
|
||||
}
|
||||
|
||||
auth.Priority = *req.Priority
|
||||
if auth.Metadata == nil {
|
||||
auth.Metadata = make(map[string]any)
|
||||
}
|
||||
if auth.Attributes == nil {
|
||||
auth.Attributes = make(map[string]string)
|
||||
}
|
||||
if *req.Priority == 0 {
|
||||
delete(auth.Metadata, "priority")
|
||||
delete(auth.Attributes, "priority")
|
||||
} else {
|
||||
auth.Metadata["priority"] = *req.Priority
|
||||
auth.Attributes["priority"] = strconv.Itoa(*req.Priority)
|
||||
}
|
||||
auth.UpdatedAt = time.Now()
|
||||
|
||||
updated, err := h.authManager.Update(c.Request.Context(), auth)
|
||||
|
||||
@@ -28,7 +28,7 @@ func (h *Handler) GetConfig(c *gin.Context) {
|
||||
c.JSON(200, gin.H{})
|
||||
return
|
||||
}
|
||||
c.JSON(200, new(*h.cfg))
|
||||
c.JSON(200, h.cfg)
|
||||
}
|
||||
|
||||
type releaseInfo struct {
|
||||
@@ -158,7 +158,8 @@ func (h *Handler) PutConfigYAML(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "reload_failed", "message": err.Error()})
|
||||
return
|
||||
}
|
||||
h.cfg = newCfg
|
||||
h.cfg = cloneConfig(newCfg)
|
||||
h.committedCfg = cloneConfig(h.cfg)
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true, "changed": []string{"config"}})
|
||||
}
|
||||
|
||||
@@ -183,14 +184,16 @@ func (h *Handler) GetConfigYAML(c *gin.Context) {
|
||||
|
||||
// Debug
|
||||
func (h *Handler) GetDebug(c *gin.Context) { c.JSON(200, gin.H{"debug": h.cfg.Debug}) }
|
||||
func (h *Handler) PutDebug(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.Debug = v }) }
|
||||
func (h *Handler) PutDebug(c *gin.Context) {
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.Debug = v })
|
||||
}
|
||||
|
||||
// UsageStatisticsEnabled
|
||||
func (h *Handler) GetUsageStatisticsEnabled(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"usage-statistics-enabled": h.cfg.UsageStatisticsEnabled})
|
||||
}
|
||||
func (h *Handler) PutUsageStatisticsEnabled(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.UsageStatisticsEnabled = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.UsageStatisticsEnabled = v })
|
||||
}
|
||||
|
||||
// UsageStatisticsEnabled
|
||||
@@ -198,7 +201,7 @@ func (h *Handler) GetLoggingToFile(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"logging-to-file": h.cfg.LoggingToFile})
|
||||
}
|
||||
func (h *Handler) PutLoggingToFile(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.LoggingToFile = v })
|
||||
}
|
||||
|
||||
// LogsMaxTotalSizeMB
|
||||
@@ -217,8 +220,9 @@ func (h *Handler) PutLogsMaxTotalSizeMB(c *gin.Context) {
|
||||
if value < 0 {
|
||||
value = 0
|
||||
}
|
||||
h.cfg.LogsMaxTotalSizeMB = value
|
||||
h.persist(c)
|
||||
h.mutateConfig(c, func(cfg *config.Config) {
|
||||
cfg.LogsMaxTotalSizeMB = value
|
||||
})
|
||||
}
|
||||
|
||||
// ErrorLogsMaxFiles
|
||||
@@ -237,14 +241,15 @@ func (h *Handler) PutErrorLogsMaxFiles(c *gin.Context) {
|
||||
if value < 0 {
|
||||
value = 10
|
||||
}
|
||||
h.cfg.ErrorLogsMaxFiles = value
|
||||
h.persist(c)
|
||||
h.mutateConfig(c, func(cfg *config.Config) {
|
||||
cfg.ErrorLogsMaxFiles = value
|
||||
})
|
||||
}
|
||||
|
||||
// Request log
|
||||
func (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }
|
||||
func (h *Handler) PutRequestLog(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.RequestLog = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.RequestLog = v })
|
||||
}
|
||||
|
||||
// Websocket auth
|
||||
@@ -252,7 +257,7 @@ func (h *Handler) GetWebsocketAuth(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"ws-auth": h.cfg.WebsocketAuth})
|
||||
}
|
||||
func (h *Handler) PutWebsocketAuth(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.WebsocketAuth = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.WebsocketAuth = v })
|
||||
}
|
||||
|
||||
// Request retry
|
||||
@@ -260,7 +265,7 @@ func (h *Handler) GetRequestRetry(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"request-retry": h.cfg.RequestRetry})
|
||||
}
|
||||
func (h *Handler) PutRequestRetry(c *gin.Context) {
|
||||
h.updateIntField(c, func(v int) { h.cfg.RequestRetry = v })
|
||||
h.updateIntField(c, func(cfg *config.Config, v int) { cfg.RequestRetry = v })
|
||||
}
|
||||
|
||||
// Max retry interval
|
||||
@@ -268,7 +273,7 @@ func (h *Handler) GetMaxRetryInterval(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"max-retry-interval": h.cfg.MaxRetryInterval})
|
||||
}
|
||||
func (h *Handler) PutMaxRetryInterval(c *gin.Context) {
|
||||
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
|
||||
h.updateIntField(c, func(cfg *config.Config, v int) { cfg.MaxRetryInterval = v })
|
||||
}
|
||||
|
||||
// ForceModelPrefix
|
||||
@@ -276,7 +281,7 @@ func (h *Handler) GetForceModelPrefix(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"force-model-prefix": h.cfg.ForceModelPrefix})
|
||||
}
|
||||
func (h *Handler) PutForceModelPrefix(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.ForceModelPrefix = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.ForceModelPrefix = v })
|
||||
}
|
||||
|
||||
func normalizeRoutingStrategy(strategy string) (string, bool) {
|
||||
@@ -313,16 +318,18 @@ func (h *Handler) PutRoutingStrategy(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid strategy"})
|
||||
return
|
||||
}
|
||||
h.cfg.Routing.Strategy = normalized
|
||||
h.persist(c)
|
||||
h.mutateConfig(c, func(cfg *config.Config) {
|
||||
cfg.Routing.Strategy = normalized
|
||||
})
|
||||
}
|
||||
|
||||
// Proxy URL
|
||||
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
|
||||
func (h *Handler) PutProxyURL(c *gin.Context) {
|
||||
h.updateStringField(c, func(v string) { h.cfg.ProxyURL = v })
|
||||
h.updateStringField(c, func(cfg *config.Config, v string) { cfg.ProxyURL = v })
|
||||
}
|
||||
func (h *Handler) DeleteProxyURL(c *gin.Context) {
|
||||
h.cfg.ProxyURL = ""
|
||||
h.persist(c)
|
||||
h.mutateConfig(c, func(cfg *config.Config) {
|
||||
cfg.ProxyURL = ""
|
||||
})
|
||||
}
|
||||
|
||||
@@ -509,8 +509,12 @@ func (h *Handler) PutVertexCompatKeys(c *gin.Context) {
|
||||
}
|
||||
for i := range arr {
|
||||
normalizeVertexCompatKey(&arr[i])
|
||||
if arr[i].APIKey == "" {
|
||||
c.JSON(400, gin.H{"error": fmt.Sprintf("vertex-api-key[%d].api-key is required", i)})
|
||||
return
|
||||
}
|
||||
}
|
||||
h.cfg.VertexCompatAPIKey = arr
|
||||
h.cfg.VertexCompatAPIKey = append([]config.VertexCompatKey(nil), arr...)
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persist(c)
|
||||
}
|
||||
@@ -1088,7 +1092,7 @@ func (h *Handler) GetAmpUpstreamURL(c *gin.Context) {
|
||||
|
||||
// PutAmpUpstreamURL updates the ampcode upstream URL.
|
||||
func (h *Handler) PutAmpUpstreamURL(c *gin.Context) {
|
||||
h.updateStringField(c, func(v string) { h.cfg.AmpCode.UpstreamURL = strings.TrimSpace(v) })
|
||||
h.updateStringField(c, func(cfg *config.Config, v string) { cfg.AmpCode.UpstreamURL = strings.TrimSpace(v) })
|
||||
}
|
||||
|
||||
// DeleteAmpUpstreamURL clears the ampcode upstream URL.
|
||||
@@ -1108,7 +1112,7 @@ func (h *Handler) GetAmpUpstreamAPIKey(c *gin.Context) {
|
||||
|
||||
// PutAmpUpstreamAPIKey updates the ampcode upstream API key.
|
||||
func (h *Handler) PutAmpUpstreamAPIKey(c *gin.Context) {
|
||||
h.updateStringField(c, func(v string) { h.cfg.AmpCode.UpstreamAPIKey = strings.TrimSpace(v) })
|
||||
h.updateStringField(c, func(cfg *config.Config, v string) { cfg.AmpCode.UpstreamAPIKey = strings.TrimSpace(v) })
|
||||
}
|
||||
|
||||
// DeleteAmpUpstreamAPIKey clears the ampcode upstream API key.
|
||||
@@ -1128,7 +1132,7 @@ func (h *Handler) GetAmpRestrictManagementToLocalhost(c *gin.Context) {
|
||||
|
||||
// PutAmpRestrictManagementToLocalhost updates the localhost restriction setting.
|
||||
func (h *Handler) PutAmpRestrictManagementToLocalhost(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.AmpCode.RestrictManagementToLocalhost = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.AmpCode.RestrictManagementToLocalhost = v })
|
||||
}
|
||||
|
||||
// GetAmpModelMappings returns the ampcode model mappings.
|
||||
@@ -1217,7 +1221,7 @@ func (h *Handler) GetAmpForceModelMappings(c *gin.Context) {
|
||||
|
||||
// PutAmpForceModelMappings updates the force model mappings setting.
|
||||
func (h *Handler) PutAmpForceModelMappings(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.AmpCode.ForceModelMappings = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.AmpCode.ForceModelMappings = v })
|
||||
}
|
||||
|
||||
// GetAmpUpstreamAPIKeys returns the ampcode upstream API keys mapping.
|
||||
|
||||
@@ -3,6 +3,8 @@ package management
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -117,9 +119,7 @@ func (h *Handler) processAPIKey(ctx context.Context, provider, key string, lineN
|
||||
// Basic duplicate check could be added here if needed
|
||||
|
||||
timestamp := time.Now().Unix()
|
||||
// Use a shortened key hash or prefix for filename to avoid leaking credentials in filenames
|
||||
safeName := fmt.Sprintf("%s-%s", provider, key[:min(8, len(key))])
|
||||
fileName := fmt.Sprintf("%s-%d.json", safeName, timestamp)
|
||||
fileName := newImportedCredentialFileName(provider, timestamp)
|
||||
|
||||
record := &coreauth.Auth{
|
||||
ID: fileName,
|
||||
@@ -161,9 +161,10 @@ func parseLines(r io.Reader) ([]string, error) {
|
||||
return lines, nil
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
func newImportedCredentialFileName(provider string, timestamp int64) string {
|
||||
suffix := make([]byte, 6)
|
||||
if _, err := rand.Read(suffix); err != nil {
|
||||
return fmt.Sprintf("%s-import-%d.json", provider, timestamp)
|
||||
}
|
||||
return b
|
||||
return fmt.Sprintf("%s-import-%d-%s.json", provider, timestamp, hex.EncodeToString(suffix))
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type attemptInfo struct {
|
||||
@@ -37,6 +38,7 @@ const attemptMaxIdleTime = 2 * time.Hour
|
||||
// Handler aggregates config reference, persistence path and helpers.
|
||||
type Handler struct {
|
||||
cfg *config.Config
|
||||
committedCfg *config.Config
|
||||
configFilePath string
|
||||
mu sync.Mutex
|
||||
attemptsMu sync.Mutex
|
||||
@@ -56,9 +58,11 @@ type Handler struct {
|
||||
func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Manager) *Handler {
|
||||
envSecret, _ := os.LookupEnv("MANAGEMENT_PASSWORD")
|
||||
envSecret = strings.TrimSpace(envSecret)
|
||||
clonedCfg := cloneConfig(cfg)
|
||||
|
||||
h := &Handler{
|
||||
cfg: cfg,
|
||||
cfg: clonedCfg,
|
||||
committedCfg: cloneConfig(clonedCfg),
|
||||
configFilePath: configFilePath,
|
||||
failedAttempts: make(map[string]*attemptInfo),
|
||||
authManager: manager,
|
||||
@@ -107,7 +111,13 @@ func NewHandlerWithoutConfigFilePath(cfg *config.Config, manager *coreauth.Manag
|
||||
}
|
||||
|
||||
// SetConfig updates the in-memory config reference when the server hot-reloads.
|
||||
func (h *Handler) SetConfig(cfg *config.Config) { h.cfg = cfg }
|
||||
func (h *Handler) SetConfig(cfg *config.Config) {
|
||||
clonedCfg := cloneConfig(cfg)
|
||||
h.mu.Lock()
|
||||
h.cfg = clonedCfg
|
||||
h.committedCfg = cloneConfig(clonedCfg)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetAuthManager updates the auth manager reference used by management endpoints.
|
||||
func (h *Handler) SetAuthManager(manager *coreauth.Manager) { h.authManager = manager }
|
||||
@@ -276,19 +286,45 @@ func (h *Handler) Middleware() gin.HandlerFunc {
|
||||
|
||||
// persist saves the current in-memory config to disk.
|
||||
func (h *Handler) persist(c *gin.Context) bool {
|
||||
h.mu.Lock()
|
||||
current := cloneConfig(h.cfg)
|
||||
h.mu.Unlock()
|
||||
return h.persistConfig(c, current)
|
||||
}
|
||||
|
||||
func (h *Handler) persistConfig(c *gin.Context, next *config.Config) bool {
|
||||
if next == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "config unavailable"})
|
||||
return false
|
||||
}
|
||||
next = cloneConfig(next)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
// Preserve comments when writing
|
||||
if err := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); err != nil {
|
||||
if err := saveConfigAtomically(h.configFilePath, next); err != nil {
|
||||
h.cfg = cloneConfig(h.committedCfg)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to save config: %v", err)})
|
||||
return false
|
||||
}
|
||||
h.cfg = next
|
||||
h.committedCfg = cloneConfig(next)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Handler) mutateConfig(c *gin.Context, mutate func(*config.Config)) bool {
|
||||
h.mu.Lock()
|
||||
next := cloneConfig(h.cfg)
|
||||
h.mu.Unlock()
|
||||
if next == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "config unavailable"})
|
||||
return false
|
||||
}
|
||||
mutate(next)
|
||||
return h.persistConfig(c, next)
|
||||
}
|
||||
|
||||
// Helper methods for simple types
|
||||
func (h *Handler) updateBoolField(c *gin.Context, set func(bool)) {
|
||||
func (h *Handler) updateBoolField(c *gin.Context, set func(*config.Config, bool)) {
|
||||
var body struct {
|
||||
Value *bool `json:"value"`
|
||||
}
|
||||
@@ -296,11 +332,12 @@ func (h *Handler) updateBoolField(c *gin.Context, set func(bool)) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
set(*body.Value)
|
||||
h.persist(c)
|
||||
h.mutateConfig(c, func(cfg *config.Config) {
|
||||
set(cfg, *body.Value)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) updateIntField(c *gin.Context, set func(int)) {
|
||||
func (h *Handler) updateIntField(c *gin.Context, set func(*config.Config, int)) {
|
||||
var body struct {
|
||||
Value *int `json:"value"`
|
||||
}
|
||||
@@ -308,11 +345,12 @@ func (h *Handler) updateIntField(c *gin.Context, set func(int)) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
set(*body.Value)
|
||||
h.persist(c)
|
||||
h.mutateConfig(c, func(cfg *config.Config) {
|
||||
set(cfg, *body.Value)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) updateStringField(c *gin.Context, set func(string)) {
|
||||
func (h *Handler) updateStringField(c *gin.Context, set func(*config.Config, string)) {
|
||||
var body struct {
|
||||
Value *string `json:"value"`
|
||||
}
|
||||
@@ -320,6 +358,58 @@ func (h *Handler) updateStringField(c *gin.Context, set func(string)) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
set(*body.Value)
|
||||
h.persist(c)
|
||||
h.mutateConfig(c, func(cfg *config.Config) {
|
||||
set(cfg, *body.Value)
|
||||
})
|
||||
}
|
||||
|
||||
func cloneConfig(cfg *config.Config) *config.Config {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := yaml.Marshal(cfg)
|
||||
if err != nil {
|
||||
cloned := *cfg
|
||||
return &cloned
|
||||
}
|
||||
var cloned config.Config
|
||||
if err = yaml.Unmarshal(raw, &cloned); err != nil {
|
||||
fallback := *cfg
|
||||
return &fallback
|
||||
}
|
||||
return &cloned
|
||||
}
|
||||
|
||||
func saveConfigAtomically(path string, cfg *config.Config) error {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return fmt.Errorf("config file path not configured")
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
original, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpFile, err := os.CreateTemp(filepath.Dir(path), ".config-save-*.yaml")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpPath := tmpFile.Name()
|
||||
if errClose := tmpFile.Close(); errClose != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return errClose
|
||||
}
|
||||
defer func() {
|
||||
_ = os.Remove(tmpPath)
|
||||
}()
|
||||
if err = os.WriteFile(tmpPath, original, info.Mode().Perm()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = config.SaveConfigPreserveComments(tmpPath, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpPath, path)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
)
|
||||
|
||||
func TestDeleteMemorySession_RejectsTraversal(t *testing.T) {
|
||||
t.Setenv("CLIPROXY_MEMORY_DIR", t.TempDir())
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
outsidePath := filepath.Join(t.TempDir(), "outside")
|
||||
if err := os.WriteFile(outsidePath, []byte("keep"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile() error = %v", err)
|
||||
}
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/memory/session?session="+url.QueryEscape("../outside"), nil)
|
||||
|
||||
h := &Handler{}
|
||||
h.DeleteMemorySession(ctx)
|
||||
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d body=%s", recorder.Code, http.StatusBadRequest, recorder.Body.String())
|
||||
}
|
||||
if _, err := os.Stat(outsidePath); err != nil {
|
||||
t.Fatalf("outside path should remain untouched: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessAPIKey_DoesNotLeakSecretPrefixInSavedPath(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
authDir := t.TempDir()
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
||||
|
||||
key := "sk-secret-prefix-1234567890"
|
||||
result := h.processAPIKey(context.Background(), "openai", key, 1)
|
||||
if !result.Success {
|
||||
t.Fatalf("processAPIKey() failed: %+v", result)
|
||||
}
|
||||
if strings.Contains(result.SavedPath, "sk-secret") {
|
||||
t.Fatalf("saved path leaked key prefix: %q", result.SavedPath)
|
||||
}
|
||||
if !strings.HasPrefix(filepath.Base(result.SavedPath), "openai-import-") {
|
||||
t.Fatalf("saved path = %q, want generated import prefix", result.SavedPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommitUploadedAuthFile_InvalidDataDoesNotWriteFile(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
authDir := t.TempDir()
|
||||
path := filepath.Join(authDir, "broken.json")
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
||||
|
||||
err := h.commitUploadedAuthFile(context.Background(), path, []byte(`{"type":`))
|
||||
if err == nil {
|
||||
t.Fatal("commitUploadedAuthFile() unexpectedly succeeded")
|
||||
}
|
||||
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("invalid upload should not leave a file behind, stat err=%v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetConfig_ReturnsLiveConfig(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{
|
||||
SDKConfig: config.SDKConfig{
|
||||
ProxyURL: "http://127.0.0.1:8080",
|
||||
},
|
||||
Debug: true,
|
||||
UsageStatisticsEnabled: true,
|
||||
}, nil)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/config", nil)
|
||||
|
||||
h.GetConfig(ctx)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
|
||||
}
|
||||
|
||||
var got config.Config
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("Unmarshal() error = %v body=%s", err, recorder.Body.String())
|
||||
}
|
||||
if !got.Debug {
|
||||
t.Fatalf("Debug = %v, want true", got.Debug)
|
||||
}
|
||||
if got.ProxyURL != "http://127.0.0.1:8080" {
|
||||
t.Fatalf("ProxyURL = %q", got.ProxyURL)
|
||||
}
|
||||
if !got.UsageStatisticsEnabled {
|
||||
t.Fatalf("UsageStatisticsEnabled = %v, want true", got.UsageStatisticsEnabled)
|
||||
}
|
||||
}
|
||||
@@ -210,12 +210,11 @@ func (h *Handler) DeleteMemorySession(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
return
|
||||
}
|
||||
session := strings.TrimSpace(c.Query("session"))
|
||||
if session == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
|
||||
store := memory.NewFileStore(base)
|
||||
_, path, ok := resolveManagedMemorySession(c, store, c.Query("session"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
path := filepath.Join(base, "sessions", session)
|
||||
if err := os.RemoveAll(path); err != nil && !os.IsNotExist(err) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -289,12 +288,11 @@ func (h *Handler) ExportMemorySession(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
|
||||
return
|
||||
}
|
||||
session := strings.TrimSpace(c.Query("session"))
|
||||
if session == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
|
||||
store := memory.NewFileStore(base)
|
||||
session, dir, ok := resolveManagedMemorySession(c, store, c.Query("session"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
dir := filepath.Join(base, "sessions", session)
|
||||
if _, err := os.Stat(dir); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
|
||||
return
|
||||
@@ -357,9 +355,9 @@ func (h *Handler) ImportMemorySession(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "multipart form required"})
|
||||
return
|
||||
}
|
||||
session := strings.TrimSpace(c.Query("session"))
|
||||
if session == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
|
||||
store := memory.NewFileStore(base)
|
||||
_, dest, ok := resolveManagedMemorySession(c, store, c.Query("session"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
replace := strings.EqualFold(strings.TrimSpace(c.Query("replace")), "true")
|
||||
@@ -388,7 +386,6 @@ func (h *Handler) ImportMemorySession(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid zip"})
|
||||
return
|
||||
}
|
||||
dest := filepath.Join(base, "sessions", session)
|
||||
if replace {
|
||||
_ = os.RemoveAll(dest)
|
||||
}
|
||||
@@ -460,3 +457,21 @@ func anchorAppendOnlyEnabled() bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func resolveManagedMemorySession(c *gin.Context, store *memory.FileStore, rawSession string) (string, string, bool) {
|
||||
session := strings.TrimSpace(rawSession)
|
||||
if session == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
|
||||
return "", "", false
|
||||
}
|
||||
if strings.Contains(session, "..") || strings.ContainsAny(session, `/\`) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session"})
|
||||
return "", "", false
|
||||
}
|
||||
dir := store.SessionDir(session)
|
||||
if dir == "" {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to resolve session path"})
|
||||
return "", "", false
|
||||
}
|
||||
return filepath.Base(dir), dir, true
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
package management
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
)
|
||||
|
||||
// Quota exceeded toggles
|
||||
func (h *Handler) GetSwitchProject(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"switch-project": h.cfg.QuotaExceeded.SwitchProject})
|
||||
}
|
||||
func (h *Handler) PutSwitchProject(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchProject = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.QuotaExceeded.SwitchProject = v })
|
||||
}
|
||||
|
||||
func (h *Handler) GetSwitchPreviewModel(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"switch-preview-model": h.cfg.QuotaExceeded.SwitchPreviewModel})
|
||||
}
|
||||
func (h *Handler) PutSwitchPreviewModel(c *gin.Context) {
|
||||
h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchPreviewModel = v })
|
||||
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.QuotaExceeded.SwitchPreviewModel = v })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
type memoryAuthStore struct {
|
||||
mu sync.Mutex
|
||||
items map[string]*coreauth.Auth
|
||||
}
|
||||
|
||||
func (s *memoryAuthStore) List(_ context.Context) ([]*coreauth.Auth, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
out := make([]*coreauth.Auth, 0, len(s.items))
|
||||
for _, item := range s.items {
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *memoryAuthStore) Save(_ context.Context, auth *coreauth.Auth) (string, error) {
|
||||
if auth == nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.items == nil {
|
||||
s.items = make(map[string]*coreauth.Auth)
|
||||
}
|
||||
s.items[auth.ID] = auth
|
||||
return auth.ID, nil
|
||||
}
|
||||
|
||||
func (s *memoryAuthStore) Delete(_ context.Context, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
delete(s.items, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memoryAuthStore) SetBaseDir(string) {}
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
)
|
||||
|
||||
const requestBodyOverrideContextKey = "REQUEST_BODY_OVERRIDE"
|
||||
const responseBodyOverrideContextKey = "RESPONSE_BODY_OVERRIDE"
|
||||
const websocketTimelineOverrideContextKey = "WEBSOCKET_TIMELINE_OVERRIDE"
|
||||
|
||||
// RequestInfo holds essential details of an incoming HTTP request for logging purposes.
|
||||
type RequestInfo struct {
|
||||
@@ -304,6 +306,10 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error {
|
||||
if len(apiResponse) > 0 {
|
||||
_ = w.streamWriter.WriteAPIResponse(apiResponse)
|
||||
}
|
||||
apiWebsocketTimeline := w.extractAPIWebsocketTimeline(c)
|
||||
if len(apiWebsocketTimeline) > 0 {
|
||||
_ = w.streamWriter.WriteAPIWebsocketTimeline(apiWebsocketTimeline)
|
||||
}
|
||||
if err := w.streamWriter.Close(); err != nil {
|
||||
w.streamWriter = nil
|
||||
return err
|
||||
@@ -312,7 +318,7 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
return w.logRequest(w.extractRequestBody(c), finalStatusCode, w.cloneHeaders(), w.body.Bytes(), w.extractAPIRequest(c), w.extractAPIResponse(c), w.extractAPIResponseTimestamp(c), slicesAPIResponseError, forceLog)
|
||||
return w.logRequest(w.extractRequestBody(c), finalStatusCode, w.cloneHeaders(), w.extractResponseBody(c), w.extractWebsocketTimeline(c), w.extractAPIRequest(c), w.extractAPIResponse(c), w.extractAPIWebsocketTimeline(c), w.extractAPIResponseTimestamp(c), slicesAPIResponseError, forceLog)
|
||||
}
|
||||
|
||||
func (w *ResponseWriterWrapper) cloneHeaders() map[string][]string {
|
||||
@@ -352,6 +358,18 @@ func (w *ResponseWriterWrapper) extractAPIResponse(c *gin.Context) []byte {
|
||||
return data
|
||||
}
|
||||
|
||||
func (w *ResponseWriterWrapper) extractAPIWebsocketTimeline(c *gin.Context) []byte {
|
||||
apiTimeline, isExist := c.Get("API_WEBSOCKET_TIMELINE")
|
||||
if !isExist {
|
||||
return nil
|
||||
}
|
||||
data, ok := apiTimeline.([]byte)
|
||||
if !ok || len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
return bytes.Clone(data)
|
||||
}
|
||||
|
||||
func (w *ResponseWriterWrapper) extractAPIResponseTimestamp(c *gin.Context) time.Time {
|
||||
ts, isExist := c.Get("API_RESPONSE_TIMESTAMP")
|
||||
if !isExist {
|
||||
@@ -364,19 +382,8 @@ func (w *ResponseWriterWrapper) extractAPIResponseTimestamp(c *gin.Context) time
|
||||
}
|
||||
|
||||
func (w *ResponseWriterWrapper) extractRequestBody(c *gin.Context) []byte {
|
||||
if c != nil {
|
||||
if bodyOverride, isExist := c.Get(requestBodyOverrideContextKey); isExist {
|
||||
switch value := bodyOverride.(type) {
|
||||
case []byte:
|
||||
if len(value) > 0 {
|
||||
return bytes.Clone(value)
|
||||
}
|
||||
case string:
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return []byte(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
if body := extractBodyOverride(c, requestBodyOverrideContextKey); len(body) > 0 {
|
||||
return body
|
||||
}
|
||||
if w.requestInfo != nil && len(w.requestInfo.Body) > 0 {
|
||||
return w.requestInfo.Body
|
||||
@@ -384,13 +391,48 @@ func (w *ResponseWriterWrapper) extractRequestBody(c *gin.Context) []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, headers map[string][]string, body []byte, apiRequestBody, apiResponseBody []byte, apiResponseTimestamp time.Time, apiResponseErrors []*interfaces.ErrorMessage, forceLog bool) error {
|
||||
func (w *ResponseWriterWrapper) extractResponseBody(c *gin.Context) []byte {
|
||||
if body := extractBodyOverride(c, responseBodyOverrideContextKey); len(body) > 0 {
|
||||
return body
|
||||
}
|
||||
if w.body == nil || w.body.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
return bytes.Clone(w.body.Bytes())
|
||||
}
|
||||
|
||||
func (w *ResponseWriterWrapper) extractWebsocketTimeline(c *gin.Context) []byte {
|
||||
return extractBodyOverride(c, websocketTimelineOverrideContextKey)
|
||||
}
|
||||
|
||||
func extractBodyOverride(c *gin.Context, key string) []byte {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
bodyOverride, isExist := c.Get(key)
|
||||
if !isExist {
|
||||
return nil
|
||||
}
|
||||
switch value := bodyOverride.(type) {
|
||||
case []byte:
|
||||
if len(value) > 0 {
|
||||
return bytes.Clone(value)
|
||||
}
|
||||
case string:
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return []byte(value)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, headers map[string][]string, body, websocketTimeline, apiRequestBody, apiResponseBody, apiWebsocketTimeline []byte, apiResponseTimestamp time.Time, apiResponseErrors []*interfaces.ErrorMessage, forceLog bool) error {
|
||||
if w.requestInfo == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if loggerWithOptions, ok := w.logger.(interface {
|
||||
LogRequestWithOptions(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []*interfaces.ErrorMessage, bool, string, time.Time, time.Time) error
|
||||
LogRequestWithOptions(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []byte, []byte, []*interfaces.ErrorMessage, bool, string, time.Time, time.Time) error
|
||||
}); ok {
|
||||
return loggerWithOptions.LogRequestWithOptions(
|
||||
w.requestInfo.URL,
|
||||
@@ -400,8 +442,10 @@ func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, h
|
||||
statusCode,
|
||||
headers,
|
||||
body,
|
||||
websocketTimeline,
|
||||
apiRequestBody,
|
||||
apiResponseBody,
|
||||
apiWebsocketTimeline,
|
||||
apiResponseErrors,
|
||||
forceLog,
|
||||
w.requestInfo.RequestID,
|
||||
@@ -418,8 +462,10 @@ func (w *ResponseWriterWrapper) logRequest(requestBody []byte, statusCode int, h
|
||||
statusCode,
|
||||
headers,
|
||||
body,
|
||||
websocketTimeline,
|
||||
apiRequestBody,
|
||||
apiResponseBody,
|
||||
apiWebsocketTimeline,
|
||||
apiResponseErrors,
|
||||
w.requestInfo.RequestID,
|
||||
w.requestInfo.Timestamp,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
)
|
||||
|
||||
func TestExtractRequestBodyPrefersOverride(t *testing.T) {
|
||||
@@ -33,7 +37,7 @@ func TestExtractRequestBodySupportsStringOverride(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
|
||||
wrapper := &ResponseWriterWrapper{}
|
||||
wrapper := &ResponseWriterWrapper{body: &bytes.Buffer{}}
|
||||
c.Set(requestBodyOverrideContextKey, "override-as-string")
|
||||
|
||||
body := wrapper.extractRequestBody(c)
|
||||
@@ -41,3 +45,158 @@ func TestExtractRequestBodySupportsStringOverride(t *testing.T) {
|
||||
t.Fatalf("request body = %q, want %q", string(body), "override-as-string")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseBodyPrefersOverride(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
|
||||
wrapper := &ResponseWriterWrapper{body: &bytes.Buffer{}}
|
||||
wrapper.body.WriteString("original-response")
|
||||
|
||||
body := wrapper.extractResponseBody(c)
|
||||
if string(body) != "original-response" {
|
||||
t.Fatalf("response body = %q, want %q", string(body), "original-response")
|
||||
}
|
||||
|
||||
c.Set(responseBodyOverrideContextKey, []byte("override-response"))
|
||||
body = wrapper.extractResponseBody(c)
|
||||
if string(body) != "override-response" {
|
||||
t.Fatalf("response body = %q, want %q", string(body), "override-response")
|
||||
}
|
||||
|
||||
body[0] = 'X'
|
||||
if got := wrapper.extractResponseBody(c); string(got) != "override-response" {
|
||||
t.Fatalf("response override should be cloned, got %q", string(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractResponseBodySupportsStringOverride(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
|
||||
wrapper := &ResponseWriterWrapper{}
|
||||
c.Set(responseBodyOverrideContextKey, "override-response-as-string")
|
||||
|
||||
body := wrapper.extractResponseBody(c)
|
||||
if string(body) != "override-response-as-string" {
|
||||
t.Fatalf("response body = %q, want %q", string(body), "override-response-as-string")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractBodyOverrideClonesBytes(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
|
||||
override := []byte("body-override")
|
||||
c.Set(requestBodyOverrideContextKey, override)
|
||||
|
||||
body := extractBodyOverride(c, requestBodyOverrideContextKey)
|
||||
if !bytes.Equal(body, override) {
|
||||
t.Fatalf("body override = %q, want %q", string(body), string(override))
|
||||
}
|
||||
|
||||
body[0] = 'X'
|
||||
if !bytes.Equal(override, []byte("body-override")) {
|
||||
t.Fatalf("override mutated: %q", string(override))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractWebsocketTimelineUsesOverride(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
|
||||
wrapper := &ResponseWriterWrapper{}
|
||||
if got := wrapper.extractWebsocketTimeline(c); got != nil {
|
||||
t.Fatalf("expected nil websocket timeline, got %q", string(got))
|
||||
}
|
||||
|
||||
c.Set(websocketTimelineOverrideContextKey, []byte("timeline"))
|
||||
body := wrapper.extractWebsocketTimeline(c)
|
||||
if string(body) != "timeline" {
|
||||
t.Fatalf("websocket timeline = %q, want %q", string(body), "timeline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeStreamingWritesAPIWebsocketTimeline(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
|
||||
streamWriter := &testStreamingLogWriter{}
|
||||
wrapper := &ResponseWriterWrapper{
|
||||
ResponseWriter: c.Writer,
|
||||
logger: &testRequestLogger{enabled: true},
|
||||
requestInfo: &RequestInfo{
|
||||
URL: "/v1/responses",
|
||||
Method: "POST",
|
||||
Headers: map[string][]string{"Content-Type": {"application/json"}},
|
||||
RequestID: "req-1",
|
||||
Timestamp: time.Date(2026, time.April, 1, 12, 0, 0, 0, time.UTC),
|
||||
},
|
||||
isStreaming: true,
|
||||
streamWriter: streamWriter,
|
||||
}
|
||||
|
||||
c.Set("API_WEBSOCKET_TIMELINE", []byte("Timestamp: 2026-04-01T12:00:00Z\nEvent: api.websocket.request\n{}"))
|
||||
|
||||
if err := wrapper.Finalize(c); err != nil {
|
||||
t.Fatalf("Finalize error: %v", err)
|
||||
}
|
||||
if string(streamWriter.apiWebsocketTimeline) != "Timestamp: 2026-04-01T12:00:00Z\nEvent: api.websocket.request\n{}" {
|
||||
t.Fatalf("stream writer websocket timeline = %q", string(streamWriter.apiWebsocketTimeline))
|
||||
}
|
||||
if !streamWriter.closed {
|
||||
t.Fatal("expected stream writer to be closed")
|
||||
}
|
||||
}
|
||||
|
||||
type testRequestLogger struct {
|
||||
enabled bool
|
||||
}
|
||||
|
||||
func (l *testRequestLogger) LogRequest(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []byte, []byte, []*interfaces.ErrorMessage, string, time.Time, time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *testRequestLogger) LogStreamingRequest(string, string, map[string][]string, []byte, string) (logging.StreamingLogWriter, error) {
|
||||
return &testStreamingLogWriter{}, nil
|
||||
}
|
||||
|
||||
func (l *testRequestLogger) IsEnabled() bool {
|
||||
return l.enabled
|
||||
}
|
||||
|
||||
type testStreamingLogWriter struct {
|
||||
apiWebsocketTimeline []byte
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (w *testStreamingLogWriter) WriteChunkAsync([]byte) {}
|
||||
|
||||
func (w *testStreamingLogWriter) WriteStatus(int, map[string][]string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *testStreamingLogWriter) WriteAPIRequest([]byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *testStreamingLogWriter) WriteAPIResponse([]byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *testStreamingLogWriter) WriteAPIWebsocketTimeline(apiWebsocketTimeline []byte) error {
|
||||
w.apiWebsocketTimeline = bytes.Clone(apiWebsocketTimeline)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *testStreamingLogWriter) SetFirstChunkTimestamp(time.Time) {}
|
||||
|
||||
func (w *testStreamingLogWriter) Close() error {
|
||||
w.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -123,6 +123,10 @@ func (fh *FallbackHandler) WrapHandler(handler gin.HandlerFunc) gin.HandlerFunc
|
||||
return
|
||||
}
|
||||
|
||||
// Sanitize request body: remove thinking blocks with invalid signatures
|
||||
// to prevent upstream API 400 errors
|
||||
bodyBytes = SanitizeAmpRequestBody(bodyBytes)
|
||||
|
||||
// Restore the body for the handler to read
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
|
||||
@@ -249,6 +253,7 @@ func (fh *FallbackHandler) WrapHandler(handler gin.HandlerFunc) gin.HandlerFunc
|
||||
log.Debugf("amp model mapping: request %s -> %s", normalizedModel, resolvedModel)
|
||||
logAmpRouting(RouteTypeModelMapping, modelName, resolvedModel, providerName, requestPath)
|
||||
rewriter := NewResponseRewriter(c.Writer, modelName)
|
||||
rewriter.suppressThinking = true
|
||||
c.Writer = rewriter
|
||||
// Filter Anthropic-Beta header only for local handling paths
|
||||
filterAntropicBetaHeader(c)
|
||||
@@ -259,10 +264,17 @@ func (fh *FallbackHandler) WrapHandler(handler gin.HandlerFunc) gin.HandlerFunc
|
||||
} else if len(providers) > 0 {
|
||||
// Log: Using local provider (free)
|
||||
logAmpRouting(RouteTypeLocalProvider, modelName, resolvedModel, providerName, requestPath)
|
||||
// Wrap with ResponseRewriter for local providers too, because upstream
|
||||
// proxies (e.g. NewAPI) may return a different model name and lack
|
||||
// Amp-required fields like thinking.signature.
|
||||
rewriter := NewResponseRewriter(c.Writer, modelName)
|
||||
rewriter.suppressThinking = providerName != "claude"
|
||||
c.Writer = rewriter
|
||||
// Filter Anthropic-Beta header only for local handling paths
|
||||
filterAntropicBetaHeader(c)
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
handler(c)
|
||||
rewriter.Flush()
|
||||
} else {
|
||||
// No provider, no mapping, no proxy: fall back to the wrapped handler so it can return an error response
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
|
||||
@@ -108,11 +108,6 @@ func createReverseProxy(upstreamURL string, secretSource SecretSource) (*httputi
|
||||
// Modify incoming responses to handle gzip without Content-Encoding
|
||||
// This addresses the same issue as inline handler gzip handling, but at the proxy level
|
||||
proxy.ModifyResponse = func(resp *http.Response) error {
|
||||
// Only process successful responses
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Skip if already marked as gzip (Content-Encoding set)
|
||||
if resp.Header.Get("Content-Encoding") != "" {
|
||||
return nil
|
||||
|
||||
@@ -2,6 +2,8 @@ package amp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -12,15 +14,17 @@ import (
|
||||
)
|
||||
|
||||
// ResponseRewriter wraps a gin.ResponseWriter to intercept and modify the response body
|
||||
// It's used to rewrite model names in responses when model mapping is used
|
||||
// It is used to rewrite model names in responses when model mapping is used
|
||||
// and to keep Amp-compatible response shapes.
|
||||
type ResponseRewriter struct {
|
||||
gin.ResponseWriter
|
||||
body *bytes.Buffer
|
||||
originalModel string
|
||||
isStreaming bool
|
||||
body *bytes.Buffer
|
||||
originalModel string
|
||||
isStreaming bool
|
||||
suppressThinking bool
|
||||
}
|
||||
|
||||
// NewResponseRewriter creates a new response rewriter for model name substitution
|
||||
// NewResponseRewriter creates a new response rewriter for model name substitution.
|
||||
func NewResponseRewriter(w gin.ResponseWriter, originalModel string) *ResponseRewriter {
|
||||
return &ResponseRewriter{
|
||||
ResponseWriter: w,
|
||||
@@ -29,17 +33,66 @@ func NewResponseRewriter(w gin.ResponseWriter, originalModel string) *ResponseRe
|
||||
}
|
||||
}
|
||||
|
||||
// Write intercepts response writes and buffers them for model name replacement
|
||||
const maxBufferedResponseBytes = 2 * 1024 * 1024 // 2MB safety cap
|
||||
|
||||
func looksLikeSSEChunk(data []byte) bool {
|
||||
for _, line := range bytes.Split(data, []byte("\n")) {
|
||||
trimmed := bytes.TrimSpace(line)
|
||||
if bytes.HasPrefix(trimmed, []byte("data:")) ||
|
||||
bytes.HasPrefix(trimmed, []byte("event:")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (rw *ResponseRewriter) enableStreaming(reason string) error {
|
||||
if rw.isStreaming {
|
||||
return nil
|
||||
}
|
||||
rw.isStreaming = true
|
||||
|
||||
if rw.body != nil && rw.body.Len() > 0 {
|
||||
buf := rw.body.Bytes()
|
||||
toFlush := make([]byte, len(buf))
|
||||
copy(toFlush, buf)
|
||||
rw.body.Reset()
|
||||
|
||||
if _, err := rw.ResponseWriter.Write(rw.rewriteStreamChunk(toFlush)); err != nil {
|
||||
return err
|
||||
}
|
||||
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
log.Debugf("amp response rewriter: switched to streaming (%s)", reason)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rw *ResponseRewriter) Write(data []byte) (int, error) {
|
||||
// Detect streaming on first write
|
||||
if rw.body.Len() == 0 && !rw.isStreaming {
|
||||
if !rw.isStreaming && rw.body.Len() == 0 {
|
||||
contentType := rw.Header().Get("Content-Type")
|
||||
rw.isStreaming = strings.Contains(contentType, "text/event-stream") ||
|
||||
strings.Contains(contentType, "stream")
|
||||
}
|
||||
|
||||
if !rw.isStreaming {
|
||||
if looksLikeSSEChunk(data) {
|
||||
if err := rw.enableStreaming("sse heuristic"); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
} else if rw.body.Len()+len(data) > maxBufferedResponseBytes {
|
||||
log.Warnf("amp response rewriter: buffer exceeded %d bytes, switching to streaming", maxBufferedResponseBytes)
|
||||
if err := rw.enableStreaming("buffer limit"); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if rw.isStreaming {
|
||||
n, err := rw.ResponseWriter.Write(rw.rewriteStreamChunk(data))
|
||||
rewritten := rw.rewriteStreamChunk(data)
|
||||
n, err := rw.ResponseWriter.Write(rewritten)
|
||||
if err == nil {
|
||||
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
@@ -50,7 +103,6 @@ func (rw *ResponseRewriter) Write(data []byte) (int, error) {
|
||||
return rw.body.Write(data)
|
||||
}
|
||||
|
||||
// Flush writes the buffered response with model names rewritten
|
||||
func (rw *ResponseRewriter) Flush() {
|
||||
if rw.isStreaming {
|
||||
if flusher, ok := rw.ResponseWriter.(http.Flusher); ok {
|
||||
@@ -59,40 +111,79 @@ func (rw *ResponseRewriter) Flush() {
|
||||
return
|
||||
}
|
||||
if rw.body.Len() > 0 {
|
||||
if _, err := rw.ResponseWriter.Write(rw.rewriteModelInResponse(rw.body.Bytes())); err != nil {
|
||||
rewritten := rw.rewriteModelInResponse(rw.body.Bytes())
|
||||
// Update Content-Length to match the rewritten body size, since
|
||||
// signature injection and model name changes alter the payload length.
|
||||
rw.ResponseWriter.Header().Set("Content-Length", fmt.Sprintf("%d", len(rewritten)))
|
||||
if _, err := rw.ResponseWriter.Write(rewritten); err != nil {
|
||||
log.Warnf("amp response rewriter: failed to write rewritten response: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// modelFieldPaths lists all JSON paths where model name may appear
|
||||
var modelFieldPaths = []string{"message.model", "model", "modelVersion", "response.model", "response.modelVersion"}
|
||||
|
||||
// rewriteModelInResponse replaces all occurrences of the mapped model with the original model in JSON
|
||||
// It also suppresses "thinking" blocks if "tool_use" is present to ensure Amp client compatibility
|
||||
func (rw *ResponseRewriter) rewriteModelInResponse(data []byte) []byte {
|
||||
// 1. Amp Compatibility: Suppress thinking blocks if tool use is detected
|
||||
// The Amp client struggles when both thinking and tool_use blocks are present
|
||||
// ensureAmpSignature injects empty signature fields into tool_use/thinking blocks
|
||||
// in API responses so that the Amp TUI does not crash on P.signature.length.
|
||||
func ensureAmpSignature(data []byte) []byte {
|
||||
for index, block := range gjson.GetBytes(data, "content").Array() {
|
||||
blockType := block.Get("type").String()
|
||||
if blockType != "tool_use" && blockType != "thinking" {
|
||||
continue
|
||||
}
|
||||
signaturePath := fmt.Sprintf("content.%d.signature", index)
|
||||
if gjson.GetBytes(data, signaturePath).Exists() {
|
||||
continue
|
||||
}
|
||||
var err error
|
||||
data, err = sjson.SetBytes(data, signaturePath, "")
|
||||
if err != nil {
|
||||
log.Warnf("Amp ResponseRewriter: failed to add empty signature to %s block: %v", blockType, err)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
contentBlockType := gjson.GetBytes(data, "content_block.type").String()
|
||||
if (contentBlockType == "tool_use" || contentBlockType == "thinking") && !gjson.GetBytes(data, "content_block.signature").Exists() {
|
||||
var err error
|
||||
data, err = sjson.SetBytes(data, "content_block.signature", "")
|
||||
if err != nil {
|
||||
log.Warnf("Amp ResponseRewriter: failed to add empty signature to streaming %s block: %v", contentBlockType, err)
|
||||
}
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func (rw *ResponseRewriter) suppressAmpThinking(data []byte) []byte {
|
||||
if !rw.suppressThinking {
|
||||
return data
|
||||
}
|
||||
if gjson.GetBytes(data, `content.#(type=="tool_use")`).Exists() {
|
||||
filtered := gjson.GetBytes(data, `content.#(type!="thinking")#`)
|
||||
if filtered.Exists() {
|
||||
originalCount := gjson.GetBytes(data, "content.#").Int()
|
||||
filteredCount := filtered.Get("#").Int()
|
||||
|
||||
if originalCount > filteredCount {
|
||||
var err error
|
||||
data, err = sjson.SetBytes(data, "content", filtered.Value())
|
||||
if err != nil {
|
||||
log.Warnf("Amp ResponseRewriter: failed to suppress thinking blocks: %v", err)
|
||||
} else {
|
||||
log.Debugf("Amp ResponseRewriter: Suppressed %d thinking blocks due to tool usage", originalCount-filteredCount)
|
||||
// Log the result for verification
|
||||
log.Debugf("Amp ResponseRewriter: Resulting content: %s", gjson.GetBytes(data, "content").String())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func (rw *ResponseRewriter) rewriteModelInResponse(data []byte) []byte {
|
||||
data = ensureAmpSignature(data)
|
||||
data = rw.suppressAmpThinking(data)
|
||||
if len(data) == 0 {
|
||||
return data
|
||||
}
|
||||
|
||||
if rw.originalModel == "" {
|
||||
return data
|
||||
}
|
||||
@@ -104,24 +195,164 @@ func (rw *ResponseRewriter) rewriteModelInResponse(data []byte) []byte {
|
||||
return data
|
||||
}
|
||||
|
||||
// rewriteStreamChunk rewrites model names in SSE stream chunks
|
||||
func (rw *ResponseRewriter) rewriteStreamChunk(chunk []byte) []byte {
|
||||
if rw.originalModel == "" {
|
||||
return chunk
|
||||
lines := bytes.Split(chunk, []byte("\n"))
|
||||
var out [][]byte
|
||||
|
||||
i := 0
|
||||
for i < len(lines) {
|
||||
line := lines[i]
|
||||
trimmed := bytes.TrimSpace(line)
|
||||
|
||||
// Case 1: "event:" line - look ahead for its "data:" line
|
||||
if bytes.HasPrefix(trimmed, []byte("event: ")) {
|
||||
// Scan forward past blank lines to find the data: line
|
||||
dataIdx := -1
|
||||
for j := i + 1; j < len(lines); j++ {
|
||||
t := bytes.TrimSpace(lines[j])
|
||||
if len(t) == 0 {
|
||||
continue
|
||||
}
|
||||
if bytes.HasPrefix(t, []byte("data: ")) {
|
||||
dataIdx = j
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if dataIdx >= 0 {
|
||||
// Found event+data pair - process through rewriter
|
||||
jsonData := bytes.TrimPrefix(bytes.TrimSpace(lines[dataIdx]), []byte("data: "))
|
||||
if len(jsonData) > 0 && jsonData[0] == '{' {
|
||||
rewritten := rw.rewriteStreamEvent(jsonData)
|
||||
if rewritten == nil {
|
||||
i = dataIdx + 1
|
||||
continue
|
||||
}
|
||||
// Emit event line
|
||||
out = append(out, line)
|
||||
// Emit blank lines between event and data
|
||||
for k := i + 1; k < dataIdx; k++ {
|
||||
out = append(out, lines[k])
|
||||
}
|
||||
// Emit rewritten data
|
||||
out = append(out, append([]byte("data: "), rewritten...))
|
||||
i = dataIdx + 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// No data line found (orphan event from cross-chunk split)
|
||||
// Pass it through as-is - the data will arrive in the next chunk
|
||||
out = append(out, line)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
// Case 2: standalone "data:" line (no preceding event: in this chunk)
|
||||
if bytes.HasPrefix(trimmed, []byte("data: ")) {
|
||||
jsonData := bytes.TrimPrefix(trimmed, []byte("data: "))
|
||||
if len(jsonData) > 0 && jsonData[0] == '{' {
|
||||
rewritten := rw.rewriteStreamEvent(jsonData)
|
||||
if rewritten != nil {
|
||||
out = append(out, append([]byte("data: "), rewritten...))
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Case 3: everything else
|
||||
out = append(out, line)
|
||||
i++
|
||||
}
|
||||
|
||||
// SSE format: "data: {json}\n\n"
|
||||
lines := bytes.Split(chunk, []byte("\n"))
|
||||
for i, line := range lines {
|
||||
if bytes.HasPrefix(line, []byte("data: ")) {
|
||||
jsonData := bytes.TrimPrefix(line, []byte("data: "))
|
||||
if len(jsonData) > 0 && jsonData[0] == '{' {
|
||||
// Rewrite JSON in the data line
|
||||
rewritten := rw.rewriteModelInResponse(jsonData)
|
||||
lines[i] = append([]byte("data: "), rewritten...)
|
||||
return bytes.Join(out, []byte("\n"))
|
||||
}
|
||||
|
||||
// rewriteStreamEvent processes a single JSON event in the SSE stream.
|
||||
// It rewrites model names and ensures signature fields exist.
|
||||
// NOTE: streaming mode does NOT suppress thinking blocks - they are
|
||||
// passed through with signature injection to avoid breaking SSE index
|
||||
// alignment and TUI rendering.
|
||||
func (rw *ResponseRewriter) rewriteStreamEvent(data []byte) []byte {
|
||||
// Inject empty signature where needed
|
||||
data = ensureAmpSignature(data)
|
||||
|
||||
// Rewrite model name
|
||||
if rw.originalModel != "" {
|
||||
for _, path := range modelFieldPaths {
|
||||
if gjson.GetBytes(data, path).Exists() {
|
||||
data, _ = sjson.SetBytes(data, path, rw.originalModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bytes.Join(lines, []byte("\n"))
|
||||
return data
|
||||
}
|
||||
|
||||
// SanitizeAmpRequestBody removes thinking blocks with empty/missing/invalid signatures
|
||||
// and strips the proxy-injected "signature" field from tool_use blocks in the messages
|
||||
// array before forwarding to the upstream API.
|
||||
// This prevents 400 errors from the API which requires valid signatures on thinking
|
||||
// blocks and does not accept a signature field on tool_use blocks.
|
||||
func SanitizeAmpRequestBody(body []byte) []byte {
|
||||
messages := gjson.GetBytes(body, "messages")
|
||||
if !messages.Exists() || !messages.IsArray() {
|
||||
return body
|
||||
}
|
||||
|
||||
modified := false
|
||||
for msgIdx, msg := range messages.Array() {
|
||||
if msg.Get("role").String() != "assistant" {
|
||||
continue
|
||||
}
|
||||
content := msg.Get("content")
|
||||
if !content.Exists() || !content.IsArray() {
|
||||
continue
|
||||
}
|
||||
|
||||
var keepBlocks []interface{}
|
||||
contentModified := false
|
||||
|
||||
for _, block := range content.Array() {
|
||||
blockType := block.Get("type").String()
|
||||
if blockType == "thinking" {
|
||||
sig := block.Get("signature")
|
||||
if !sig.Exists() || sig.Type != gjson.String || strings.TrimSpace(sig.String()) == "" {
|
||||
contentModified = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Use raw JSON to prevent float64 rounding of large integers in tool_use inputs
|
||||
blockRaw := []byte(block.Raw)
|
||||
if blockType == "tool_use" && block.Get("signature").Exists() {
|
||||
blockRaw, _ = sjson.DeleteBytes(blockRaw, "signature")
|
||||
contentModified = true
|
||||
}
|
||||
|
||||
// sjson.SetBytes supports raw JSON strings if wrapped in gjson.Raw
|
||||
keepBlocks = append(keepBlocks, json.RawMessage(blockRaw))
|
||||
}
|
||||
|
||||
if contentModified {
|
||||
contentPath := fmt.Sprintf("messages.%d.content", msgIdx)
|
||||
var err error
|
||||
if len(keepBlocks) == 0 {
|
||||
body, err = sjson.SetBytes(body, contentPath, []interface{}{})
|
||||
} else {
|
||||
body, err = sjson.SetBytes(body, contentPath, keepBlocks)
|
||||
}
|
||||
if err != nil {
|
||||
log.Warnf("Amp RequestSanitizer: failed to sanitize message %d: %v", msgIdx, err)
|
||||
continue
|
||||
}
|
||||
modified = true
|
||||
}
|
||||
}
|
||||
|
||||
if modified {
|
||||
log.Debugf("Amp RequestSanitizer: sanitized request body")
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package amp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -100,6 +101,80 @@ func TestRewriteStreamChunk_MessageModel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteStreamChunk_PreservesThinkingWithSignatureInjection(t *testing.T) {
|
||||
rw := &ResponseRewriter{}
|
||||
|
||||
chunk := []byte("event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"abc\"}}\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"tool_use\",\"name\":\"bash\",\"input\":{}}}\n\n")
|
||||
result := rw.rewriteStreamChunk(chunk)
|
||||
|
||||
// Streaming mode preserves thinking blocks (does NOT suppress them)
|
||||
// to avoid breaking SSE index alignment and TUI rendering
|
||||
if !contains(result, []byte(`"content_block":{"type":"thinking"`)) {
|
||||
t.Fatalf("expected thinking content_block_start to be preserved, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte(`"delta":{"type":"thinking_delta"`)) {
|
||||
t.Fatalf("expected thinking_delta to be preserved, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte(`"type":"content_block_stop","index":0`)) {
|
||||
t.Fatalf("expected content_block_stop for thinking block to be preserved, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte(`"content_block":{"type":"tool_use"`)) {
|
||||
t.Fatalf("expected tool_use content_block frame to remain, got %s", string(result))
|
||||
}
|
||||
// Signature should be injected into both thinking and tool_use blocks
|
||||
if count := strings.Count(string(result), `"signature":""`); count != 2 {
|
||||
t.Fatalf("expected 2 signature injections, but got %d in %s", count, string(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeAmpRequestBody_RemovesWhitespaceAndNonStringSignatures(t *testing.T) {
|
||||
input := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"drop-whitespace","signature":" "},{"type":"thinking","thinking":"drop-number","signature":123},{"type":"thinking","thinking":"keep-valid","signature":"valid-signature"},{"type":"text","text":"keep-text"}]}]}`)
|
||||
result := SanitizeAmpRequestBody(input)
|
||||
|
||||
if contains(result, []byte("drop-whitespace")) {
|
||||
t.Fatalf("expected whitespace-only signature block to be removed, got %s", string(result))
|
||||
}
|
||||
if contains(result, []byte("drop-number")) {
|
||||
t.Fatalf("expected non-string signature block to be removed, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte("keep-valid")) {
|
||||
t.Fatalf("expected valid thinking block to remain, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte("keep-text")) {
|
||||
t.Fatalf("expected non-thinking content to remain, got %s", string(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeAmpRequestBody_StripsSignatureFromToolUseBlocks(t *testing.T) {
|
||||
input := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"thought","signature":"valid-sig"},{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"cmd":"ls"},"signature":""}]}]}`)
|
||||
result := SanitizeAmpRequestBody(input)
|
||||
|
||||
if contains(result, []byte(`"signature":""`)) {
|
||||
t.Fatalf("expected signature to be stripped from tool_use block, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte(`"valid-sig"`)) {
|
||||
t.Fatalf("expected thinking signature to remain, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte(`"tool_use"`)) {
|
||||
t.Fatalf("expected tool_use block to remain, got %s", string(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeAmpRequestBody_MixedInvalidThinkingAndToolUseSignature(t *testing.T) {
|
||||
input := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"drop-me","signature":""},{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"cmd":"ls"},"signature":""}]}]}`)
|
||||
result := SanitizeAmpRequestBody(input)
|
||||
|
||||
if contains(result, []byte("drop-me")) {
|
||||
t.Fatalf("expected invalid thinking block to be removed, got %s", string(result))
|
||||
}
|
||||
if contains(result, []byte(`"signature"`)) {
|
||||
t.Fatalf("expected signature to be stripped from tool_use block, got %s", string(result))
|
||||
}
|
||||
if !contains(result, []byte(`"tool_use"`)) {
|
||||
t.Fatalf("expected tool_use block to remain, got %s", string(result))
|
||||
}
|
||||
}
|
||||
|
||||
func contains(data, substr []byte) bool {
|
||||
for i := 0; i <= len(data)-len(substr); i++ {
|
||||
if string(data[i:i+len(substr)]) == string(substr) {
|
||||
|
||||
@@ -317,6 +317,10 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk
|
||||
// setupRoutes configures the API routes for the server.
|
||||
// It defines the endpoints and associates them with their respective handlers.
|
||||
func (s *Server) setupRoutes() {
|
||||
s.engine.GET("/healthz", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
s.engine.GET("/management.html", s.serveManagementControlPanel)
|
||||
openaiHandlers := openai.NewOpenAIAPIHandler(s.handlers)
|
||||
geminiHandlers := gemini.NewGeminiAPIHandler(s.handlers)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -46,6 +47,28 @@ func newTestServer(t *testing.T) *Server {
|
||||
return NewServer(cfg, authManager, accessManager, configPath)
|
||||
}
|
||||
|
||||
func TestHealthz(t *testing.T) {
|
||||
server := newTestServer(t)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
server.engine.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("unexpected status code: got %d want %d; body=%s", rr.Code, http.StatusOK, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to parse response JSON: %v; body=%s", err, rr.Body.String())
|
||||
}
|
||||
if resp.Status != "ok" {
|
||||
t.Fatalf("unexpected response status: got %q want %q", resp.Status, "ok")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAmpProviderModelRoutes(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
@@ -172,6 +195,8 @@ func TestDefaultRequestLoggerFactory_UsesResolvedLogDirectory(t *testing.T) {
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
true,
|
||||
"issue-1711",
|
||||
time.Now(),
|
||||
|
||||
@@ -88,7 +88,7 @@ func (o *ClaudeAuth) GenerateAuthURL(state string, pkceCodes *PKCECodes) (string
|
||||
"client_id": {ClientID},
|
||||
"response_type": {"code"},
|
||||
"redirect_uri": {RedirectURI},
|
||||
"scope": {"org:create_api_key user:profile user:inference"},
|
||||
"scope": {"user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload"},
|
||||
"code_challenge": {pkceCodes.CodeChallenge},
|
||||
"code_challenge_method": {"S256"},
|
||||
"state": {state},
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
)
|
||||
@@ -61,28 +58,13 @@ func (ts *ClaudeTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
misc.LogSavingCredentials(authFilePath)
|
||||
ts.Type = "claude"
|
||||
|
||||
// Create directory structure if it doesn't exist
|
||||
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
// Create the token file
|
||||
f, err := os.Create(authFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create token file: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
// Merge metadata using helper
|
||||
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
|
||||
if errMerge != nil {
|
||||
return fmt.Errorf("failed to merge metadata: %w", errMerge)
|
||||
}
|
||||
|
||||
// Encode and write the token data as JSON
|
||||
if err = json.NewEncoder(f).Encode(data); err != nil {
|
||||
if err := misc.WriteJSONFileSecure(authFilePath, data, false); err != nil {
|
||||
return fmt.Errorf("failed to write token to file: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -378,10 +378,18 @@ func TestToken_SaveTokenToFile(t *testing.T) {
|
||||
|
||||
if !tt.wantErr {
|
||||
// Verify file was created
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
info, err := os.Stat(filePath)
|
||||
if os.IsNotExist(err) {
|
||||
t.Error("Token file was not created")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Stat() error = %v", err)
|
||||
return
|
||||
}
|
||||
if got := info.Mode().Perm(); got != 0o600 {
|
||||
t.Errorf("file mode = %v, want %v", got, os.FileMode(0o600))
|
||||
}
|
||||
|
||||
// Verify file contents can be parsed back
|
||||
data, err := os.ReadFile(filePath)
|
||||
|
||||
@@ -4,12 +4,12 @@ package claude
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
tls "github.com/refraction-networking/utls"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/proxy"
|
||||
@@ -31,17 +31,12 @@ type utlsRoundTripper struct {
|
||||
// newUtlsRoundTripper creates a new utls-based round tripper with optional proxy support
|
||||
func newUtlsRoundTripper(cfg *config.SDKConfig) *utlsRoundTripper {
|
||||
var dialer proxy.Dialer = proxy.Direct
|
||||
if cfg != nil && cfg.ProxyURL != "" {
|
||||
proxyURL, err := url.Parse(cfg.ProxyURL)
|
||||
if err != nil {
|
||||
log.Errorf("failed to parse proxy URL %q: %v", cfg.ProxyURL, err)
|
||||
} else {
|
||||
pDialer, err := proxy.FromURL(proxyURL, proxy.Direct)
|
||||
if err != nil {
|
||||
log.Errorf("failed to create proxy dialer for %q: %v", cfg.ProxyURL, err)
|
||||
} else {
|
||||
dialer = pDialer
|
||||
}
|
||||
if cfg != nil {
|
||||
proxyDialer, mode, errBuild := proxyutil.BuildDialer(cfg.ProxyURL)
|
||||
if errBuild != nil {
|
||||
log.Errorf("failed to configure proxy dialer for %q: %v", cfg.ProxyURL, errBuild)
|
||||
} else if mode != proxyutil.ModeInherit && proxyDialer != nil {
|
||||
dialer = proxyDialer
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
)
|
||||
@@ -56,17 +53,6 @@ func (ts *CodexTokenStorage) SetMetadata(meta map[string]any) {
|
||||
func (ts *CodexTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
misc.LogSavingCredentials(authFilePath)
|
||||
ts.Type = "codex"
|
||||
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
f, err := os.Create(authFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create token file: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
// Merge metadata using helper
|
||||
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
|
||||
@@ -74,7 +60,7 @@ func (ts *CodexTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
return fmt.Errorf("failed to merge metadata: %w", errMerge)
|
||||
}
|
||||
|
||||
if err = json.NewEncoder(f).Encode(data); err != nil {
|
||||
if err := misc.WriteJSONFileSecure(authFilePath, data, false); err != nil {
|
||||
return fmt.Errorf("failed to write token to file: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -304,10 +304,18 @@ func TestCodexTokenStorage_SaveTokenToFile(t *testing.T) {
|
||||
|
||||
if !tt.wantErr {
|
||||
// Verify the file was created
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
info, err := os.Stat(filePath)
|
||||
if os.IsNotExist(err) {
|
||||
t.Errorf("SaveTokenToFile() file was not created at %s", filePath)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Stat() error = %v", err)
|
||||
return
|
||||
}
|
||||
if got := info.Mode().Perm(); got != 0o600 {
|
||||
t.Errorf("file mode = %v, want %v", got, os.FileMode(0o600))
|
||||
}
|
||||
|
||||
// Read and verify content
|
||||
data, err := os.ReadFile(filePath)
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
package copilot
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
)
|
||||
@@ -74,19 +71,7 @@ type DeviceCodeResponse struct {
|
||||
func (ts *CopilotTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
misc.LogSavingCredentials(authFilePath)
|
||||
ts.Type = "github-copilot"
|
||||
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
f, err := os.Create(authFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create token file: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
if err = json.NewEncoder(f).Encode(ts); err != nil {
|
||||
if err := misc.WriteJSONFileSecure(authFilePath, ts, false); err != nil {
|
||||
return fmt.Errorf("failed to write token to file: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -10,9 +10,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex"
|
||||
@@ -20,9 +18,9 @@ import (
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/proxyutil"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/net/proxy"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
@@ -80,36 +78,16 @@ func (g *GeminiAuth) GetAuthenticatedClient(ctx context.Context, ts *GeminiToken
|
||||
}
|
||||
callbackURL := fmt.Sprintf("http://localhost:%d/oauth2callback", callbackPort)
|
||||
|
||||
// Configure proxy settings for the HTTP client if a proxy URL is provided.
|
||||
proxyURL, err := url.Parse(cfg.ProxyURL)
|
||||
if err == nil {
|
||||
var transport *http.Transport
|
||||
if proxyURL.Scheme == "socks5" {
|
||||
// Handle SOCKS5 proxy.
|
||||
username := proxyURL.User.Username()
|
||||
password, _ := proxyURL.User.Password()
|
||||
auth := &proxy.Auth{User: username, Password: password}
|
||||
dialer, errSOCKS5 := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct)
|
||||
if errSOCKS5 != nil {
|
||||
log.Errorf("create SOCKS5 dialer failed: %v", errSOCKS5)
|
||||
return nil, fmt.Errorf("create SOCKS5 dialer failed: %w", errSOCKS5)
|
||||
}
|
||||
transport = &http.Transport{
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return dialer.Dial(network, addr)
|
||||
},
|
||||
}
|
||||
} else if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" {
|
||||
// Handle HTTP/HTTPS proxy.
|
||||
transport = &http.Transport{Proxy: http.ProxyURL(proxyURL)}
|
||||
}
|
||||
|
||||
if transport != nil {
|
||||
proxyClient := &http.Client{Transport: transport}
|
||||
ctx = context.WithValue(ctx, oauth2.HTTPClient, proxyClient)
|
||||
}
|
||||
transport, _, errBuild := proxyutil.BuildHTTPTransport(cfg.ProxyURL)
|
||||
if errBuild != nil {
|
||||
log.Errorf("%v", errBuild)
|
||||
} else if transport != nil {
|
||||
proxyClient := &http.Client{Transport: transport}
|
||||
ctx = context.WithValue(ctx, oauth2.HTTPClient, proxyClient)
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
// Configure the OAuth2 client.
|
||||
conf := &oauth2.Config{
|
||||
ClientID: ClientID,
|
||||
@@ -327,6 +305,9 @@ func (g *GeminiAuth) getTokenFromWeb(ctx context.Context, config *oauth2.Config,
|
||||
defer manualPromptTimer.Stop()
|
||||
}
|
||||
|
||||
var manualInputCh <-chan string
|
||||
var manualInputErrCh <-chan error
|
||||
|
||||
waitForCallback:
|
||||
for {
|
||||
select {
|
||||
@@ -348,13 +329,14 @@ waitForCallback:
|
||||
return nil, err
|
||||
default:
|
||||
}
|
||||
input, err := opts.Prompt("Paste the Gemini callback URL (or press Enter to keep waiting): ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parsed, err := misc.ParseOAuthCallback(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
manualInputCh, manualInputErrCh = misc.AsyncPrompt(opts.Prompt, "Paste the Gemini callback URL (or press Enter to keep waiting): ")
|
||||
continue
|
||||
case input := <-manualInputCh:
|
||||
manualInputCh = nil
|
||||
manualInputErrCh = nil
|
||||
parsed, errParse := misc.ParseOAuthCallback(input)
|
||||
if errParse != nil {
|
||||
return nil, errParse
|
||||
}
|
||||
if parsed == nil {
|
||||
continue
|
||||
@@ -367,6 +349,8 @@ waitForCallback:
|
||||
}
|
||||
authCode = parsed.Code
|
||||
break waitForCallback
|
||||
case errManual := <-manualInputErrCh:
|
||||
return nil, errManual
|
||||
case <-timeoutTimer.C:
|
||||
return nil, fmt.Errorf("oauth flow timed out")
|
||||
}
|
||||
|
||||
@@ -4,14 +4,10 @@
|
||||
package gemini
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// GeminiTokenStorage stores OAuth2 token information for Google Gemini API authentication.
|
||||
@@ -64,23 +60,7 @@ func (ts *GeminiTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
if errMerge != nil {
|
||||
return fmt.Errorf("failed to merge metadata: %w", errMerge)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
f, err := os.Create(authFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create token file: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if errClose := f.Close(); errClose != nil {
|
||||
log.Errorf("failed to close file: %v", errClose)
|
||||
}
|
||||
}()
|
||||
|
||||
enc := json.NewEncoder(f)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(data); err != nil {
|
||||
if err := misc.WriteJSONFileSecure(authFilePath, data, true); err != nil {
|
||||
return fmt.Errorf("failed to write token to file: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -86,9 +86,16 @@ func TestGeminiTokenStorage_SaveTokenToFile(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify file exists
|
||||
if _, err := os.Stat(authPath); os.IsNotExist(err) {
|
||||
info, err := os.Stat(authPath)
|
||||
if os.IsNotExist(err) {
|
||||
t.Fatal("token file was not created")
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Stat() error = %v", err)
|
||||
}
|
||||
if got := info.Mode().Perm(); got != 0o600 {
|
||||
t.Fatalf("file mode = %v, want %v", got, os.FileMode(0o600))
|
||||
}
|
||||
|
||||
// Verify type was set
|
||||
if ts.Type != "gemini" {
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package iflow
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
)
|
||||
@@ -36,15 +33,6 @@ func (ts *IFlowTokenStorage) SetMetadata(meta map[string]any) {
|
||||
func (ts *IFlowTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
misc.LogSavingCredentials(authFilePath)
|
||||
ts.Type = "iflow"
|
||||
if err := os.MkdirAll(filepath.Dir(authFilePath), 0o700); err != nil {
|
||||
return fmt.Errorf("iflow token: create directory failed: %w", err)
|
||||
}
|
||||
|
||||
f, err := os.Create(authFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("iflow token: create file failed: %w", err)
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
|
||||
// Merge metadata using helper
|
||||
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
|
||||
@@ -52,7 +40,7 @@ func (ts *IFlowTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
return fmt.Errorf("failed to merge metadata: %w", errMerge)
|
||||
}
|
||||
|
||||
if err = json.NewEncoder(f).Encode(data); err != nil {
|
||||
if err := misc.WriteJSONFileSecure(authFilePath, data, false); err != nil {
|
||||
return fmt.Errorf("iflow token: encode token failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
package kimi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
@@ -83,27 +80,13 @@ func (ts *KimiTokenStorage) SaveTokenToFile(authFilePath string) error {
|
||||
misc.LogSavingCredentials(authFilePath)
|
||||
ts.Type = "kimi"
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(authFilePath), 0700); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
f, err := os.Create(authFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create token file: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
// Merge metadata using helper
|
||||
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)
|
||||
if errMerge != nil {
|
||||
return fmt.Errorf("failed to merge metadata: %w", errMerge)
|
||||
}
|
||||
|
||||
encoder := json.NewEncoder(f)
|
||||
encoder.SetIndent("", " ")
|
||||
if err = encoder.Encode(data); err != nil {
|
||||
if err := misc.WriteJSONFileSecure(authFilePath, data, true); err != nil {
|
||||
return fmt.Errorf("failed to write token to file: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -433,8 +433,7 @@ func GenerateTokenFileName(tokenData *KiroTokenData) string {
|
||||
|
||||
// Priority 1: Use email if available
|
||||
if tokenData.Email != "" {
|
||||
// Sanitize email for filename (replace @ and . with -)
|
||||
sanitizedEmail := tokenData.Email
|
||||
sanitizedEmail := SanitizeEmailForFilename(tokenData.Email)
|
||||
sanitizedEmail = strings.ReplaceAll(sanitizedEmail, "@", "-")
|
||||
sanitizedEmail = strings.ReplaceAll(sanitizedEmail, ".", "-")
|
||||
return fmt.Sprintf("kiro-%s-%s.json", authMethod, sanitizedEmail)
|
||||
|
||||
@@ -194,7 +194,9 @@ func (r *BackgroundRefresher) refreshSingle(ctx context.Context, token *Token) {
|
||||
}
|
||||
|
||||
token.AccessToken = newTokenData.AccessToken
|
||||
token.RefreshToken = newTokenData.RefreshToken
|
||||
if newRefreshToken := strings.TrimSpace(newTokenData.RefreshToken); newRefreshToken != "" {
|
||||
token.RefreshToken = newRefreshToken
|
||||
}
|
||||
token.LastVerified = time.Now()
|
||||
|
||||
if newTokenData.ExpiresAt != "" {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
@@ -105,6 +106,12 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
|
||||
// Use http scheme for local callback server
|
||||
redirectURI := fmt.Sprintf("http://localhost:%d/oauth/callback", port)
|
||||
resultChan := make(chan AuthResult, 1)
|
||||
callbackReceived := make(chan struct{})
|
||||
var callbackOnce sync.Once
|
||||
sendResult := func(result AuthResult) {
|
||||
resultChan <- result
|
||||
callbackOnce.Do(func() { close(callbackReceived) })
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
@@ -120,7 +127,7 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprintf(w, `<html><body><h1>Login Failed</h1><p>%s</p><p>You can close this window.</p></body></html>`, html.EscapeString(errParam))
|
||||
resultChan <- AuthResult{Error: errParam}
|
||||
sendResult(AuthResult{Error: errParam})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -128,13 +135,13 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, `<html><body><h1>Login Failed</h1><p>Invalid state parameter</p><p>You can close this window.</p></body></html>`)
|
||||
resultChan <- AuthResult{Error: "state mismatch"}
|
||||
sendResult(AuthResult{Error: "state mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
fmt.Fprint(w, `<html><body><h1>Login Successful!</h1><p>You can close this window and return to the terminal.</p></body></html>`)
|
||||
resultChan <- AuthResult{Code: code, State: state}
|
||||
sendResult(AuthResult{Code: code, State: state})
|
||||
})
|
||||
|
||||
server.Handler = mux
|
||||
@@ -149,7 +156,7 @@ func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState strin
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(authTimeout):
|
||||
case <-resultChan:
|
||||
case <-callbackReceived:
|
||||
}
|
||||
_ = server.Shutdown(context.Background())
|
||||
}()
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/browser"
|
||||
@@ -117,6 +118,12 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
|
||||
// Use http scheme for local callback server
|
||||
redirectURI := fmt.Sprintf("http://localhost:%d/oauth/callback", port)
|
||||
resultChan := make(chan WebCallbackResult, 1)
|
||||
callbackReceived := make(chan struct{})
|
||||
var callbackOnce sync.Once
|
||||
sendResult := func(result WebCallbackResult) {
|
||||
resultChan <- result
|
||||
callbackOnce.Do(func() { close(callbackReceived) })
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
@@ -134,7 +141,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
|
||||
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||
<html><head><title>Login Failed</title></head>
|
||||
<body><h1>Login Failed</h1><p>%s</p><p>You can close this window.</p></body></html>`, html.EscapeString(errParam))
|
||||
resultChan <- WebCallbackResult{Error: errParam}
|
||||
sendResult(WebCallbackResult{Error: errParam})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -144,7 +151,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
|
||||
fmt.Fprint(w, `<!DOCTYPE html>
|
||||
<html><head><title>Login Failed</title></head>
|
||||
<body><h1>Login Failed</h1><p>Invalid state parameter</p><p>You can close this window.</p></body></html>`)
|
||||
resultChan <- WebCallbackResult{Error: "state mismatch"}
|
||||
sendResult(WebCallbackResult{Error: "state mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -153,7 +160,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
|
||||
<html><head><title>Login Successful</title></head>
|
||||
<body><h1>Login Successful!</h1><p>You can close this window and return to the terminal.</p>
|
||||
<script>window.close();</script></body></html>`)
|
||||
resultChan <- WebCallbackResult{Code: code, State: state}
|
||||
sendResult(WebCallbackResult{Code: code, State: state})
|
||||
})
|
||||
|
||||
server.Handler = mux
|
||||
@@ -168,7 +175,7 @@ func (c *SocialAuthClient) startWebCallbackServer(ctx context.Context, expectedS
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(socialAuthTimeout):
|
||||
case <-resultChan:
|
||||
case <-callbackReceived:
|
||||
}
|
||||
_ = server.Shutdown(context.Background())
|
||||
}()
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/browser"
|
||||
@@ -1116,6 +1117,12 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
redirectURI := fmt.Sprintf("http://127.0.0.1:%d%s", port, authCodeCallbackPath)
|
||||
resultChan := make(chan AuthCodeCallbackResult, 1)
|
||||
callbackReceived := make(chan struct{})
|
||||
var callbackOnce sync.Once
|
||||
sendResult := func(result AuthCodeCallbackResult) {
|
||||
resultChan <- result
|
||||
callbackOnce.Do(func() { close(callbackReceived) })
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
@@ -1134,7 +1141,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
|
||||
fmt.Fprintf(w, `<!DOCTYPE html>
|
||||
<html><head><title>Login Failed</title></head>
|
||||
<body><h1>Login Failed</h1><p>Error: %s</p><p>You can close this window.</p></body></html>`, html.EscapeString(errParam))
|
||||
resultChan <- AuthCodeCallbackResult{Error: errParam}
|
||||
sendResult(AuthCodeCallbackResult{Error: errParam})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1143,7 +1150,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
|
||||
fmt.Fprint(w, `<!DOCTYPE html>
|
||||
<html><head><title>Login Failed</title></head>
|
||||
<body><h1>Login Failed</h1><p>Invalid state parameter</p><p>You can close this window.</p></body></html>`)
|
||||
resultChan <- AuthCodeCallbackResult{Error: "state mismatch"}
|
||||
sendResult(AuthCodeCallbackResult{Error: "state mismatch"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1151,7 +1158,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
|
||||
<html><head><title>Login Successful</title></head>
|
||||
<body><h1>Login Successful!</h1><p>You can close this window and return to the terminal.</p>
|
||||
<script>window.close();</script></body></html>`)
|
||||
resultChan <- AuthCodeCallbackResult{Code: code, State: state}
|
||||
sendResult(AuthCodeCallbackResult{Code: code, State: state})
|
||||
})
|
||||
|
||||
server.Handler = mux
|
||||
@@ -1166,7 +1173,7 @@ func (c *SSOOIDCClient) startAuthCodeCallbackServer(ctx context.Context, expecte
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(10 * time.Minute):
|
||||
case <-resultChan:
|
||||
case <-callbackReceived:
|
||||
}
|
||||
_ = server.Shutdown(context.Background())
|
||||
}()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user