@evandu/super-pi 0.1.259 → 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/README.md +3 -1
- package/bin/super-pi.js +1 -1
- package/desktop/brand.svg +6 -0
- package/desktop/icon.png +0 -0
- package/desktop/launch.cjs +7 -7
- package/desktop/login-item.cjs +7 -0
- package/desktop/main.cjs +27 -7
- package/desktop/preload.cjs +19 -0
- package/desktop/runtime.cjs +107 -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 +199 -20
- package/dist/server/managed-ssh.d.ts +14 -1
- package/dist/server/managed-ssh.js +55 -5
- package/dist/server/runtime.js +2 -2
- package/dist/shared/managed-servers.d.ts +23 -2
- package/package.json +8 -1
- package/scripts/pack-server.mjs +1 -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;
|
|
@@ -53,11 +57,15 @@ export class ManagedServers {
|
|
|
53
57
|
}
|
|
54
58
|
this.gatewayServer = createServer((request, response) => {
|
|
55
59
|
const value = request.headers.authorization?.replace(/^Bearer /, "") ?? "";
|
|
60
|
+
const supplied = Buffer.from(value);
|
|
56
61
|
const valid = [...this.records.values()].some(entry => {
|
|
57
62
|
if (!entry.profile.enabled)
|
|
58
63
|
return false;
|
|
59
64
|
const token = this.secrets.get(entry.profile.id)?.modelToken;
|
|
60
|
-
|
|
65
|
+
if (!token)
|
|
66
|
+
return false;
|
|
67
|
+
const expected = Buffer.from(token);
|
|
68
|
+
return supplied.length === expected.length && timingSafeEqual(supplied, expected);
|
|
61
69
|
});
|
|
62
70
|
if (request.url !== "/model" || !valid) {
|
|
63
71
|
response.writeHead(403).end();
|
|
@@ -71,7 +79,41 @@ export class ManagedServers {
|
|
|
71
79
|
this.timer.unref();
|
|
72
80
|
void this.maintain();
|
|
73
81
|
}
|
|
74
|
-
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
|
+
}
|
|
75
117
|
persist() {
|
|
76
118
|
const data = JSON.stringify({ servers: [...this.records.values()] }, null, 2);
|
|
77
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); });
|
|
@@ -89,10 +131,11 @@ export class ManagedServers {
|
|
|
89
131
|
const id = input.id ?? randomUUID(), previous = input.id ? this.entry(input.id) : undefined;
|
|
90
132
|
if (this.jobs.has(id))
|
|
91
133
|
throw new Error("部署尚未完成,暂不能修改连接");
|
|
134
|
+
await this.cancelConnection(id, "SSH 连接配置已修改,请重新验证");
|
|
92
135
|
if ([...this.records.values()].some(item => item.profile.id !== id && item.profile.name === input.name.trim()))
|
|
93
136
|
throw new Error("服务器名称已存在");
|
|
94
137
|
const old = this.secrets.get(id);
|
|
95
|
-
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 };
|
|
96
139
|
if (input.authentication === "password" && !secret.ssh.password)
|
|
97
140
|
throw new Error("请输入 SSH 密码");
|
|
98
141
|
if (input.authentication === "privateKey" && !input.identityFile && !secret.ssh.privateKey)
|
|
@@ -104,18 +147,18 @@ export class ManagedServers {
|
|
|
104
147
|
delete secret.ssh.passphrase;
|
|
105
148
|
}
|
|
106
149
|
const changedHost = previous && (previous.profile.host !== input.host.trim() || previous.profile.sshPort !== input.sshPort || previous.profile.username !== input.username.trim());
|
|
107
|
-
if (changedHost && previous.installation)
|
|
108
|
-
throw new Error("
|
|
150
|
+
if ((changedHost && (previous.installation || previous.compatibility)) || (previous?.compatibility && previous.profile.servicePort !== input.servicePort))
|
|
151
|
+
throw new Error("已接入服务器不能改为另一台主机或服务,请添加新连接以保护工作区归属");
|
|
109
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 };
|
|
110
153
|
this.clients.get(id)?.end();
|
|
111
154
|
this.clients.delete(id);
|
|
112
155
|
await this.vault.write(id, secret);
|
|
113
156
|
this.secrets.set(id, secret);
|
|
114
|
-
this.records.set(id, { ...previous, profile });
|
|
157
|
+
this.records.set(id, { ...(changedHost ? {} : previous), profile });
|
|
115
158
|
await this.persist();
|
|
116
159
|
return profile;
|
|
117
160
|
}
|
|
118
|
-
async trust(id, fingerprint) {
|
|
161
|
+
async trust(id, fingerprint, background = false) {
|
|
119
162
|
const entry = this.entry(id);
|
|
120
163
|
if (!entry.profile.observedFingerprint || fingerprint !== entry.profile.observedFingerprint)
|
|
121
164
|
throw new Error("主机指纹已变化,请重新检测后确认");
|
|
@@ -123,10 +166,35 @@ export class ManagedServers {
|
|
|
123
166
|
delete entry.profile.observedFingerprint;
|
|
124
167
|
entry.profile.phase = "idle";
|
|
125
168
|
await this.persist();
|
|
126
|
-
|
|
169
|
+
this.authBlocked.delete(id);
|
|
170
|
+
if (background)
|
|
171
|
+
this.startConnection(id);
|
|
172
|
+
else
|
|
173
|
+
await this.connect(id);
|
|
127
174
|
return this.entry(id).profile;
|
|
128
175
|
}
|
|
129
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) {
|
|
130
198
|
const entry = this.entry(id), profile = entry.profile;
|
|
131
199
|
const existing = this.clients.get(id);
|
|
132
200
|
if (existing)
|
|
@@ -143,8 +211,19 @@ export class ManagedServers {
|
|
|
143
211
|
if (profile.phase !== "deploying")
|
|
144
212
|
profile.phase = "connecting";
|
|
145
213
|
delete profile.error;
|
|
214
|
+
let requestedVerification = false;
|
|
146
215
|
try {
|
|
147
|
-
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
|
+
});
|
|
148
227
|
if (!profile.enabled || this.stopped) {
|
|
149
228
|
client.end();
|
|
150
229
|
throw new Error("连接已取消");
|
|
@@ -161,12 +240,18 @@ export class ManagedServers {
|
|
|
161
240
|
await this.syncModels(id);
|
|
162
241
|
await this.ensureService(id);
|
|
163
242
|
}
|
|
164
|
-
else
|
|
165
|
-
|
|
243
|
+
else {
|
|
244
|
+
await this.detectExisting(id);
|
|
245
|
+
profile.phase = profile.existingService?.attached ? "ready" : "idle";
|
|
246
|
+
}
|
|
166
247
|
await this.persist();
|
|
167
248
|
return client;
|
|
168
249
|
}
|
|
169
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);
|
|
170
255
|
const failed = this.clients.get(id);
|
|
171
256
|
this.clients.delete(id);
|
|
172
257
|
failed?.end();
|
|
@@ -178,9 +263,6 @@ export class ManagedServers {
|
|
|
178
263
|
await this.persist();
|
|
179
264
|
throw cause;
|
|
180
265
|
}
|
|
181
|
-
finally {
|
|
182
|
-
this.connecting.delete(id);
|
|
183
|
-
}
|
|
184
266
|
}
|
|
185
267
|
async reverseModelChannel(entry, client) {
|
|
186
268
|
if (entry.profile.modelChannel === "online")
|
|
@@ -222,6 +304,10 @@ export class ManagedServers {
|
|
|
222
304
|
const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
|
|
223
305
|
if (!client || !secret)
|
|
224
306
|
return;
|
|
307
|
+
if (entry.compatibility) {
|
|
308
|
+
await this.detectExisting(id);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
225
311
|
try {
|
|
226
312
|
const info = await tunnelJson(client, entry.profile.servicePort, "/api/browser-access", secret.browserKey);
|
|
227
313
|
if (info.id !== entry.profile.identity)
|
|
@@ -238,6 +324,80 @@ export class ManagedServers {
|
|
|
238
324
|
entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
|
|
239
325
|
}
|
|
240
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
|
+
}
|
|
241
401
|
async ensureService(id) {
|
|
242
402
|
await this.health(id);
|
|
243
403
|
const entry = this.entry(id), client = this.clients.get(id);
|
|
@@ -278,6 +438,13 @@ export class ManagedServers {
|
|
|
278
438
|
try {
|
|
279
439
|
const client = await this.connect(id);
|
|
280
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 安装,请先启动并接入已有服务,不会另建空实例覆盖原来的工作区和会话");
|
|
281
448
|
this.progress(entry, "生成与本地版本一致的纯服务安装包");
|
|
282
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; });
|
|
283
450
|
const artifact = await this.artifact;
|
|
@@ -327,6 +494,7 @@ export class ManagedServers {
|
|
|
327
494
|
const entry = this.entry(id);
|
|
328
495
|
if (action === "disconnect") {
|
|
329
496
|
entry.profile.enabled = false;
|
|
497
|
+
await this.cancelConnection(id);
|
|
330
498
|
this.clients.get(id)?.end();
|
|
331
499
|
this.clients.delete(id);
|
|
332
500
|
entry.profile.ssh = "offline";
|
|
@@ -337,19 +505,23 @@ export class ManagedServers {
|
|
|
337
505
|
}
|
|
338
506
|
else if (action === "connect" || action === "test") {
|
|
339
507
|
entry.profile.enabled = true;
|
|
340
|
-
|
|
508
|
+
this.startConnection(id);
|
|
341
509
|
}
|
|
342
510
|
else if (action === "sync")
|
|
343
511
|
await this.syncModels(id, true);
|
|
512
|
+
else if (action === "startExisting")
|
|
513
|
+
return this.startExisting(id);
|
|
344
514
|
else if (action === "deploy")
|
|
345
515
|
return this.deploy(id);
|
|
346
516
|
else if (action === "remove") {
|
|
347
517
|
if (this.jobs.has(id))
|
|
348
518
|
throw new Error("部署期间不能移除服务器");
|
|
519
|
+
await this.cancelConnection(id);
|
|
349
520
|
this.clients.get(id)?.end();
|
|
350
521
|
this.clients.delete(id);
|
|
351
522
|
this.records.delete(id);
|
|
352
523
|
this.secrets.delete(id);
|
|
524
|
+
this.authBlocked.delete(id);
|
|
353
525
|
await rm(join(this.directory, "credentials", `${id}.secret`), { force: true });
|
|
354
526
|
}
|
|
355
527
|
else
|
|
@@ -361,7 +533,7 @@ export class ManagedServers {
|
|
|
361
533
|
if (this.stopped)
|
|
362
534
|
return;
|
|
363
535
|
for (const entry of this.records.values()) {
|
|
364
|
-
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")
|
|
365
537
|
continue;
|
|
366
538
|
try {
|
|
367
539
|
if (!this.clients.has(entry.profile.id))
|
|
@@ -370,23 +542,30 @@ export class ManagedServers {
|
|
|
370
542
|
await this.ensureService(entry.profile.id);
|
|
371
543
|
await this.syncModels(entry.profile.id);
|
|
372
544
|
}
|
|
545
|
+
else if (entry.compatibility)
|
|
546
|
+
await this.detectExisting(entry.profile.id);
|
|
373
547
|
}
|
|
374
548
|
catch { /* Each record carries its own actionable connection failure. */ }
|
|
375
549
|
}
|
|
376
550
|
}
|
|
377
|
-
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 })); }
|
|
378
552
|
proxy(id, path, request, response) {
|
|
379
553
|
const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
|
|
380
554
|
if (!entry.profile.enabled || !client || !secret) {
|
|
381
555
|
response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "SSH 连接不可用,请在服务器连接设置中查看状态" }));
|
|
382
556
|
return;
|
|
383
557
|
}
|
|
384
|
-
|
|
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));
|
|
385
563
|
}
|
|
386
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) {
|
|
387
565
|
socket.destroy();
|
|
388
566
|
return;
|
|
389
|
-
} await proxyWebSocketThroughSsh(client, entry.profile.servicePort, secret.browserKey, path, request, socket, head); }
|
|
390
|
-
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())
|
|
391
570
|
client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
|
|
392
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;
|