@evandu/super-pi 0.1.260 → 0.1.261
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/desktop/brand.svg +6 -0
- package/desktop/icon.png +0 -0
- package/desktop/main.cjs +16 -4
- package/desktop/preload.cjs +19 -0
- package/desktop/tray-icon.png +0 -0
- package/desktop/tray-icon@2x.png +0 -0
- package/desktop/tray.svg +1 -0
- package/dist/client/.super-pi-client-sources.json +7 -6
- package/dist/client/assets/{CodeMirrorEditor-mi9rGUce.js → CodeMirrorEditor-DGK07ECt.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-FQBfGxOY.js → GitDiffEditor-DCQ2HgfJ.js} +1 -1
- package/dist/client/assets/index-BVn_-dwp.js +350 -0
- package/dist/client/assets/{index-UfzqdECL.css → index-DhW875H-.css} +1 -1
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.png +0 -0
- package/dist/client/favicon.svg +5 -9
- package/dist/client/index.html +2 -2
- package/dist/server/existing-service.d.ts +12 -0
- package/dist/server/existing-service.js +18 -0
- package/dist/server/managed-http-tunnel.d.ts +2 -2
- package/dist/server/managed-http-tunnel.js +7 -5
- package/dist/server/managed-http.js +6 -2
- package/dist/server/managed-servers.d.ts +46 -3
- package/dist/server/managed-servers.js +194 -19
- package/dist/server/managed-ssh.d.ts +14 -1
- package/dist/server/managed-ssh.js +55 -5
- package/dist/shared/managed-servers.d.ts +23 -2
- package/package.json +4 -1
- package/dist/client/assets/index-Cn7hdrDw.js +0 -350
package/dist/client/favicon.ico
CHANGED
|
Binary file
|
package/dist/client/favicon.png
CHANGED
|
Binary file
|
package/dist/client/favicon.svg
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
|
-
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0
|
|
2
|
-
<defs>
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
</linearGradient>
|
|
7
|
-
</defs>
|
|
8
|
-
<rect width="64" height="64" rx="20" ry="20" fill="url(#orbGrad)" />
|
|
9
|
-
<text x="32" y="43" text-anchor="middle" font-family="Georgia, 'Times New Roman', serif" font-weight="bold" font-size="44" fill="#05070c">π</text>
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" style="--brand-start:#526ff5;--brand-end:#6844ce;--brand-mark:#ffffff;--brand-edge:#ffffff">
|
|
2
|
+
<defs><linearGradient id="brand" x1="0" y1="0" x2="1" y2="1"><stop stop-color="var(--brand-start)"/><stop offset="1" stop-color="var(--brand-end)"/></linearGradient></defs>
|
|
3
|
+
<rect x="16" y="16" width="224" height="224" rx="52" fill="url(#brand)"/>
|
|
4
|
+
<rect x="17" y="17" width="222" height="222" rx="51" fill="none" stroke="var(--brand-edge)" stroke-opacity=".16" stroke-width="2"/>
|
|
5
|
+
<g fill="none" stroke="var(--brand-mark)" stroke-width="16" stroke-linecap="round" stroke-linejoin="round"><path d="M66 86h124"/><path d="M103 88v49c0 19-5 34-15 47"/><path d="M158 88v69c0 16 8 23 23 23h5"/></g>
|
|
10
6
|
</svg>
|
package/dist/client/index.html
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
<link rel="alternate icon" href="/favicon.ico" />
|
|
9
9
|
<link rel="apple-touch-icon" href="/favicon.svg" />
|
|
10
10
|
<title>Super Pi</title>
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-BVn_-dwp.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/index-DhW875H-.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
|
16
16
|
<div id="root"></div>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Client } from "ssh2";
|
|
2
|
+
export interface ExistingInstallation {
|
|
3
|
+
node: string;
|
|
4
|
+
cli: string;
|
|
5
|
+
packageName: string;
|
|
6
|
+
version: string;
|
|
7
|
+
dataDir: string;
|
|
8
|
+
hasData: boolean;
|
|
9
|
+
port?: number;
|
|
10
|
+
}
|
|
11
|
+
/** Read-only discovery; never invoke an old CLI with a flag that might start a daemon. */
|
|
12
|
+
export declare function discoverExistingInstallation(client: Client): Promise<ExistingInstallation | undefined>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { sh, sshExec } from "./managed-ssh.js";
|
|
2
|
+
/** Read-only discovery; never invoke an old CLI with a flag that might start a daemon. */
|
|
3
|
+
export async function discoverExistingInstallation(client) {
|
|
4
|
+
const script = `const fs=require('fs'),p=require('path'),os=require('os');const home=os.homedir(),dataDir=p.join(home,'.super-pi');const exists=x=>{try{return fs.statSync(x).isFile()}catch{return false}};const candidates=[p.join(home,'.npm-global/bin/super_pi'),p.join(home,'.local/bin/super_pi'),'/opt/homebrew/bin/super_pi','/usr/local/bin/super_pi','/usr/bin/super_pi'];try{for(const value of require('child_process').execFileSync('which',['super_pi'],{encoding:'utf8'}).trim().split('\\n'))candidates.unshift(value)}catch{};const roots=[p.join(home,'.pi/agent/npm/node_modules/@evandu/super-pi'),p.join(home,'.npm-global/lib/node_modules/@evandu/super-pi'),p.join(home,'.local/lib/node_modules/@evandu/super-pi'),'/opt/homebrew/lib/node_modules/@evandu/super-pi','/usr/local/lib/node_modules/@evandu/super-pi','/usr/lib/node_modules/@evandu/super-pi'];for(const cli of candidates){try{roots.unshift(p.resolve(fs.realpathSync(cli),'../..'))}catch{}};let config={};try{config=JSON.parse(fs.readFileSync(p.join(dataDir,'config.json'),'utf8'))}catch{};for(const root of roots){try{const pkg=JSON.parse(fs.readFileSync(p.join(root,'package.json'),'utf8'));if(!['@evandu/super-pi','@evandu/super-pi-server'].includes(pkg.name)||!exists(p.join(root,'bin/super-pi.js')))continue;console.log(JSON.stringify({node:process.execPath,cli:p.join(root,'bin/super-pi.js'),packageName:pkg.name,version:String(pkg.version),dataDir,hasData:exists(p.join(dataDir,'state.json')),port:Number.isInteger(config.port)?config.port:undefined}));process.exit(0)}catch{}};if(exists(p.join(dataDir,'state.json')))console.log(JSON.stringify({node:process.execPath,cli:'',packageName:'',version:'',dataDir,hasData:true}));`;
|
|
5
|
+
try {
|
|
6
|
+
const command = `for candidate in "$(command -v node 2>/dev/null || true)" /opt/homebrew/bin/node /usr/local/bin/node "$HOME"/.nvm/versions/node/*/bin/node; do if [ -n "$candidate" ] && [ -x "$candidate" ]; then "$candidate" -e ${sh(script)}; exit; fi; done`;
|
|
7
|
+
const text = (await sshExec(client, command, { timeout: 8000 })).trim();
|
|
8
|
+
if (!text)
|
|
9
|
+
return;
|
|
10
|
+
const value = JSON.parse(text);
|
|
11
|
+
if (!value.node?.startsWith("/") || !value.dataDir?.startsWith("/") || (value.cli && !value.cli.startsWith("/")) || /[\r\n\0]/.test(`${value.node}${value.dataDir}${value.cli}`))
|
|
12
|
+
return;
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -2,5 +2,5 @@ import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
|
2
2
|
import type { Duplex } from "node:stream";
|
|
3
3
|
import type { Client } from "ssh2";
|
|
4
4
|
export declare function tunnelJson(client: Client, port: number, path: string, key: string, method?: string): Promise<any>;
|
|
5
|
-
export declare function proxyThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath?: string): void;
|
|
6
|
-
export declare function proxyWebSocketThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
|
|
5
|
+
export declare function proxyThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath?: string, sameOrigin?: boolean): void;
|
|
6
|
+
export declare function proxyWebSocketThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer, sameOrigin?: boolean): Promise<void>;
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { request as httpRequest, Agent } from "node:http";
|
|
2
2
|
import { sshForward } from "./managed-ssh.js";
|
|
3
|
-
function headers(input, port, key) {
|
|
3
|
+
function headers(input, port, key, sameOrigin = false) {
|
|
4
4
|
const next = { ...input, host: `127.0.0.1:${port}`, authorization: `Bearer ${key}` };
|
|
5
5
|
delete next.cookie;
|
|
6
6
|
// Only an upstream owner credential travels through the private SSH channel.
|
|
7
7
|
delete next["sec-websocket-protocol"];
|
|
8
|
+
if (sameOrigin)
|
|
9
|
+
next.origin = `http://127.0.0.1:${port}`;
|
|
8
10
|
return next;
|
|
9
11
|
}
|
|
10
12
|
function agentFor(client, port) {
|
|
@@ -44,9 +46,9 @@ export async function tunnelJson(client, port, path, key, method = "GET") {
|
|
|
44
46
|
request.end();
|
|
45
47
|
});
|
|
46
48
|
}
|
|
47
|
-
export function proxyThroughSsh(client, port, key, path, request, response, basePath = "") {
|
|
49
|
+
export function proxyThroughSsh(client, port, key, path, request, response, basePath = "", sameOrigin = false) {
|
|
48
50
|
const agent = agentFor(client, port);
|
|
49
|
-
const upstream = httpRequest({ hostname: "127.0.0.1", port, method: request.method, path, headers: headers(request.headers, port, key), agent }, result => {
|
|
51
|
+
const upstream = httpRequest({ hostname: "127.0.0.1", port, method: request.method, path, headers: headers(request.headers, port, key, sameOrigin), agent }, result => {
|
|
50
52
|
const outgoing = { ...result.headers };
|
|
51
53
|
delete outgoing["set-cookie"];
|
|
52
54
|
// The trusted artifact wrapper uses an origin-root URL; keep its inner frame on this backend.
|
|
@@ -70,9 +72,9 @@ export function proxyThroughSsh(client, port, key, path, request, response, base
|
|
|
70
72
|
response.once("close", () => { upstream.destroy(); agent.destroy(); });
|
|
71
73
|
request.pipe(upstream);
|
|
72
74
|
}
|
|
73
|
-
export async function proxyWebSocketThroughSsh(client, port, key, path, request, socket, head) {
|
|
75
|
+
export async function proxyWebSocketThroughSsh(client, port, key, path, request, socket, head, sameOrigin = false) {
|
|
74
76
|
const channel = await sshForward(client, port);
|
|
75
|
-
const outgoing = headers(request.headers, port, key);
|
|
77
|
+
const outgoing = headers(request.headers, port, key, sameOrigin);
|
|
76
78
|
channel.write(`GET ${path} HTTP/1.1\r\n${Object.entries(outgoing).filter(([, value]) => value !== undefined).map(([name, value]) => `${name}: ${Array.isArray(value) ? value.join(", ") : value}`).join("\r\n")}\r\n\r\n`);
|
|
77
79
|
if (head.length)
|
|
78
80
|
channel.write(head);
|
|
@@ -65,10 +65,14 @@ export async function handleManagedHttp(context, request, response, url) {
|
|
|
65
65
|
await context.managedServers.save(body.profile);
|
|
66
66
|
}
|
|
67
67
|
else if (body.action === "trust")
|
|
68
|
-
await context.managedServers.trust(body.id, body.fingerprint);
|
|
68
|
+
await context.managedServers.trust(body.id, body.fingerprint, true);
|
|
69
|
+
else if (body.action === "answerVerification")
|
|
70
|
+
context.managedServers.answerVerification(body.id, body.verificationId, body.answers);
|
|
71
|
+
else if (body.action === "cancelVerification")
|
|
72
|
+
await context.managedServers.cancelVerification(body.id, body.verificationId);
|
|
69
73
|
else if (body.action === "syncAll") {
|
|
70
74
|
for (const profile of context.managedServers.list())
|
|
71
|
-
if (profile.enabled && profile.service === "online")
|
|
75
|
+
if (profile.enabled && profile.service === "online" && !profile.existingService?.attached)
|
|
72
76
|
await context.managedServers.action(profile.id, "sync");
|
|
73
77
|
}
|
|
74
78
|
else {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
2
|
import type { Duplex } from "node:stream";
|
|
3
3
|
import type { Client } from "ssh2";
|
|
4
|
-
import type { ManagedServerInput, ManagedServerProfile } from "../shared/managed-servers.js";
|
|
4
|
+
import type { ManagedServerInput, ManagedServerProfile, SshVerification } from "../shared/managed-servers.js";
|
|
5
5
|
export declare class ManagedServers {
|
|
6
6
|
private readonly directory;
|
|
7
7
|
private readonly packageRoot;
|
|
@@ -10,6 +10,9 @@ export declare class ManagedServers {
|
|
|
10
10
|
private readonly clients;
|
|
11
11
|
private readonly secrets;
|
|
12
12
|
private readonly connecting;
|
|
13
|
+
private readonly pendingConnections;
|
|
14
|
+
private readonly verifications;
|
|
15
|
+
private readonly authBlocked;
|
|
13
16
|
private readonly jobs;
|
|
14
17
|
private readonly recoveries;
|
|
15
18
|
private readonly vault;
|
|
@@ -25,15 +28,54 @@ export declare class ManagedServers {
|
|
|
25
28
|
modelId: string;
|
|
26
29
|
} | undefined);
|
|
27
30
|
initialize(): Promise<void>;
|
|
28
|
-
list():
|
|
31
|
+
list(): {
|
|
32
|
+
id: string;
|
|
33
|
+
name: string;
|
|
34
|
+
host: string;
|
|
35
|
+
sshPort: number;
|
|
36
|
+
username: string;
|
|
37
|
+
servicePort: number;
|
|
38
|
+
authentication: "agent" | "password" | "privateKey";
|
|
39
|
+
identityFile?: string;
|
|
40
|
+
fingerprint?: string;
|
|
41
|
+
observedFingerprint?: string;
|
|
42
|
+
enabled: boolean;
|
|
43
|
+
identity?: string;
|
|
44
|
+
deployedAt?: string;
|
|
45
|
+
remoteRoot?: string;
|
|
46
|
+
ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
|
|
47
|
+
service: "unknown" | "offline" | "online";
|
|
48
|
+
modelChannel: "offline" | "online";
|
|
49
|
+
phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
|
|
50
|
+
existingService?: {
|
|
51
|
+
running: boolean;
|
|
52
|
+
attached: boolean;
|
|
53
|
+
version?: string;
|
|
54
|
+
dataDirectory?: string;
|
|
55
|
+
hasData?: boolean;
|
|
56
|
+
canStart?: boolean;
|
|
57
|
+
requiresToken?: boolean;
|
|
58
|
+
};
|
|
59
|
+
step?: string;
|
|
60
|
+
error?: string;
|
|
61
|
+
log?: string[];
|
|
62
|
+
verification: SshVerification | undefined;
|
|
63
|
+
}[];
|
|
64
|
+
private cancelConnection;
|
|
65
|
+
private startConnection;
|
|
66
|
+
answerVerification(id: string, verificationId: string, answers: unknown): void;
|
|
67
|
+
cancelVerification(id: string, verificationId: string): Promise<void>;
|
|
29
68
|
private persist;
|
|
30
69
|
private entry;
|
|
31
70
|
save(input: ManagedServerInput): Promise<ManagedServerProfile>;
|
|
32
|
-
trust(id: string, fingerprint: string): Promise<ManagedServerProfile>;
|
|
71
|
+
trust(id: string, fingerprint: string, background?: boolean): Promise<ManagedServerProfile>;
|
|
33
72
|
connect(id: string): Promise<Client>;
|
|
73
|
+
private openConnection;
|
|
34
74
|
private reverseModelChannel;
|
|
35
75
|
syncModels(id: string, force?: boolean): Promise<void>;
|
|
36
76
|
private health;
|
|
77
|
+
private detectExisting;
|
|
78
|
+
private startExisting;
|
|
37
79
|
private ensureService;
|
|
38
80
|
private progress;
|
|
39
81
|
deploy(id: string): ManagedServerProfile;
|
|
@@ -43,6 +85,7 @@ export declare class ManagedServers {
|
|
|
43
85
|
id: string;
|
|
44
86
|
managedId: string;
|
|
45
87
|
managed: boolean;
|
|
88
|
+
legacy: boolean;
|
|
46
89
|
name: string;
|
|
47
90
|
url: string;
|
|
48
91
|
enabled: boolean;
|
|
@@ -9,6 +9,7 @@ import { ManagedModelGateway } from "./managed-model-gateway.js";
|
|
|
9
9
|
import { connectSsh, HostTrustRequired, sshWrite, sshExec, sh } from "./managed-ssh.js";
|
|
10
10
|
import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed-http-tunnel.js";
|
|
11
11
|
import { installRemote, startRemote } from "./remote-bootstrap.js";
|
|
12
|
+
import { discoverExistingInstallation } from "./existing-service.js";
|
|
12
13
|
export class ManagedServers {
|
|
13
14
|
directory;
|
|
14
15
|
packageRoot;
|
|
@@ -17,6 +18,9 @@ export class ManagedServers {
|
|
|
17
18
|
clients = new Map();
|
|
18
19
|
secrets = new Map();
|
|
19
20
|
connecting = new Set();
|
|
21
|
+
pendingConnections = new Map();
|
|
22
|
+
verifications = new Map();
|
|
23
|
+
authBlocked = new Set();
|
|
20
24
|
jobs = new Map();
|
|
21
25
|
recoveries = new Map();
|
|
22
26
|
vault;
|
|
@@ -75,7 +79,41 @@ export class ManagedServers {
|
|
|
75
79
|
this.timer.unref();
|
|
76
80
|
void this.maintain();
|
|
77
81
|
}
|
|
78
|
-
list() { return [...this.records.values()].map(entry => structuredClone(entry.profile)); }
|
|
82
|
+
list() { return [...this.records.values()].map(entry => structuredClone({ ...entry.profile, verification: this.verifications.get(entry.profile.id)?.challenge })); }
|
|
83
|
+
async cancelConnection(id, reason = "SSH 连接已取消") {
|
|
84
|
+
const pending = this.pendingConnections.get(id);
|
|
85
|
+
this.verifications.get(id)?.reject(new Error(reason));
|
|
86
|
+
this.verifications.delete(id);
|
|
87
|
+
if (pending) {
|
|
88
|
+
pending.controller.abort(new Error(reason));
|
|
89
|
+
await pending.promise.catch(() => { });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
startConnection(id) {
|
|
93
|
+
this.authBlocked.delete(id);
|
|
94
|
+
void this.connect(id).catch(() => { });
|
|
95
|
+
}
|
|
96
|
+
answerVerification(id, verificationId, answers) {
|
|
97
|
+
const pending = this.verifications.get(id);
|
|
98
|
+
if (!pending || pending.challenge.id !== verificationId)
|
|
99
|
+
throw new Error("这轮 SSH 验证已经结束,请使用当前服务器的最新提示");
|
|
100
|
+
if (Date.parse(pending.challenge.expiresAt) <= Date.now())
|
|
101
|
+
throw new Error("这轮 SSH 验证已超时,请重新连接");
|
|
102
|
+
if (!Array.isArray(answers) || answers.length !== pending.challenge.prompts.length || answers.some(answer => typeof answer !== "string" || answer.length > 8192))
|
|
103
|
+
throw new Error("请完成当前验证轮次的全部提示");
|
|
104
|
+
this.verifications.delete(id);
|
|
105
|
+
const profile = this.entry(id).profile;
|
|
106
|
+
profile.ssh = "connecting";
|
|
107
|
+
if (!this.jobs.has(id))
|
|
108
|
+
profile.phase = "connecting";
|
|
109
|
+
pending.resolve(answers);
|
|
110
|
+
}
|
|
111
|
+
async cancelVerification(id, verificationId) {
|
|
112
|
+
if (this.verifications.get(id)?.challenge.id !== verificationId)
|
|
113
|
+
throw new Error("这轮 SSH 验证已经结束,请使用最新提示");
|
|
114
|
+
this.authBlocked.add(id);
|
|
115
|
+
await this.cancelConnection(id, "SSH 交互验证已取消,可重新检测/连接");
|
|
116
|
+
}
|
|
79
117
|
persist() {
|
|
80
118
|
const data = JSON.stringify({ servers: [...this.records.values()] }, null, 2);
|
|
81
119
|
this.persistence = this.persistence.catch(() => { }).then(async () => { const path = join(this.directory, "servers.json"), temp = `${path}.tmp`; await writeFile(temp, data, { mode: 0o600 }); await rename(temp, path); });
|
|
@@ -93,10 +131,11 @@ export class ManagedServers {
|
|
|
93
131
|
const id = input.id ?? randomUUID(), previous = input.id ? this.entry(input.id) : undefined;
|
|
94
132
|
if (this.jobs.has(id))
|
|
95
133
|
throw new Error("部署尚未完成,暂不能修改连接");
|
|
134
|
+
await this.cancelConnection(id, "SSH 连接配置已修改,请重新验证");
|
|
96
135
|
if ([...this.records.values()].some(item => item.profile.id !== id && item.profile.name === input.name.trim()))
|
|
97
136
|
throw new Error("服务器名称已存在");
|
|
98
137
|
const old = this.secrets.get(id);
|
|
99
|
-
const secret = { ssh: { password: input.password || old?.ssh.password, privateKey: input.privateKey || old?.ssh.privateKey, passphrase: input.passphrase || old?.ssh.passphrase }, browserKey: old?.browserKey ?? randomBytes(32).toString("base64url"), modelToken: old?.modelToken ?? randomBytes(32).toString("base64url") };
|
|
138
|
+
const secret = { ssh: { password: input.password || old?.ssh.password, privateKey: input.privateKey || old?.ssh.privateKey, passphrase: input.passphrase || old?.ssh.passphrase }, browserKey: old?.browserKey ?? randomBytes(32).toString("base64url"), modelToken: old?.modelToken ?? randomBytes(32).toString("base64url"), serviceAccessToken: input.serviceAccessToken || old?.serviceAccessToken };
|
|
100
139
|
if (input.authentication === "password" && !secret.ssh.password)
|
|
101
140
|
throw new Error("请输入 SSH 密码");
|
|
102
141
|
if (input.authentication === "privateKey" && !input.identityFile && !secret.ssh.privateKey)
|
|
@@ -108,18 +147,18 @@ export class ManagedServers {
|
|
|
108
147
|
delete secret.ssh.passphrase;
|
|
109
148
|
}
|
|
110
149
|
const changedHost = previous && (previous.profile.host !== input.host.trim() || previous.profile.sshPort !== input.sshPort || previous.profile.username !== input.username.trim());
|
|
111
|
-
if (changedHost && previous.installation)
|
|
112
|
-
throw new Error("
|
|
150
|
+
if ((changedHost && (previous.installation || previous.compatibility)) || (previous?.compatibility && previous.profile.servicePort !== input.servicePort))
|
|
151
|
+
throw new Error("已接入服务器不能改为另一台主机或服务,请添加新连接以保护工作区归属");
|
|
113
152
|
const profile = { ...previous?.profile, id, name: input.name.trim(), host: input.host.trim(), sshPort: input.sshPort, username: input.username.trim(), servicePort: input.servicePort, authentication: input.authentication, identityFile: input.identityFile?.trim(), fingerprint: changedHost ? undefined : previous?.profile.fingerprint, observedFingerprint: undefined, enabled: true, ssh: "offline", service: "unknown", modelChannel: "offline", phase: "idle", error: undefined };
|
|
114
153
|
this.clients.get(id)?.end();
|
|
115
154
|
this.clients.delete(id);
|
|
116
155
|
await this.vault.write(id, secret);
|
|
117
156
|
this.secrets.set(id, secret);
|
|
118
|
-
this.records.set(id, { ...previous, profile });
|
|
157
|
+
this.records.set(id, { ...(changedHost ? {} : previous), profile });
|
|
119
158
|
await this.persist();
|
|
120
159
|
return profile;
|
|
121
160
|
}
|
|
122
|
-
async trust(id, fingerprint) {
|
|
161
|
+
async trust(id, fingerprint, background = false) {
|
|
123
162
|
const entry = this.entry(id);
|
|
124
163
|
if (!entry.profile.observedFingerprint || fingerprint !== entry.profile.observedFingerprint)
|
|
125
164
|
throw new Error("主机指纹已变化,请重新检测后确认");
|
|
@@ -127,10 +166,35 @@ export class ManagedServers {
|
|
|
127
166
|
delete entry.profile.observedFingerprint;
|
|
128
167
|
entry.profile.phase = "idle";
|
|
129
168
|
await this.persist();
|
|
130
|
-
|
|
169
|
+
this.authBlocked.delete(id);
|
|
170
|
+
if (background)
|
|
171
|
+
this.startConnection(id);
|
|
172
|
+
else
|
|
173
|
+
await this.connect(id);
|
|
131
174
|
return this.entry(id).profile;
|
|
132
175
|
}
|
|
133
176
|
async connect(id) {
|
|
177
|
+
const pending = this.pendingConnections.get(id);
|
|
178
|
+
if (pending)
|
|
179
|
+
return pending.promise;
|
|
180
|
+
const existing = this.clients.get(id);
|
|
181
|
+
if (existing)
|
|
182
|
+
return existing;
|
|
183
|
+
const controller = new AbortController();
|
|
184
|
+
const promise = this.openConnection(id, controller);
|
|
185
|
+
this.pendingConnections.set(id, { controller, promise });
|
|
186
|
+
try {
|
|
187
|
+
return await promise;
|
|
188
|
+
}
|
|
189
|
+
finally {
|
|
190
|
+
if (this.pendingConnections.get(id)?.promise === promise) {
|
|
191
|
+
this.pendingConnections.delete(id);
|
|
192
|
+
this.connecting.delete(id);
|
|
193
|
+
this.verifications.delete(id);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
async openConnection(id, controller) {
|
|
134
198
|
const entry = this.entry(id), profile = entry.profile;
|
|
135
199
|
const existing = this.clients.get(id);
|
|
136
200
|
if (existing)
|
|
@@ -147,8 +211,19 @@ export class ManagedServers {
|
|
|
147
211
|
if (profile.phase !== "deploying")
|
|
148
212
|
profile.phase = "connecting";
|
|
149
213
|
delete profile.error;
|
|
214
|
+
let requestedVerification = false;
|
|
150
215
|
try {
|
|
151
|
-
const client = await connectSsh({ host: profile.host, port: profile.sshPort, username: profile.username, authentication: profile.authentication, identityFile: profile.identityFile, fingerprint: profile.fingerprint, ...secret.ssh }
|
|
216
|
+
const client = await connectSsh({ host: profile.host, port: profile.sshPort, username: profile.username, authentication: profile.authentication, identityFile: profile.identityFile, fingerprint: profile.fingerprint, ...secret.ssh }, {
|
|
217
|
+
signal: controller.signal,
|
|
218
|
+
onVerification: challenge => new Promise((resolve, reject) => {
|
|
219
|
+
requestedVerification = true;
|
|
220
|
+
this.verifications.get(id)?.reject(new Error("SSH 服务器已更换验证轮次"));
|
|
221
|
+
const value = { ...challenge, id: randomUUID(), expiresAt: new Date(Date.now() + 180_000).toISOString() };
|
|
222
|
+
this.verifications.set(id, { challenge: value, resolve, reject });
|
|
223
|
+
profile.ssh = "awaitingVerification";
|
|
224
|
+
profile.phase = "awaitingVerification";
|
|
225
|
+
}),
|
|
226
|
+
});
|
|
152
227
|
if (!profile.enabled || this.stopped) {
|
|
153
228
|
client.end();
|
|
154
229
|
throw new Error("连接已取消");
|
|
@@ -165,12 +240,18 @@ export class ManagedServers {
|
|
|
165
240
|
await this.syncModels(id);
|
|
166
241
|
await this.ensureService(id);
|
|
167
242
|
}
|
|
168
|
-
else
|
|
169
|
-
|
|
243
|
+
else {
|
|
244
|
+
await this.detectExisting(id);
|
|
245
|
+
profile.phase = profile.existingService?.attached ? "ready" : "idle";
|
|
246
|
+
}
|
|
170
247
|
await this.persist();
|
|
171
248
|
return client;
|
|
172
249
|
}
|
|
173
250
|
catch (cause) {
|
|
251
|
+
if (requestedVerification || controller.signal.aborted)
|
|
252
|
+
this.authBlocked.add(id);
|
|
253
|
+
this.verifications.get(id)?.reject(cause instanceof Error ? cause : new Error("SSH 验证已结束"));
|
|
254
|
+
this.verifications.delete(id);
|
|
174
255
|
const failed = this.clients.get(id);
|
|
175
256
|
this.clients.delete(id);
|
|
176
257
|
failed?.end();
|
|
@@ -182,9 +263,6 @@ export class ManagedServers {
|
|
|
182
263
|
await this.persist();
|
|
183
264
|
throw cause;
|
|
184
265
|
}
|
|
185
|
-
finally {
|
|
186
|
-
this.connecting.delete(id);
|
|
187
|
-
}
|
|
188
266
|
}
|
|
189
267
|
async reverseModelChannel(entry, client) {
|
|
190
268
|
if (entry.profile.modelChannel === "online")
|
|
@@ -226,6 +304,10 @@ export class ManagedServers {
|
|
|
226
304
|
const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
|
|
227
305
|
if (!client || !secret)
|
|
228
306
|
return;
|
|
307
|
+
if (entry.compatibility) {
|
|
308
|
+
await this.detectExisting(id);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
229
311
|
try {
|
|
230
312
|
const info = await tunnelJson(client, entry.profile.servicePort, "/api/browser-access", secret.browserKey);
|
|
231
313
|
if (info.id !== entry.profile.identity)
|
|
@@ -242,6 +324,80 @@ export class ManagedServers {
|
|
|
242
324
|
entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
|
|
243
325
|
}
|
|
244
326
|
}
|
|
327
|
+
async detectExisting(id) {
|
|
328
|
+
const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
|
|
329
|
+
if (!client || !secret)
|
|
330
|
+
return;
|
|
331
|
+
let found = false;
|
|
332
|
+
try {
|
|
333
|
+
const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.serviceAccessToken ?? "");
|
|
334
|
+
if (health.service !== "super-pi" || typeof health.runningVersion !== "string")
|
|
335
|
+
throw new Error("所选端口不是可识别的 Super Pi 服务");
|
|
336
|
+
found = true;
|
|
337
|
+
entry.profile.existingService = { running: true, attached: false, version: health.runningVersion, dataDirectory: entry.existingInstallation?.dataDir };
|
|
338
|
+
const access = await tunnelJson(client, entry.profile.servicePort, "/api/terminal-shell", secret.serviceAccessToken ?? "");
|
|
339
|
+
if (!access || typeof access !== "object" || !("shell" in access))
|
|
340
|
+
throw new Error("已有服务未提供兼容的管理接口");
|
|
341
|
+
entry.compatibility = true;
|
|
342
|
+
entry.profile.identity ??= randomUUID();
|
|
343
|
+
entry.profile.existingService.attached = true;
|
|
344
|
+
entry.profile.service = "online";
|
|
345
|
+
entry.profile.modelChannel = "offline";
|
|
346
|
+
entry.profile.phase = "ready";
|
|
347
|
+
delete entry.profile.error;
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
entry.profile.service = "offline";
|
|
351
|
+
if (found) {
|
|
352
|
+
entry.profile.existingService.requiresToken = /401|403/.test(error instanceof Error ? error.message : "");
|
|
353
|
+
entry.profile.error = entry.profile.existingService.requiresToken ? "已有 Super Pi 服务要求访问密钥,请编辑连接填写原服务的访问密钥" : error instanceof Error ? error.message : "已有服务暂不可访问";
|
|
354
|
+
}
|
|
355
|
+
else if (!entry.existingInstallation) {
|
|
356
|
+
entry.existingInstallation = await discoverExistingInstallation(client);
|
|
357
|
+
if (entry.existingInstallation)
|
|
358
|
+
entry.profile.existingService = { running: false, attached: false, version: entry.existingInstallation.version, dataDirectory: entry.existingInstallation.dataDir, hasData: entry.existingInstallation.hasData, canStart: Boolean(entry.existingInstallation.cli && entry.existingInstallation.hasData) };
|
|
359
|
+
}
|
|
360
|
+
else if (entry.profile.existingService) {
|
|
361
|
+
entry.profile.existingService.running = false;
|
|
362
|
+
entry.profile.existingService.attached = false;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
await this.persist();
|
|
366
|
+
}
|
|
367
|
+
startExisting(id) {
|
|
368
|
+
const entry = this.entry(id);
|
|
369
|
+
if (this.jobs.has(id))
|
|
370
|
+
throw new Error("此服务器已有操作进行中");
|
|
371
|
+
if (!entry.existingInstallation?.cli || !entry.existingInstallation.hasData)
|
|
372
|
+
throw new Error("尚未确认原安装及数据目录,不会猜测目录并启动空实例");
|
|
373
|
+
const job = (async () => {
|
|
374
|
+
try {
|
|
375
|
+
entry.profile.phase = "connecting";
|
|
376
|
+
const client = await this.connect(id), old = entry.existingInstallation;
|
|
377
|
+
if (entry.profile.existingService?.attached)
|
|
378
|
+
return;
|
|
379
|
+
this.progress(entry, "启动已有 Super Pi,保留原数据和模型配置");
|
|
380
|
+
await sshExec(client, `SUPER_PI_DATA_DIR=${sh(old.dataDir)} ${sh(old.node)} ${sh(old.cli)} start --no-browser --port ${entry.profile.servicePort}`, { timeout: 90_000 });
|
|
381
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
382
|
+
await this.detectExisting(id);
|
|
383
|
+
if (entry.profile.existingService?.attached)
|
|
384
|
+
return;
|
|
385
|
+
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
386
|
+
}
|
|
387
|
+
throw new Error("原服务尚未启动,请查看原安装的服务日志;未修改其数据或安装包");
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
entry.profile.phase = "failed";
|
|
391
|
+
entry.profile.error = error instanceof Error ? error.message : "原服务启动失败";
|
|
392
|
+
}
|
|
393
|
+
finally {
|
|
394
|
+
this.jobs.delete(id);
|
|
395
|
+
await this.persist();
|
|
396
|
+
}
|
|
397
|
+
})();
|
|
398
|
+
this.jobs.set(id, job);
|
|
399
|
+
return entry.profile;
|
|
400
|
+
}
|
|
245
401
|
async ensureService(id) {
|
|
246
402
|
await this.health(id);
|
|
247
403
|
const entry = this.entry(id), client = this.clients.get(id);
|
|
@@ -282,6 +438,13 @@ export class ManagedServers {
|
|
|
282
438
|
try {
|
|
283
439
|
const client = await this.connect(id);
|
|
284
440
|
entry.profile.phase = "deploying";
|
|
441
|
+
if (entry.profile.existingService?.running && entry.compatibility) {
|
|
442
|
+
entry.profile.phase = "ready";
|
|
443
|
+
this.progress(entry, "已接入已有服务,原端口、工作区、会话和模型配置保持可用");
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
if (entry.existingInstallation)
|
|
447
|
+
throw new Error("检测到原有 Super Pi 安装,请先启动并接入已有服务,不会另建空实例覆盖原来的工作区和会话");
|
|
285
448
|
this.progress(entry, "生成与本地版本一致的纯服务安装包");
|
|
286
449
|
this.artifact ??= import(pathToFileURL(join(this.packageRoot, "scripts", "pack-server.mjs")).href).then(module => module.packServer(this.packageRoot, join(this.directory, "packages"))).catch(error => { this.artifact = undefined; throw error; });
|
|
287
450
|
const artifact = await this.artifact;
|
|
@@ -331,6 +494,7 @@ export class ManagedServers {
|
|
|
331
494
|
const entry = this.entry(id);
|
|
332
495
|
if (action === "disconnect") {
|
|
333
496
|
entry.profile.enabled = false;
|
|
497
|
+
await this.cancelConnection(id);
|
|
334
498
|
this.clients.get(id)?.end();
|
|
335
499
|
this.clients.delete(id);
|
|
336
500
|
entry.profile.ssh = "offline";
|
|
@@ -341,19 +505,23 @@ export class ManagedServers {
|
|
|
341
505
|
}
|
|
342
506
|
else if (action === "connect" || action === "test") {
|
|
343
507
|
entry.profile.enabled = true;
|
|
344
|
-
|
|
508
|
+
this.startConnection(id);
|
|
345
509
|
}
|
|
346
510
|
else if (action === "sync")
|
|
347
511
|
await this.syncModels(id, true);
|
|
512
|
+
else if (action === "startExisting")
|
|
513
|
+
return this.startExisting(id);
|
|
348
514
|
else if (action === "deploy")
|
|
349
515
|
return this.deploy(id);
|
|
350
516
|
else if (action === "remove") {
|
|
351
517
|
if (this.jobs.has(id))
|
|
352
518
|
throw new Error("部署期间不能移除服务器");
|
|
519
|
+
await this.cancelConnection(id);
|
|
353
520
|
this.clients.get(id)?.end();
|
|
354
521
|
this.clients.delete(id);
|
|
355
522
|
this.records.delete(id);
|
|
356
523
|
this.secrets.delete(id);
|
|
524
|
+
this.authBlocked.delete(id);
|
|
357
525
|
await rm(join(this.directory, "credentials", `${id}.secret`), { force: true });
|
|
358
526
|
}
|
|
359
527
|
else
|
|
@@ -365,7 +533,7 @@ export class ManagedServers {
|
|
|
365
533
|
if (this.stopped)
|
|
366
534
|
return;
|
|
367
535
|
for (const entry of this.records.values()) {
|
|
368
|
-
if (!entry.profile.enabled || this.jobs.has(entry.profile.id) || this.connecting.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
|
|
536
|
+
if (!entry.profile.enabled || this.jobs.has(entry.profile.id) || this.connecting.has(entry.profile.id) || this.authBlocked.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
|
|
369
537
|
continue;
|
|
370
538
|
try {
|
|
371
539
|
if (!this.clients.has(entry.profile.id))
|
|
@@ -374,23 +542,30 @@ export class ManagedServers {
|
|
|
374
542
|
await this.ensureService(entry.profile.id);
|
|
375
543
|
await this.syncModels(entry.profile.id);
|
|
376
544
|
}
|
|
545
|
+
else if (entry.compatibility)
|
|
546
|
+
await this.detectExisting(entry.profile.id);
|
|
377
547
|
}
|
|
378
548
|
catch { /* Each record carries its own actionable connection failure. */ }
|
|
379
549
|
}
|
|
380
550
|
}
|
|
381
|
-
connectionProfiles() { return [...this.records.values()].filter(entry => entry.profile.identity).map(entry => ({ id: `ssh-${entry.profile.id}`, managedId: entry.profile.id, managed: true, name: entry.profile.name, url: `/managed/${entry.profile.id}`, enabled: entry.profile.enabled, identity: entry.profile.identity, revision: entry.profile.deployedAt ? Date.parse(entry.profile.deployedAt) : 0 })); }
|
|
551
|
+
connectionProfiles() { return [...this.records.values()].filter(entry => entry.profile.identity).map(entry => ({ id: `ssh-${entry.profile.id}`, managedId: entry.profile.id, managed: true, legacy: Boolean(entry.compatibility), name: entry.profile.name, url: `/managed/${entry.profile.id}`, enabled: entry.profile.enabled, identity: entry.profile.identity, revision: entry.profile.deployedAt ? Date.parse(entry.profile.deployedAt) : 0 })); }
|
|
382
552
|
proxy(id, path, request, response) {
|
|
383
553
|
const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
|
|
384
554
|
if (!entry.profile.enabled || !client || !secret) {
|
|
385
555
|
response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "SSH 连接不可用,请在服务器连接设置中查看状态" }));
|
|
386
556
|
return;
|
|
387
557
|
}
|
|
388
|
-
|
|
558
|
+
if (entry.compatibility && path.split("?")[0] === "/api/browser-access") {
|
|
559
|
+
response.writeHead(request.method === "GET" ? 200 : 405, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(request.method === "GET" ? { id: entry.profile.identity, protocol: 1, enabled: true, legacy: true } : { error: "已有服务通过 SSH 连接授权,不在此处修改其原授权配置" }));
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
proxyThroughSsh(client, entry.profile.servicePort, entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey, path, request, response, `/managed/${id}`, Boolean(entry.compatibility));
|
|
389
563
|
}
|
|
390
564
|
async upgrade(id, path, request, socket, head) { const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id); if (!entry.profile.enabled || !client || !secret) {
|
|
391
565
|
socket.destroy();
|
|
392
566
|
return;
|
|
393
|
-
} await proxyWebSocketThroughSsh(client, entry.profile.servicePort, secret.browserKey, path, request, socket, head); }
|
|
394
|
-
async close() { this.stopped = true; clearInterval(this.timer); for (const
|
|
567
|
+
} await proxyWebSocketThroughSsh(client, entry.profile.servicePort, entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey, path, request, socket, head, Boolean(entry.compatibility)); }
|
|
568
|
+
async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
|
|
569
|
+
await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
|
|
395
570
|
client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
|
|
396
571
|
}
|
|
@@ -16,7 +16,20 @@ export declare class HostTrustRequired extends Error {
|
|
|
16
16
|
constructor(fingerprint: string, changed: boolean);
|
|
17
17
|
}
|
|
18
18
|
export declare const sh: (value: string) => string;
|
|
19
|
-
export
|
|
19
|
+
export interface SshConnectOptions {
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
handshakeTimeoutMs?: number;
|
|
22
|
+
verificationTimeoutMs?: number;
|
|
23
|
+
onVerification?: (challenge: {
|
|
24
|
+
name: string;
|
|
25
|
+
instruction: string;
|
|
26
|
+
prompts: {
|
|
27
|
+
prompt: string;
|
|
28
|
+
echo: boolean;
|
|
29
|
+
}[];
|
|
30
|
+
}) => Promise<string[]>;
|
|
31
|
+
}
|
|
32
|
+
export declare function connectSsh(profile: SshProfile, options?: SshConnectOptions): Promise<Client>;
|
|
20
33
|
export declare function sshExec(client: Client, command: string, options?: {
|
|
21
34
|
timeout?: number;
|
|
22
35
|
onOutput?: (chunk: string) => void;
|