@seaveyon/harness-switch 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +110 -0
- package/bin/harness-switch.js +180 -0
- package/package.json +38 -0
- package/public/app.js +17 -0
- package/public/index.html +3 -0
- package/public/style.css +1 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Harness Switch contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# harness-switch
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@seaveyon/harness-switch)
|
|
4
|
+
|
|
5
|
+
**harness-switch** is a dependency-free Node.js web control plane for managing API profiles on an SSH or headless server. It switches API Base URL, API key, and model profiles for **Claude Code**, **pi**, **Codex**, **zcode**, and **Kimi Code**.
|
|
6
|
+
|
|
7
|
+
It is a configuration manager, not an API proxy: it does not route or inspect model traffic.
|
|
8
|
+
|
|
9
|
+
## Install and run
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npx @seaveyon/harness-switch
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or install it globally:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install -g @seaveyon/harness-switch
|
|
19
|
+
harness-switch
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The server listens on `127.0.0.1:8787` by default. The first startup prints a randomly generated Web password in the terminal.
|
|
23
|
+
|
|
24
|
+
For a remote SSH server, keep the server bound to loopback and use an SSH tunnel:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
ssh -N -L 8787:127.0.0.1:8787 user@your-server
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Then open <http://127.0.0.1:8787> in your local browser.
|
|
31
|
+
|
|
32
|
+
## Configuration
|
|
33
|
+
|
|
34
|
+
Create one or more profiles per harness in the web UI. A profile contains a display name, API Base URL, API key, model, and notes. Select **Activate** to make a profile current.
|
|
35
|
+
|
|
36
|
+
Every activation writes `~/.harness-switch/env.sh`. In the exact SSH shell that launches a harness, load it with:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
source ~/.harness-switch/env.sh
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
| Harness | Activation behaviour | Environment variables |
|
|
43
|
+
|---|---|---|
|
|
44
|
+
| Claude Code | Updates `~/.claude/settings.json` and the shared env file | `ANTHROPIC_BASE_URL`, `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL` |
|
|
45
|
+
| Codex | Writes the shared env file without overwriting complex native config | `OPENAI_BASE_URL`, `OPENAI_API_KEY`, `CODEX_MODEL` |
|
|
46
|
+
| pi | Writes the shared env file without overwriting custom provider files | `PI_API_BASE`, `PI_API_KEY`, `PI_MODEL` |
|
|
47
|
+
| zcode | Writes the shared env file; variable names are a portable bridge | `ZCODE_BASE_URL`, `ZCODE_API_KEY`, `ZCODE_MODEL` |
|
|
48
|
+
| Kimi Code | Updates `~/.kimi/config.toml` and the shared env file | `KIMI_BASE_URL`, `KIMI_API_KEY`, `KIMI_MODEL` |
|
|
49
|
+
|
|
50
|
+
> The web UI changes files on the **server**; it cannot modify an existing parent shell or the browser computer. Source the generated file again after changing profiles, or use a new shell session.
|
|
51
|
+
|
|
52
|
+
## Security
|
|
53
|
+
|
|
54
|
+
The service defaults to loopback only. Do **not** expose the management port directly to the public Internet. Use SSH port forwarding or a TLS-enabled reverse proxy with additional access control.
|
|
55
|
+
|
|
56
|
+
API keys are encrypted with AES-256-GCM in `~/.harness-switch/profiles.json`; the local encryption key lives in `~/.harness-switch/aes-256-gcm.key`. Both files, the generated password, and `env.sh` are stored with permissions set to `0600` on POSIX systems. This protects against accidental plaintext disclosure in profile storage, but does not replace host-level controls such as disk encryption and a secure Unix account.
|
|
57
|
+
|
|
58
|
+
## Environment variables
|
|
59
|
+
|
|
60
|
+
| Variable | Default | Purpose |
|
|
61
|
+
|---|---:|---|
|
|
62
|
+
| `HOST` | `127.0.0.1` | Bind address. Keep the default when using SSH tunnelling. |
|
|
63
|
+
| `PORT` | `8787` | Listening port. |
|
|
64
|
+
| `HSW_DATA_DIR` | `~/.harness-switch` | Directory for encrypted profiles, active state, key, password, and env file. |
|
|
65
|
+
|
|
66
|
+
## systemd
|
|
67
|
+
|
|
68
|
+
Create `/etc/systemd/system/harness-switch.service`:
|
|
69
|
+
|
|
70
|
+
```ini
|
|
71
|
+
[Unit]
|
|
72
|
+
Description=Harness Switch Web Control Plane
|
|
73
|
+
After=network.target
|
|
74
|
+
|
|
75
|
+
[Service]
|
|
76
|
+
Type=simple
|
|
77
|
+
User=ubuntu
|
|
78
|
+
Environment=HOST=127.0.0.1
|
|
79
|
+
Environment=PORT=8787
|
|
80
|
+
ExecStart=/usr/bin/env harness-switch
|
|
81
|
+
Restart=on-failure
|
|
82
|
+
RestartSec=3
|
|
83
|
+
NoNewPrivileges=true
|
|
84
|
+
PrivateTmp=true
|
|
85
|
+
|
|
86
|
+
[Install]
|
|
87
|
+
WantedBy=multi-user.target
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Then run:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
sudo systemctl daemon-reload
|
|
94
|
+
sudo systemctl enable --now harness-switch
|
|
95
|
+
sudo journalctl -u harness-switch -f
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
git clone <your-repository-url>
|
|
102
|
+
cd harness-switch
|
|
103
|
+
npm test
|
|
104
|
+
npm start
|
|
105
|
+
npm pack --dry-run
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## License
|
|
109
|
+
|
|
110
|
+
[MIT](./LICENSE)
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const http = require('node:http');
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const fsp = require('node:fs/promises');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const os = require('node:os');
|
|
9
|
+
const crypto = require('node:crypto');
|
|
10
|
+
|
|
11
|
+
const APP_ROOT = path.resolve(__dirname, '..');
|
|
12
|
+
const DATA_DIR = process.env.HSW_DATA_DIR || path.join(os.homedir(), '.harness-switch');
|
|
13
|
+
const HOST = process.env.HOST || '127.0.0.1';
|
|
14
|
+
const PORT = Number(process.env.PORT || 8787);
|
|
15
|
+
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
16
|
+
const sessions = new Map();
|
|
17
|
+
const files = {
|
|
18
|
+
profiles: path.join(DATA_DIR, 'profiles.json'),
|
|
19
|
+
active: path.join(DATA_DIR, 'active.json'),
|
|
20
|
+
password: path.join(DATA_DIR, 'web_password'),
|
|
21
|
+
key: path.join(DATA_DIR, 'aes-256-gcm.key'),
|
|
22
|
+
env: path.join(DATA_DIR, 'env.sh'),
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const harnesses = {
|
|
26
|
+
claude: { label: 'Claude Code' },
|
|
27
|
+
pi: { label: 'pi' },
|
|
28
|
+
codex: { label: 'Codex' },
|
|
29
|
+
zcode: { label: 'zcode' },
|
|
30
|
+
kimi: { label: 'Kimi Code' },
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function ensureDir() { fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 }); }
|
|
34
|
+
function secureWrite(file, text) {
|
|
35
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
36
|
+
fs.writeFileSync(tmp, text, { encoding: 'utf8', mode: 0o600 });
|
|
37
|
+
fs.renameSync(tmp, file);
|
|
38
|
+
try { fs.chmodSync(file, 0o600); } catch { /* Windows has no POSIX file permissions */ }
|
|
39
|
+
}
|
|
40
|
+
function readJson(file, fallback = {}) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; } }
|
|
41
|
+
function writeJson(file, object) { secureWrite(file, `${JSON.stringify(object, null, 2)}\n`); }
|
|
42
|
+
function initSecret(file, bytes) {
|
|
43
|
+
if (!fs.existsSync(file)) secureWrite(file, crypto.randomBytes(bytes).toString('base64url') + '\n');
|
|
44
|
+
return Buffer.from(fs.readFileSync(file, 'utf8').trim(), 'base64url');
|
|
45
|
+
}
|
|
46
|
+
function getPassword() {
|
|
47
|
+
if (!fs.existsSync(files.password)) {
|
|
48
|
+
const password = crypto.randomBytes(18).toString('base64url');
|
|
49
|
+
secureWrite(files.password, `${password}\n`);
|
|
50
|
+
console.log(`[harness-switch] Initial web password: ${password}`);
|
|
51
|
+
}
|
|
52
|
+
return fs.readFileSync(files.password, 'utf8').trim();
|
|
53
|
+
}
|
|
54
|
+
function encrypt(plain) {
|
|
55
|
+
const key = initSecret(files.key, 32);
|
|
56
|
+
const iv = crypto.randomBytes(12);
|
|
57
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
58
|
+
const ciphertext = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
|
59
|
+
return { iv: iv.toString('base64url'), tag: cipher.getAuthTag().toString('base64url'), data: ciphertext.toString('base64url') };
|
|
60
|
+
}
|
|
61
|
+
function decrypt(value) {
|
|
62
|
+
try {
|
|
63
|
+
const key = initSecret(files.key, 32);
|
|
64
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(value.iv, 'base64url'));
|
|
65
|
+
decipher.setAuthTag(Buffer.from(value.tag, 'base64url'));
|
|
66
|
+
return Buffer.concat([decipher.update(Buffer.from(value.data, 'base64url')), decipher.final()]).toString('utf8');
|
|
67
|
+
} catch { return ''; }
|
|
68
|
+
}
|
|
69
|
+
function escapeToml(value) { return String(value || '').replace(/\\/g, '\\\\').replace(/"/g, '\\"'); }
|
|
70
|
+
function shellQuote(value) { return `'${String(value || '').replace(/'/g, `'"'"'`)}'`; }
|
|
71
|
+
function activeForResponse(active) {
|
|
72
|
+
return Object.fromEntries(Object.entries(active).map(([h, p]) => [h, { name: p.name, base_url: p.base_url, model: p.model || '' }]));
|
|
73
|
+
}
|
|
74
|
+
function profileForResponse(harness, name, profile) {
|
|
75
|
+
return { harness, name, base_url: profile.base_url || '', model: profile.model || '', notes: profile.notes || '', updated_at: profile.updated_at || '' };
|
|
76
|
+
}
|
|
77
|
+
function writeEnv(active) {
|
|
78
|
+
const map = {
|
|
79
|
+
claude: { ANTHROPIC_BASE_URL: 'base_url', ANTHROPIC_API_KEY: 'api_key', ANTHROPIC_MODEL: 'model' },
|
|
80
|
+
codex: { OPENAI_BASE_URL: 'base_url', OPENAI_API_KEY: 'api_key', CODEX_MODEL: 'model' },
|
|
81
|
+
pi: { PI_API_BASE: 'base_url', PI_API_KEY: 'api_key', PI_MODEL: 'model' },
|
|
82
|
+
zcode: { ZCODE_BASE_URL: 'base_url', ZCODE_API_KEY: 'api_key', ZCODE_MODEL: 'model' },
|
|
83
|
+
kimi: { KIMI_BASE_URL: 'base_url', KIMI_API_KEY: 'api_key', KIMI_MODEL: 'model' },
|
|
84
|
+
};
|
|
85
|
+
const lines = ['# Generated by harness-switch. Source this file in the shell where you launch your harness.', '# This file contains secrets. Do not commit it.'];
|
|
86
|
+
for (const [harness, profile] of Object.entries(active)) {
|
|
87
|
+
lines.push(`# ${harnesses[harness].label} / ${profile.name}`);
|
|
88
|
+
for (const [env, field] of Object.entries(map[harness])) if (profile[field]) lines.push(`export ${env}=${shellQuote(profile[field])}`);
|
|
89
|
+
}
|
|
90
|
+
secureWrite(files.env, `${lines.join('\n')}\n`);
|
|
91
|
+
}
|
|
92
|
+
function writeNativeConfig(harness, profile) {
|
|
93
|
+
const home = os.homedir();
|
|
94
|
+
if (harness === 'claude') {
|
|
95
|
+
const target = path.join(home, '.claude', 'settings.json');
|
|
96
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
97
|
+
const current = readJson(target, {});
|
|
98
|
+
current.env = { ...(current.env || {}), ANTHROPIC_BASE_URL: profile.base_url, ANTHROPIC_API_KEY: profile.api_key };
|
|
99
|
+
if (profile.model) current.env.ANTHROPIC_MODEL = profile.model;
|
|
100
|
+
secureWrite(target, `${JSON.stringify(current, null, 2)}\n`);
|
|
101
|
+
}
|
|
102
|
+
if (harness === 'kimi') {
|
|
103
|
+
const target = path.join(home, '.kimi', 'config.toml');
|
|
104
|
+
const model = profile.model || 'kimi-for-coding';
|
|
105
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
106
|
+
const content = `default_model = "${escapeToml(model)}"\n\n[providers.harness_switch]\ntype = "kimi"\nbase_url = "${escapeToml(profile.base_url)}"\napi_key = "${escapeToml(profile.api_key)}"\n\n[models.harness_switch_model]\nprovider = "harness_switch"\nmodel = "${escapeToml(model)}"\nmax_context_size = 262144\n`;
|
|
107
|
+
secureWrite(target, content);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function send(res, code, body, headers = {}) { res.writeHead(code, headers); res.end(body); }
|
|
111
|
+
function json(res, code, data) { send(res, code, JSON.stringify(data), { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }); }
|
|
112
|
+
function parseCookies(req) { return Object.fromEntries((req.headers.cookie || '').split(';').map(x => x.trim()).filter(Boolean).map(x => { const i = x.indexOf('='); return [x.slice(0, i), decodeURIComponent(x.slice(i + 1))]; })); }
|
|
113
|
+
function isAuthed(req) { const t = parseCookies(req).hsw_session; const entry = t && sessions.get(t); if (!entry || entry.expires < Date.now()) { if (t) sessions.delete(t); return false; } return true; }
|
|
114
|
+
function requireAuth(req, res) { if (isAuthed(req)) return true; if (req.url.startsWith('/api/')) json(res, 401, { error: 'authentication required' }); else send(res, 303, '', { Location: '/login' }); return false; }
|
|
115
|
+
function body(req) { return new Promise((resolve, reject) => { let raw = ''; req.on('data', c => { raw += c; if (raw.length > 1024 * 1024) req.destroy(); }); req.on('end', () => resolve(raw)); req.on('error', reject); }); }
|
|
116
|
+
function contentType(file) { return file.endsWith('.css') ? 'text/css; charset=utf-8' : file.endsWith('.js') ? 'text/javascript; charset=utf-8' : 'text/html; charset=utf-8'; }
|
|
117
|
+
function sendStatic(res, relative) {
|
|
118
|
+
const target = path.resolve(APP_ROOT, 'public', relative);
|
|
119
|
+
if (!target.startsWith(path.resolve(APP_ROOT, 'public') + path.sep) || !fs.existsSync(target)) return send(res, 404, 'Not found');
|
|
120
|
+
send(res, 200, fs.readFileSync(target), { 'Content-Type': contentType(target), 'X-Content-Type-Options': 'nosniff' });
|
|
121
|
+
}
|
|
122
|
+
function loginPage() { return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>harness-switch 登录</title><link rel="stylesheet" href="/static/style.css"></head><body class="auth"><form class="card auth-card" method="post" action="/login"><div class="eyebrow">HARNESS SWITCH</div><h1>服务器端配置中枢</h1><p class="muted">输入首次启动时终端打印的 Web 密码。</p><label>Web 密码<input type="password" name="password" autofocus required></label><button>登录</button></form></body></html>`; }
|
|
123
|
+
|
|
124
|
+
ensureDir();
|
|
125
|
+
const server = http.createServer(async (req, res) => {
|
|
126
|
+
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
|
127
|
+
try {
|
|
128
|
+
if (req.method === 'GET' && url.pathname === '/healthz') return json(res, 200, { ok: true });
|
|
129
|
+
if (req.method === 'GET' && url.pathname === '/login') return send(res, 200, loginPage(), { 'Content-Type': 'text/html; charset=utf-8' });
|
|
130
|
+
if (req.method === 'POST' && url.pathname === '/login') {
|
|
131
|
+
const form = new URLSearchParams(await body(req));
|
|
132
|
+
const provided = form.get('password') || '';
|
|
133
|
+
const expected = getPassword();
|
|
134
|
+
const match = Buffer.byteLength(provided) === Buffer.byteLength(expected) && crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(expected));
|
|
135
|
+
if (!match) return send(res, 303, '', { Location: '/login' });
|
|
136
|
+
const token = crypto.randomBytes(32).toString('base64url'); sessions.set(token, { expires: Date.now() + SESSION_TTL_MS });
|
|
137
|
+
return send(res, 303, '', { Location: '/', 'Set-Cookie': `hsw_session=${token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${SESSION_TTL_MS / 1000}` });
|
|
138
|
+
}
|
|
139
|
+
if (req.method === 'POST' && url.pathname === '/logout') { const t = parseCookies(req).hsw_session; if (t) sessions.delete(t); return send(res, 303, '', { Location: '/login', 'Set-Cookie': 'hsw_session=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0' }); }
|
|
140
|
+
if (url.pathname.startsWith('/static/')) return sendStatic(res, url.pathname.slice('/static/'.length));
|
|
141
|
+
if (req.method === 'GET' && url.pathname === '/') { if (!requireAuth(req, res)) return; return sendStatic(res, 'index.html'); }
|
|
142
|
+
if (url.pathname.startsWith('/api/')) {
|
|
143
|
+
if (!requireAuth(req, res)) return;
|
|
144
|
+
if (req.method !== 'GET' && req.headers.origin && req.headers.origin !== `http://${req.headers.host}` && req.headers.origin !== `https://${req.headers.host}`) return json(res, 403, { error: 'cross-origin request denied' });
|
|
145
|
+
if (req.method === 'GET' && url.pathname === '/api/state') {
|
|
146
|
+
const profiles = readJson(files.profiles, {}), active = readJson(files.active, {}), result = Object.fromEntries(Object.keys(harnesses).map(h => [h, []]));
|
|
147
|
+
for (const [h, entries] of Object.entries(profiles)) for (const [name, p] of Object.entries(entries || {})) if (harnesses[h]) result[h].push(profileForResponse(h, name, p));
|
|
148
|
+
return json(res, 200, { profiles: result, active: activeForResponse(active), env_file: files.env });
|
|
149
|
+
}
|
|
150
|
+
if (req.method === 'POST' && url.pathname === '/api/profile') {
|
|
151
|
+
const p = JSON.parse(await body(req)); const harness = p.harness; const name = String(p.name || '').trim();
|
|
152
|
+
if (!harnesses[harness] || !name) return json(res, 400, { error: 'harness and name are required' });
|
|
153
|
+
const profiles = readJson(files.profiles, {}); profiles[harness] ||= {}; const prior = profiles[harness][name] || {};
|
|
154
|
+
const apiKey = p.api_key || decrypt(prior.api_key || {});
|
|
155
|
+
profiles[harness][name] = { base_url: String(p.base_url || '').trim(), api_key: encrypt(apiKey), model: String(p.model || '').trim(), notes: String(p.notes || ''), updated_at: new Date().toISOString() };
|
|
156
|
+
writeJson(files.profiles, profiles); return json(res, 200, { ok: true });
|
|
157
|
+
}
|
|
158
|
+
if (req.method === 'POST' && url.pathname === '/api/activate') {
|
|
159
|
+
const p = JSON.parse(await body(req)); const profiles = readJson(files.profiles, {}); const stored = profiles[p.harness]?.[p.name];
|
|
160
|
+
if (!harnesses[p.harness] || !stored) return json(res, 404, { error: 'profile not found' });
|
|
161
|
+
const active = readJson(files.active, {}); const profile = { name: p.name, base_url: stored.base_url || '', api_key: decrypt(stored.api_key || {}), model: stored.model || '' };
|
|
162
|
+
active[p.harness] = profile; writeJson(files.active, active); writeNativeConfig(p.harness, profile); writeEnv(active);
|
|
163
|
+
return json(res, 200, { ok: true, env_file: files.env });
|
|
164
|
+
}
|
|
165
|
+
if (req.method === 'DELETE' && url.pathname.startsWith('/api/profile/')) {
|
|
166
|
+
const [, , , harness, ...parts] = url.pathname.split('/'); const name = decodeURIComponent(parts.join('/')); const profiles = readJson(files.profiles, {});
|
|
167
|
+
if (profiles[harness]?.[name]) { delete profiles[harness][name]; writeJson(files.profiles, profiles); }
|
|
168
|
+
return json(res, 200, { ok: true });
|
|
169
|
+
}
|
|
170
|
+
return json(res, 404, { error: 'not found' });
|
|
171
|
+
}
|
|
172
|
+
return send(res, 404, 'Not found');
|
|
173
|
+
} catch (err) { console.error(err); return json(res, 500, { error: 'internal server error' }); }
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
server.listen(PORT, HOST, () => {
|
|
177
|
+
getPassword(); initSecret(files.key, 32);
|
|
178
|
+
console.log(`[harness-switch] data directory: ${DATA_DIR}`);
|
|
179
|
+
console.log(`[harness-switch] listening on http://${HOST}:${PORT}`);
|
|
180
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@seaveyon/harness-switch",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A secure web control plane for switching API profiles across Claude Code, pi, Codex, zcode, and Kimi Code on SSH servers.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"claude-code",
|
|
7
|
+
"codex",
|
|
8
|
+
"kimi-code",
|
|
9
|
+
"zcode",
|
|
10
|
+
"pi",
|
|
11
|
+
"api-key",
|
|
12
|
+
"ssh",
|
|
13
|
+
"headless"
|
|
14
|
+
],
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"type": "commonjs",
|
|
17
|
+
"main": "bin/harness-switch.js",
|
|
18
|
+
"bin": {
|
|
19
|
+
"harness-switch": "bin/harness-switch.js"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"bin/",
|
|
23
|
+
"public/",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"start": "node bin/harness-switch.js",
|
|
29
|
+
"test": "node --check bin/harness-switch.js",
|
|
30
|
+
"pack:check": "npm pack --dry-run"
|
|
31
|
+
},
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=18"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/public/app.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const state = { data: null };
|
|
2
|
+
const labels = { claude: 'Claude Code', pi: 'pi', codex: 'Codex', zcode: 'zcode', kimi: 'Kimi Code' };
|
|
3
|
+
const esc = (s='') => String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
4
|
+
async function api(url, options={}) { const r = await fetch(url, {headers:{'Content-Type':'application/json'}, ...options}); const j = await r.json(); if(!r.ok) throw new Error(j.error || '请求失败'); return j; }
|
|
5
|
+
async function load() { state.data = await api('/api/state'); render(); }
|
|
6
|
+
function render() {
|
|
7
|
+
const root = document.querySelector('#cards');
|
|
8
|
+
root.innerHTML = Object.keys(labels).map(h => {
|
|
9
|
+
const profiles = state.data.profiles[h] || []; const active = state.data.active[h];
|
|
10
|
+
return `<article class="card harness"><div class="card-head"><div><div class="eyebrow">${h.toUpperCase()}</div><h3>${labels[h]}</h3></div><button class="small" onclick="openModal('${h}')">+ 新增</button></div><div class="active">当前:<strong>${active ? esc(active.name) : '未激活'}</strong>${active ? `<span class="dot"></span>` : ''}</div><div class="profiles">${profiles.length ? profiles.map(p => `<div class="profile"><div><strong>${esc(p.name)}</strong><span>${esc(p.base_url)}</span>${p.model ? `<small>${esc(p.model)}</small>` : ''}</div><div class="profile-actions"><button class="small ${active && active.name===p.name ? 'selected':''}" onclick="activate('${h}', ${JSON.stringify(p.name)})">${active && active.name===p.name ? '已激活' : '激活'}</button><button class="icon" title="删除" onclick="removeProfile('${h}', ${JSON.stringify(p.name)})">删除</button></div></div>`).join('') : '<div class="empty">还没有配置档案</div>'}</div></article>`;
|
|
11
|
+
}).join('');
|
|
12
|
+
}
|
|
13
|
+
function openModal(h, name='') { document.querySelector('#harness').value=h; document.querySelector('#modal-title').textContent=`新增 ${labels[h]} 配置`; ['name','base_url','api_key','model','notes'].forEach(id=>document.querySelector('#'+id).value=''); document.querySelector('#modal').showModal(); }
|
|
14
|
+
document.querySelector('#profile-form').addEventListener('submit', async e => { e.preventDefault(); const payload = Object.fromEntries(['harness','name','base_url','api_key','model','notes'].map(id=>[id,document.querySelector('#'+id).value])); try { await api('/api/profile',{method:'POST',body:JSON.stringify(payload)}); document.querySelector('#modal').close(); await load(); } catch(err){ alert(err.message); } });
|
|
15
|
+
async function activate(h,name) { try { const j=await api('/api/activate',{method:'POST',body:JSON.stringify({harness:h,name})}); await load(); alert(`已激活 ${labels[h]} / ${name}\n\n请在 SSH shell 执行:\nsource ${j.env_file}`); } catch(err){ alert(err.message); } }
|
|
16
|
+
async function removeProfile(h,name) { if(!confirm(`删除 ${labels[h]} / ${name}?`)) return; await api(`/api/profile/${h}/${encodeURIComponent(name)}`,{method:'DELETE'}); await load(); }
|
|
17
|
+
load().catch(err=>alert(err.message));
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>harness-switch</title><link rel="stylesheet" href="/static/style.css"></head>
|
|
3
|
+
<body><header class="topbar"><div><div class="eyebrow">SERVER-SIDE CONTROL PLANE</div><h1>harness-switch</h1></div><form method="post" action="/logout"><button class="ghost">退出</button></form></header><main class="layout"><section class="hero"><div><span class="pill">SSH / HEADLESS</span><h2>把 API 路由切换变成一个动作。</h2><p>配置档案按 harness 独立管理。激活后会更新相应配置,并生成可在 SSH shell 中 source 的环境文件。</p></div><div class="hero-note"><strong>安全提示</strong><span>API key 仅在服务器本地加密保存,列表和页面不会回显明文。</span></div></section><section class="grid" id="cards"></section><section class="card help"><div><h3>Shell 使用方式</h3><p>激活后,在运行 harness 的同一个 shell 执行:</p><code>source ~/.harness-switch/env.sh</code><p class="muted">也可以直接使用下面的服务器数据目录路径。Claude Code 与 Kimi Code 会额外写入各自的原生配置文件;pi、Codex、zcode 使用统一环境文件,避免覆盖你现有的复杂配置。</p></div><div><h3>设计取舍</h3><p class="muted">Web 页面改变的是服务器主机上的配置,不会改变浏览器本机环境;父 shell 需要 source 环境文件才能获取新变量。</p></div></section></main><dialog id="modal"><form method="dialog" class="card modal-card" id="profile-form"><button class="close" value="cancel">×</button><div class="eyebrow">PROFILE</div><h3 id="modal-title">新增配置</h3><input type="hidden" id="harness"><label>配置名称<input id="name" required placeholder="例如:openrouter-main"></label><label>API Base URL<input id="base_url" required placeholder="https://api.example.com/v1"></label><label>API Key<input id="api_key" type="password" placeholder="留空则保留已有密钥"></label><label>模型(可选)<input id="model" placeholder="例如:claude-sonnet-4-5"></label><label>备注(可选)<textarea id="notes" rows="3"></textarea></label><div class="actions"><button value="cancel" class="ghost">取消</button><button id="save" value="default">保存配置</button></div></form></dialog><script src="/static/app.js"></script></body></html>
|
package/public/style.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
:root{--bg:#0b1020;--panel:#111a2f;--panel2:#17223b;--line:#263553;--text:#eaf0ff;--muted:#93a2c4;--accent:#7c9cff;--accent2:#8ef0c4;--danger:#ff8e9e}*{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 15% 0%,#1a2850 0,transparent 38%),var(--bg);color:var(--text);font:15px/1.6 ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}h1,h2,h3,p{margin-top:0}h1{font-size:25px;letter-spacing:-.03em;margin-bottom:0}h2{font-size:38px;line-height:1.1;letter-spacing:-.05em;max-width:720px;margin:16px 0}h3{font-size:19px;margin:5px 0}.topbar{height:76px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 max(24px,calc((100% - 1180px)/2))}.layout{max-width:1180px;margin:auto;padding:56px 24px}.eyebrow{font-size:11px;letter-spacing:.18em;color:var(--accent2);font-weight:800}.muted{color:var(--muted)}.hero{display:flex;justify-content:space-between;gap:36px;align-items:end;margin-bottom:40px}.hero p{color:var(--muted);max-width:720px;font-size:16px}.hero-note{border-left:2px solid var(--accent2);padding:4px 0 4px 17px;max-width:270px;color:var(--muted)}.hero-note strong,.hero-note span{display:block}.hero-note strong{color:var(--text);margin-bottom:5px}.pill{border:1px solid #405485;border-radius:99px;padding:5px 10px;color:var(--accent);font-size:11px;font-weight:800;letter-spacing:.12em}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.card{background:linear-gradient(145deg,rgba(23,34,59,.95),rgba(17,26,47,.95));border:1px solid var(--line);border-radius:18px;box-shadow:0 18px 50px rgba(0,0,0,.18)}.harness{padding:22px}.card-head{display:flex;justify-content:space-between;align-items:start}.active{color:var(--muted);font-size:13px;padding:14px 0;border-bottom:1px solid var(--line)}.active strong{color:var(--text);margin-left:6px}.dot{display:inline-block;width:7px;height:7px;border-radius:99px;background:var(--accent2);margin-left:8px}.profiles{padding-top:7px}.profile{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 0;border-bottom:1px solid rgba(38,53,83,.65)}.profile:last-child{border-bottom:0}.profile strong,.profile span,.profile small{display:block}.profile span{color:var(--muted);font-size:12px;max-width:280px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.profile small{color:#b9c6e4;font-size:11px;margin-top:2px}.profile-actions{display:flex;gap:7px;align-items:center}.empty{color:var(--muted);padding:18px 0;font-size:13px}.small,.icon,button{font:inherit;cursor:pointer;border:0;color:var(--text);background:var(--accent);border-radius:9px;padding:8px 12px;font-weight:700}.small{font-size:12px;padding:7px 10px}.small.selected{background:var(--accent2);color:#08130f}.icon{background:transparent;color:var(--danger);font-size:12px;padding:5px}.ghost{background:transparent;border:1px solid var(--line);color:var(--muted)}button:active{transform:scale(.97)}.help{margin-top:16px;padding:24px;display:grid;grid-template-columns:1.3fr 1fr;gap:38px}.help code{display:block;background:#0a0f1d;border:1px solid var(--line);border-radius:9px;padding:12px 14px;color:var(--accent2);margin:10px 0 14px}.auth{min-height:100vh;display:grid;place-items:center;padding:20px}.auth-card{width:min(420px,100%);padding:32px}.auth-card h1{font-size:30px;margin:12px 0}.auth-card button{width:100%;margin-top:16px}label{display:block;color:var(--muted);font-size:13px;margin:14px 0}input,textarea{width:100%;margin-top:6px;background:#0b1224;border:1px solid var(--line);border-radius:9px;padding:11px;color:var(--text);font:inherit}input:focus,textarea:focus{outline:2px solid var(--accent);border-color:transparent}.modal-card{width:min(520px,calc(100vw - 32px));padding:26px;position:relative}.close{position:absolute;right:18px;top:15px;background:transparent;color:var(--muted);font-size:24px;padding:0}.actions{display:flex;justify-content:end;gap:10px;margin-top:20px}dialog{border:0;padding:0;background:transparent;color:var(--text)}dialog::backdrop{background:rgba(3,6,15,.75);backdrop-filter:blur(3px)}@media(max-width:800px){.grid{grid-template-columns:1fr}.hero,.help{display:block}.hero-note{margin-top:25px}.help>div+div{margin-top:25px}}
|