@artenx/dshb 0.1.39 → 0.1.41
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/lib/auth/gate.d.ts +9 -1
- package/lib/auth/gate.js +12 -5
- package/lib/auth/gate.js.map +1 -1
- package/lib/auth/index.js +42 -9
- package/lib/auth/index.js.map +1 -1
- package/lib/catalog-BPkswHoz.js +121 -0
- package/lib/catalog-BPkswHoz.js.map +1 -0
- package/lib/client.js +482 -45
- package/lib/client.js.map +1 -1
- package/lib/{connection-sIX25pkS.d.ts → connection-CDJM9aUw.d.ts} +10 -3
- package/lib/core/index.js +480 -4
- package/lib/core/index.js.map +1 -1
- package/lib/core/routes.d.ts +1 -1
- package/lib/core/sync/coordinator.d.ts +5 -5
- package/lib/core/sync/coordinator.js +39 -6
- package/lib/core/sync/coordinator.js.map +1 -1
- package/lib/core/sync/host-key.d.ts +1 -1
- package/lib/core/sync/internal-routes.d.ts +3 -3
- package/lib/core/sync/internal-routes.js +36 -3
- package/lib/core/sync/internal-routes.js.map +1 -1
- package/lib/core/sync/model.d.ts +2 -2
- package/lib/core/sync/model.js +62 -1
- package/lib/core/sync/model.js.map +1 -1
- package/lib/core/sync/node-sync.d.ts +1 -1
- package/lib/core/sync/offline-archive.d.ts +6 -4
- package/lib/core/sync/offline-archive.js +31 -8
- package/lib/core/sync/offline-archive.js.map +1 -1
- package/lib/core/sync/offline-routes.js +29 -3
- package/lib/core/sync/offline-routes.js.map +1 -1
- package/lib/core/sync/peer-manager.d.ts +2 -2
- package/lib/core/sync/peer-manager.js +2 -0
- package/lib/core/sync/peer-manager.js.map +1 -1
- package/lib/core/sync/protocol.d.ts +2 -2
- package/lib/core/sync/protocol.js +2 -1
- package/lib/core/sync/protocol.js.map +1 -1
- package/lib/core/sync/remote-helper.js +4 -2
- package/lib/core/sync/remote-helper.js.map +1 -1
- package/lib/core/sync/routes.d.ts +1 -1
- package/lib/core/sync/routes.js +26 -1
- package/lib/core/sync/routes.js.map +1 -1
- package/lib/core/sync/session-journal.d.ts +1 -1
- package/lib/core/sync/session-routes.d.ts +1 -1
- package/lib/core/sync/session-routes.js +1 -1
- package/lib/core/sync/session-routes.js.map +1 -1
- package/lib/core/sync/session-sync.d.ts +1 -1
- package/lib/core/sync/session-sync.js +1 -1
- package/lib/core/sync/ssh-transport.d.ts +1 -1
- package/lib/core/sync/ssh-transport.js +73 -3
- package/lib/core/sync/ssh-transport.js.map +1 -1
- package/lib/core/sync/stores.d.ts +1 -1
- package/lib/core/sync/stores.js +8 -2
- package/lib/core/sync/stores.js.map +1 -1
- package/lib/core/workspaces.d.ts +1 -1
- package/lib/exec-ssh/connection-pool.d.ts +1 -1
- package/lib/exec-ssh/connection.d.ts +2 -2
- package/lib/exec-ssh/connection.js +29 -12
- package/lib/exec-ssh/connection.js.map +1 -1
- package/lib/exec-ssh/executor.d.ts +10 -1
- package/lib/exec-ssh/executor.js +91 -42
- package/lib/exec-ssh/executor.js.map +1 -1
- package/lib/exec-ssh/index.d.ts +1 -1
- package/lib/{host-key-CSnpIrjq.d.ts → host-key-CjO13Ds4.d.ts} +2 -2
- package/lib/{model-CKTBf-Pl.d.ts → model-CX2TlH2E.d.ts} +70 -6
- package/lib/{node-sync-C3Ym-HDu.d.ts → node-sync-qnJ7u0TU.d.ts} +3 -3
- package/lib/{protocol-DJ0zyVlB.d.ts → protocol-DyPDIJWa.d.ts} +3 -2
- package/lib/selection-BABQH1Rt.js +48 -0
- package/lib/selection-BABQH1Rt.js.map +1 -0
- package/lib/{session-journal-VE_1tA2-.d.ts → session-journal-lum5L2ip.d.ts} +2 -2
- package/lib/{session-sync-BBCm_ou2.js → session-sync-BV1CSYic.js} +85 -2
- package/lib/session-sync-BV1CSYic.js.map +1 -0
- package/lib/{session-sync-Bw0cZ4oa.d.ts → session-sync-Be5wuYHJ.d.ts} +12 -6
- package/lib/{ssh-transport-COZe0BDr.d.ts → ssh-transport-Cevwfre9.d.ts} +25 -6
- package/lib/{stores-puyTC075.d.ts → stores-BwQLabuJ.d.ts} +2 -2
- package/package.json +3 -1
- package/lib/session-sync-BBCm_ou2.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Client } from "ssh2";
|
|
1
|
+
import { Client, ConnectConfig } from "ssh2";
|
|
2
2
|
//#region src/exec-ssh/connection.d.ts
|
|
3
3
|
interface SshAuthConfig {
|
|
4
4
|
kind: 'password' | 'key' | 'agent';
|
|
@@ -29,6 +29,7 @@ interface SshConnectionError extends Error {
|
|
|
29
29
|
}
|
|
30
30
|
declare function classifySshError(err: unknown): SshErrorCategory;
|
|
31
31
|
declare function toConnectionError(err: unknown): SshConnectionError;
|
|
32
|
+
declare function buildConnectConfig(target: SshTarget, secrets: SshSecrets): ConnectConfig;
|
|
32
33
|
declare class SshConnection {
|
|
33
34
|
private readonly target;
|
|
34
35
|
private readonly secrets;
|
|
@@ -37,10 +38,16 @@ declare class SshConnection {
|
|
|
37
38
|
private closed;
|
|
38
39
|
constructor(target: SshTarget, secrets: SshSecrets);
|
|
39
40
|
getClient(): Promise<Client>;
|
|
41
|
+
/**
|
|
42
|
+
* Discard the current client after an operation-level fault (for example a
|
|
43
|
+
* timed-out channel or SFTP request on a frozen connection) so the next
|
|
44
|
+
* getClient() performs a fresh handshake instead of reusing a dead socket.
|
|
45
|
+
*/
|
|
46
|
+
invalidate(): void;
|
|
40
47
|
private connectWithRetry;
|
|
41
48
|
private connectOnce;
|
|
42
49
|
close(): void;
|
|
43
50
|
}
|
|
44
51
|
//#endregion
|
|
45
|
-
export { SshJumpHop as a,
|
|
46
|
-
//# sourceMappingURL=connection-
|
|
52
|
+
export { SshJumpHop as a, buildConnectConfig as c, SshErrorCategory as i, classifySshError as l, SshConnection as n, SshSecrets as o, SshConnectionError as r, SshTarget as s, SshAuthConfig as t, toConnectionError as u };
|
|
53
|
+
//# sourceMappingURL=connection-CDJM9aUw.d.ts.map
|
package/lib/core/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isLoopbackRequest } from "../auth/loopback.js";
|
|
1
2
|
import { sharedWorldResolver } from "../router/resolve.js";
|
|
2
3
|
import { sharedAuditLogger } from "./audit.js";
|
|
3
4
|
import { KnownHostsStore } from "./known-hosts.js";
|
|
@@ -10,10 +11,10 @@ import { sharedSessionInstructionSnapshotStore, sharedWorkspaceInstructionStore
|
|
|
10
11
|
import { registerWorkspaceInstructionRoutes } from "./workspace-instruction-routes.js";
|
|
11
12
|
import { WorkspaceBindingsStore } from "./workspace-bindings.js";
|
|
12
13
|
import { registerWorkspaceInstructionInjector } from "./workspace-instruction-context.js";
|
|
13
|
-
import { SyncPeerManager } from "./sync/peer-manager.js";
|
|
14
|
-
import { i as SyncSessionService } from "../session-sync-
|
|
14
|
+
import { SyncPeerManager, SyncPeerNotFoundError } from "./sync/peer-manager.js";
|
|
15
|
+
import { i as SyncSessionService } from "../session-sync-BV1CSYic.js";
|
|
15
16
|
import { registerSyncInternalRoutes } from "./sync/internal-routes.js";
|
|
16
|
-
import { SyncSshTransport } from "./sync/ssh-transport.js";
|
|
17
|
+
import { SyncSshProbeError, SyncSshTransport } from "./sync/ssh-transport.js";
|
|
17
18
|
import { SyncCoordinator } from "./sync/coordinator.js";
|
|
18
19
|
import { registerSyncPeerRoutes } from "./sync/routes.js";
|
|
19
20
|
import { SyncScheduler } from "./sync/scheduler.js";
|
|
@@ -21,6 +22,474 @@ import { registerSyncSessionRoutes } from "./sync/session-routes.js";
|
|
|
21
22
|
import { SyncOfflineArchiveService } from "./sync/offline-archive.js";
|
|
22
23
|
import { registerSyncOfflineRoutes } from "./sync/offline-routes.js";
|
|
23
24
|
import { SyncPeerStore, SyncStateStore } from "./sync/stores.js";
|
|
25
|
+
import { createHash, createHmac, randomUUID } from "node:crypto";
|
|
26
|
+
import { credentialKey } from "@deepseek-ai/dsh-credentials";
|
|
27
|
+
import { request } from "node:http";
|
|
28
|
+
//#region src/core/sync/relay-auth.ts
|
|
29
|
+
const RELAY_COOKIE_PREFIX = "dsh-auth-";
|
|
30
|
+
const RELAY_COOKIE_VERSION = 1;
|
|
31
|
+
const RELAY_SECRET_BYTES = 32;
|
|
32
|
+
const RELAY_TICKET_MAX_AGE_MS = 6e5;
|
|
33
|
+
const MAX_TICKETS_PER_MINUTE = 30;
|
|
34
|
+
const AUTHORITY_PATTERN = /^(?:[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?|\[(?:[0-9A-Fa-f:.]+)\])(?::\d{1,5})?$/;
|
|
35
|
+
var RelayTicketError = class extends Error {
|
|
36
|
+
code;
|
|
37
|
+
constructor(code, message) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.code = code;
|
|
40
|
+
this.name = "RelayTicketError";
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
function encodeBase64Url(value) {
|
|
44
|
+
return Buffer.from(value).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
|
|
45
|
+
}
|
|
46
|
+
function decodeBase64Url(value) {
|
|
47
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value) || value.length % 4 === 1) return void 0;
|
|
48
|
+
const decoded = Buffer.from(value.replaceAll("-", "+").replaceAll("_", "/"), "base64");
|
|
49
|
+
return encodeBase64Url(decoded) === value ? decoded : void 0;
|
|
50
|
+
}
|
|
51
|
+
/** 校验并提取 credentials 记录中的浏览器会话签名密钥(32 字节)。 */
|
|
52
|
+
function browserSessionSecret(record) {
|
|
53
|
+
if (record === null || typeof record !== "object" || Array.isArray(record)) throw new RelayTicketError("relay-secret-unavailable", "browser session credential record is missing");
|
|
54
|
+
const payload = record.payload;
|
|
55
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) throw new RelayTicketError("relay-secret-unavailable", "browser session credential payload is missing");
|
|
56
|
+
const { version, secret } = payload;
|
|
57
|
+
if (version !== RELAY_COOKIE_VERSION || typeof secret !== "string") throw new RelayTicketError("relay-secret-unavailable", "browser session credential payload is unsupported");
|
|
58
|
+
const decoded = decodeBase64Url(secret);
|
|
59
|
+
if (decoded === void 0 || decoded.byteLength !== RELAY_SECRET_BYTES) throw new RelayTicketError("relay-secret-unavailable", "browser session credential secret is invalid");
|
|
60
|
+
return decoded;
|
|
61
|
+
}
|
|
62
|
+
function validateRelayAuthority(value) {
|
|
63
|
+
if (typeof value !== "string" || value.length > 255 || !AUTHORITY_PATTERN.test(value)) throw new RelayTicketError("authority-invalid", "relay authority must be a bare host or host:port");
|
|
64
|
+
const port = value.includes("]:") || !value.includes("]") && value.includes(":") ? Number(value.slice(value.lastIndexOf(":") + 1)) : 80;
|
|
65
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new RelayTicketError("authority-invalid", "relay authority port is invalid");
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
/** 与 browser-auth 相同的 cookie 名派生:dsh-auth- + base64url(sha256(authority))。 */
|
|
69
|
+
function relayCookieName(authority) {
|
|
70
|
+
return RELAY_COOKIE_PREFIX + encodeBase64Url(createHash("sha256").update(authority).digest());
|
|
71
|
+
}
|
|
72
|
+
/** 按远端 Host browser-auth 的格式铸造一个权威名绑定的短时效签名 cookie。 */
|
|
73
|
+
function mintRelayCookie(secret, authority, now, maxAgeMs = RELAY_TICKET_MAX_AGE_MS) {
|
|
74
|
+
const issuedAt = now;
|
|
75
|
+
const expiresAt = issuedAt + maxAgeMs;
|
|
76
|
+
const body = encodeBase64Url(Buffer.from(JSON.stringify({
|
|
77
|
+
version: RELAY_COOKIE_VERSION,
|
|
78
|
+
authority,
|
|
79
|
+
issuedAt,
|
|
80
|
+
expiresAt
|
|
81
|
+
}), "utf8"));
|
|
82
|
+
const signature = createHmac("sha256", secret).update(body).digest();
|
|
83
|
+
return {
|
|
84
|
+
name: relayCookieName(authority),
|
|
85
|
+
value: `v1.${body}.${encodeBase64Url(signature)}`,
|
|
86
|
+
expiresAt,
|
|
87
|
+
maxAgeSeconds: Math.floor(maxAgeMs / 1e3)
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function relayCookieHeader(cookie) {
|
|
91
|
+
return `${cookie.name}=${cookie.value}`;
|
|
92
|
+
}
|
|
93
|
+
function readJsonBody(req, maxBytes) {
|
|
94
|
+
return new Promise((resolve) => {
|
|
95
|
+
const chunks = [];
|
|
96
|
+
let size = 0;
|
|
97
|
+
let settled = false;
|
|
98
|
+
const fail = () => {
|
|
99
|
+
if (settled) return;
|
|
100
|
+
settled = true;
|
|
101
|
+
resolve(null);
|
|
102
|
+
};
|
|
103
|
+
req.on("data", (chunk) => {
|
|
104
|
+
if (settled) return;
|
|
105
|
+
size += chunk.length;
|
|
106
|
+
if (size > maxBytes) {
|
|
107
|
+
fail();
|
|
108
|
+
req.destroy();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
chunks.push(chunk);
|
|
112
|
+
});
|
|
113
|
+
req.on("end", () => {
|
|
114
|
+
if (settled) return;
|
|
115
|
+
try {
|
|
116
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
117
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
118
|
+
fail();
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
settled = true;
|
|
122
|
+
resolve(value);
|
|
123
|
+
} catch {
|
|
124
|
+
fail();
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
req.on("error", fail);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* 远端侧中继凭据铸造路由:POST /api/dshb/sync/internal/relay-ticket。
|
|
132
|
+
* 仅接受回环请求;用本机 credentials 的浏览器会话密钥为请求指定的
|
|
133
|
+
* authority 铸造 ≤10 分钟签名 cookie。凭据只在响应中返回一次。
|
|
134
|
+
*/
|
|
135
|
+
function registerRelayTicketRoutes(ctx, credentials) {
|
|
136
|
+
const rateLimit = {
|
|
137
|
+
windowStart: 0,
|
|
138
|
+
count: 0
|
|
139
|
+
};
|
|
140
|
+
ctx.effect(() => ctx.webServer.register({
|
|
141
|
+
kind: "exact",
|
|
142
|
+
path: "/api/dshb/sync/internal/relay-ticket",
|
|
143
|
+
handler: async (req, res) => {
|
|
144
|
+
const deny = (status, body) => {
|
|
145
|
+
res.writeHead(status, {
|
|
146
|
+
"content-type": "application/json",
|
|
147
|
+
"cache-control": "no-store"
|
|
148
|
+
});
|
|
149
|
+
res.end(JSON.stringify(body));
|
|
150
|
+
};
|
|
151
|
+
if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {
|
|
152
|
+
deny(403, {
|
|
153
|
+
ok: false,
|
|
154
|
+
error: "loopback access required"
|
|
155
|
+
});
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (req.method !== "POST") {
|
|
159
|
+
deny(405, {
|
|
160
|
+
ok: false,
|
|
161
|
+
error: "method not allowed"
|
|
162
|
+
});
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const now = Date.now();
|
|
166
|
+
if (now - rateLimit.windowStart > 6e4) {
|
|
167
|
+
rateLimit.windowStart = now;
|
|
168
|
+
rateLimit.count = 0;
|
|
169
|
+
}
|
|
170
|
+
rateLimit.count += 1;
|
|
171
|
+
if (rateLimit.count > MAX_TICKETS_PER_MINUTE) {
|
|
172
|
+
deny(429, {
|
|
173
|
+
ok: false,
|
|
174
|
+
error: "relay ticket rate limit exceeded"
|
|
175
|
+
});
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const body = await readJsonBody(req, 1024);
|
|
179
|
+
let authority;
|
|
180
|
+
try {
|
|
181
|
+
authority = validateRelayAuthority(body?.authority);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
deny(400, {
|
|
184
|
+
ok: false,
|
|
185
|
+
code: error instanceof RelayTicketError ? error.code : "authority-invalid",
|
|
186
|
+
error: error instanceof Error ? error.message : "authority is invalid"
|
|
187
|
+
});
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
const cookie = mintRelayCookie(browserSessionSecret(await credentials.readRecord(credentialKey("client-connection", "browser-session"))), authority, now);
|
|
192
|
+
res.writeHead(200, {
|
|
193
|
+
"content-type": "application/json",
|
|
194
|
+
"cache-control": "no-store"
|
|
195
|
+
});
|
|
196
|
+
res.end(JSON.stringify({
|
|
197
|
+
ok: true,
|
|
198
|
+
cookie: {
|
|
199
|
+
name: cookie.name,
|
|
200
|
+
value: cookie.value,
|
|
201
|
+
maxAgeSeconds: cookie.maxAgeSeconds
|
|
202
|
+
}
|
|
203
|
+
}));
|
|
204
|
+
} catch (error) {
|
|
205
|
+
if (error instanceof RelayTicketError) {
|
|
206
|
+
deny(503, {
|
|
207
|
+
ok: false,
|
|
208
|
+
code: error.code,
|
|
209
|
+
error: error.message
|
|
210
|
+
});
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
deny(500, {
|
|
214
|
+
ok: false,
|
|
215
|
+
code: "relay-ticket-failed",
|
|
216
|
+
error: "relay ticket minting failed"
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
//#endregion
|
|
223
|
+
//#region src/core/sync/remote-relay.ts
|
|
224
|
+
const DEFAULT_REMOTE_WEB_PORT = 3080;
|
|
225
|
+
const MAX_RELAY_RESPONSE_BYTES = 67108864;
|
|
226
|
+
const TICKET_REFRESH_MARGIN_MS = 6e4;
|
|
227
|
+
const ENDPOINT_PATTERN = /^[a-z][A-Za-z0-9$]*\/[A-Za-z0-9$.]+$/;
|
|
228
|
+
var RemoteRelayError = class extends Error {
|
|
229
|
+
code;
|
|
230
|
+
constructor(code, message) {
|
|
231
|
+
super(message);
|
|
232
|
+
this.code = code;
|
|
233
|
+
this.name = "RemoteRelayError";
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
var RemoteRelayService = class {
|
|
237
|
+
peers;
|
|
238
|
+
transport;
|
|
239
|
+
now;
|
|
240
|
+
tickets = /* @__PURE__ */ new Map();
|
|
241
|
+
constructor(peers, transport, now = Date.now) {
|
|
242
|
+
this.peers = peers;
|
|
243
|
+
this.transport = transport;
|
|
244
|
+
this.now = now;
|
|
245
|
+
}
|
|
246
|
+
/** peer 的远端回环权威名;铸造 cookie 与改写 Host 头都必须用它。 */
|
|
247
|
+
remoteAuthority(peerId) {
|
|
248
|
+
return this.withPeer(peerId, (peer) => `127.0.0.1:${peer.remoteWebPort ?? DEFAULT_REMOTE_WEB_PORT}`);
|
|
249
|
+
}
|
|
250
|
+
async withPeer(peerId, action) {
|
|
251
|
+
const peer = await this.peers.get(peerId);
|
|
252
|
+
if (!peer) throw new SyncPeerNotFoundError(peerId);
|
|
253
|
+
return action(peer);
|
|
254
|
+
}
|
|
255
|
+
/** 取得有效中继凭据;过期前 60 秒起重新铸造,凭据仅存内存。 */
|
|
256
|
+
async relayTicket(peerId) {
|
|
257
|
+
const authority = await this.remoteAuthority(peerId);
|
|
258
|
+
const cached = this.tickets.get(peerId);
|
|
259
|
+
if (cached && cached.authority === authority && cached.cookie.expiresAt - TICKET_REFRESH_MARGIN_MS > this.now()) return cached.cookie;
|
|
260
|
+
const fetched = await this.transport.fetchRelayTicket(peerId, authority);
|
|
261
|
+
const cookie = {
|
|
262
|
+
name: fetched.name,
|
|
263
|
+
value: fetched.value,
|
|
264
|
+
expiresAt: this.now() + fetched.maxAgeSeconds * 1e3,
|
|
265
|
+
maxAgeSeconds: fetched.maxAgeSeconds
|
|
266
|
+
};
|
|
267
|
+
this.tickets.set(peerId, {
|
|
268
|
+
authority,
|
|
269
|
+
cookie,
|
|
270
|
+
fetchedAt: this.now()
|
|
271
|
+
});
|
|
272
|
+
return cookie;
|
|
273
|
+
}
|
|
274
|
+
/** 打开到远端回环端口的 SSH direct-tcpip 通道;调用方负责 close()。 */
|
|
275
|
+
async openChannel(peerId) {
|
|
276
|
+
const authority = await this.remoteAuthority(peerId);
|
|
277
|
+
const remotePort = Number(authority.slice(authority.lastIndexOf(":") + 1));
|
|
278
|
+
const { peer, client, stream } = await this.transport.openDirectChannel(peerId, "127.0.0.1", remotePort);
|
|
279
|
+
return {
|
|
280
|
+
client,
|
|
281
|
+
socket: stream,
|
|
282
|
+
peerRemotePort: remotePort,
|
|
283
|
+
close: () => {
|
|
284
|
+
try {
|
|
285
|
+
stream.destroy();
|
|
286
|
+
} catch {}
|
|
287
|
+
try {
|
|
288
|
+
client.end();
|
|
289
|
+
} catch {}
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
/** 转发一次 Remote unary 调用:POST /api/<endpoint>,返回远端信封。 */
|
|
294
|
+
async relayCall(peerId, endpoint, payload) {
|
|
295
|
+
if (!ENDPOINT_PATTERN.test(endpoint)) throw new RemoteRelayError("endpoint-invalid", "relay endpoint is invalid");
|
|
296
|
+
const authority = await this.remoteAuthority(peerId);
|
|
297
|
+
const cookie = await this.relayTicket(peerId);
|
|
298
|
+
return this.relayRequest(peerId, {
|
|
299
|
+
method: "POST",
|
|
300
|
+
path: `/api/${endpoint}`,
|
|
301
|
+
authority,
|
|
302
|
+
headers: { "content-type": "application/json" },
|
|
303
|
+
body: Buffer.from(JSON.stringify({
|
|
304
|
+
type: "client-request",
|
|
305
|
+
rpcId: randomUUID(),
|
|
306
|
+
method: endpoint,
|
|
307
|
+
payload
|
|
308
|
+
}), "utf8"),
|
|
309
|
+
cookie
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
async relayRequest(peerId, request$1) {
|
|
313
|
+
const channel = await this.openChannel(peerId);
|
|
314
|
+
try {
|
|
315
|
+
return await new Promise((resolve, reject) => {
|
|
316
|
+
const req = request({
|
|
317
|
+
host: "127.0.0.1",
|
|
318
|
+
port: channel.peerRemotePort,
|
|
319
|
+
method: request$1.method,
|
|
320
|
+
path: request$1.path,
|
|
321
|
+
headers: {
|
|
322
|
+
host: request$1.authority,
|
|
323
|
+
...request$1.cookie ? { cookie: relayCookieHeader(request$1.cookie) } : {},
|
|
324
|
+
...request$1.headers
|
|
325
|
+
},
|
|
326
|
+
createConnection: () => channel.socket
|
|
327
|
+
});
|
|
328
|
+
let settled = false;
|
|
329
|
+
const finish = (error, value) => {
|
|
330
|
+
if (settled) return;
|
|
331
|
+
settled = true;
|
|
332
|
+
if (error) reject(error);
|
|
333
|
+
else resolve(value);
|
|
334
|
+
};
|
|
335
|
+
req.on("error", (error) => finish(new RemoteRelayError("relay-unreachable", `relay request failed: ${error.message}`)));
|
|
336
|
+
const responseChunks = [];
|
|
337
|
+
let responseBytes = 0;
|
|
338
|
+
req.on("response", (res) => {
|
|
339
|
+
res.on("data", (chunk) => {
|
|
340
|
+
responseBytes += chunk.length;
|
|
341
|
+
if (responseBytes > MAX_RELAY_RESPONSE_BYTES) {
|
|
342
|
+
res.destroy();
|
|
343
|
+
finish(new RemoteRelayError("relay-response-too-large", "relay response exceeds the size limit"));
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
responseChunks.push(chunk);
|
|
347
|
+
});
|
|
348
|
+
res.on("end", () => {
|
|
349
|
+
finish(void 0, {
|
|
350
|
+
status: res.statusCode ?? 502,
|
|
351
|
+
body: Buffer.concat(responseChunks, responseBytes),
|
|
352
|
+
contentType: String(res.headers["content-type"] ?? "application/json")
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
res.on("error", (error) => finish(new RemoteRelayError("relay-unreachable", `relay response failed: ${error.message}`)));
|
|
356
|
+
});
|
|
357
|
+
if (request$1.body) req.write(request$1.body);
|
|
358
|
+
req.end();
|
|
359
|
+
});
|
|
360
|
+
} finally {
|
|
361
|
+
channel.close();
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/** 丢弃指定对端缓存的中继凭据(对端重启或凭据被拒时调用)。 */
|
|
365
|
+
dropTicket(peerId) {
|
|
366
|
+
this.tickets.delete(peerId);
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
/**
|
|
370
|
+
* 本地路由:POST /api/dshb/sync/relay/<peerId>/call/<namespace>/<method>。
|
|
371
|
+
* 认证由 DSHB 登录门覆盖(/api 前缀);凭据铸造失败按分类返回。
|
|
372
|
+
*/
|
|
373
|
+
function registerRemoteRelayRoutes(ctx, relay) {
|
|
374
|
+
ctx.effect(() => ctx.webServer.register({
|
|
375
|
+
kind: "prefix",
|
|
376
|
+
path: "/api/dshb/sync/relay",
|
|
377
|
+
handler: async (req, res) => {
|
|
378
|
+
const segments = new URL(req.url ?? "/", "http://x").pathname.split("/").filter(Boolean);
|
|
379
|
+
const peerId = segments[4];
|
|
380
|
+
const action = segments[5];
|
|
381
|
+
const deny = (status, body) => {
|
|
382
|
+
res.writeHead(status, {
|
|
383
|
+
"content-type": "application/json",
|
|
384
|
+
"cache-control": "no-store"
|
|
385
|
+
});
|
|
386
|
+
res.end(JSON.stringify(body));
|
|
387
|
+
};
|
|
388
|
+
if (!peerId || segments.length < 5) {
|
|
389
|
+
deny(404, {
|
|
390
|
+
ok: false,
|
|
391
|
+
error: "not found"
|
|
392
|
+
});
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (action === "call" && req.method === "POST") {
|
|
396
|
+
const endpoint = segments.slice(6).join("/");
|
|
397
|
+
let payload;
|
|
398
|
+
try {
|
|
399
|
+
const raw = await readBody(req);
|
|
400
|
+
payload = raw === void 0 ? void 0 : JSON.parse(raw.toString("utf8"));
|
|
401
|
+
} catch {
|
|
402
|
+
deny(400, {
|
|
403
|
+
ok: false,
|
|
404
|
+
error: "request body must be JSON"
|
|
405
|
+
});
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
try {
|
|
409
|
+
const result = await relay.relayCall(peerId, endpoint, payload);
|
|
410
|
+
res.writeHead(result.status, {
|
|
411
|
+
"content-type": result.contentType,
|
|
412
|
+
"cache-control": "no-store"
|
|
413
|
+
});
|
|
414
|
+
res.end(result.body);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
relayFailure(res, deny, error);
|
|
417
|
+
}
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
deny(404, {
|
|
421
|
+
ok: false,
|
|
422
|
+
error: "not found"
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
}));
|
|
426
|
+
}
|
|
427
|
+
function relayFailure(res, deny, error) {
|
|
428
|
+
if (error instanceof RelayTicketError) {
|
|
429
|
+
deny(502, {
|
|
430
|
+
ok: false,
|
|
431
|
+
code: error.code,
|
|
432
|
+
error: error.message
|
|
433
|
+
});
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
if (error instanceof SyncPeerNotFoundError) {
|
|
437
|
+
deny(404, {
|
|
438
|
+
ok: false,
|
|
439
|
+
error: "sync peer not found"
|
|
440
|
+
});
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (error instanceof SyncSshProbeError) {
|
|
444
|
+
deny(error.category === "auth" ? 502 : error.category === "protocol" || error.category === "hostkey" ? 409 : 503, {
|
|
445
|
+
ok: false,
|
|
446
|
+
code: `ssh-${error.category}`,
|
|
447
|
+
error: error.message
|
|
448
|
+
});
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (error instanceof RemoteRelayError) {
|
|
452
|
+
deny(error.code === "endpoint-invalid" || error.code === "relay-response-too-large" ? 400 : 502, {
|
|
453
|
+
ok: false,
|
|
454
|
+
code: error.code,
|
|
455
|
+
error: error.message
|
|
456
|
+
});
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
deny(500, {
|
|
460
|
+
ok: false,
|
|
461
|
+
error: "remote relay failed"
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
function readBody(req, maxBytes = 8388608) {
|
|
465
|
+
return new Promise((resolve) => {
|
|
466
|
+
const chunks = [];
|
|
467
|
+
let size = 0;
|
|
468
|
+
let settled = false;
|
|
469
|
+
const fail = () => {
|
|
470
|
+
if (settled) return;
|
|
471
|
+
settled = true;
|
|
472
|
+
resolve(void 0);
|
|
473
|
+
};
|
|
474
|
+
req.on("data", (chunk) => {
|
|
475
|
+
if (settled) return;
|
|
476
|
+
size += chunk.length;
|
|
477
|
+
if (size > maxBytes) {
|
|
478
|
+
fail();
|
|
479
|
+
req.destroy();
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
chunks.push(chunk);
|
|
483
|
+
});
|
|
484
|
+
req.on("end", () => {
|
|
485
|
+
if (settled) return;
|
|
486
|
+
settled = true;
|
|
487
|
+
resolve(Buffer.concat(chunks, size));
|
|
488
|
+
});
|
|
489
|
+
req.on("error", fail);
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
//#endregion
|
|
24
493
|
//#region src/core/index.ts
|
|
25
494
|
const name = "dshb-core";
|
|
26
495
|
const inject = ["webServer", "credentials"];
|
|
@@ -42,7 +511,10 @@ function apply(ctx) {
|
|
|
42
511
|
sshWorlds?.remove?.(nodeId);
|
|
43
512
|
dockerWorlds?.remove?.(nodeId);
|
|
44
513
|
});
|
|
45
|
-
const syncSessions = new SyncSessionService(syncState, syncNodes, registry, bindings, () => workspaceRegistry, () => ctx.get("sessionPersistence"), () => ctx.get("attachments"), () => ctx.get("spillStore"), sharedSessionInstructionSnapshotStore(), void 0, void 0, process.env.DSH_HOME)
|
|
514
|
+
const syncSessions = new SyncSessionService(syncState, syncNodes, registry, bindings, () => workspaceRegistry, () => ctx.get("sessionPersistence"), () => ctx.get("attachments"), () => ctx.get("spillStore"), sharedSessionInstructionSnapshotStore(), void 0, void 0, process.env.DSH_HOME, void 0, (header) => {
|
|
515
|
+
const title = ctx.get("sessionProjectionCache")?.cachedSnapshot?.(header, ["title"])?.values?.title;
|
|
516
|
+
return typeof title === "string" && title.trim() ? title : void 0;
|
|
517
|
+
});
|
|
46
518
|
const syncOfflineArchives = new SyncOfflineArchiveService(syncNodes, syncSessions, void 0, void 0, syncState);
|
|
47
519
|
try {
|
|
48
520
|
syncOfflineArchives.cleanupStagingDirectories();
|
|
@@ -75,6 +547,10 @@ function apply(ctx) {
|
|
|
75
547
|
registerSyncInternalRoutes(ctx, syncState, syncNodes, syncSessions);
|
|
76
548
|
registerSyncSessionRoutes(ctx, syncSessions);
|
|
77
549
|
registerSyncOfflineRoutes(ctx, syncOfflineArchives);
|
|
550
|
+
registerRelayTicketRoutes(ctx, ctx.credentials);
|
|
551
|
+
const remoteRelay = new RemoteRelayService(syncPeerManager, syncSshTransport);
|
|
552
|
+
ctx.provide("remoteRelayService", remoteRelay);
|
|
553
|
+
registerRemoteRelayRoutes(ctx, remoteRelay);
|
|
78
554
|
ctx.effect(() => {
|
|
79
555
|
const stopScheduler = syncScheduler.start();
|
|
80
556
|
const inboxSweeper = setInterval(() => {
|