mirror of
https://github.com/Finesssee/ProxyPilot.git
synced 2026-11-20 20:34:36 +00:00
Compare commits
424
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5058240026 | ||
|
|
44b6e577ec | ||
|
|
d846b2a56f | ||
|
|
cc9d1baf51 | ||
|
|
313d86d7d5 | ||
|
|
76e32b6032 | ||
|
|
f62e779d86 | ||
|
|
25b7aa62e3 | ||
|
|
a1ce124748 | ||
|
|
cedb38d1cf | ||
|
|
c36e214e2e | ||
|
|
c26de75913 | ||
|
|
bd3901ca29 | ||
|
|
3636be31d6 | ||
|
|
1fca942b9c | ||
|
|
18d9369ce4 | ||
|
|
5e5b1bce35 | ||
|
|
15ac7fb932 | ||
|
|
8300ee8bbe | ||
|
|
dc1cc7f115 | ||
|
|
a44e5eb1ab | ||
|
|
67fb4eb98e | ||
|
|
66c3dae06b | ||
|
|
1abf8625d8 | ||
|
|
3cbd587b2c | ||
|
|
41f4ee7c7d | ||
|
|
c69ff49758 | ||
|
|
68fddaa319 | ||
|
|
09ac8a1165 | ||
|
|
0dcb8bd714 | ||
|
|
0f0fcd2304 | ||
|
|
c67096b687 | ||
|
|
1721994111 | ||
|
|
4cbe172934 | ||
|
|
4071fdef84 | ||
|
|
c883114a4d | ||
|
|
e50cabac4b | ||
|
|
785b00c312 | ||
|
|
a034cf8b8d | ||
|
|
01171742a6 | ||
|
|
fb08b92402 | ||
|
|
a09a16e8f6 | ||
|
|
68b97075af | ||
|
|
ad3f4f2ce5 | ||
|
|
17a1f53c47 | ||
|
|
ed1458aa6d | ||
|
|
99dfbaef61 | ||
|
|
da6c599efd | ||
|
|
61b39d49bd | ||
|
|
ba5d8ca733 | ||
|
|
28b4b19e7e | ||
|
|
bdc424007e | ||
|
|
e4a93c02c5 | ||
|
|
8262a03f29 | ||
|
|
ecf1c2590c | ||
|
|
162897e02a | ||
|
|
c1caa454b3 | ||
|
|
bf6fa402e2 | ||
|
|
85c0150653 | ||
|
|
89d80bfff4 | ||
|
|
a1eba112f3 | ||
|
|
6b4bc0a9a8 | ||
|
|
08b0fe6816 | ||
|
|
c19ae1d5be | ||
|
|
17be6442a8 | ||
|
|
38dad2afdf | ||
|
|
8e6ef3fa64 | ||
|
|
a1487b0958 | ||
|
|
82ebe24b9e | ||
|
|
2753d9fb71 | ||
|
|
bf0e5c23f7 | ||
|
|
672fdd14ed | ||
|
|
af65908cb0 | ||
|
|
756b600b7a | ||
|
|
054d0dee1d | ||
|
|
d2386a3114 | ||
|
|
7972130513 | ||
|
|
81db7fdc1e | ||
|
|
5fc6f662e1 | ||
|
|
593995a404 | ||
|
|
101b59cfe8 | ||
|
|
56df36895a | ||
|
|
85124f098b | ||
|
|
2efa56dbb8 | ||
|
|
79579c34bf | ||
|
|
18bb9c315f | ||
|
|
b8bba053fc | ||
|
|
8c2f1a80d3 | ||
|
|
e37f3be0bf | ||
|
|
b0dc9df887 | ||
|
|
6187919000 | ||
|
|
4035abc0cd | ||
|
|
101099ca3a | ||
|
|
8b286e8fb3 | ||
|
|
aa70d13f60 | ||
|
|
05ecfb6241 | ||
|
|
243c582159 | ||
|
|
6ba7c810a7 | ||
|
|
f56a19e5b8 | ||
|
|
46018417ad | ||
|
|
dbf432c3e7 | ||
|
|
e3e60f914b | ||
|
|
270e273254 | ||
|
|
359ec30d0c | ||
|
|
a1f0ed9575 | ||
|
|
b3b92f334e | ||
|
|
2c1539ead7 | ||
|
|
0d107dd566 | ||
|
|
1c0c426b85 | ||
|
|
4982512da2 | ||
|
|
2ea8f77efb | ||
|
|
f95ab4cdf1 | ||
|
|
c4965befe7 | ||
|
|
0e1235122e | ||
|
|
e78d45acc9 | ||
|
|
b34f3be13e | ||
|
|
9fb6a49260 | ||
|
|
a992dee4e8 | ||
|
|
3ac39dcc7d | ||
|
|
34027da7f1 | ||
|
|
c523101439 | ||
|
|
d85e13b044 | ||
|
|
01e16a8509 | ||
|
|
04a336f7df | ||
|
|
a325533f20 | ||
|
|
6fc23568df | ||
|
|
736ae61e4a | ||
|
|
c5bea6f6f8 | ||
|
|
c7b28ba058 | ||
|
|
38573050aa | ||
|
|
153d8c160f | ||
|
|
32ef1588e8 | ||
|
|
80eb03709a | ||
|
|
d36e70e9dc | ||
|
|
fd45dece7f | ||
|
|
95318ad46d | ||
|
|
fc1ddf365f | ||
|
|
03ea4e569f | ||
|
|
e707cf7d46 | ||
|
|
0a7c6b0a4a | ||
|
|
ea670ef8c0 | ||
|
|
2c626efc59 | ||
|
|
28d78273e4 | ||
|
|
be0fe6fab3 | ||
|
|
cf043f6c07 | ||
|
|
faad8e30dd | ||
|
|
a7e92e2639 | ||
|
|
4056c2590b | ||
|
|
36cc762fc9 | ||
|
|
5f5d5936fa | ||
|
|
35a58873b0 | ||
|
|
f1ba6151a9 | ||
|
|
7b89583cf8 | ||
|
|
1576d14137 | ||
|
|
736018a0b0 | ||
|
|
7d5f6d9382 | ||
|
|
12195a276e | ||
|
|
25137b1984 | ||
|
|
7ad1900041 | ||
|
|
8eb56e5602 | ||
|
|
f130846ec1 | ||
|
|
920b6efffa | ||
|
|
e75daa299b | ||
|
|
8e49c795f5 | ||
|
|
4de5c29f86 | ||
|
|
4d6457e6ec | ||
|
|
14d46a0a5d | ||
|
|
31934ae04c | ||
|
|
a188159632 | ||
|
|
fd71960c3e | ||
|
|
e935196df4 | ||
|
|
4fc2c619fb | ||
|
|
8ced7a548f | ||
|
|
3444820958 | ||
|
|
1716a845eb | ||
|
|
b6781d69be | ||
|
|
bb8408cef5 | ||
|
|
e6866ff19c | ||
|
|
2ebbb59670 | ||
|
|
8f4a4eabfc | ||
|
|
e05abec01f | ||
|
|
f4eb16102b | ||
|
|
86c856f56f | ||
|
|
2221b8e557 | ||
|
|
c6baa64b4e | ||
|
|
a64141a9a6 | ||
|
|
c26936e2e6 | ||
|
|
894baad829 | ||
|
|
eba561bf6f | ||
|
|
da43f63735 | ||
|
|
d9a3b3e5f3 | ||
|
|
7ec328f952 | ||
|
|
5dcca69e8c | ||
|
|
f5dc6483d5 | ||
|
|
d949921143 | ||
|
|
7b03f04670 | ||
|
|
8f9e6622b0 | ||
|
|
71be5e897b | ||
|
|
1267fddf61 | ||
|
|
ba454dbfbf | ||
|
|
d1508ca030 | ||
|
|
d4a6a5ae15 | ||
|
|
7c24d54ca8 | ||
|
|
a4c1e32ff6 | ||
|
|
f56cf42461 | ||
|
|
3dea1da249 | ||
|
|
8fac29631d | ||
|
|
8fecd625d2 | ||
|
|
10b55b5ddd | ||
|
|
41ae2c81e7 | ||
|
|
278a89824c | ||
|
|
06c3e95454 | ||
|
|
a6cc1a2e71 | ||
|
|
c4459c4346 | ||
|
|
61e0447f92 | ||
|
|
1dc3018fd6 | ||
|
|
26fd3eff03 | ||
|
|
5bfaf8086b | ||
|
|
6c0a1efd71 | ||
|
|
f5ed5c7453 | ||
|
|
65158cce46 | ||
|
|
9cc006c941 | ||
|
|
a583463d60 | ||
|
|
8ed290c1c4 | ||
|
|
727221df2e | ||
|
|
0ab1f5412f | ||
|
|
9ded75d335 | ||
|
|
f135fdf7fc | ||
|
|
828df80088 | ||
|
|
c585caa0ce | ||
|
|
5bb69fa4ab | ||
|
|
85267e7379 | ||
|
|
45dc09d487 | ||
|
|
5ab9afac83 | ||
|
|
65ce86338b | ||
|
|
2a97037d7b | ||
|
|
d801393841 | ||
|
|
b2c0cdfc88 | ||
|
|
f32c8c9620 | ||
|
|
0f45d89255 | ||
|
|
96056d0137 | ||
|
|
f780c289e8 | ||
|
|
ac36119a02 | ||
|
|
39dc4557c1 | ||
|
|
30e94b6792 | ||
|
|
38f0ae5970 | ||
|
|
cf249586a9 | ||
|
|
1dba2d0f81 | ||
|
|
730809d8ea | ||
|
|
e8d1b79cb3 | ||
|
|
5e81b65f2f | ||
|
|
5775476bc0 | ||
|
|
7e8e2226a6 | ||
|
|
f0c20e852f | ||
|
|
7cdf8e9872 | ||
|
|
e2e3c7dde0 | ||
|
|
9e0ab4d116 | ||
|
|
8783caf313 | ||
|
|
f6f4640c5e | ||
|
|
613fe6768d | ||
|
|
ad8e3964ff | ||
|
|
941334da79 | ||
|
|
d54f816363 | ||
|
|
69b950db4c | ||
|
|
343a2fc2f7 | ||
|
|
12b967118b | ||
|
|
70efd4e016 | ||
|
|
f5aa68ecda | ||
|
|
d390b95b76 | ||
|
|
d1f6224b70 | ||
|
|
fcc59d606d | ||
|
|
91e7591955 | ||
|
|
c8b7e2b8d6 | ||
|
|
4ca00f7983 | ||
|
|
d2d0e6f6a1 | ||
|
|
a0fe273081 | ||
|
|
cad45ffa33 | ||
|
|
6a27bceec0 | ||
|
|
163d68318f | ||
|
|
0ea768011b | ||
|
|
8b9dbe10f0 | ||
|
|
29e32aaab9 | ||
|
|
6431cec7d3 | ||
|
|
9f5bdfaa31 | ||
|
|
9eabdd09db | ||
|
|
c3f8dc362e | ||
|
|
b85120873b | ||
|
|
6f58518c69 | ||
|
|
000fcb15fa | ||
|
|
ea43361492 | ||
|
|
c1818f197b | ||
|
|
b0653cec7b | ||
|
|
22a1a24cf5 | ||
|
|
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 | ||
|
|
91387ca247 | ||
|
|
486cd4c343 | ||
|
|
25feceb783 | ||
|
|
d26752250d | ||
|
|
b15453c369 | ||
|
|
04ba8c8bc3 | ||
|
|
fccfb162b4 | ||
|
|
6570692291 | ||
|
|
f73d55ddaa | ||
|
|
13aa5b3375 | ||
|
|
0fcc02fbea | ||
|
|
c03883ccf0 | ||
|
|
134a9eac9d | ||
|
|
6d8de0ade4 | ||
|
|
1587ff5e74 | ||
|
|
f033d3a6df | ||
|
|
145e0e0b5d | ||
|
|
5fc2bd393e | ||
|
|
66eb12294a | ||
|
|
73b22ec29b | ||
|
|
c31ae2f3b5 | ||
|
|
76b53d6b5b | ||
|
|
a34dfed378 | ||
|
|
36efcc6e28 | ||
|
|
a337ecf35c | ||
|
|
e08f68ed7c | ||
|
|
f09ed25fd3 | ||
|
|
e166e56249 | ||
|
|
5f58248016 | ||
|
|
07d6689d87 | ||
|
|
14cb2b95c6 | ||
|
|
fdeef48498 |
@@ -0,0 +1,81 @@
|
||||
name: agents-md-guard
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
close-when-agents-md-changed:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Detect AGENTS.md changes and close PR
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const prNumber = context.payload.pull_request.number;
|
||||
const { owner, repo } = context.repo;
|
||||
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, {
|
||||
owner,
|
||||
repo,
|
||||
pull_number: prNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const touchesAgentsMd = (path) =>
|
||||
typeof path === "string" &&
|
||||
(path === "AGENTS.md" || path.endsWith("/AGENTS.md"));
|
||||
|
||||
const touched = files.filter(
|
||||
(f) => touchesAgentsMd(f.filename) || touchesAgentsMd(f.previous_filename),
|
||||
);
|
||||
|
||||
if (touched.length === 0) {
|
||||
core.info("No AGENTS.md changes detected.");
|
||||
return;
|
||||
}
|
||||
|
||||
const changedList = touched
|
||||
.map((f) =>
|
||||
f.previous_filename && f.previous_filename !== f.filename
|
||||
? `- ${f.previous_filename} -> ${f.filename}`
|
||||
: `- ${f.filename}`,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
const body = [
|
||||
"This repository does not allow modifying `AGENTS.md` in pull requests.",
|
||||
"",
|
||||
"Detected changes:",
|
||||
changedList,
|
||||
"",
|
||||
"Please revert these changes and open a new PR without touching `AGENTS.md`.",
|
||||
].join("\n");
|
||||
|
||||
try {
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
body,
|
||||
});
|
||||
} catch (error) {
|
||||
core.warning(`Failed to comment on PR #${prNumber}: ${error.message}`);
|
||||
}
|
||||
|
||||
await github.rest.pulls.update({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: prNumber,
|
||||
state: "closed",
|
||||
});
|
||||
|
||||
core.setFailed("PR modifies AGENTS.md");
|
||||
@@ -0,0 +1,73 @@
|
||||
name: auto-retarget-main-pr-to-dev
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- edited
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
retarget:
|
||||
if: github.actor != 'github-actions[bot]'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Retarget PR base to dev
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
const prNumber = pr.number;
|
||||
const { owner, repo } = context.repo;
|
||||
|
||||
const baseRef = pr.base?.ref;
|
||||
const headRef = pr.head?.ref;
|
||||
const desiredBase = "dev";
|
||||
|
||||
if (baseRef !== "main") {
|
||||
core.info(`PR #${prNumber} base is ${baseRef}; nothing to do.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (headRef === desiredBase) {
|
||||
core.info(`PR #${prNumber} is ${desiredBase} -> main; skipping retarget.`);
|
||||
return;
|
||||
}
|
||||
|
||||
core.info(`Retargeting PR #${prNumber} base from ${baseRef} to ${desiredBase}.`);
|
||||
|
||||
try {
|
||||
await github.rest.pulls.update({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: prNumber,
|
||||
base: desiredBase,
|
||||
});
|
||||
} catch (error) {
|
||||
core.setFailed(`Failed to retarget PR #${prNumber} to ${desiredBase}: ${error.message}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const body = [
|
||||
`This pull request targeted \`${baseRef}\`.`,
|
||||
"",
|
||||
`The base branch has been automatically changed to \`${desiredBase}\`.`,
|
||||
].join("\n");
|
||||
|
||||
try {
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number: prNumber,
|
||||
body,
|
||||
});
|
||||
} catch (error) {
|
||||
core.warning(`Failed to comment on PR #${prNumber}: ${error.message}`);
|
||||
}
|
||||
@@ -22,7 +22,6 @@ jobs:
|
||||
- uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '>=1.26.0'
|
||||
cache: true
|
||||
- name: Generate Build Metadata
|
||||
run: |
|
||||
VERSION=$(git describe --tags --always --dirty)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
name: rust-replatform
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "rust/**"
|
||||
- "docs/rust-replatform.md"
|
||||
- ".github/workflows/rust-replatform.yml"
|
||||
push:
|
||||
branches:
|
||||
- rust-replatform-v2
|
||||
paths:
|
||||
- "rust/**"
|
||||
- "docs/rust-replatform.md"
|
||||
- ".github/workflows/rust-replatform.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Test
|
||||
working-directory: rust
|
||||
run: cargo test -p proxypilot-rs
|
||||
+11
-2
@@ -1,6 +1,6 @@
|
||||
# Binaries
|
||||
cli-proxy-api
|
||||
cliproxy
|
||||
/cli-proxy-api
|
||||
/cliproxy
|
||||
proxypilot-linux
|
||||
proxypilot-darwin
|
||||
proxypilot-windows
|
||||
@@ -55,6 +55,7 @@ GEMINI.md
|
||||
|
||||
# Tooling metadata
|
||||
.vscode/*
|
||||
.worktrees/
|
||||
.codex/*
|
||||
.claude/*
|
||||
.gemini/*
|
||||
@@ -63,6 +64,7 @@ GEMINI.md
|
||||
.agents/*
|
||||
.opencode/*
|
||||
.idea/*
|
||||
.beads/*
|
||||
.bmad/*
|
||||
_bmad/*
|
||||
_bmad-output/*
|
||||
@@ -83,6 +85,7 @@ tui-ttyd.png
|
||||
# macOS
|
||||
.DS_Store
|
||||
._*
|
||||
.gocache/
|
||||
|
||||
# Windows artifacts
|
||||
nul
|
||||
@@ -118,3 +121,9 @@ config-debug.yaml
|
||||
test_results.txt
|
||||
test_results_full.txt
|
||||
tmpclaude-*
|
||||
|
||||
# Opencode
|
||||
.beads/
|
||||
.opencode/
|
||||
.cli-proxy-api/
|
||||
.venv/
|
||||
|
||||
@@ -27,6 +27,8 @@ builds:
|
||||
archives:
|
||||
- id: "cli-proxy-api-plus"
|
||||
format: tar.gz
|
||||
name_template: >-
|
||||
{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{- if eq .Arch "arm64" -}}aarch64{{- else -}}{{ .Arch }}{{- end -}}
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
15ac7fb9324095330e60f522147b8a8e81f16ab5
|
||||
@@ -0,0 +1 @@
|
||||
v7.0.2
|
||||
@@ -0,0 +1,58 @@
|
||||
# AGENTS.md
|
||||
|
||||
Go 1.26+ proxy server providing OpenAI/Gemini/Claude/Codex compatible APIs with OAuth and round-robin load balancing.
|
||||
|
||||
## Repository
|
||||
- GitHub: https://github.com/router-for-me/CLIProxyAPI
|
||||
|
||||
## Commands
|
||||
```bash
|
||||
gofmt -w . # Format (required after Go changes)
|
||||
go build -o cli-proxy-api ./cmd/server # Build
|
||||
go run ./cmd/server # Run dev server
|
||||
go test ./... # Run all tests
|
||||
go test -v -run TestName ./path/to/pkg # Run single test
|
||||
go build -o test-output ./cmd/server && rm test-output # Verify compile (REQUIRED after changes)
|
||||
```
|
||||
- Common flags: `--config <path>`, `--tui`, `--standalone`, `--local-model`, `--no-browser`, `--oauth-callback-port <port>`
|
||||
|
||||
## Config
|
||||
- Default config: `config.yaml` (template: `config.example.yaml`)
|
||||
- `.env` is auto-loaded from the working directory
|
||||
- Auth material defaults under `auths/`
|
||||
- Storage backends: file-based default; optional Postgres/git/object store (`PGSTORE_*`, `GITSTORE_*`, `OBJECTSTORE_*`)
|
||||
|
||||
## Architecture
|
||||
- `cmd/server/` — Server entrypoint
|
||||
- `internal/api/` — Gin HTTP API (routes, middleware, modules)
|
||||
- `internal/api/modules/amp/` — Amp integration (Amp-style routes + reverse proxy)
|
||||
- `internal/thinking/` — Main thinking/reasoning pipeline. `ApplyThinking()` (apply.go) parses suffixes (`suffix.go`, suffix overrides body), normalizes config to canonical `ThinkingConfig` (`types.go`), normalizes and validates centrally (`validate.go`/`convert.go`), then applies provider-specific output via `ProviderApplier`. Do not break this "canonical representation → per-provider translation" architecture.
|
||||
- `internal/runtime/executor/` — Per-provider runtime executors (incl. Codex WebSocket)
|
||||
- `internal/translator/` — Provider protocol translators (and shared `common`)
|
||||
- `internal/registry/` — Model registry + remote updater (`StartModelsUpdater`); `--local-model` disables remote updates
|
||||
- `internal/store/` — Storage implementations and secret resolution
|
||||
- `internal/managementasset/` — Config snapshots and management assets
|
||||
- `internal/cache/` — Request signature caching
|
||||
- `internal/watcher/` — Config hot-reload and watchers
|
||||
- `internal/wsrelay/` — WebSocket relay sessions
|
||||
- `internal/usage/` — Usage and token accounting
|
||||
- `internal/tui/` — Bubbletea terminal UI (`--tui`, `--standalone`)
|
||||
- `sdk/cliproxy/` — Embeddable SDK entry (service/builder/watchers/pipeline)
|
||||
- `test/` — Cross-module integration tests
|
||||
|
||||
## Code Conventions
|
||||
- Keep changes small and simple (KISS)
|
||||
- Comments in English only
|
||||
- If editing code that already contains non-English comments, translate them to English (don’t add new non-English comments)
|
||||
- For user-visible strings, keep the existing language used in that file/area
|
||||
- New Markdown docs should be in English unless the file is explicitly language-specific (e.g. `README_CN.md`)
|
||||
- As a rule, do not make standalone changes to `internal/translator/`. You may modify it only as part of broader changes elsewhere.
|
||||
- If a task requires changing only `internal/translator/`, run `gh repo view --json viewerPermission -q .viewerPermission` to confirm you have `WRITE`, `MAINTAIN`, or `ADMIN`. If you do, you may proceed; otherwise, file a GitHub issue including the goal, rationale, and the intended implementation code, then stop further work.
|
||||
- `internal/runtime/executor/` should contain executors and their unit tests only. Place any helper/supporting files under `internal/runtime/executor/helps/`.
|
||||
- Follow `gofmt`; keep imports goimports-style; wrap errors with context where helpful
|
||||
- Do not use `log.Fatal`/`log.Fatalf` (terminates the process); prefer returning errors and logging via logrus
|
||||
- Shadowed variables: use method suffix (`errStart := server.Start()`)
|
||||
- Wrap defer errors: `defer func() { if err := f.Close(); err != nil { log.Errorf(...) } }()`
|
||||
- Use logrus structured logging; avoid leaking secrets/tokens in logs
|
||||
- Avoid panics in HTTP handlers; prefer logged errors and meaningful HTTP status codes
|
||||
- Timeouts are allowed only during credential acquisition; after an upstream connection is established, do not set timeouts for any subsequent network behavior. Intentional exceptions that must remain allowed are the Codex websocket liveness deadlines in `internal/runtime/executor/codex_websockets_executor.go`, the wsrelay session deadlines in `internal/wsrelay/session.go`, the management APICall timeout in `internal/api/handlers/management/api_tools.go`, and the `cmd/fetch_antigravity_models` utility timeouts
|
||||
+2
-2
@@ -14,13 +14,13 @@ ARG BUILD_DATE=unknown
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w -X 'main.Version=${VERSION}-plus' -X 'main.Commit=${COMMIT}' -X 'main.BuildDate=${BUILD_DATE}'" -o ./CLIProxyAPIPlus ./cmd/server/
|
||||
|
||||
FROM alpine:3.22.0
|
||||
FROM alpine:3.23
|
||||
|
||||
RUN apk add --no-cache tzdata
|
||||
|
||||
RUN mkdir /ProxyPilot
|
||||
|
||||
COPY --from=builder ./app/CLIProxyAPIPlus /CLIProxyAPI/CLIProxyAPIPlus
|
||||
COPY --from=builder ./app/CLIProxyAPIPlus /ProxyPilot/CLIProxyAPIPlus
|
||||
|
||||
COPY config.example.yaml /ProxyPilot/config.example.yaml
|
||||
|
||||
|
||||
@@ -67,6 +67,8 @@
|
||||
| Zhipu AI | API Key | GLM-4.5, GLM-4.6, GLM-4.7 |
|
||||
| Custom | API Key | Any OpenAI-compatible endpoint |
|
||||
|
||||
> **Account risk warning:** Claude/Anthropic OAuth, Google/Gemini OAuth, Gemini CLI OAuth, and Antigravity OAuth are unofficial compatibility paths. Providers may treat proxy, automation, shared-token, or third-party OAuth traffic as a policy violation or abnormal usage. Using these login flows can risk quota loss, account restriction, or account suspension. Prefer official API-key or officially supported developer access for important accounts.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
@@ -92,10 +94,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
|
||||
|
||||
@@ -106,8 +109,8 @@ Run OAuth login for your provider:
|
||||
./proxypilot --claude-login # Claude
|
||||
./proxypilot --codex-login # OpenAI/Codex
|
||||
./proxypilot --login # Gemini
|
||||
./proxypilot --kiro-login # Kiro (Google OAuth)
|
||||
./proxypilot --kiro-aws-login # Kiro (AWS Builder ID)
|
||||
./proxypilot --kiro-login # Kiro (AWS Builder ID)
|
||||
./proxypilot --kiro-aws-login # Kiro (AWS Builder ID device code)
|
||||
./proxypilot --qwen-login # Qwen
|
||||
./proxypilot --antigravity-login # Antigravity
|
||||
|
||||
@@ -121,6 +124,10 @@ Run OAuth login for your provider:
|
||||
|
||||
OAuth tokens are stored locally and auto-refreshed before expiry.
|
||||
|
||||
**High-risk OAuth providers:** `--claude-login`, `--login` / Gemini, Gemini CLI OAuth, and `--antigravity-login` may violate provider expectations or trigger anti-abuse/account-protection systems. Do not use production, billing-critical, school/work, or irreplaceable personal accounts with these flows unless you accept the account-risk tradeoff. Prefer official API keys where available.
|
||||
|
||||
Kiro Google/GitHub OAuth is not currently supported because AWS Cognito rejects third-party localhost callbacks. Use AWS Builder ID (`--kiro-login` / `--kiro-aws-login`) or import from the official Kiro IDE.
|
||||
|
||||
### Security Defaults (Auth + CORS)
|
||||
|
||||
- Proxy requests require API keys by default. To allow unauthenticated access (not recommended), set `allow-unauthenticated: true` in `config.yaml`.
|
||||
@@ -250,6 +257,15 @@ prompt-cache:
|
||||
|
||||
---
|
||||
|
||||
## Ecosystem
|
||||
|
||||
### [CPA Usage Keeper](https://github.com/Willxup/cpa-usage-keeper)
|
||||
|
||||
Standalone persistence and visualization service for CLIProxyAPI, with periodic data sync, SQLite storage, aggregate APIs, and a built-in dashboard for usage and statistics.
|
||||
|
||||
> [!NOTE]
|
||||
> If you developed a project based on CLIProxyAPI, please open a PR to add it to this list.
|
||||
|
||||
## Auto-Updates
|
||||
|
||||
ProxyPilot includes a built-in auto-update system that checks for new releases and allows one-click installation.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
v6.9.5
|
||||
v7.0.2
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 170 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 401 KiB |
@@ -25,10 +25,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
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"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
|
||||
sdkauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
@@ -188,7 +189,7 @@ func fetchModels(ctx context.Context, auth *coreauth.Auth) []modelEntry {
|
||||
httpReq.Close = true
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
httpReq.Header.Set("User-Agent", "antigravity/1.19.6 darwin/arm64")
|
||||
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 {
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/desktopctl"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
|
||||
@@ -22,20 +22,20 @@ import (
|
||||
|
||||
"github.com/getlantern/systray"
|
||||
"github.com/jchv/go-webview2"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/cmd"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/integrations"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/trayicon"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/updates"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/winutil"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/cmd"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/desktopctl"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/integrations"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v7/internal/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/trayicon"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/updates"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/winutil"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/trayicon"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/trayicon"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
+137
-43
@@ -10,29 +10,34 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/cmd"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
|
||||
"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/store"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/tui"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/buildinfo"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/cmd"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/desktopctl"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/home"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/managementasset"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/redisqueue"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/startupconfig"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/store"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v7/internal/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/tui"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -105,6 +110,7 @@ func main() {
|
||||
var switchMode string
|
||||
var projectID string
|
||||
var vertexImport string
|
||||
var vertexImportPrefix string
|
||||
var configPath string
|
||||
var password string
|
||||
var noIncognito bool
|
||||
@@ -139,6 +145,8 @@ func main() {
|
||||
|
||||
// TUI flag
|
||||
var launchTUI bool
|
||||
var homeAddr string
|
||||
var homePassword string
|
||||
var standalone bool
|
||||
var localModel bool
|
||||
|
||||
@@ -155,8 +163,8 @@ func main() {
|
||||
flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)")
|
||||
flag.IntVar(&oauthCallbackPort, "oauth-callback-port", 0, "Override OAuth callback port (defaults to provider-specific port)")
|
||||
flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth")
|
||||
flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using Google OAuth")
|
||||
flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Login to Kiro using Google OAuth (same as --kiro-login)")
|
||||
flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using AWS Builder ID")
|
||||
flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Show Kiro Google OAuth limitation and supported alternatives")
|
||||
flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)")
|
||||
flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)")
|
||||
flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)")
|
||||
@@ -180,8 +188,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.StringVar(&homeAddr, "home", "", "Home control plane address in host:port format (loads config from home and skips local config file)")
|
||||
flag.StringVar(&homePassword, "home-password", "", "Home control plane password (Redis AUTH)")
|
||||
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")
|
||||
|
||||
@@ -299,6 +310,7 @@ func main() {
|
||||
var err error
|
||||
var cfg *config.Config
|
||||
var isCloudDeploy bool
|
||||
var configLoadedFromHome bool
|
||||
var (
|
||||
usePostgresStore bool
|
||||
pgStoreDSN string
|
||||
@@ -309,6 +321,7 @@ func main() {
|
||||
gitStoreRemoteURL string
|
||||
gitStoreUser string
|
||||
gitStorePassword string
|
||||
gitStoreBranch string
|
||||
gitStoreLocalPath string
|
||||
gitStoreInst *store.GitTokenStore
|
||||
gitStoreRoot string
|
||||
@@ -378,6 +391,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
|
||||
@@ -405,7 +421,68 @@ func main() {
|
||||
// Determine and load the configuration file.
|
||||
// Prefer the Postgres store when configured, otherwise fallback to git or local files.
|
||||
var configFilePath string
|
||||
if usePostgresStore {
|
||||
if strings.TrimSpace(homeAddr) != "" {
|
||||
configLoadedFromHome = true
|
||||
trimmedHomePassword := strings.TrimSpace(homePassword)
|
||||
host, portStr, errSplit := net.SplitHostPort(strings.TrimSpace(homeAddr))
|
||||
if errSplit != nil {
|
||||
log.Errorf("invalid -home address %q (expected host:port): %v", homeAddr, errSplit)
|
||||
return
|
||||
}
|
||||
host = strings.TrimSpace(host)
|
||||
if host == "" {
|
||||
log.Errorf("invalid -home address %q: host is empty", homeAddr)
|
||||
return
|
||||
}
|
||||
port, errPort := strconv.Atoi(strings.TrimSpace(portStr))
|
||||
if errPort != nil || port <= 0 {
|
||||
log.Errorf("invalid -home address %q: invalid port %q", homeAddr, portStr)
|
||||
return
|
||||
}
|
||||
|
||||
homeCfg := config.HomeConfig{
|
||||
Enabled: true,
|
||||
Host: host,
|
||||
Port: port,
|
||||
Password: trimmedHomePassword,
|
||||
}
|
||||
homeClient := home.New(homeCfg)
|
||||
defer homeClient.Close()
|
||||
|
||||
ctxHome, cancelHome := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
raw, errGetConfig := homeClient.GetConfig(ctxHome)
|
||||
cancelHome()
|
||||
if errGetConfig != nil {
|
||||
log.Errorf("failed to fetch config from home: %v", errGetConfig)
|
||||
return
|
||||
}
|
||||
|
||||
parsed, errParseConfig := config.ParseConfigBytes(raw)
|
||||
if errParseConfig != nil {
|
||||
log.Errorf("failed to parse config payload from home: %v", errParseConfig)
|
||||
return
|
||||
}
|
||||
if parsed == nil {
|
||||
parsed = &config.Config{}
|
||||
}
|
||||
parsed.Home = homeCfg
|
||||
parsed.Port = 8317 // Default to 8317 for home mode, can be overridden by home config
|
||||
parsed.UsageStatisticsEnabled = true
|
||||
cfg = parsed
|
||||
|
||||
// Keep a non-empty config path for downstream components (log paths, management assets, etc),
|
||||
// but do not require the file to exist when loading config from home.
|
||||
if strings.TrimSpace(configPath) != "" {
|
||||
configFilePath = configPath
|
||||
} else {
|
||||
configFilePath = filepath.Join(wd, "config.yaml")
|
||||
}
|
||||
|
||||
// Local stores are intentionally disabled when config is loaded from home.
|
||||
usePostgresStore = false
|
||||
useObjectStore = false
|
||||
useGitStore = false
|
||||
} else if usePostgresStore {
|
||||
if pgStoreLocalPath == "" {
|
||||
pgStoreLocalPath = wd
|
||||
}
|
||||
@@ -512,7 +589,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)
|
||||
@@ -550,12 +627,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 {
|
||||
@@ -574,24 +657,27 @@ func main() {
|
||||
// In cloud deploy mode, check if we have a valid configuration
|
||||
var configFileExists bool
|
||||
if isCloudDeploy {
|
||||
if info, errStat := os.Stat(configFilePath); errStat != nil {
|
||||
// Don't mislead: API server will not start until configuration is provided.
|
||||
log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration")
|
||||
configFileExists = false
|
||||
} else if info.IsDir() {
|
||||
log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration")
|
||||
configFileExists = false
|
||||
} else if cfg.Port == 0 {
|
||||
// LoadConfigOptional returns empty config when file is empty or invalid.
|
||||
// Config file exists but is empty or invalid; treat as missing config
|
||||
log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration")
|
||||
configFileExists = false
|
||||
if configLoadedFromHome && cfg != nil {
|
||||
configFileExists = cfg.Port != 0
|
||||
} else {
|
||||
log.Info("Cloud deploy mode: Configuration file detected; starting service")
|
||||
configFileExists = true
|
||||
if info, errStat := os.Stat(configFilePath); errStat != nil {
|
||||
// Don't mislead: API server will not start until configuration is provided.
|
||||
log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration")
|
||||
configFileExists = false
|
||||
} else if info.IsDir() {
|
||||
log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration")
|
||||
configFileExists = false
|
||||
} else if cfg.Port == 0 {
|
||||
// LoadConfigOptional returns empty config when file is empty or invalid.
|
||||
// Config file exists but is empty or invalid; treat as missing config
|
||||
log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration")
|
||||
configFileExists = false
|
||||
} else {
|
||||
log.Info("Cloud deploy mode: Configuration file detected; starting service")
|
||||
configFileExists = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Perform basic semantic validation of the loaded configuration.
|
||||
if warnings, errValidate := config.ValidateConfig(cfg); errValidate != nil {
|
||||
log.Errorf("invalid configuration: %v", errValidate)
|
||||
@@ -603,6 +689,8 @@ func main() {
|
||||
}
|
||||
|
||||
usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled)
|
||||
redisqueue.SetUsageStatisticsEnabled(cfg.UsageStatisticsEnabled)
|
||||
redisqueue.SetRetentionSeconds(cfg.RedisUsageQueueRetentionSeconds)
|
||||
coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling)
|
||||
// AntigravityPrimaryEmail removed - field does not exist
|
||||
|
||||
@@ -655,7 +743,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
|
||||
@@ -839,8 +927,11 @@ func main() {
|
||||
if standalone {
|
||||
// Standalone mode: start an embedded local server and connect TUI client to it.
|
||||
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
||||
if !localModel {
|
||||
misc.StartAntigravityVersionUpdater(context.Background())
|
||||
if !localModel && !cfg.Home.Enabled {
|
||||
registry.StartModelsUpdater(context.Background())
|
||||
} else if cfg.Home.Enabled {
|
||||
log.Info("Home mode: remote model updates disabled")
|
||||
}
|
||||
origStdout := os.Stdout
|
||||
origStderr := os.Stderr
|
||||
@@ -908,8 +999,11 @@ func main() {
|
||||
}
|
||||
} else {
|
||||
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
||||
if !localModel {
|
||||
misc.StartAntigravityVersionUpdater(context.Background())
|
||||
if !localModel && !cfg.Home.Enabled {
|
||||
registry.StartModelsUpdater(context.Background())
|
||||
} else if cfg.Home.Enabled {
|
||||
log.Info("Home mode: remote model updates disabled")
|
||||
}
|
||||
if autoGenPassword {
|
||||
cmd.StartServiceStandalone(cfg, configFilePath, password)
|
||||
|
||||
@@ -14,11 +14,11 @@ import (
|
||||
"golang.org/x/sys/windows/svc/eventlog"
|
||||
"golang.org/x/sys/windows/svc/mgr"
|
||||
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy"
|
||||
)
|
||||
|
||||
const serviceName = "ProxyPilot"
|
||||
|
||||
+55
-2
@@ -11,6 +11,13 @@ tls:
|
||||
cert: ""
|
||||
key: ""
|
||||
|
||||
# Optional "home" control plane integration over Redis protocol.
|
||||
home:
|
||||
enabled: false
|
||||
host: "127.0.0.1"
|
||||
port: 6379
|
||||
password: ""
|
||||
|
||||
# Management API settings
|
||||
remote-management:
|
||||
# Whether to allow remote (non-localhost) management access.
|
||||
@@ -66,6 +73,11 @@ error-logs-max-files: 10
|
||||
# When false, disable in-memory usage statistics aggregation
|
||||
usage-statistics-enabled: false
|
||||
|
||||
# How long (in seconds) Redis usage queue items are retained in memory for the RESP interface (LPOP/RPOP).
|
||||
# Note: the in-process Redis RESP usage output is disabled when home.enabled is true.
|
||||
# Default: 60. Max: 3600.
|
||||
redis-usage-queue-retention-seconds: 60
|
||||
|
||||
# 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: ""
|
||||
@@ -87,30 +99,65 @@ 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
|
||||
|
||||
# disable-image-generation supports: false (default), true, or "chat".
|
||||
# - true: disable image_generation everywhere (also returns 404 for /v1/images/generations and /v1/images/edits).
|
||||
# - "chat": disable image_generation injection on non-images endpoints, but keep /v1/images/generations and /v1/images/edits enabled.
|
||||
disable-image-generation: false
|
||||
|
||||
# Core auth auto-refresh worker pool size (OAuth/file-based auth token refresh).
|
||||
# When > 0, overrides the default worker count (16).
|
||||
# auth-auto-refresh-workers: 16
|
||||
|
||||
# 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 use credits as last-resort fallback when all free-tier auths are exhausted for Claude models
|
||||
|
||||
# Routing strategy for selecting credentials when multiple match.
|
||||
routing:
|
||||
strategy: "round-robin" # round-robin (default), fill-first
|
||||
# Enable universal session-sticky routing for all clients.
|
||||
# Session IDs are extracted from: metadata.user_id (Claude Code session format),
|
||||
# X-Session-ID, Session_id (Codex), X-Amp-Thread-Id (Amp CLI),
|
||||
# X-Client-Request-Id (PI), conversation_id, or first few messages hash.
|
||||
# Automatic failover is always enabled when bound auth becomes unavailable.
|
||||
session-affinity: false # default: false
|
||||
# How long session-to-auth bindings are retained. Default: 1h
|
||||
session-affinity-ttl: "1h"
|
||||
|
||||
# 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
|
||||
|
||||
# Streaming behavior (SSE keep-alives + safe bootstrap retries).
|
||||
# streaming:
|
||||
# keepalive-seconds: 15 # Default: 0 (disabled). <= 0 disables keep-alives.
|
||||
# bootstrap-retries: 1 # Default: 0 (disabled). Retries before first byte is sent.
|
||||
|
||||
# Signature cache validation for thinking blocks (Antigravity/Claude).
|
||||
# When true (default), cached signatures are preferred and validated.
|
||||
# When false, client signatures are used directly after normalization (bypass mode for testing).
|
||||
# antigravity-signature-cache-enabled: true
|
||||
|
||||
# Bypass mode signature validation strictness (only applies when signature cache is disabled).
|
||||
# When true, validates full Claude protobuf tree (Field 2 -> Field 1 structure).
|
||||
# When false (default), only checks R/E prefix + base64 + first byte 0x12.
|
||||
# antigravity-signature-bypass-strict: false
|
||||
|
||||
# Gemini API keys
|
||||
# gemini-api-key:
|
||||
# - api-key: "AIzaSy...01"
|
||||
# prefix: "test" # optional: require calls like "test/gemini-3-pro-preview" to target this credential
|
||||
# disable-cooling: false # optional: per-auth override for auth/model cooldown scheduling
|
||||
# base-url: "https://generativelanguage.googleapis.com"
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
@@ -130,6 +177,7 @@ nonstream-keepalive-interval: 0
|
||||
# codex-api-key:
|
||||
# - api-key: "sk-atSM..."
|
||||
# prefix: "test" # optional: require calls like "test/gpt-5-codex" to target this credential
|
||||
# disable-cooling: false # optional: per-auth override for auth/model cooldown scheduling
|
||||
# base-url: "https://www.example.com" # use the custom codex API endpoint
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
@@ -149,6 +197,7 @@ nonstream-keepalive-interval: 0
|
||||
# - api-key: "sk-atSM..." # use the official claude API key, no need to set the base url
|
||||
# - api-key: "sk-atSM..."
|
||||
# prefix: "test" # optional: require calls like "test/claude-sonnet-latest" to target this credential
|
||||
# disable-cooling: false # optional: per-auth override for auth/model cooldown scheduling
|
||||
# base-url: "https://www.example.com" # use the custom claude API endpoint
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
@@ -172,6 +221,8 @@ 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.
|
||||
# In legacy mode, user-agent/package-version/runtime-version/timeout are used as fallbacks
|
||||
@@ -199,8 +250,10 @@ nonstream-keepalive-interval: 0
|
||||
# OpenAI compatibility providers
|
||||
# openai-compatibility:
|
||||
# - name: "openrouter" # The name of the provider; it will be used in the user agent and other places.
|
||||
# disabled: false # optional: set to true to disable this provider without removing it
|
||||
# prefix: "test" # optional: require calls like "test/kimi-k2" to target this provider's credentials
|
||||
# base-url: "https://openrouter.ai/api/v1" # The base URL of the provider.
|
||||
# disable-cooling: false # optional: per-provider override for auth/model cooldown scheduling
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
# api-key-entries:
|
||||
@@ -218,7 +271,7 @@ nonstream-keepalive-interval: 0
|
||||
# # Requests to that alias will round-robin across the upstream names below,
|
||||
# # and if the chosen upstream fails before producing output, the request will
|
||||
# # continue with the next upstream model in the same alias pool.
|
||||
# - name: "qwen3.5-plus"
|
||||
# - name: "deepseek-v3.1"
|
||||
# alias: "claude-opus-4.66"
|
||||
# - name: "glm-5"
|
||||
# alias: "claude-opus-4.66"
|
||||
|
||||
+4
-4
@@ -17,10 +17,10 @@ services:
|
||||
ports:
|
||||
- "8317:8317"
|
||||
- "8085:8085"
|
||||
- "1455:1455"
|
||||
- "54545:54545"
|
||||
- "51121:51121"
|
||||
- "11451:11451"
|
||||
- "127.0.0.1:1455:1455"
|
||||
- "127.0.0.1:54545:54545"
|
||||
- "127.0.0.1:51121:51121"
|
||||
- "127.0.0.1:11451:11451"
|
||||
volumes:
|
||||
- ${CLI_PROXY_CONFIG_PATH:-./config.yaml}:/ProxyPilot/config.yaml
|
||||
- ${CLI_PROXY_AUTH_PATH:-./auths}:/root/.cli-proxy-api
|
||||
|
||||
@@ -32,6 +32,25 @@ Important:
|
||||
- Avoid Claude Code “Auth conflict”: do **not** set both `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the same time.
|
||||
- Restart Claude Code after editing settings so the new env vars take effect.
|
||||
|
||||
## Account risk warning
|
||||
|
||||
Claude/Anthropic OAuth, Google/Gemini OAuth, Gemini CLI OAuth, and Antigravity OAuth are unofficial compatibility paths. Providers may treat proxy, automation, shared-token, or third-party OAuth traffic as abnormal usage or a policy violation. These flows can risk quota loss, account restriction, or account suspension.
|
||||
|
||||
Do not use production, billing-critical, school/work, or irreplaceable personal accounts with these OAuth paths unless you accept that risk. Prefer official API keys or officially supported developer access for important accounts.
|
||||
|
||||
## Claude OAuth quota limitation
|
||||
|
||||
Anthropic currently treats third-party app traffic differently from regular Claude.ai or Claude Code subscription usage. If a Claude OAuth request fails with:
|
||||
|
||||
```text
|
||||
Third-party apps now draw from your extra usage, not your plan limits.
|
||||
Add more at claude.ai/settings/usage and keep going.
|
||||
```
|
||||
|
||||
that response is coming from Anthropic, not ProxyPilot. It means the OAuth credential is valid, but Anthropic is requiring paid extra usage for this third-party API path. ProxyPilot cannot make those requests draw from normal Claude.ai subscription quota.
|
||||
|
||||
For Claude through ProxyPilot, either add extra usage in Anthropic settings, use a supported API-key billing path, or route the client to another provider/model alias such as Antigravity, Codex, Gemini, or Kiro.
|
||||
|
||||
## Server-side model aliasing (Claude handler)
|
||||
|
||||
CLIProxyAPI rewrites common Claude Code model aliases to locally-available models before routing:
|
||||
|
||||
+8
-4
@@ -57,12 +57,16 @@ proxypilot --codex-login # Login to Codex using OAuth
|
||||
proxypilot --claude-login # Login to Claude using OAuth
|
||||
proxypilot --qwen-login # Login to Qwen using OAuth
|
||||
proxypilot --antigravity-login # Login to Antigravity using OAuth
|
||||
proxypilot --kiro-login # Login to Kiro using Google OAuth
|
||||
proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID
|
||||
proxypilot --kiro-login # Login to Kiro using AWS Builder ID
|
||||
proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID device code
|
||||
proxypilot --minimax-login # Add MiniMax API key
|
||||
proxypilot --zhipu-login # Add Zhipu AI API key
|
||||
```
|
||||
|
||||
Account risk warning: `--claude-login`, `--login` / Gemini, Gemini CLI OAuth, and `--antigravity-login` are unofficial compatibility login paths. Providers may treat proxy, automation, shared-token, or third-party OAuth traffic as abnormal usage or a policy violation. These flows can risk quota loss, account restriction, or account suspension. Prefer official API-key or officially supported developer access for accounts you cannot afford to lose.
|
||||
|
||||
Kiro Google/GitHub OAuth is not currently supported because AWS Cognito rejects third-party localhost callbacks. Use AWS Builder ID or import a token from the official Kiro IDE instead.
|
||||
|
||||
### Login Options
|
||||
|
||||
```bash
|
||||
@@ -309,8 +313,8 @@ proxypilot --codex-login # Codex OAuth
|
||||
proxypilot --claude-login # Claude OAuth
|
||||
proxypilot --qwen-login # Qwen OAuth
|
||||
proxypilot --antigravity-login # Antigravity OAuth
|
||||
proxypilot --kiro-login # Kiro Google OAuth
|
||||
proxypilot --kiro-aws-login # Kiro AWS Builder ID
|
||||
proxypilot --kiro-login # Kiro AWS Builder ID
|
||||
proxypilot --kiro-aws-login # Kiro AWS Builder ID device code
|
||||
|
||||
# Agent Detection & Setup
|
||||
proxypilot --detect-agents # Detect installed agents
|
||||
|
||||
@@ -61,6 +61,8 @@ ProxyPilot tray app includes:
|
||||
- One-click login launchers: Antigravity, Gemini CLI, Codex, Claude, Qwen
|
||||
- `Open Auth Folder` shortcut
|
||||
|
||||
Account risk warning: Antigravity, Gemini/Gemini CLI, and Claude login launchers use unofficial compatibility OAuth paths. Providers may treat proxy, automation, shared-token, or third-party OAuth traffic as abnormal usage or a policy violation. These flows can risk quota loss, account restriction, or account suspension. Use disposable or non-critical accounts only if you accept that risk; prefer official API keys or officially supported developer access for important accounts.
|
||||
|
||||
## Logs / diagnostics
|
||||
|
||||
Useful paths:
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# 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`, `/v1/responses`, `/v1/responses/compact`, and Codex direct `/backend-api/codex/responses` aliases
|
||||
- a local `/v0/runtime/stats` operator surface for runtime-memory counters, auth-health, and last refresh status
|
||||
- read-only `/v0/management/status`, `/v0/management/config`, and `/v0/management/accounts` endpoints with API key and token material redacted
|
||||
- CLI account commands for adding, importing, exporting, device-login, refresh, listing, activating, and removing 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 export --file proxypilot-rs.accounts.toml
|
||||
cargo run -p proxypilot-rs -- account import --file proxypilot-rs.accounts.toml
|
||||
cargo run -p proxypilot-rs -- account import --file proxypilot-rs.accounts.toml --replace
|
||||
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
|
||||
```
|
||||
|
||||
Run the local Codex-compatible smoke check without touching real provider
|
||||
accounts:
|
||||
|
||||
```bash
|
||||
cd rust
|
||||
./scripts/codex-smoke.sh
|
||||
```
|
||||
|
||||
The smoke check starts a local mock upstream, saves a temporary Codex account,
|
||||
starts the Rust proxy, and verifies `/healthz`, `/v0/runtime/stats`,
|
||||
`/v1/models`, `/v1/chat/completions`, and `/v1/responses`.
|
||||
|
||||
Run the local Claude API-key smoke check:
|
||||
|
||||
```bash
|
||||
cd rust
|
||||
./scripts/claude-smoke.sh
|
||||
```
|
||||
|
||||
The Claude smoke starts a local mock Anthropic-compatible upstream, starts the
|
||||
Rust proxy with `providers.active = "claude"`, and verifies Claude API-key
|
||||
headers on `/v1/models` and `/v1/messages`.
|
||||
|
||||
## Current Codex Gaps
|
||||
|
||||
The Rust line is not ready to replace the Go Codex surface yet. Current status:
|
||||
|
||||
- `/health` and `/healthz` both return Rust health status.
|
||||
- `/v1/responses/compact` forwards to the active provider upstream.
|
||||
- `/backend-api/codex/responses` and `/backend-api/codex/responses/compact`
|
||||
forward through the Codex-compatible `/v1/responses` paths when the active
|
||||
provider is `codex`; they reject non-Codex active providers instead of
|
||||
silently routing a Codex direct alias to Claude or another provider.
|
||||
- `GET /v1/responses` and `GET /backend-api/codex/responses` return explicit
|
||||
`501 Not Implemented` responses because Rust websocket response proxying is
|
||||
still deferred.
|
||||
- Codex websocket streaming
|
||||
- Codex image generation and image edit handling
|
||||
- Browser dashboard and broad `/v0/management/**` parity beyond status, config,
|
||||
and accounts
|
||||
- Go model registry and model-mapping behavior
|
||||
|
||||
Open the TUI with:
|
||||
|
||||
```bash
|
||||
cd rust
|
||||
cargo run -p proxypilot-rs -- tui --config proxypilot-rs.toml
|
||||
```
|
||||
@@ -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`
|
||||
@@ -0,0 +1,9 @@
|
||||
# Session 2026-04-11
|
||||
|
||||
- Targeted upstream sync: `CLIProxyAPI v6.9.22`
|
||||
- Merge base from shipping line: `v0.3.0-dev-0.53` on `main`
|
||||
- Upstream merge branch: `sync-upstream-v6.9.18-to-v6.9.22`
|
||||
- Conflict resolution:
|
||||
- kept ProxyPilot-local `.gitignore` entries while accepting upstream code changes
|
||||
- updated upstream tracking markers and release metadata to `v6.9.22`
|
||||
- Planned release target after validation: `v0.3.0-dev-0.54`
|
||||
@@ -0,0 +1,13 @@
|
||||
# Session 2026-04-12
|
||||
|
||||
- Target upstream release: `CLIProxyAPI v6.9.23` (`0ab1f54173d477d6a39457b6aaf1f663b315fdb2`)
|
||||
- Base local release line before merge: `ProxyPilot v0.3.0-dev-0.54` on `main`
|
||||
- Merge branch: `sync-upstream-v6.9.22-to-v6.9.23`
|
||||
- Conflict resolution:
|
||||
- kept ProxyPilot branding and docs flow in `README.md`
|
||||
- kept upstream Qwen executor/runtime changes from `v6.9.23`
|
||||
- did not revive upstream locale README files (`README_CN.md`, `README_JA.md`)
|
||||
- Validation plan:
|
||||
- `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 ./...`
|
||||
@@ -0,0 +1,12 @@
|
||||
# Session 2026-04-13
|
||||
|
||||
- Target upstream release: `CLIProxyAPI v6.9.24` (`c4459c43462c45bcd8ac346c72b98647675a014e`)
|
||||
- Base local release line before merge: `ProxyPilot main` at `v6.9.23`
|
||||
- Merge branch: `sync-upstream-v6.9.23-to-v6.9.24`
|
||||
- Merge result:
|
||||
- clean merge with no manual conflict resolution required
|
||||
- kept ProxyPilot fork structure intact while taking upstream auth auto-refresh loop and Antigravity fixes
|
||||
- Validation plan:
|
||||
- `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 ./...`
|
||||
@@ -0,0 +1,14 @@
|
||||
# Session 2026-04-16
|
||||
|
||||
- Target upstream release: `CLIProxyAPI v6.9.27` (`ba454dbfbfb41c3a8218118323f828ea19e92c3d`)
|
||||
- Base local release line before merge: `ProxyPilot main` at `v6.9.24` (`06c3e954`)
|
||||
- Merge branch: `sync-upstream-v6.9.24-to-v6.9.27`
|
||||
- Conflict resolution:
|
||||
- kept ProxyPilot branding and docs flow in `README.md`
|
||||
- did not revive upstream locale README files (`README_CN.md`, `README_JA.md`)
|
||||
- preserved ProxyPilot Qwen auth/runtime support while taking upstream session-affinity and Antigravity fixes
|
||||
- kept local request execution metadata behavior in `sdk/api/handlers/handlers.go` so pinned-auth selection remains stable
|
||||
- Validation:
|
||||
- `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 ./...`
|
||||
@@ -0,0 +1,14 @@
|
||||
# Session 2026-04-17
|
||||
|
||||
- Target upstream release: `CLIProxyAPI v6.9.28` (`5dcca69ea5be9de76e04c7f5dcd51098e7fc9018`)
|
||||
- Base local release line before merge: `ProxyPilot main` at `v6.9.27` (`71be5e89`)
|
||||
- Merge branch: `sync-upstream-v6.9.27-to-v6.9.28`
|
||||
- Conflict resolution:
|
||||
- kept ProxyPilot branding and docs flow in `README.md`
|
||||
- did not revive upstream locale README files (`README_CN.md`, `README_JA.md`)
|
||||
- preserved ProxyPilot `qwen` and `iflow` auth/runtime/config/model support while taking upstream auth proxy-override support and Claude Opus 4.7 model catalog updates
|
||||
- kept local synthetic idempotency-key behavior in `sdk/api/handlers/handlers.go` and updated the new upstream metadata test to match fork behavior
|
||||
- Validation:
|
||||
- `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 ./...`
|
||||
@@ -0,0 +1,14 @@
|
||||
# Session 2026-04-18
|
||||
|
||||
- Target upstream release: `CLIProxyAPI v6.9.29` (`c6baa64b4e3cf85f8400e2cc9d9bd3d7040db187`)
|
||||
- Base local release line before merge: `ProxyPilot main` at `v6.9.28` (`7ec328f9`)
|
||||
- Merge branch: `sync-upstream-v6.9.28-to-v6.9.29`
|
||||
- Conflict resolution:
|
||||
- preserved ProxyPilot's clone-and-rollback config persistence behavior in `internal/api/handlers/management/handler.go` while integrating upstream `auth-index` management handlers
|
||||
- took upstream Claude executor test expectations that tighten forwarded system-prompt behavior and strict-mode assertions
|
||||
- no provider-surface carry work was needed this round; local `qwen`, `iflow`, and synthetic idempotency behavior remained intact
|
||||
- Validation:
|
||||
- `go test ./internal/api/handlers/management ./internal/runtime/executor`
|
||||
- `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 ./...`
|
||||
@@ -0,0 +1,13 @@
|
||||
# Session 2026-04-24
|
||||
|
||||
- Target upstream release: `CLIProxyAPI v6.9.36` (`f1ba6151a99240902bcda12102c921b0ead01d2d`)
|
||||
- Base local release line before merge: `ProxyPilot main` at upstream `v6.9.30` (`2ebbb596`)
|
||||
- Merge branch: `sync-upstream-v6.9.30-to-v6.9.36`
|
||||
- Conflict resolution:
|
||||
- no textual conflicts in the upstream merge; existing ProxyPilot fork surfaces carried forward cleanly
|
||||
- corrected stale upstream marker files from the prior `v6.9.30` sync so `.upstream-sync-tag` and `.upstream-sync-sha` now match the merged upstream release
|
||||
- kept the existing fork behavior around local provider support while taking upstream Codex image-generation, Antigravity credits fallback, logging, and `/healthz` improvements
|
||||
- Validation:
|
||||
- `go test ./...`
|
||||
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
|
||||
- `go vet ./...`
|
||||
@@ -24,14 +24,14 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
clipexec "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/logging"
|
||||
sdktr "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/api"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
clipexec "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/executor"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/logging"
|
||||
sdktr "github.com/router-for-me/CLIProxyAPI/v7/sdk/translator"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
clipexec "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
clipexec "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/executor"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator/builtin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/translator"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v7/sdk/translator/builtin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"project": "ProxyPilot",
|
||||
"version": "0.3.0",
|
||||
"upstream": "CLIProxyAPI v6.9.5",
|
||||
"upstream": "CLIProxyAPI v6.9.36",
|
||||
"features": [
|
||||
{
|
||||
"id": 1,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
module github.com/router-for-me/CLIProxyAPI/v6
|
||||
module github.com/router-for-me/CLIProxyAPI/v7
|
||||
|
||||
go 1.26.0
|
||||
|
||||
@@ -22,6 +22,7 @@ require (
|
||||
github.com/pelletier/go-toml/v2 v2.2.2
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/redis/go-redis/v9 v9.19.0
|
||||
github.com/refraction-networking/utls v1.8.2
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.11.1
|
||||
@@ -38,6 +39,11 @@ require (
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/compute/metadata v0.3.0 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
@@ -45,7 +51,6 @@ require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
|
||||
github.com/charmbracelet/x/ansi v0.10.1 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
|
||||
@@ -96,6 +101,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
|
||||
@@ -113,6 +119,6 @@ require (
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/text v0.31.0 // indirect
|
||||
google.golang.org/protobuf v1.36.8 // indirect
|
||||
google.golang.org/protobuf v1.36.8
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
)
|
||||
|
||||
@@ -16,6 +16,10 @@ github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWp
|
||||
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
@@ -180,6 +184,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=
|
||||
@@ -194,6 +200,8 @@ github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9Z
|
||||
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||
github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthOm/k=
|
||||
github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
||||
github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=
|
||||
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
@@ -239,6 +247,10 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
|
||||
sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v7/sdk/access"
|
||||
sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
||||
)
|
||||
|
||||
// Register ensures the config-access provider is available to the access manager.
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v7/sdk/access"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
)
|
||||
|
||||
type bufferedConn struct {
|
||||
net.Conn
|
||||
reader *bufio.Reader
|
||||
}
|
||||
|
||||
func (c *bufferedConn) Read(p []byte) (int, error) {
|
||||
if c == nil {
|
||||
return 0, net.ErrClosed
|
||||
}
|
||||
if c.reader == nil {
|
||||
return c.Conn.Read(p)
|
||||
}
|
||||
return c.reader.Read(p)
|
||||
}
|
||||
|
||||
func (c *bufferedConn) ConnectionState() tls.ConnectionState {
|
||||
if c == nil || c.Conn == nil {
|
||||
return tls.ConnectionState{}
|
||||
}
|
||||
if stater, ok := c.Conn.(interface{ ConnectionState() tls.ConnectionState }); ok {
|
||||
return stater.ConnectionState()
|
||||
}
|
||||
return tls.ConnectionState{}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
|
||||
)
|
||||
|
||||
// mockCoreManager implements memory.CoreManagerExecutor for testing
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/agents"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/agents"
|
||||
)
|
||||
|
||||
// AgentsV2Handler provides the new unified agent configuration API
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
type apiKeyUsageEntry struct {
|
||||
Success int64 `json:"success"`
|
||||
Failed int64 `json:"failed"`
|
||||
RecentRequests []coreauth.RecentRequestBucket `json:"recent_requests"`
|
||||
}
|
||||
|
||||
func mergeRecentRequestBuckets(dst, src []coreauth.RecentRequestBucket) []coreauth.RecentRequestBucket {
|
||||
if len(dst) == 0 {
|
||||
return src
|
||||
}
|
||||
if len(src) == 0 {
|
||||
return dst
|
||||
}
|
||||
if len(dst) != len(src) {
|
||||
n := len(dst)
|
||||
if len(src) < n {
|
||||
n = len(src)
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
dst[i].Success += src[i].Success
|
||||
dst[i].Failed += src[i].Failed
|
||||
}
|
||||
return dst
|
||||
}
|
||||
for i := range dst {
|
||||
dst[i].Success += src[i].Success
|
||||
dst[i].Failed += src[i].Failed
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// GetAPIKeyUsage returns recent request buckets for all in-memory api_key auths,
|
||||
// grouped by provider and keyed by "base_url|api_key".
|
||||
func (h *Handler) GetAPIKeyUsage(c *gin.Context) {
|
||||
if h == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler not initialized"})
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
manager := h.authManager
|
||||
h.mu.Unlock()
|
||||
if manager == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
out := make(map[string]map[string]apiKeyUsageEntry)
|
||||
for _, auth := range manager.List() {
|
||||
if auth == nil {
|
||||
continue
|
||||
}
|
||||
kind, apiKey := auth.AccountInfo()
|
||||
if !strings.EqualFold(strings.TrimSpace(kind), "api_key") {
|
||||
continue
|
||||
}
|
||||
apiKey = strings.TrimSpace(apiKey)
|
||||
if apiKey == "" {
|
||||
continue
|
||||
}
|
||||
baseURL := ""
|
||||
if auth.Attributes != nil {
|
||||
baseURL = strings.TrimSpace(auth.Attributes["base_url"])
|
||||
if baseURL == "" {
|
||||
baseURL = strings.TrimSpace(auth.Attributes["base-url"])
|
||||
}
|
||||
}
|
||||
compositeKey := baseURL + "|" + apiKey
|
||||
provider := strings.ToLower(strings.TrimSpace(auth.Provider))
|
||||
if provider == "" {
|
||||
provider = "unknown"
|
||||
}
|
||||
|
||||
recent := auth.RecentRequestsSnapshot(now)
|
||||
providerBucket, ok := out[provider]
|
||||
if !ok {
|
||||
providerBucket = make(map[string]apiKeyUsageEntry)
|
||||
out[provider] = providerBucket
|
||||
}
|
||||
if existing, exists := providerBucket[compositeKey]; exists {
|
||||
existing.Success += auth.Success
|
||||
existing.Failed += auth.Failed
|
||||
existing.RecentRequests = mergeRecentRequestBuckets(existing.RecentRequests, recent)
|
||||
providerBucket[compositeKey] = existing
|
||||
continue
|
||||
}
|
||||
providerBucket[compositeKey] = apiKeyUsageEntry{
|
||||
Success: auth.Success,
|
||||
Failed: auth.Failed,
|
||||
RecentRequests: recent,
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
func sumRecentRequestBuckets(buckets []coreauth.RecentRequestBucket) (int64, int64) {
|
||||
var success int64
|
||||
var failed int64
|
||||
for _, bucket := range buckets {
|
||||
success += bucket.Success
|
||||
failed += bucket.Failed
|
||||
}
|
||||
return success, failed
|
||||
}
|
||||
|
||||
func TestGetAPIKeyUsage_GroupsByProviderAndAPIKey(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
if _, err := manager.Register(context.Background(), &coreauth.Auth{
|
||||
ID: "codex-auth",
|
||||
Provider: "codex",
|
||||
Attributes: map[string]string{
|
||||
"api_key": "codex-key",
|
||||
"base_url": "https://codex.example.com",
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("register codex auth: %v", err)
|
||||
}
|
||||
if _, err := manager.Register(context.Background(), &coreauth.Auth{
|
||||
ID: "claude-auth",
|
||||
Provider: "claude",
|
||||
Attributes: map[string]string{
|
||||
"api_key": "claude-key",
|
||||
"base_url": "https://claude.example.com",
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("register claude auth: %v", err)
|
||||
}
|
||||
|
||||
manager.MarkResult(context.Background(), coreauth.Result{AuthID: "codex-auth", Provider: "codex", Model: "gpt-5", Success: true})
|
||||
manager.MarkResult(context.Background(), coreauth.Result{AuthID: "codex-auth", Provider: "codex", Model: "gpt-5", Success: false})
|
||||
manager.MarkResult(context.Background(), coreauth.Result{AuthID: "claude-auth", Provider: "claude", Model: "claude-4", Success: true})
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ginCtx, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/management/api-key-usage", nil)
|
||||
ginCtx.Request = req
|
||||
h.GetAPIKeyUsage(ginCtx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
|
||||
var payload map[string]map[string]apiKeyUsageEntry
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("decode payload: %v", err)
|
||||
}
|
||||
|
||||
codexEntry := payload["codex"]["https://codex.example.com|codex-key"]
|
||||
if codexEntry.Success != 1 || codexEntry.Failed != 1 {
|
||||
t.Fatalf("codex totals = %d/%d, want 1/1", codexEntry.Success, codexEntry.Failed)
|
||||
}
|
||||
if len(codexEntry.RecentRequests) != 20 {
|
||||
t.Fatalf("codex buckets len = %d, want 20", len(codexEntry.RecentRequests))
|
||||
}
|
||||
codexSuccess, codexFailed := sumRecentRequestBuckets(codexEntry.RecentRequests)
|
||||
if codexSuccess != 1 || codexFailed != 1 {
|
||||
t.Fatalf("codex totals = %d/%d, want 1/1", codexSuccess, codexFailed)
|
||||
}
|
||||
|
||||
claudeEntry := payload["claude"]["https://claude.example.com|claude-key"]
|
||||
if claudeEntry.Success != 1 || claudeEntry.Failed != 0 {
|
||||
t.Fatalf("claude totals = %d/%d, want 1/0", claudeEntry.Success, claudeEntry.Failed)
|
||||
}
|
||||
if len(claudeEntry.RecentRequests) != 20 {
|
||||
t.Fatalf("claude buckets len = %d, want 20", len(claudeEntry.RecentRequests))
|
||||
}
|
||||
claudeSuccess, claudeFailed := sumRecentRequestBuckets(claudeEntry.RecentRequests)
|
||||
if claudeSuccess != 1 || claudeFailed != 0 {
|
||||
t.Fatalf("claude totals = %d/%d, want 1/0", claudeSuccess, claudeFailed)
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"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"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/runtime/geminicli"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
@@ -636,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 != "" {
|
||||
@@ -658,6 +664,126 @@ func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper {
|
||||
return clone
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
attrKey, attrBase := "", ""
|
||||
if auth.Attributes != nil {
|
||||
attrKey = strings.TrimSpace(auth.Attributes["api_key"])
|
||||
attrBase = strings.TrimSpace(auth.Attributes["base_url"])
|
||||
}
|
||||
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
|
||||
}
|
||||
if attrKey != "" && strings.EqualFold(cfgKey, attrKey) {
|
||||
if cfgBase == "" || strings.EqualFold(cfgBase, attrBase) {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
if attrKey == "" && attrBase != "" && strings.EqualFold(cfgBase, attrBase) {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
if attrKey != "" {
|
||||
for i := range entries {
|
||||
entry := &entries[i]
|
||||
if strings.EqualFold(strings.TrimSpace((*entry).GetAPIKey()), attrKey) {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
}
|
||||
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]
|
||||
if compat.Disabled {
|
||||
continue
|
||||
}
|
||||
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 {
|
||||
|
||||
@@ -5,9 +5,9 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"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"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
||||
)
|
||||
|
||||
func TestAPICallTransportDirectBypassesGlobalProxy(t *testing.T) {
|
||||
@@ -58,6 +58,105 @@ func TestAPICallTransportInvalidAuthFallsBackToGlobalProxy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
|
||||
@@ -22,19 +22,19 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/antigravity"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/claude"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex"
|
||||
geminiAuth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/gemini"
|
||||
iflowauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/iflow"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/kimi"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/qwen"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
|
||||
"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/util"
|
||||
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/v7/internal/auth/antigravity"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/claude"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/codex"
|
||||
geminiAuth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/gemini"
|
||||
iflowauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/iflow"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/kimi"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/qwen"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/interfaces"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/oauth2"
|
||||
@@ -390,6 +390,9 @@ func (h *Handler) buildAuthFileEntry(auth *coreauth.Auth) gin.H {
|
||||
"source": "memory",
|
||||
"size": int64(0),
|
||||
}
|
||||
entry["success"] = auth.Success
|
||||
entry["failed"] = auth.Failed
|
||||
entry["recent_requests"] = auth.RecentRequestsSnapshot(time.Now())
|
||||
if email := authEmail(auth); email != "" {
|
||||
entry["email"] = email
|
||||
}
|
||||
@@ -1055,6 +1058,17 @@ func (h *Handler) buildAuthFromFileData(path string, data []byte) (*coreauth.Aut
|
||||
if hasLastRefresh {
|
||||
auth.LastRefreshedAt = lastRefresh
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1142,7 +1156,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, note) 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"})
|
||||
@@ -1150,11 +1164,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"`
|
||||
Note *string `json:"note"`
|
||||
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"})
|
||||
@@ -1190,39 +1205,117 @@ func (h *Handler) PatchAuthFileFields(c *gin.Context) {
|
||||
|
||||
changed := false
|
||||
if req.Prefix != nil {
|
||||
targetAuth.Prefix = *req.Prefix
|
||||
prefix := strings.TrimSpace(*req.Prefix)
|
||||
targetAuth.Prefix = prefix
|
||||
if targetAuth.Metadata == nil {
|
||||
targetAuth.Metadata = make(map[string]any)
|
||||
}
|
||||
if targetAuth.Attributes == nil {
|
||||
targetAuth.Attributes = make(map[string]string)
|
||||
}
|
||||
if targetAuth.Prefix == "" {
|
||||
if prefix == "" {
|
||||
delete(targetAuth.Metadata, "prefix")
|
||||
delete(targetAuth.Attributes, "prefix")
|
||||
} else {
|
||||
targetAuth.Metadata["prefix"] = targetAuth.Prefix
|
||||
targetAuth.Attributes["prefix"] = targetAuth.Prefix
|
||||
targetAuth.Metadata["prefix"] = prefix
|
||||
targetAuth.Attributes["prefix"] = prefix
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if req.ProxyURL != nil {
|
||||
targetAuth.ProxyURL = *req.ProxyURL
|
||||
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 targetAuth.ProxyURL == "" {
|
||||
if proxyURL == "" {
|
||||
delete(targetAuth.Metadata, "proxy_url")
|
||||
delete(targetAuth.Attributes, "proxy_url")
|
||||
} else {
|
||||
targetAuth.Metadata["proxy_url"] = targetAuth.ProxyURL
|
||||
targetAuth.Attributes["proxy_url"] = targetAuth.ProxyURL
|
||||
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)
|
||||
@@ -2092,10 +2185,8 @@ func (h *Handler) RequestQwenToken(c *gin.Context) {
|
||||
fmt.Println("Initializing Qwen authentication...")
|
||||
|
||||
state := fmt.Sprintf("gem-%d", time.Now().UnixNano())
|
||||
// Initialize Qwen auth service
|
||||
qwenAuth := qwen.NewQwenAuth(h.cfg)
|
||||
|
||||
// Generate authorization URL
|
||||
deviceFlow, err := qwenAuth.InitiateDeviceFlow(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("Failed to generate authorization URL: %v", err)
|
||||
@@ -2115,9 +2206,7 @@ func (h *Handler) RequestQwenToken(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Create token storage
|
||||
tokenStorage := qwenAuth.CreateTokenStorage(tokenData)
|
||||
|
||||
tokenStorage.Email = fmt.Sprintf("%d", time.Now().UnixMilli())
|
||||
record := &coreauth.Auth{
|
||||
ID: fmt.Sprintf("qwen-%s.json", tokenStorage.Email),
|
||||
@@ -2644,23 +2733,10 @@ func performGeminiCLISetup(ctx context.Context, httpClient *http.Client, storage
|
||||
finalProjectID := projectID
|
||||
if responseProjectID != "" {
|
||||
if explicitProject && !strings.EqualFold(responseProjectID, projectID) {
|
||||
// Check if this is a free user (gen-lang-client projects or free/legacy tier)
|
||||
isFreeUser := strings.HasPrefix(projectID, "gen-lang-client-") ||
|
||||
strings.EqualFold(tierID, "FREE") ||
|
||||
strings.EqualFold(tierID, "LEGACY")
|
||||
|
||||
if isFreeUser {
|
||||
// For free users, use backend project ID for preview model access
|
||||
log.Infof("Gemini onboarding: frontend project %s maps to backend project %s", projectID, responseProjectID)
|
||||
log.Infof("Using backend project ID: %s (recommended for preview model access)", responseProjectID)
|
||||
finalProjectID = responseProjectID
|
||||
} else {
|
||||
// Pro users: keep requested project ID (original behavior)
|
||||
log.Warnf("Gemini onboarding returned project %s instead of requested %s; keeping requested project ID.", responseProjectID, projectID)
|
||||
}
|
||||
} else {
|
||||
finalProjectID = responseProjectID
|
||||
log.Infof("Gemini onboarding: requested project %s maps to backend project %s", projectID, responseProjectID)
|
||||
log.Infof("Using backend project ID: %s", responseProjectID)
|
||||
}
|
||||
finalProjectID = responseProjectID
|
||||
}
|
||||
|
||||
storage.ProjectID = strings.TrimSpace(finalProjectID)
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
"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"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
func TestUploadAuthFile_BatchMultipart(t *testing.T) {
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"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"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
func TestDeleteAuthFile_UsesAuthPathFromManager(t *testing.T) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
func TestDownloadAuthFile_ReturnsFile(t *testing.T) {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
func TestDownloadAuthFile_PreventsWindowsSlashTraversal(t *testing.T) {
|
||||
|
||||
@@ -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/v7/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
func TestListAuthFiles_IncludesRecentRequestsBuckets(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
record := &coreauth.Auth{
|
||||
ID: "runtime-only-auth-1",
|
||||
Provider: "codex",
|
||||
Attributes: map[string]string{
|
||||
"runtime_only": "true",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
},
|
||||
}
|
||||
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)
|
||||
h.tokenStore = &memoryAuthStore{}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ginCtx, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/management/auth-files", nil)
|
||||
ginCtx.Request = req
|
||||
|
||||
h.ListAuthFiles(ginCtx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected list status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &payload); errUnmarshal != nil {
|
||||
t.Fatalf("failed to decode list payload: %v", errUnmarshal)
|
||||
}
|
||||
filesRaw, ok := payload["files"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("expected files array, payload: %#v", payload)
|
||||
}
|
||||
if len(filesRaw) != 1 {
|
||||
t.Fatalf("expected 1 auth entry, got %d", len(filesRaw))
|
||||
}
|
||||
|
||||
fileEntry, ok := filesRaw[0].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("expected file entry object, got %#v", filesRaw[0])
|
||||
}
|
||||
|
||||
if _, ok := fileEntry["success"].(float64); !ok {
|
||||
t.Fatalf("expected success number, got %#v", fileEntry["success"])
|
||||
}
|
||||
if _, ok := fileEntry["failed"].(float64); !ok {
|
||||
t.Fatalf("expected failed number, got %#v", fileEntry["failed"])
|
||||
}
|
||||
|
||||
recentRaw, ok := fileEntry["recent_requests"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("expected recent_requests array, got %#v", fileEntry["recent_requests"])
|
||||
}
|
||||
if len(recentRaw) != 20 {
|
||||
t.Fatalf("expected 20 recent_requests buckets, got %d", len(recentRaw))
|
||||
}
|
||||
for idx, item := range recentRaw {
|
||||
bucket, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("expected bucket object at %d, got %#v", idx, item)
|
||||
}
|
||||
if _, ok := bucket["time"].(string); !ok {
|
||||
t.Fatalf("expected bucket time string at %d, got %#v", idx, bucket["time"])
|
||||
}
|
||||
if _, ok := bucket["success"].(float64); !ok {
|
||||
t.Fatalf("expected bucket success number at %d, got %#v", idx, bucket["success"])
|
||||
}
|
||||
if _, ok := bucket["failed"].(float64); !ok {
|
||||
t.Fatalf("expected bucket failed number at %d, got %#v", idx, bucket["failed"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
type authResetCooldownRequest struct {
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/cache"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/cache"
|
||||
)
|
||||
|
||||
// CacheStatsResponse represents the response for cache statistics.
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/watcher/synthesizer"
|
||||
)
|
||||
|
||||
type geminiKeyWithAuthIndex struct {
|
||||
config.GeminiKey
|
||||
AuthIndex string `json:"auth-index,omitempty"`
|
||||
}
|
||||
|
||||
type claudeKeyWithAuthIndex struct {
|
||||
config.ClaudeKey
|
||||
AuthIndex string `json:"auth-index,omitempty"`
|
||||
}
|
||||
|
||||
type codexKeyWithAuthIndex struct {
|
||||
config.CodexKey
|
||||
AuthIndex string `json:"auth-index,omitempty"`
|
||||
}
|
||||
|
||||
type vertexCompatKeyWithAuthIndex struct {
|
||||
config.VertexCompatKey
|
||||
AuthIndex string `json:"auth-index,omitempty"`
|
||||
}
|
||||
|
||||
type openAICompatibilityAPIKeyWithAuthIndex struct {
|
||||
config.OpenAICompatibilityAPIKey
|
||||
AuthIndex string `json:"auth-index,omitempty"`
|
||||
}
|
||||
|
||||
type openAICompatibilityWithAuthIndex struct {
|
||||
Name string `json:"name"`
|
||||
Priority int `json:"priority,omitempty"`
|
||||
Disabled bool `json:"disabled"`
|
||||
Prefix string `json:"prefix,omitempty"`
|
||||
BaseURL string `json:"base-url"`
|
||||
APIKeyEntries []openAICompatibilityAPIKeyWithAuthIndex `json:"api-key-entries,omitempty"`
|
||||
Models []config.OpenAICompatibilityModel `json:"models,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
AuthIndex string `json:"auth-index,omitempty"`
|
||||
}
|
||||
|
||||
func (h *Handler) liveAuthIndexByID() map[string]string {
|
||||
out := map[string]string{}
|
||||
if h == nil {
|
||||
return out
|
||||
}
|
||||
h.mu.Lock()
|
||||
manager := h.authManager
|
||||
h.mu.Unlock()
|
||||
if manager == nil {
|
||||
return out
|
||||
}
|
||||
// authManager.List() returns clones, so EnsureIndex only affects these copies.
|
||||
for _, auth := range manager.List() {
|
||||
if auth == nil {
|
||||
continue
|
||||
}
|
||||
id := strings.TrimSpace(auth.ID)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
idx := strings.TrimSpace(auth.Index)
|
||||
if idx == "" {
|
||||
idx = auth.EnsureIndex()
|
||||
}
|
||||
if idx == "" {
|
||||
continue
|
||||
}
|
||||
out[id] = idx
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Handler) geminiKeysWithAuthIndex() []geminiKeyWithAuthIndex {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
liveIndexByID := h.liveAuthIndexByID()
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
idGen := synthesizer.NewStableIDGenerator()
|
||||
out := make([]geminiKeyWithAuthIndex, len(h.cfg.GeminiKey))
|
||||
for i := range h.cfg.GeminiKey {
|
||||
entry := h.cfg.GeminiKey[i]
|
||||
authIndex := ""
|
||||
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
||||
id, _ := idGen.Next("gemini:apikey", key, entry.BaseURL)
|
||||
authIndex = liveIndexByID[id]
|
||||
}
|
||||
out[i] = geminiKeyWithAuthIndex{
|
||||
GeminiKey: entry,
|
||||
AuthIndex: authIndex,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Handler) claudeKeysWithAuthIndex() []claudeKeyWithAuthIndex {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
liveIndexByID := h.liveAuthIndexByID()
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
idGen := synthesizer.NewStableIDGenerator()
|
||||
out := make([]claudeKeyWithAuthIndex, len(h.cfg.ClaudeKey))
|
||||
for i := range h.cfg.ClaudeKey {
|
||||
entry := h.cfg.ClaudeKey[i]
|
||||
authIndex := ""
|
||||
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
||||
id, _ := idGen.Next("claude:apikey", key, entry.BaseURL)
|
||||
authIndex = liveIndexByID[id]
|
||||
}
|
||||
out[i] = claudeKeyWithAuthIndex{
|
||||
ClaudeKey: entry,
|
||||
AuthIndex: authIndex,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Handler) codexKeysWithAuthIndex() []codexKeyWithAuthIndex {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
liveIndexByID := h.liveAuthIndexByID()
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
idGen := synthesizer.NewStableIDGenerator()
|
||||
out := make([]codexKeyWithAuthIndex, len(h.cfg.CodexKey))
|
||||
for i := range h.cfg.CodexKey {
|
||||
entry := h.cfg.CodexKey[i]
|
||||
authIndex := ""
|
||||
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
||||
id, _ := idGen.Next("codex:apikey", key, entry.BaseURL)
|
||||
authIndex = liveIndexByID[id]
|
||||
}
|
||||
out[i] = codexKeyWithAuthIndex{
|
||||
CodexKey: entry,
|
||||
AuthIndex: authIndex,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Handler) vertexCompatKeysWithAuthIndex() []vertexCompatKeyWithAuthIndex {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
liveIndexByID := h.liveAuthIndexByID()
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
idGen := synthesizer.NewStableIDGenerator()
|
||||
out := make([]vertexCompatKeyWithAuthIndex, len(h.cfg.VertexCompatAPIKey))
|
||||
for i := range h.cfg.VertexCompatAPIKey {
|
||||
entry := h.cfg.VertexCompatAPIKey[i]
|
||||
id, _ := idGen.Next("vertex:apikey", entry.APIKey, entry.BaseURL, entry.ProxyURL)
|
||||
authIndex := liveIndexByID[id]
|
||||
out[i] = vertexCompatKeyWithAuthIndex{
|
||||
VertexCompatKey: entry,
|
||||
AuthIndex: authIndex,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (h *Handler) openAICompatibilityWithAuthIndex() []openAICompatibilityWithAuthIndex {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
liveIndexByID := h.liveAuthIndexByID()
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
normalized := normalizedOpenAICompatibilityEntries(h.cfg.OpenAICompatibility)
|
||||
out := make([]openAICompatibilityWithAuthIndex, len(normalized))
|
||||
idGen := synthesizer.NewStableIDGenerator()
|
||||
for i := range normalized {
|
||||
entry := normalized[i]
|
||||
providerName := strings.ToLower(strings.TrimSpace(entry.Name))
|
||||
if providerName == "" {
|
||||
providerName = "openai-compatibility"
|
||||
}
|
||||
idKind := fmt.Sprintf("openai-compatibility:%s", providerName)
|
||||
|
||||
response := openAICompatibilityWithAuthIndex{
|
||||
Name: entry.Name,
|
||||
Priority: entry.Priority,
|
||||
Disabled: entry.Disabled,
|
||||
Prefix: entry.Prefix,
|
||||
BaseURL: entry.BaseURL,
|
||||
Models: entry.Models,
|
||||
Headers: entry.Headers,
|
||||
AuthIndex: "",
|
||||
}
|
||||
if len(entry.APIKeyEntries) == 0 {
|
||||
id, _ := idGen.Next(idKind, entry.BaseURL)
|
||||
response.AuthIndex = liveIndexByID[id]
|
||||
} else {
|
||||
response.APIKeyEntries = make([]openAICompatibilityAPIKeyWithAuthIndex, len(entry.APIKeyEntries))
|
||||
for j := range entry.APIKeyEntries {
|
||||
apiKeyEntry := entry.APIKeyEntries[j]
|
||||
id, _ := idGen.Next(idKind, apiKeyEntry.APIKey, entry.BaseURL, apiKeyEntry.ProxyURL)
|
||||
response.APIKeyEntries[j] = openAICompatibilityAPIKeyWithAuthIndex{
|
||||
OpenAICompatibilityAPIKey: apiKeyEntry,
|
||||
AuthIndex: liveIndexByID[id],
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = response
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -11,9 +11,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
// Generic helpers for list[string]
|
||||
@@ -120,7 +120,7 @@ func (h *Handler) DeleteAPIKeys(c *gin.Context) {
|
||||
|
||||
// gemini-api-key: []GeminiKey
|
||||
func (h *Handler) GetGeminiKeys(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"gemini-api-key": h.cfg.GeminiKey})
|
||||
c.JSON(200, gin.H{"gemini-api-key": h.geminiKeysWithAuthIndex()})
|
||||
}
|
||||
func (h *Handler) PutGeminiKeys(c *gin.Context) {
|
||||
data, err := c.GetRawData()
|
||||
@@ -139,9 +139,11 @@ func (h *Handler) PutGeminiKeys(c *gin.Context) {
|
||||
}
|
||||
arr = obj.Items
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.cfg.GeminiKey = append([]config.GeminiKey(nil), arr...)
|
||||
h.cfg.SanitizeGeminiKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
func (h *Handler) PatchGeminiKey(c *gin.Context) {
|
||||
type geminiKeyPatch struct {
|
||||
@@ -161,6 +163,9 @@ func (h *Handler) PatchGeminiKey(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
targetIndex := -1
|
||||
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.GeminiKey) {
|
||||
targetIndex = *body.Index
|
||||
@@ -187,7 +192,7 @@ func (h *Handler) PatchGeminiKey(c *gin.Context) {
|
||||
if trimmed == "" {
|
||||
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:targetIndex], h.cfg.GeminiKey[targetIndex+1:]...)
|
||||
h.cfg.SanitizeGeminiKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
entry.APIKey = trimmed
|
||||
@@ -209,24 +214,53 @@ func (h *Handler) PatchGeminiKey(c *gin.Context) {
|
||||
}
|
||||
h.cfg.GeminiKey[targetIndex] = entry
|
||||
h.cfg.SanitizeGeminiKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteGeminiKey(c *gin.Context) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
||||
out := make([]config.GeminiKey, 0, len(h.cfg.GeminiKey))
|
||||
for _, v := range h.cfg.GeminiKey {
|
||||
if v.APIKey != val {
|
||||
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
||||
base := strings.TrimSpace(baseRaw)
|
||||
out := make([]config.GeminiKey, 0, len(h.cfg.GeminiKey))
|
||||
for _, v := range h.cfg.GeminiKey {
|
||||
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
||||
continue
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
if len(out) != len(h.cfg.GeminiKey) {
|
||||
h.cfg.GeminiKey = out
|
||||
h.cfg.SanitizeGeminiKeys()
|
||||
h.persistLocked(c)
|
||||
} else {
|
||||
c.JSON(404, gin.H{"error": "item not found"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(out) != len(h.cfg.GeminiKey) {
|
||||
h.cfg.GeminiKey = out
|
||||
h.cfg.SanitizeGeminiKeys()
|
||||
h.persist(c)
|
||||
} else {
|
||||
|
||||
matchIndex := -1
|
||||
matchCount := 0
|
||||
for i := range h.cfg.GeminiKey {
|
||||
if strings.TrimSpace(h.cfg.GeminiKey[i].APIKey) == val {
|
||||
matchCount++
|
||||
if matchIndex == -1 {
|
||||
matchIndex = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if matchCount == 0 {
|
||||
c.JSON(404, gin.H{"error": "item not found"})
|
||||
return
|
||||
}
|
||||
if matchCount > 1 {
|
||||
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
||||
return
|
||||
}
|
||||
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:matchIndex], h.cfg.GeminiKey[matchIndex+1:]...)
|
||||
h.cfg.SanitizeGeminiKeys()
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
if idxStr := c.Query("index"); idxStr != "" {
|
||||
@@ -234,7 +268,7 @@ func (h *Handler) DeleteGeminiKey(c *gin.Context) {
|
||||
if _, err := fmt.Sscanf(idxStr, "%d", &idx); err == nil && idx >= 0 && idx < len(h.cfg.GeminiKey) {
|
||||
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:idx], h.cfg.GeminiKey[idx+1:]...)
|
||||
h.cfg.SanitizeGeminiKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -243,7 +277,7 @@ func (h *Handler) DeleteGeminiKey(c *gin.Context) {
|
||||
|
||||
// claude-api-key: []ClaudeKey
|
||||
func (h *Handler) GetClaudeKeys(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"claude-api-key": h.cfg.ClaudeKey})
|
||||
c.JSON(200, gin.H{"claude-api-key": h.claudeKeysWithAuthIndex()})
|
||||
}
|
||||
func (h *Handler) PutClaudeKeys(c *gin.Context) {
|
||||
data, err := c.GetRawData()
|
||||
@@ -265,9 +299,11 @@ func (h *Handler) PutClaudeKeys(c *gin.Context) {
|
||||
for i := range arr {
|
||||
normalizeClaudeKey(&arr[i])
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.cfg.ClaudeKey = arr
|
||||
h.cfg.SanitizeClaudeKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
func (h *Handler) PatchClaudeKey(c *gin.Context) {
|
||||
type claudeKeyPatch struct {
|
||||
@@ -288,6 +324,9 @@ func (h *Handler) PatchClaudeKey(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
targetIndex := -1
|
||||
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.ClaudeKey) {
|
||||
targetIndex = *body.Index
|
||||
@@ -331,20 +370,47 @@ func (h *Handler) PatchClaudeKey(c *gin.Context) {
|
||||
normalizeClaudeKey(&entry)
|
||||
h.cfg.ClaudeKey[targetIndex] = entry
|
||||
h.cfg.SanitizeClaudeKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteClaudeKey(c *gin.Context) {
|
||||
if val := c.Query("api-key"); val != "" {
|
||||
out := make([]config.ClaudeKey, 0, len(h.cfg.ClaudeKey))
|
||||
for _, v := range h.cfg.ClaudeKey {
|
||||
if v.APIKey != val {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
||||
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
||||
base := strings.TrimSpace(baseRaw)
|
||||
out := make([]config.ClaudeKey, 0, len(h.cfg.ClaudeKey))
|
||||
for _, v := range h.cfg.ClaudeKey {
|
||||
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
||||
continue
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
h.cfg.ClaudeKey = out
|
||||
h.cfg.SanitizeClaudeKeys()
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
|
||||
matchIndex := -1
|
||||
matchCount := 0
|
||||
for i := range h.cfg.ClaudeKey {
|
||||
if strings.TrimSpace(h.cfg.ClaudeKey[i].APIKey) == val {
|
||||
matchCount++
|
||||
if matchIndex == -1 {
|
||||
matchIndex = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if matchCount > 1 {
|
||||
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
||||
return
|
||||
}
|
||||
if matchIndex != -1 {
|
||||
h.cfg.ClaudeKey = append(h.cfg.ClaudeKey[:matchIndex], h.cfg.ClaudeKey[matchIndex+1:]...)
|
||||
}
|
||||
h.cfg.ClaudeKey = out
|
||||
h.cfg.SanitizeClaudeKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
if idxStr := c.Query("index"); idxStr != "" {
|
||||
@@ -353,7 +419,7 @@ func (h *Handler) DeleteClaudeKey(c *gin.Context) {
|
||||
if err == nil && idx >= 0 && idx < len(h.cfg.ClaudeKey) {
|
||||
h.cfg.ClaudeKey = append(h.cfg.ClaudeKey[:idx], h.cfg.ClaudeKey[idx+1:]...)
|
||||
h.cfg.SanitizeClaudeKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -362,7 +428,7 @@ func (h *Handler) DeleteClaudeKey(c *gin.Context) {
|
||||
|
||||
// openai-compatibility: []OpenAICompatibility
|
||||
func (h *Handler) GetOpenAICompat(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"openai-compatibility": normalizedOpenAICompatibilityEntries(h.cfg.OpenAICompatibility)})
|
||||
c.JSON(200, gin.H{"openai-compatibility": h.openAICompatibilityWithAuthIndex()})
|
||||
}
|
||||
func (h *Handler) PutOpenAICompat(c *gin.Context) {
|
||||
data, err := c.GetRawData()
|
||||
@@ -388,14 +454,17 @@ func (h *Handler) PutOpenAICompat(c *gin.Context) {
|
||||
filtered = append(filtered, arr[i])
|
||||
}
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.cfg.OpenAICompatibility = filtered
|
||||
h.cfg.SanitizeOpenAICompatibility()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
func (h *Handler) PatchOpenAICompat(c *gin.Context) {
|
||||
type openAICompatPatch struct {
|
||||
Name *string `json:"name"`
|
||||
Prefix *string `json:"prefix"`
|
||||
Disabled *bool `json:"disabled"`
|
||||
BaseURL *string `json:"base-url"`
|
||||
APIKeyEntries *[]config.OpenAICompatibilityAPIKey `json:"api-key-entries"`
|
||||
Models *[]config.OpenAICompatibilityModel `json:"models"`
|
||||
@@ -410,6 +479,9 @@ func (h *Handler) PatchOpenAICompat(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
targetIndex := -1
|
||||
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.OpenAICompatibility) {
|
||||
targetIndex = *body.Index
|
||||
@@ -435,12 +507,15 @@ func (h *Handler) PatchOpenAICompat(c *gin.Context) {
|
||||
if body.Value.Prefix != nil {
|
||||
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
||||
}
|
||||
if body.Value.Disabled != nil {
|
||||
entry.Disabled = *body.Value.Disabled
|
||||
}
|
||||
if body.Value.BaseURL != nil {
|
||||
trimmed := strings.TrimSpace(*body.Value.BaseURL)
|
||||
if trimmed == "" {
|
||||
h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:targetIndex], h.cfg.OpenAICompatibility[targetIndex+1:]...)
|
||||
h.cfg.SanitizeOpenAICompatibility()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
entry.BaseURL = trimmed
|
||||
@@ -457,10 +532,12 @@ func (h *Handler) PatchOpenAICompat(c *gin.Context) {
|
||||
normalizeOpenAICompatibilityEntry(&entry)
|
||||
h.cfg.OpenAICompatibility[targetIndex] = entry
|
||||
h.cfg.SanitizeOpenAICompatibility()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if name := c.Query("name"); name != "" {
|
||||
out := make([]config.OpenAICompatibility, 0, len(h.cfg.OpenAICompatibility))
|
||||
for _, v := range h.cfg.OpenAICompatibility {
|
||||
@@ -470,7 +547,7 @@ func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
|
||||
}
|
||||
h.cfg.OpenAICompatibility = out
|
||||
h.cfg.SanitizeOpenAICompatibility()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
if idxStr := c.Query("index"); idxStr != "" {
|
||||
@@ -479,7 +556,7 @@ func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
|
||||
if err == nil && idx >= 0 && idx < len(h.cfg.OpenAICompatibility) {
|
||||
h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:idx], h.cfg.OpenAICompatibility[idx+1:]...)
|
||||
h.cfg.SanitizeOpenAICompatibility()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -488,7 +565,7 @@ func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
|
||||
|
||||
// vertex-api-key: []VertexCompatKey
|
||||
func (h *Handler) GetVertexCompatKeys(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"vertex-api-key": h.cfg.VertexCompatAPIKey})
|
||||
c.JSON(200, gin.H{"vertex-api-key": h.vertexCompatKeysWithAuthIndex()})
|
||||
}
|
||||
func (h *Handler) PutVertexCompatKeys(c *gin.Context) {
|
||||
data, err := c.GetRawData()
|
||||
@@ -514,9 +591,11 @@ func (h *Handler) PutVertexCompatKeys(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.cfg.VertexCompatAPIKey = append([]config.VertexCompatKey(nil), arr...)
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
func (h *Handler) PatchVertexCompatKey(c *gin.Context) {
|
||||
type vertexCompatPatch struct {
|
||||
@@ -537,6 +616,9 @@ func (h *Handler) PatchVertexCompatKey(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
targetIndex := -1
|
||||
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.VertexCompatAPIKey) {
|
||||
targetIndex = *body.Index
|
||||
@@ -563,7 +645,7 @@ func (h *Handler) PatchVertexCompatKey(c *gin.Context) {
|
||||
if trimmed == "" {
|
||||
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:targetIndex], h.cfg.VertexCompatAPIKey[targetIndex+1:]...)
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
entry.APIKey = trimmed
|
||||
@@ -576,7 +658,7 @@ func (h *Handler) PatchVertexCompatKey(c *gin.Context) {
|
||||
if trimmed == "" {
|
||||
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:targetIndex], h.cfg.VertexCompatAPIKey[targetIndex+1:]...)
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
entry.BaseURL = trimmed
|
||||
@@ -596,20 +678,47 @@ func (h *Handler) PatchVertexCompatKey(c *gin.Context) {
|
||||
normalizeVertexCompatKey(&entry)
|
||||
h.cfg.VertexCompatAPIKey[targetIndex] = entry
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteVertexCompatKey(c *gin.Context) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
||||
out := make([]config.VertexCompatKey, 0, len(h.cfg.VertexCompatAPIKey))
|
||||
for _, v := range h.cfg.VertexCompatAPIKey {
|
||||
if v.APIKey != val {
|
||||
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
||||
base := strings.TrimSpace(baseRaw)
|
||||
out := make([]config.VertexCompatKey, 0, len(h.cfg.VertexCompatAPIKey))
|
||||
for _, v := range h.cfg.VertexCompatAPIKey {
|
||||
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
||||
continue
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
h.cfg.VertexCompatAPIKey = out
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
|
||||
matchIndex := -1
|
||||
matchCount := 0
|
||||
for i := range h.cfg.VertexCompatAPIKey {
|
||||
if strings.TrimSpace(h.cfg.VertexCompatAPIKey[i].APIKey) == val {
|
||||
matchCount++
|
||||
if matchIndex == -1 {
|
||||
matchIndex = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if matchCount > 1 {
|
||||
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
||||
return
|
||||
}
|
||||
if matchIndex != -1 {
|
||||
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:matchIndex], h.cfg.VertexCompatAPIKey[matchIndex+1:]...)
|
||||
}
|
||||
h.cfg.VertexCompatAPIKey = out
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
if idxStr := c.Query("index"); idxStr != "" {
|
||||
@@ -618,7 +727,7 @@ func (h *Handler) DeleteVertexCompatKey(c *gin.Context) {
|
||||
if errScan == nil && idx >= 0 && idx < len(h.cfg.VertexCompatAPIKey) {
|
||||
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:idx], h.cfg.VertexCompatAPIKey[idx+1:]...)
|
||||
h.cfg.SanitizeVertexCompatKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -809,7 +918,7 @@ func (h *Handler) DeleteOAuthModelAlias(c *gin.Context) {
|
||||
|
||||
// codex-api-key: []CodexKey
|
||||
func (h *Handler) GetCodexKeys(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"codex-api-key": h.cfg.CodexKey})
|
||||
c.JSON(200, gin.H{"codex-api-key": h.codexKeysWithAuthIndex()})
|
||||
}
|
||||
func (h *Handler) PutCodexKeys(c *gin.Context) {
|
||||
data, err := c.GetRawData()
|
||||
@@ -838,9 +947,11 @@ func (h *Handler) PutCodexKeys(c *gin.Context) {
|
||||
}
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.cfg.CodexKey = filtered
|
||||
h.cfg.SanitizeCodexKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
func (h *Handler) PatchCodexKey(c *gin.Context) {
|
||||
type codexKeyPatch struct {
|
||||
@@ -861,6 +972,9 @@ func (h *Handler) PatchCodexKey(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "invalid body"})
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
targetIndex := -1
|
||||
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.CodexKey) {
|
||||
targetIndex = *body.Index
|
||||
@@ -891,7 +1005,7 @@ func (h *Handler) PatchCodexKey(c *gin.Context) {
|
||||
if trimmed == "" {
|
||||
h.cfg.CodexKey = append(h.cfg.CodexKey[:targetIndex], h.cfg.CodexKey[targetIndex+1:]...)
|
||||
h.cfg.SanitizeCodexKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
entry.BaseURL = trimmed
|
||||
@@ -911,20 +1025,47 @@ func (h *Handler) PatchCodexKey(c *gin.Context) {
|
||||
normalizeCodexKey(&entry)
|
||||
h.cfg.CodexKey[targetIndex] = entry
|
||||
h.cfg.SanitizeCodexKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteCodexKey(c *gin.Context) {
|
||||
if val := c.Query("api-key"); val != "" {
|
||||
out := make([]config.CodexKey, 0, len(h.cfg.CodexKey))
|
||||
for _, v := range h.cfg.CodexKey {
|
||||
if v.APIKey != val {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
||||
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
||||
base := strings.TrimSpace(baseRaw)
|
||||
out := make([]config.CodexKey, 0, len(h.cfg.CodexKey))
|
||||
for _, v := range h.cfg.CodexKey {
|
||||
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
||||
continue
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
h.cfg.CodexKey = out
|
||||
h.cfg.SanitizeCodexKeys()
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
|
||||
matchIndex := -1
|
||||
matchCount := 0
|
||||
for i := range h.cfg.CodexKey {
|
||||
if strings.TrimSpace(h.cfg.CodexKey[i].APIKey) == val {
|
||||
matchCount++
|
||||
if matchIndex == -1 {
|
||||
matchIndex = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if matchCount > 1 {
|
||||
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
||||
return
|
||||
}
|
||||
if matchIndex != -1 {
|
||||
h.cfg.CodexKey = append(h.cfg.CodexKey[:matchIndex], h.cfg.CodexKey[matchIndex+1:]...)
|
||||
}
|
||||
h.cfg.CodexKey = out
|
||||
h.cfg.SanitizeCodexKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
if idxStr := c.Query("index"); idxStr != "" {
|
||||
@@ -933,7 +1074,7 @@ func (h *Handler) DeleteCodexKey(c *gin.Context) {
|
||||
if err == nil && idx >= 0 && idx < len(h.cfg.CodexKey) {
|
||||
h.cfg.CodexKey = append(h.cfg.CodexKey[:idx], h.cfg.CodexKey[idx+1:]...)
|
||||
h.cfg.SanitizeCodexKeys()
|
||||
h.persist(c)
|
||||
h.persistLocked(c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
func writeTestConfigFile(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
if errWrite := os.WriteFile(path, []byte("{}\n"), 0o600); errWrite != nil {
|
||||
t.Fatalf("failed to write test config: %v", errWrite)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestDeleteGeminiKey_RequiresBaseURLWhenAPIKeyDuplicated(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
GeminiKey: []config.GeminiKey{
|
||||
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
||||
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
||||
},
|
||||
},
|
||||
configFilePath: writeTestConfigFile(t),
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/gemini-api-key?api-key=shared-key", nil)
|
||||
|
||||
h.DeleteGeminiKey(c)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
if got := len(h.cfg.GeminiKey); got != 2 {
|
||||
t.Fatalf("gemini keys len = %d, want 2", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteGeminiKey_DeletesOnlyMatchingBaseURL(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
GeminiKey: []config.GeminiKey{
|
||||
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
||||
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
||||
},
|
||||
},
|
||||
configFilePath: writeTestConfigFile(t),
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/gemini-api-key?api-key=shared-key&base-url=https://a.example.com", nil)
|
||||
|
||||
h.DeleteGeminiKey(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
if got := len(h.cfg.GeminiKey); got != 1 {
|
||||
t.Fatalf("gemini keys len = %d, want 1", got)
|
||||
}
|
||||
if got := h.cfg.GeminiKey[0].BaseURL; got != "https://b.example.com" {
|
||||
t.Fatalf("remaining base-url = %q, want %q", got, "https://b.example.com")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteClaudeKey_DeletesEmptyBaseURLWhenExplicitlyProvided(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
ClaudeKey: []config.ClaudeKey{
|
||||
{APIKey: "shared-key", BaseURL: ""},
|
||||
{APIKey: "shared-key", BaseURL: "https://claude.example.com"},
|
||||
},
|
||||
},
|
||||
configFilePath: writeTestConfigFile(t),
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/claude-api-key?api-key=shared-key&base-url=", nil)
|
||||
|
||||
h.DeleteClaudeKey(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
if got := len(h.cfg.ClaudeKey); got != 1 {
|
||||
t.Fatalf("claude keys len = %d, want 1", got)
|
||||
}
|
||||
if got := h.cfg.ClaudeKey[0].BaseURL; got != "https://claude.example.com" {
|
||||
t.Fatalf("remaining base-url = %q, want %q", got, "https://claude.example.com")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteVertexCompatKey_DeletesOnlyMatchingBaseURL(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
VertexCompatAPIKey: []config.VertexCompatKey{
|
||||
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
||||
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
||||
},
|
||||
},
|
||||
configFilePath: writeTestConfigFile(t),
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/vertex-api-key?api-key=shared-key&base-url=https://b.example.com", nil)
|
||||
|
||||
h.DeleteVertexCompatKey(c)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
if got := len(h.cfg.VertexCompatAPIKey); got != 1 {
|
||||
t.Fatalf("vertex keys len = %d, want 1", got)
|
||||
}
|
||||
if got := h.cfg.VertexCompatAPIKey[0].BaseURL; got != "https://a.example.com" {
|
||||
t.Fatalf("remaining base-url = %q, want %q", got, "https://a.example.com")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteCodexKey_RequiresBaseURLWhenAPIKeyDuplicated(t *testing.T) {
|
||||
t.Parallel()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
h := &Handler{
|
||||
cfg: &config.Config{
|
||||
CodexKey: []config.CodexKey{
|
||||
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
||||
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
||||
},
|
||||
},
|
||||
configFilePath: writeTestConfigFile(t),
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/codex-api-key?api-key=shared-key", nil)
|
||||
|
||||
h.DeleteCodexKey(c)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
if got := len(h.cfg.CodexKey); got != 2 {
|
||||
t.Fatalf("codex keys len = %d, want 2", got)
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
// ImportCredential handles uploading a text file with credentials for a specific provider.
|
||||
|
||||
@@ -13,12 +13,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/integrations"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
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/v7/internal/buildinfo"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/integrations"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
@@ -44,7 +43,6 @@ type Handler struct {
|
||||
attemptsMu sync.Mutex
|
||||
failedAttempts map[string]*attemptInfo // keyed by client IP
|
||||
authManager *coreauth.Manager
|
||||
usageStats *usage.RequestStatistics
|
||||
tokenStore coreauth.Store
|
||||
localPassword string
|
||||
allowRemoteOverride bool
|
||||
@@ -66,7 +64,6 @@ func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Man
|
||||
configFilePath: configFilePath,
|
||||
failedAttempts: make(map[string]*attemptInfo),
|
||||
authManager: manager,
|
||||
usageStats: usage.GetRequestStatistics(),
|
||||
tokenStore: sdkAuth.GetTokenStore(),
|
||||
allowRemoteOverride: envSecret != "",
|
||||
envSecret: envSecret,
|
||||
@@ -113,6 +110,9 @@ 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) {
|
||||
clonedCfg := cloneConfig(cfg)
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
h.cfg = clonedCfg
|
||||
h.committedCfg = cloneConfig(clonedCfg)
|
||||
@@ -120,10 +120,14 @@ func (h *Handler) SetConfig(cfg *config.Config) {
|
||||
}
|
||||
|
||||
// SetAuthManager updates the auth manager reference used by management endpoints.
|
||||
func (h *Handler) SetAuthManager(manager *coreauth.Manager) { h.authManager = manager }
|
||||
|
||||
// SetUsageStatistics allows replacing the usage statistics reference.
|
||||
func (h *Handler) SetUsageStatistics(stats *usage.RequestStatistics) { h.usageStats = stats }
|
||||
func (h *Handler) SetAuthManager(manager *coreauth.Manager) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
h.authManager = manager
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetLocalPassword configures the runtime-local password accepted for localhost requests.
|
||||
func (h *Handler) SetLocalPassword(password string) { h.localPassword = password }
|
||||
@@ -150,9 +154,6 @@ func (h *Handler) SetPostAuthHook(hook coreauth.PostAuthHook) {
|
||||
// All requests (local and remote) require a valid management key.
|
||||
// Additionally, remote access requires allow-remote-management=true.
|
||||
func (h *Handler) Middleware() gin.HandlerFunc {
|
||||
const maxFailures = 5
|
||||
const banDuration = 30 * time.Minute
|
||||
|
||||
return func(c *gin.Context) {
|
||||
c.Header("X-CPA-VERSION", buildinfo.Version)
|
||||
c.Header("X-CPA-COMMIT", buildinfo.Commit)
|
||||
@@ -160,64 +161,6 @@ func (h *Handler) Middleware() gin.HandlerFunc {
|
||||
|
||||
clientIP := c.ClientIP()
|
||||
localClient := clientIP == "127.0.0.1" || clientIP == "::1"
|
||||
cfg := h.cfg
|
||||
var (
|
||||
allowRemote bool
|
||||
secretHash string
|
||||
)
|
||||
if cfg != nil {
|
||||
allowRemote = cfg.RemoteManagement.AllowRemote
|
||||
secretHash = cfg.RemoteManagement.SecretKey
|
||||
}
|
||||
if h.allowRemoteOverride {
|
||||
allowRemote = true
|
||||
}
|
||||
envSecret := h.envSecret
|
||||
|
||||
fail := func() {}
|
||||
if !localClient {
|
||||
h.attemptsMu.Lock()
|
||||
ai := h.failedAttempts[clientIP]
|
||||
if ai != nil {
|
||||
if !ai.blockedUntil.IsZero() {
|
||||
if time.Now().Before(ai.blockedUntil) {
|
||||
remaining := time.Until(ai.blockedUntil).Round(time.Second)
|
||||
h.attemptsMu.Unlock()
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": fmt.Sprintf("IP banned due to too many failed attempts. Try again in %s", remaining)})
|
||||
return
|
||||
}
|
||||
// Ban expired, reset state
|
||||
ai.blockedUntil = time.Time{}
|
||||
ai.count = 0
|
||||
}
|
||||
}
|
||||
h.attemptsMu.Unlock()
|
||||
|
||||
if !allowRemote {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "remote management disabled"})
|
||||
return
|
||||
}
|
||||
|
||||
fail = func() {
|
||||
h.attemptsMu.Lock()
|
||||
aip := h.failedAttempts[clientIP]
|
||||
if aip == nil {
|
||||
aip = &attemptInfo{}
|
||||
h.failedAttempts[clientIP] = aip
|
||||
}
|
||||
aip.count++
|
||||
aip.lastActivity = time.Now()
|
||||
if aip.count >= maxFailures {
|
||||
aip.blockedUntil = time.Now().Add(banDuration)
|
||||
aip.count = 0
|
||||
}
|
||||
h.attemptsMu.Unlock()
|
||||
}
|
||||
}
|
||||
if secretHash == "" && envSecret == "" {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "remote management key not set"})
|
||||
return
|
||||
}
|
||||
|
||||
// Accept either Authorization: Bearer <key> or X-Management-Key
|
||||
var provided string
|
||||
@@ -233,57 +176,116 @@ func (h *Handler) Middleware() gin.HandlerFunc {
|
||||
provided = c.GetHeader("X-Management-Key")
|
||||
}
|
||||
|
||||
if provided == "" {
|
||||
if !localClient {
|
||||
fail()
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing management key"})
|
||||
allowed, statusCode, errMsg := h.AuthenticateManagementKey(clientIP, localClient, provided)
|
||||
if !allowed {
|
||||
c.AbortWithStatusJSON(statusCode, gin.H{"error": errMsg})
|
||||
return
|
||||
}
|
||||
|
||||
if localClient {
|
||||
if lp := h.localPassword; lp != "" {
|
||||
if subtle.ConstantTimeCompare([]byte(provided), []byte(lp)) == 1 {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if envSecret != "" && subtle.ConstantTimeCompare([]byte(provided), []byte(envSecret)) == 1 {
|
||||
if !localClient {
|
||||
h.attemptsMu.Lock()
|
||||
if ai := h.failedAttempts[clientIP]; ai != nil {
|
||||
ai.count = 0
|
||||
ai.blockedUntil = time.Time{}
|
||||
}
|
||||
h.attemptsMu.Unlock()
|
||||
}
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
if secretHash == "" || bcrypt.CompareHashAndPassword([]byte(secretHash), []byte(provided)) != nil {
|
||||
if !localClient {
|
||||
fail()
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid management key"})
|
||||
return
|
||||
}
|
||||
|
||||
if !localClient {
|
||||
h.attemptsMu.Lock()
|
||||
if ai := h.failedAttempts[clientIP]; ai != nil {
|
||||
ai.count = 0
|
||||
ai.blockedUntil = time.Time{}
|
||||
}
|
||||
h.attemptsMu.Unlock()
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// AuthenticateManagementKey verifies the provided management key for the given client.
|
||||
// It mirrors the behaviour of Middleware() so non-HTTP callers can reuse the same logic.
|
||||
func (h *Handler) AuthenticateManagementKey(clientIP string, localClient bool, provided string) (bool, int, string) {
|
||||
const maxFailures = 5
|
||||
const banDuration = 30 * time.Minute
|
||||
|
||||
if h == nil {
|
||||
return false, http.StatusForbidden, "remote management disabled"
|
||||
}
|
||||
|
||||
cfg := h.cfg
|
||||
var (
|
||||
allowRemote bool
|
||||
secretHash string
|
||||
)
|
||||
if cfg != nil {
|
||||
allowRemote = cfg.RemoteManagement.AllowRemote
|
||||
secretHash = cfg.RemoteManagement.SecretKey
|
||||
}
|
||||
if h.allowRemoteOverride {
|
||||
allowRemote = true
|
||||
}
|
||||
envSecret := h.envSecret
|
||||
|
||||
now := time.Now()
|
||||
h.attemptsMu.Lock()
|
||||
ai := h.failedAttempts[clientIP]
|
||||
if ai != nil && !ai.blockedUntil.IsZero() {
|
||||
if now.Before(ai.blockedUntil) {
|
||||
remaining := ai.blockedUntil.Sub(now).Round(time.Second)
|
||||
h.attemptsMu.Unlock()
|
||||
return false, http.StatusForbidden, fmt.Sprintf("IP banned due to too many failed attempts. Try again in %s", remaining)
|
||||
}
|
||||
// Ban expired, reset state
|
||||
ai.blockedUntil = time.Time{}
|
||||
ai.count = 0
|
||||
}
|
||||
h.attemptsMu.Unlock()
|
||||
|
||||
if !localClient && !allowRemote {
|
||||
return false, http.StatusForbidden, "remote management disabled"
|
||||
}
|
||||
|
||||
fail := func() {
|
||||
h.attemptsMu.Lock()
|
||||
aip := h.failedAttempts[clientIP]
|
||||
if aip == nil {
|
||||
aip = &attemptInfo{}
|
||||
h.failedAttempts[clientIP] = aip
|
||||
}
|
||||
aip.count++
|
||||
aip.lastActivity = time.Now()
|
||||
if aip.count >= maxFailures {
|
||||
aip.blockedUntil = time.Now().Add(banDuration)
|
||||
aip.count = 0
|
||||
}
|
||||
h.attemptsMu.Unlock()
|
||||
}
|
||||
|
||||
reset := func() {
|
||||
h.attemptsMu.Lock()
|
||||
if ai := h.failedAttempts[clientIP]; ai != nil {
|
||||
ai.count = 0
|
||||
ai.blockedUntil = time.Time{}
|
||||
}
|
||||
h.attemptsMu.Unlock()
|
||||
}
|
||||
|
||||
if secretHash == "" && envSecret == "" {
|
||||
return false, http.StatusForbidden, "remote management key not set"
|
||||
}
|
||||
|
||||
if provided == "" {
|
||||
fail()
|
||||
return false, http.StatusUnauthorized, "missing management key"
|
||||
}
|
||||
|
||||
if localClient {
|
||||
if lp := h.localPassword; lp != "" {
|
||||
if subtle.ConstantTimeCompare([]byte(provided), []byte(lp)) == 1 {
|
||||
reset()
|
||||
return true, 0, ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if envSecret != "" && subtle.ConstantTimeCompare([]byte(provided), []byte(envSecret)) == 1 {
|
||||
reset()
|
||||
return true, 0, ""
|
||||
}
|
||||
|
||||
if secretHash == "" || bcrypt.CompareHashAndPassword([]byte(secretHash), []byte(provided)) != nil {
|
||||
fail()
|
||||
return false, http.StatusUnauthorized, "invalid management key"
|
||||
}
|
||||
|
||||
reset()
|
||||
|
||||
return true, 0, ""
|
||||
}
|
||||
|
||||
// persist saves the current in-memory config to disk.
|
||||
func (h *Handler) persist(c *gin.Context) bool {
|
||||
h.mu.Lock()
|
||||
@@ -311,6 +313,25 @@ func (h *Handler) persistConfig(c *gin.Context, next *config.Config) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// persistLocked saves the current in-memory config to disk.
|
||||
// It expects the caller to hold h.mu.
|
||||
func (h *Handler) persistLocked(c *gin.Context) bool {
|
||||
if h.cfg == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "config unavailable"})
|
||||
return false
|
||||
}
|
||||
current := cloneConfig(h.cfg)
|
||||
if err := saveConfigAtomically(h.configFilePath, current); 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 = current
|
||||
h.committedCfg = cloneConfig(current)
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
func TestAuthenticateManagementKey_LocalhostIPBan_BlocksCorrectKeyDuringBan(t *testing.T) {
|
||||
h := &Handler{
|
||||
cfg: &config.Config{},
|
||||
failedAttempts: make(map[string]*attemptInfo),
|
||||
envSecret: "test-secret",
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "wrong-secret")
|
||||
if allowed {
|
||||
t.Fatalf("expected auth to be denied at attempt %d", i+1)
|
||||
}
|
||||
if statusCode != http.StatusUnauthorized || errMsg != "invalid management key" {
|
||||
t.Fatalf("unexpected auth failure at attempt %d: status=%d msg=%q", i+1, statusCode, errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret")
|
||||
if allowed {
|
||||
t.Fatalf("expected correct key to be denied while banned")
|
||||
}
|
||||
if statusCode != http.StatusForbidden {
|
||||
t.Fatalf("expected forbidden status while banned, got %d", statusCode)
|
||||
}
|
||||
if !strings.HasPrefix(errMsg, "IP banned due to too many failed attempts. Try again in") {
|
||||
t.Fatalf("unexpected banned message: %q", errMsg)
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
|
||||
)
|
||||
|
||||
// GetHarnessFiles returns the list of harness files for a session.
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/integrations"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/integrations"
|
||||
)
|
||||
|
||||
// GetIntegrationsStatus returns the list of detected tools and their configuration status.
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
func TestDeleteMemorySession_RejectsTraversal(t *testing.T) {
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
|
||||
)
|
||||
|
||||
func (h *Handler) ListMemorySessions(c *gin.Context) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
)
|
||||
|
||||
func memoryBaseDir() string {
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
||||
)
|
||||
|
||||
// GetStaticModelDefinitions returns static model metadata for a given channel.
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
// ModelMappingEntry represents a global model mapping for the API
|
||||
|
||||
@@ -225,12 +225,8 @@ func NormalizeOAuthProvider(provider string) (string, error) {
|
||||
return "codex", nil
|
||||
case "gemini", "google":
|
||||
return "gemini", nil
|
||||
case "iflow", "i-flow":
|
||||
return "iflow", nil
|
||||
case "antigravity", "anti-gravity":
|
||||
return "antigravity", nil
|
||||
case "qwen":
|
||||
return "qwen", nil
|
||||
default:
|
||||
return "", errUnsupportedOAuthFlow
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/buildinfo"
|
||||
)
|
||||
|
||||
// GetProxyPilotLogTail returns tail lines for the launcher-managed stdout/stderr logs.
|
||||
|
||||
@@ -2,7 +2,7 @@ package management
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
// Quota exceeded toggles
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/middleware"
|
||||
)
|
||||
|
||||
// GetRequestHistory returns the persistent request history with optional filtering.
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/middleware"
|
||||
)
|
||||
|
||||
// GetRequests returns the list of recent requests from the in-memory ring buffer.
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
|
||||
)
|
||||
|
||||
func (h *Handler) GetSemanticHealth(c *gin.Context) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
type memoryAuthStore struct {
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
)
|
||||
|
||||
// ThinkingBudgetResponse represents the thinking budget settings response.
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/updates"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/updates"
|
||||
)
|
||||
|
||||
// updateState tracks the current update operation state.
|
||||
|
||||
@@ -2,78 +2,54 @@ package management
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/redisqueue"
|
||||
)
|
||||
|
||||
type usageExportPayload struct {
|
||||
Version int `json:"version"`
|
||||
ExportedAt time.Time `json:"exported_at"`
|
||||
Usage usage.StatisticsSnapshot `json:"usage"`
|
||||
}
|
||||
type usageQueueRecord []byte
|
||||
|
||||
type usageImportPayload struct {
|
||||
Version int `json:"version"`
|
||||
Usage usage.StatisticsSnapshot `json:"usage"`
|
||||
}
|
||||
|
||||
// GetUsageStatistics returns the in-memory request statistics snapshot.
|
||||
func (h *Handler) GetUsageStatistics(c *gin.Context) {
|
||||
var snapshot usage.StatisticsSnapshot
|
||||
if h != nil && h.usageStats != nil {
|
||||
snapshot = h.usageStats.Snapshot()
|
||||
func (r usageQueueRecord) MarshalJSON() ([]byte, error) {
|
||||
if json.Valid(r) {
|
||||
return append([]byte(nil), r...), nil
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"usage": snapshot,
|
||||
"failed_requests": snapshot.FailureCount,
|
||||
})
|
||||
return json.Marshal(string(r))
|
||||
}
|
||||
|
||||
// ExportUsageStatistics returns a complete usage snapshot for backup/migration.
|
||||
func (h *Handler) ExportUsageStatistics(c *gin.Context) {
|
||||
var snapshot usage.StatisticsSnapshot
|
||||
if h != nil && h.usageStats != nil {
|
||||
snapshot = h.usageStats.Snapshot()
|
||||
}
|
||||
c.JSON(http.StatusOK, usageExportPayload{
|
||||
Version: 1,
|
||||
ExportedAt: time.Now().UTC(),
|
||||
Usage: snapshot,
|
||||
})
|
||||
}
|
||||
|
||||
// ImportUsageStatistics merges a previously exported usage snapshot into memory.
|
||||
func (h *Handler) ImportUsageStatistics(c *gin.Context) {
|
||||
if h == nil || h.usageStats == nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "usage statistics unavailable"})
|
||||
// GetUsageQueue pops queued usage records from the usage queue.
|
||||
func (h *Handler) GetUsageQueue(c *gin.Context) {
|
||||
if h == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
|
||||
return
|
||||
}
|
||||
|
||||
data, err := c.GetRawData()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read request body"})
|
||||
count, errCount := parseUsageQueueCount(c.Query("count"))
|
||||
if errCount != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": errCount.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var payload usageImportPayload
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
if payload.Version != 0 && payload.Version != 1 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported version"})
|
||||
return
|
||||
items := redisqueue.PopOldest(count)
|
||||
records := make([]usageQueueRecord, 0, len(items))
|
||||
for _, item := range items {
|
||||
records = append(records, usageQueueRecord(append([]byte(nil), item...)))
|
||||
}
|
||||
|
||||
result := h.usageStats.MergeSnapshot(payload.Usage)
|
||||
snapshot := h.usageStats.Snapshot()
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"added": result.Added,
|
||||
"skipped": result.Skipped,
|
||||
"total_requests": snapshot.TotalRequests,
|
||||
"failed_requests": snapshot.FailureCount,
|
||||
})
|
||||
c.JSON(http.StatusOK, records)
|
||||
}
|
||||
|
||||
func parseUsageQueueCount(value string) (int, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return 1, nil
|
||||
}
|
||||
count, errCount := strconv.Atoi(value)
|
||||
if errCount != nil || count <= 0 {
|
||||
return 0, errors.New("count must be a positive integer")
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/redisqueue"
|
||||
)
|
||||
|
||||
func TestGetUsageQueuePopsRequestedRecords(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
withManagementUsageQueue(t, func() {
|
||||
redisqueue.Enqueue([]byte(`{"id":1}`))
|
||||
redisqueue.Enqueue([]byte(`{"id":2}`))
|
||||
redisqueue.Enqueue([]byte(`{"id":3}`))
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ginCtx, _ := gin.CreateTestContext(rec)
|
||||
ginCtx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/usage-queue?count=2", nil)
|
||||
|
||||
h := &Handler{}
|
||||
h.GetUsageQueue(ginCtx)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
||||
}
|
||||
|
||||
var payload []json.RawMessage
|
||||
if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &payload); errUnmarshal != nil {
|
||||
t.Fatalf("unmarshal response: %v", errUnmarshal)
|
||||
}
|
||||
if len(payload) != 2 {
|
||||
t.Fatalf("response records = %d, want 2", len(payload))
|
||||
}
|
||||
requireRecordID(t, payload[0], 1)
|
||||
requireRecordID(t, payload[1], 2)
|
||||
|
||||
remaining := redisqueue.PopOldest(10)
|
||||
if len(remaining) != 1 || string(remaining[0]) != `{"id":3}` {
|
||||
t.Fatalf("remaining queue = %q, want third item only", remaining)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetUsageQueueInvalidCountDoesNotPop(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
withManagementUsageQueue(t, func() {
|
||||
redisqueue.Enqueue([]byte(`{"id":1}`))
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
ginCtx, _ := gin.CreateTestContext(rec)
|
||||
ginCtx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/usage-queue?count=0", nil)
|
||||
|
||||
h := &Handler{}
|
||||
h.GetUsageQueue(ginCtx)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
|
||||
remaining := redisqueue.PopOldest(10)
|
||||
if len(remaining) != 1 || string(remaining[0]) != `{"id":1}` {
|
||||
t.Fatalf("remaining queue = %q, want original item", remaining)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func withManagementUsageQueue(t *testing.T, fn func()) {
|
||||
t.Helper()
|
||||
|
||||
prevQueueEnabled := redisqueue.Enabled()
|
||||
redisqueue.SetEnabled(false)
|
||||
redisqueue.SetEnabled(true)
|
||||
|
||||
defer func() {
|
||||
redisqueue.SetEnabled(false)
|
||||
redisqueue.SetEnabled(prevQueueEnabled)
|
||||
}()
|
||||
|
||||
fn()
|
||||
}
|
||||
|
||||
func requireRecordID(t *testing.T, raw json.RawMessage, want int) {
|
||||
t.Helper()
|
||||
|
||||
var payload struct {
|
||||
ID int `json:"id"`
|
||||
}
|
||||
if errUnmarshal := json.Unmarshal(raw, &payload); errUnmarshal != nil {
|
||||
t.Fatalf("unmarshal record: %v", errUnmarshal)
|
||||
}
|
||||
if payload.ID != want {
|
||||
t.Fatalf("record id = %d, want %d", payload.ID, want)
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/vertex"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/vertex"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
// ImportVertexCredential handles uploading a Vertex service account JSON and saving it as an auth record.
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/translator"
|
||||
)
|
||||
|
||||
// TranslatorHandler provides HTTP handlers for translation-related endpoints.
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/translator"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/runtime/executor"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/runtime/executor"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
@@ -9,10 +9,10 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/embeddings"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/embeddings"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/interfaces"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/usage"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
)
|
||||
|
||||
const maxErrorOnlyCapturedRequestBodyBytes int64 = 1 << 20 // 1 MiB
|
||||
|
||||
@@ -10,11 +10,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/interfaces"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
||||
)
|
||||
|
||||
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/v7/internal/interfaces"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/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
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/modules"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/modules"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v7/sdk/access"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
|
||||
@@ -9,10 +9,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/modules"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/modules"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
||||
sdkaccess "github.com/router-for-me/CLIProxyAPI/v7/sdk/access"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/sdk/api/handlers"
|
||||
)
|
||||
|
||||
func TestAmpModule_Name(t *testing.T) {
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/thinking"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/thinking"
|
||||
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
@@ -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))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user