@a-tether/server 0.1.0 → 0.1.2
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/README.md +8 -7
- package/dist/backends/claude-code/claude-process.js +22 -4
- package/dist/backends/claude-code/claude-turn.js +23 -10
- package/dist/server/http.js +8 -10
- package/dist/server.js +30 -1
- package/dist/shared/protocol.js +3 -2
- package/dist/shared/settings.js +108 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
# @a-tether/server
|
|
2
2
|
|
|
3
|
-
A-tether 的 C
|
|
3
|
+
A-tether 的 C 端服务:把 C 上已登录的 Claude Code 借给另一台电脑(A)上的 Pi 使用。A 端请使用 [`@a-tether/pi`](https://www.npmjs.com/package/@a-tether/pi)。
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
|
-
|
|
7
|
-
npx -y @a-tether/server
|
|
6
|
+
npx -y @a-tether/server # 全局安装后命令为 a-tether-server
|
|
7
|
+
npx -y @a-tether/server token # 再次显示 A 端的配置命令
|
|
8
8
|
```
|
|
9
9
|
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
10
|
+
- 第一次启动会生成令牌,保存到 `~/.a-tether/settings.json`,并打印一行 `npx -y @a-tether/pi login <令牌>`,到 A 上运行一次即可。A 和 C 是同一台电脑时不需要这一步。
|
|
11
|
+
- 默认只监听 `127.0.0.1:7310`,A 通过 SSH 隧道等端口转发连接。端口、监听地址、`claude` 路径等都在 `~/.a-tether/settings.json` 中配置。
|
|
12
|
+
- 需要 C 上已登录的 `claude` CLI。
|
|
13
|
+
- 请求失败时在终端输出一行脱敏诊断,不记录对话内容或令牌。
|
|
14
|
+
- 完整说明见 [README](https://github.com/SandyKidYao/a-tether#readme)。
|
|
@@ -1,24 +1,42 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createInterface } from "node:readline";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
4
7
|
import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
|
|
5
8
|
import { api, providerId, defaultUrl } from "../../shared/protocol.js";
|
|
9
|
+
import { loadSettings } from "../../shared/settings.js";
|
|
6
10
|
export const isolated = ["-p", "--tools", "", "--setting-sources", "", "--strict-mcp-config",
|
|
7
11
|
"--settings", JSON.stringify({ disableAllHooks: true }), "--disable-slash-commands", "--no-session-persistence", "--permission-mode", "dontAsk"];
|
|
8
12
|
export const streaming = ["--verbose", "--input-format", "stream-json", "--output-format", "stream-json"];
|
|
13
|
+
// Turns run with --setting-sources "", so Claude Code ignores the env block of its own
|
|
14
|
+
// settings.json, while `claude auth status` reads it. A login token kept there must
|
|
15
|
+
// reach every invocation, or status reports logged in and each turn fails.
|
|
16
|
+
function settingsToken(env) {
|
|
17
|
+
try {
|
|
18
|
+
const file = join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "settings.json");
|
|
19
|
+
const token = JSON.parse(readFileSync(file, "utf8"))?.env?.CLAUDE_CODE_OAUTH_TOKEN;
|
|
20
|
+
return typeof token === "string" && token ? token : undefined;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
9
26
|
export async function invoke(args, options) {
|
|
10
27
|
const { signal } = options;
|
|
11
28
|
signal?.throwIfAborted();
|
|
12
29
|
const env = { ...process.env, ...options.env };
|
|
13
|
-
const command =
|
|
30
|
+
const command = loadSettings().server.claude;
|
|
14
31
|
delete env.ANTHROPIC_API_KEY;
|
|
15
|
-
delete env.A_TETHER_TOKEN;
|
|
32
|
+
delete env.A_TETHER_TOKEN; // a leftover 0.1.0 variable must not reach Claude either
|
|
16
33
|
if (env.ANTHROPIC_BASE_URL || env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_FOUNDRY_API_KEY ||
|
|
17
34
|
["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"].some(k => env[k] && !["false", "0"].includes(env[k]))) {
|
|
18
35
|
throw new Error("Conflicting backend configuration");
|
|
19
36
|
}
|
|
20
|
-
|
|
21
|
-
|
|
37
|
+
const oauth = env.CLAUDE_CODE_OAUTH_TOKEN || settingsToken(env);
|
|
38
|
+
if (oauth)
|
|
39
|
+
env.CLAUDE_CODE_OAUTH_TOKEN = oauth;
|
|
22
40
|
Object.assign(env, { ENABLE_TOOL_SEARCH: "false", CLAUDE_CODE_DISABLE_FILE_MENTIONS: "1",
|
|
23
41
|
CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1", DISABLE_AUTOUPDATER: "1",
|
|
24
42
|
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1" });
|
|
@@ -4,9 +4,12 @@ import { tmpdir } from "node:os";
|
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { calculateCost, createAssistantMessageEventStream, getCurrentSystemPrompt, getCurrentTools } from "@earendil-works/pi-ai";
|
|
6
6
|
import { invoke, isolated, streaming } from "./claude-process.js";
|
|
7
|
+
import { loadSettings } from "../../shared/settings.js";
|
|
7
8
|
// Present the conversation in order, retaining call IDs and images. Do not forward
|
|
8
9
|
// provider diagnostics, local tool details, or session bookkeeping to Claude.
|
|
9
|
-
|
|
10
|
+
// History names tools the way Claude must call them, so the model does not copy
|
|
11
|
+
// Pi's bare names into new calls.
|
|
12
|
+
function userInput(context, toolName) {
|
|
10
13
|
const blocks = [];
|
|
11
14
|
for (const msg of context.messages) {
|
|
12
15
|
if (msg.role === "system")
|
|
@@ -17,10 +20,12 @@ function userInput(context) {
|
|
|
17
20
|
return [{ type: "image", attachment: true }];
|
|
18
21
|
if (p.type === "thinking")
|
|
19
22
|
return [];
|
|
23
|
+
if (p.type === "toolCall")
|
|
24
|
+
return [{ ...p, name: toolName(p.name) }];
|
|
20
25
|
return [p];
|
|
21
26
|
});
|
|
22
27
|
const record = msg.role === "toolResult"
|
|
23
|
-
? { role: msg.role, toolCallId: msg.toolCallId, name: msg.toolName, isError: msg.isError, content }
|
|
28
|
+
? { role: msg.role, toolCallId: msg.toolCallId, name: toolName(msg.toolName), isError: msg.isError, content }
|
|
24
29
|
: { role: msg.role, content };
|
|
25
30
|
blocks.push({ type: "text", text: JSON.stringify(record) });
|
|
26
31
|
for (const p of parts)
|
|
@@ -36,6 +41,7 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
36
41
|
timestamp: Date.now(), content: [], stopReason: "pending",
|
|
37
42
|
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
38
43
|
async function generate() {
|
|
44
|
+
const { allowUsageCredits } = loadSettings().server;
|
|
39
45
|
const tools = getCurrentTools(context.messages);
|
|
40
46
|
const reserved = new Set(tools.map(tool => tool.name));
|
|
41
47
|
function transportName(name, index) {
|
|
@@ -51,7 +57,12 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
51
57
|
name: transportName(tool.name, index),
|
|
52
58
|
description: tool.description, inputSchema: tool.parameters,
|
|
53
59
|
}));
|
|
54
|
-
const
|
|
60
|
+
const claudeNames = new Map(tools.map((tool, i) => [tool.name, "mcp__tether__" + catalog[i].name]));
|
|
61
|
+
// A model sometimes drops the MCP prefix. Map bare names back as well; any other
|
|
62
|
+
// name goes to Pi unchanged, which answers it with a "not found" tool result.
|
|
63
|
+
const names = new Map(tools.flatMap((tool, i) => [
|
|
64
|
+
[tool.name, tool.name], [catalog[i].name, tool.name], ["mcp__tether__" + catalog[i].name, tool.name]
|
|
65
|
+
]));
|
|
55
66
|
const dir = await mkdtemp(join(tmpdir(), "a-tether-turn-"));
|
|
56
67
|
try {
|
|
57
68
|
const file = join(dir, "catalog.json");
|
|
@@ -104,7 +115,8 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
104
115
|
throw new Error("Claude final content differs from stream");
|
|
105
116
|
}
|
|
106
117
|
stream.push({ type: "start", partial: message });
|
|
107
|
-
const
|
|
118
|
+
const input = userInput(context, name => claudeNames.get(name) ?? name);
|
|
119
|
+
const { code, stderr } = await invoke(args, { signal: options.signal, cwd: dir, input,
|
|
108
120
|
env: options.maxTokens ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(options.maxTokens) } : {}, onLine(line) {
|
|
109
121
|
let envelope;
|
|
110
122
|
try {
|
|
@@ -174,15 +186,16 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
174
186
|
}
|
|
175
187
|
if (b.type !== "tool_use")
|
|
176
188
|
continue;
|
|
177
|
-
|
|
178
|
-
if (!name)
|
|
179
|
-
throw new Error("Unexpected Claude tool");
|
|
180
|
-
if (typeof b.id !== "string" || !b.input || typeof b.input !== "object" || Array.isArray(b.input))
|
|
189
|
+
if (typeof b.id !== "string" || typeof b.name !== "string")
|
|
181
190
|
throw new Error("Invalid tool call");
|
|
182
191
|
if (callsSeen.has(b.id))
|
|
183
192
|
continue;
|
|
184
193
|
callsSeen.add(b.id);
|
|
185
|
-
|
|
194
|
+
// Pi owns the tools: it rejects unknown names and validates arguments,
|
|
195
|
+
// and the model corrects itself on the next turn.
|
|
196
|
+
const name = names.get(b.name) ?? b.name;
|
|
197
|
+
const input = b.input && typeof b.input === "object" && !Array.isArray(b.input) ? b.input : {};
|
|
198
|
+
const toolCall = { type: "toolCall", id: b.id, name, arguments: input };
|
|
186
199
|
const i = message.content.push(toolCall) - 1;
|
|
187
200
|
stream.push({ type: "toolcall_start", contentIndex: i, partial: message });
|
|
188
201
|
stream.push({ type: "toolcall_end", contentIndex: i, toolCall, partial: message });
|
|
@@ -202,7 +215,7 @@ export function streamClaudeCode(model, context, options, route = model.id) {
|
|
|
202
215
|
calculateCost(model, message.usage);
|
|
203
216
|
}
|
|
204
217
|
else if (envelope.type === "rate_limit_event" && envelope.rate_limit_info?.isUsingOverage &&
|
|
205
|
-
|
|
218
|
+
!allowUsageCredits) {
|
|
206
219
|
throw new Error("Claude billing limit");
|
|
207
220
|
}
|
|
208
221
|
} });
|
package/dist/server/http.js
CHANGED
|
@@ -6,6 +6,7 @@ import { mkdtemp, rm } from "node:fs/promises";
|
|
|
6
6
|
import { tmpdir } from "node:os";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { generationOptions, uuid, wireEvent } from "../shared/protocol.js";
|
|
9
|
+
import { isLoopback, validToken } from "../shared/settings.js";
|
|
9
10
|
function json(res, status, data) {
|
|
10
11
|
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(data));
|
|
11
12
|
}
|
|
@@ -68,16 +69,11 @@ async function readRequest(req) {
|
|
|
68
69
|
throw new Failure(400, "invalid");
|
|
69
70
|
}
|
|
70
71
|
}
|
|
71
|
-
export async function runServer(backend) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
throw new Error("Set A_TETHER_TOKEN to a random token of at least 32 characters");
|
|
72
|
+
export async function runServer(backend, { token, host, port }) {
|
|
73
|
+
if (!validToken(token))
|
|
74
|
+
throw new Error("A-tether token must be at least 32 characters without whitespace");
|
|
75
75
|
const digest = (value) => createHash("sha256").update(value).digest();
|
|
76
76
|
const expected = digest("Bearer " + token);
|
|
77
|
-
delete process.env.A_TETHER_TOKEN;
|
|
78
|
-
const port = Number(process.env.A_TETHER_PORT ?? 7310);
|
|
79
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
80
|
-
throw new Error("Invalid A_TETHER_PORT");
|
|
81
77
|
const directory = await mkdtemp(join(tmpdir(), "a-tether-"));
|
|
82
78
|
process.chdir(directory);
|
|
83
79
|
const active = new Map();
|
|
@@ -202,9 +198,11 @@ export async function runServer(backend) {
|
|
|
202
198
|
: health.diagnostic ? "status check failed" + (health.detail ? " (" + clip(health.detail) + ")" : "")
|
|
203
199
|
: health.loggedIn ? "logged in" : "not logged in";
|
|
204
200
|
console.log(backend.name + ":", state);
|
|
205
|
-
server.listen(port,
|
|
201
|
+
server.listen(port, host);
|
|
206
202
|
await once(server, "listening", { signal: startup.signal });
|
|
207
|
-
console.log("A-tether listening on
|
|
203
|
+
console.log("A-tether listening on " + (host.includes(":") ? `[${host}]` : host) + ":" + port);
|
|
204
|
+
if (!isLoopback(host))
|
|
205
|
+
console.log("注意:服务监听在非本机地址,令牌以明文 HTTP 传输,同一网络中的设备都能连接。");
|
|
208
206
|
await once(server, "close");
|
|
209
207
|
}
|
|
210
208
|
catch (error) {
|
package/dist/server.js
CHANGED
|
@@ -1,8 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { claudeCode } from "./backends/claude-code/index.js";
|
|
3
3
|
import { runServer } from "./server/http.js";
|
|
4
|
+
import { displayPath, generateToken, loadSettings, loginCommand, saveToken } from "./shared/settings.js";
|
|
5
|
+
const showToken = "npx -y @a-tether/server token";
|
|
6
|
+
function main(args) {
|
|
7
|
+
const settings = loadSettings();
|
|
8
|
+
if (args[0] === "token" && args.length === 1) {
|
|
9
|
+
if (!settings.token)
|
|
10
|
+
throw new Error(`还没有令牌。运行 npx -y @a-tether/server 启动服务时会自动生成并保存到 ${displayPath}。`);
|
|
11
|
+
console.log(["在 A 端电脑上运行下面这行(同一台电脑上使用 Pi 无需运行):", "", " " + loginCommand(settings.token), ""].join("\n"));
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
if (args.length)
|
|
15
|
+
throw new Error("用法:a-tether-server 启动服务\n a-tether-server token 显示 A 端的配置命令");
|
|
16
|
+
let token = settings.token;
|
|
17
|
+
if (token)
|
|
18
|
+
console.log(`令牌:已配置(${displayPath})。查看 A 端配置命令:${showToken}`);
|
|
19
|
+
else {
|
|
20
|
+
token = generateToken();
|
|
21
|
+
saveToken(token);
|
|
22
|
+
console.log([
|
|
23
|
+
`已生成 A-tether 令牌,保存在 ${displayPath}。`,
|
|
24
|
+
"在 A 端电脑上运行一次下面这行(同一台电脑上使用 Pi 无需运行):",
|
|
25
|
+
"",
|
|
26
|
+
" " + loginCommand(token),
|
|
27
|
+
"",
|
|
28
|
+
`以后可运行 ${showToken} 再次查看。`,
|
|
29
|
+
].join("\n"));
|
|
30
|
+
}
|
|
31
|
+
return runServer(claudeCode, { token, host: settings.server.host, port: settings.server.port });
|
|
32
|
+
}
|
|
4
33
|
try {
|
|
5
|
-
await
|
|
34
|
+
await main(process.argv.slice(2));
|
|
6
35
|
}
|
|
7
36
|
catch (error) {
|
|
8
37
|
console.error(error instanceof Error ? error.message : String(error));
|
package/dist/shared/protocol.js
CHANGED
|
@@ -3,7 +3,8 @@ export const api = "a-tether-v1";
|
|
|
3
3
|
export const defaultUrl = "http://127.0.0.1:7310";
|
|
4
4
|
export const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
|
|
5
5
|
export const messages = {
|
|
6
|
-
unauthorized: "A-tether
|
|
6
|
+
unauthorized: "A-tether 令牌与 C 端不一致。在 C 上运行 npx -y @a-tether/server token,再在本机运行它给出的 login 命令。",
|
|
7
|
+
token: "A-tether 还没有配置令牌。在 C 上运行 npx -y @a-tether/server token,再在本机运行它给出的 login 命令。",
|
|
7
8
|
unavailable: "C 上找不到 Claude Code,请检查服务进程的 PATH。",
|
|
8
9
|
login: "C 上的 Claude Code 尚未登录或登录已失效。",
|
|
9
10
|
quota: "Claude 额度、速率或计费限制,请在 C 上检查账户。",
|
|
@@ -16,7 +17,7 @@ export const messages = {
|
|
|
16
17
|
invalid: "请求格式或模型 ID 无效。",
|
|
17
18
|
duplicate: "请求 ID 已在使用。",
|
|
18
19
|
large: "请求超过 32 MiB 上限。",
|
|
19
|
-
connection: "A-tether
|
|
20
|
+
connection: "A-tether 连接中断,请检查端口转发(如 SSH 隧道)和 C 端服务。",
|
|
20
21
|
};
|
|
21
22
|
// Runtime whitelist on BOTH ends. In particular, never forward env, headers,
|
|
22
23
|
// sessionId, filesystem paths, credentials, or callbacks from Pi.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Both ends read ~/.a-tether/settings.json. On one machine they share the file,
|
|
2
|
+
// so the token generated by the server works for the Pi plugin without setup.
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { isIPv4, isIPv6 } from "node:net";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
export const displayPath = "~/.a-tether/settings.json";
|
|
9
|
+
export const settingsPath = () => join(homedir(), ".a-tether", "settings.json");
|
|
10
|
+
export class SettingsError extends Error {
|
|
11
|
+
}
|
|
12
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13
|
+
// Printable ASCII only: the token travels in an HTTP header.
|
|
14
|
+
export const validToken = (value) => typeof value === "string" && /^[\x21-\x7e]{32,}$/.test(value);
|
|
15
|
+
export const generateToken = () => randomBytes(32).toString("hex");
|
|
16
|
+
export const loginCommand = (token) => "npx -y @a-tether/pi login " + token;
|
|
17
|
+
export function isLoopback(host) {
|
|
18
|
+
const h = host.toLowerCase();
|
|
19
|
+
if (h === "localhost")
|
|
20
|
+
return true;
|
|
21
|
+
if (isIPv4(h))
|
|
22
|
+
return h.startsWith("127.");
|
|
23
|
+
return isIPv6(h) && (/^(0{1,4}:){7}0{0,3}1$/.test(h) || h === "::1" || /^::ffff:127\./.test(h));
|
|
24
|
+
}
|
|
25
|
+
function readRaw(file) {
|
|
26
|
+
let text;
|
|
27
|
+
try {
|
|
28
|
+
text = readFileSync(file, "utf8");
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (error.code === "ENOENT")
|
|
32
|
+
return undefined;
|
|
33
|
+
throw new SettingsError(`无法读取 ${file}:${error.message}`);
|
|
34
|
+
}
|
|
35
|
+
let data;
|
|
36
|
+
try {
|
|
37
|
+
data = JSON.parse(text);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new SettingsError(`${file} 不是合法的 JSON,请修正或删除后重试。`);
|
|
41
|
+
}
|
|
42
|
+
if (!isObject(data))
|
|
43
|
+
throw new SettingsError(`${file} 的内容必须是一个 JSON 对象。`);
|
|
44
|
+
return data;
|
|
45
|
+
}
|
|
46
|
+
export function loadSettings(file = settingsPath()) {
|
|
47
|
+
const raw = readRaw(file) ?? {};
|
|
48
|
+
const fail = (field, rule) => { throw new SettingsError(`${file} 中的 ${field} ${rule}。`); };
|
|
49
|
+
const section = (name) => {
|
|
50
|
+
const value = raw[name];
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
return {};
|
|
53
|
+
return isObject(value) ? value : fail(name, "必须是对象");
|
|
54
|
+
};
|
|
55
|
+
const text = (obj, field) => {
|
|
56
|
+
const value = obj[field.split(".")[1]];
|
|
57
|
+
if (value === undefined)
|
|
58
|
+
return undefined;
|
|
59
|
+
return typeof value === "string" && value.trim() ? value : fail(field, "必须是非空字符串");
|
|
60
|
+
};
|
|
61
|
+
const server = section("server");
|
|
62
|
+
const client = section("client");
|
|
63
|
+
if (raw.token !== undefined && !validToken(raw.token))
|
|
64
|
+
fail("token", "必须是至少 32 个字符的字符串,只含字母、数字和符号,不含空白");
|
|
65
|
+
const port = server.port ?? 7310;
|
|
66
|
+
if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)
|
|
67
|
+
fail("server.port", "必须是 1–65535 的整数");
|
|
68
|
+
const allowUsageCredits = server.allowUsageCredits ?? false;
|
|
69
|
+
if (typeof allowUsageCredits !== "boolean")
|
|
70
|
+
fail("server.allowUsageCredits", "必须是 true 或 false");
|
|
71
|
+
// Without client.url, Pi on the same machine follows server.port.
|
|
72
|
+
const url = text(client, "client.url") ?? "http://127.0.0.1:" + port;
|
|
73
|
+
let origin = "";
|
|
74
|
+
try {
|
|
75
|
+
const parsed = new URL(url);
|
|
76
|
+
if (parsed.protocol === "http:" && parsed.hostname && !parsed.username && !parsed.password &&
|
|
77
|
+
parsed.pathname === "/" && !parsed.search && !parsed.hash)
|
|
78
|
+
origin = parsed.origin;
|
|
79
|
+
}
|
|
80
|
+
catch { }
|
|
81
|
+
if (!origin)
|
|
82
|
+
fail("client.url", "必须形如 http://127.0.0.1:7310(不带路径和账号密码)");
|
|
83
|
+
return {
|
|
84
|
+
token: raw.token,
|
|
85
|
+
server: { host: text(server, "server.host") ?? "127.0.0.1", port: port,
|
|
86
|
+
claude: text(server, "server.claude") ?? "claude", allowUsageCredits: allowUsageCredits },
|
|
87
|
+
client: { url: origin, pi: text(client, "client.pi") },
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
// Replaces only the token and keeps every other field. Writes a private temp
|
|
91
|
+
// file and renames it, so an interrupted write never leaves half a file.
|
|
92
|
+
export function saveToken(token, file = settingsPath()) {
|
|
93
|
+
if (!validToken(token))
|
|
94
|
+
throw new SettingsError("令牌必须是至少 32 个字符的字符串,只含字母、数字和符号,不含空白。请完整复制 C 端打印的令牌。");
|
|
95
|
+
const data = { ...readRaw(file), token };
|
|
96
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
97
|
+
chmodSync(dirname(file), 0o700); // mode above only applies when the directory is new
|
|
98
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
99
|
+
try {
|
|
100
|
+
writeFileSync(temp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
|
|
101
|
+
chmodSync(temp, 0o600);
|
|
102
|
+
renameSync(temp, file);
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
rmSync(temp, { force: true });
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|