@hjd-hitsz/claudex-web 4.1.5 → 4.2.1
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/.env.example +2 -0
- package/CHANGELOG.md +57 -0
- package/README.md +16 -4
- package/bin/auth.mjs +86 -0
- package/bin/claudex-web.mjs +20 -0
- package/bin/p2p.mjs +134 -0
- package/build-info.json +4 -4
- package/client/dist/app.js +154 -122
- package/client/dist/code-highlight-style.js +23 -45
- package/client/dist/document-editor.js +54 -54
- package/client/dist/file-panel.js +5 -5
- package/client/dist/notification-worker.js +2 -1
- package/client/dist/p2p-sw.js +162 -0
- package/client/dist/style.css +1 -1
- package/client/dist/terminal-panel.js +11 -11
- package/docs/architecture/backends.md +11 -2
- package/docs/architecture/behavior.md +173 -59
- package/docs/architecture.md +36 -339
- package/docs/background-tasks.md +32 -26
- package/docs/deployment.md +53 -12
- package/docs/development.md +121 -149
- package/docs/images/desktop-dark.png +0 -0
- package/docs/images/desktop-light.png +0 -0
- package/docs/images/mobile-sidebar.png +0 -0
- package/docs/images/mobile.png +0 -0
- package/docs/releases/v4.2.0.md +15 -0
- package/docs/releases/v4.2.1.md +15 -0
- package/docs/versioning.md +15 -5
- package/package.json +9 -2
- package/packages/background-terminal/LICENSE +674 -0
- package/packages/background-terminal/README.md +17 -0
- package/packages/background-terminal/background-jobs.mjs +457 -0
- package/packages/background-terminal/background-mcp.mjs +79 -0
- package/packages/background-terminal/background-protocol.mjs +90 -0
- package/packages/background-terminal/cli.mjs +14 -0
- package/packages/background-terminal/client.mjs +61 -0
- package/packages/background-terminal/codex.mjs +88 -0
- package/packages/background-terminal/delivery.mjs +194 -0
- package/packages/background-terminal/log.mjs +25 -0
- package/packages/background-terminal/native-watches.mjs +160 -0
- package/packages/background-terminal/package.json +15 -0
- package/packages/background-terminal/service.mjs +126 -0
- package/packages/translation-engine/package.json +1 -1
- package/server/src/application.mjs +82 -10
- package/server/src/auth-http.mjs +187 -0
- package/server/src/auth-login.mjs +144 -0
- package/server/src/auth-totp.mjs +233 -0
- package/server/src/auth.mjs +169 -220
- package/server/src/backends/claude/background-tasks.mjs +88 -35
- package/server/src/backends/claude/messages.mjs +1 -1
- package/server/src/backends/claude/worker-client.mjs +47 -35
- package/server/src/backends/claude/worker-lines.mjs +17 -0
- package/server/src/backends/claude/worker-server.mjs +49 -69
- package/server/src/backends/codex/adapter.mjs +57 -7
- package/server/src/backends/codex/background-service.mjs +85 -0
- package/server/src/backends/codex/background-task-views.mjs +87 -0
- package/server/src/backends/codex/background-terminals.mjs +103 -0
- package/server/src/backends/codex/events.mjs +25 -1
- package/server/src/backends/codex/methods.mjs +1 -0
- package/server/src/backends/codex/native-background-handoff.mjs +72 -0
- package/server/src/backends/codex/requests.mjs +67 -38
- package/server/src/backends/codex/streaming-messages.mjs +50 -0
- package/server/src/backends/codex/subscriptions.mjs +34 -4
- package/server/src/backends/configuration.mjs +8 -0
- package/server/src/backends/manager.mjs +34 -32
- package/server/src/backends/storage.mjs +3 -14
- package/server/src/config.mjs +13 -0
- package/server/src/http/business.mjs +21 -0
- package/server/src/http/router.mjs +12 -25
- package/server/src/p2p/http.mjs +136 -0
- package/server/src/p2p/peers.mjs +132 -0
- package/server/src/p2p/service.mjs +229 -0
- package/server/src/p2p/storage.mjs +45 -0
- package/server/src/p2p/tunnel.mjs +95 -0
- package/server/src/p2p-http.mjs +149 -0
- package/server/src/p2p-peer.mjs +135 -0
- package/server/src/private-file.mjs +14 -0
- package/server/src/summary-translation.mjs +1 -1
- package/server/src/thread-folders.mjs +3 -13
- package/server/src/translation-service.mjs +3 -8
- package/shared/codex-preferences.mjs +9 -0
- package/shared/p2p-wire.mjs +157 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { fail, openSignalingServer } from "./http.mjs";
|
|
4
|
+
import { createPeerRegistry } from "./peers.mjs";
|
|
5
|
+
import { readPrivateJson, writePrivateJson } from "./storage.mjs";
|
|
6
|
+
import { runPublicTunnel } from "./tunnel.mjs";
|
|
7
|
+
|
|
8
|
+
export { createP2pManagementHandler } from "./http.mjs";
|
|
9
|
+
|
|
10
|
+
const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
|
|
11
|
+
const idPattern = /^[a-f0-9-]{36}$/;
|
|
12
|
+
|
|
13
|
+
function asHttpsOrigin(input) {
|
|
14
|
+
const url = new URL(input);
|
|
15
|
+
if (url.protocol !== "https:" || url.href !== `${url.origin}/`)
|
|
16
|
+
throw new Error("P2P 域名须为 HTTPS 来源地址");
|
|
17
|
+
return url.origin;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function validSettings(value) {
|
|
21
|
+
return (
|
|
22
|
+
typeof value?.enabled === "boolean" &&
|
|
23
|
+
(value.origin === null || asHttpsOrigin(value.origin) === value.origin) &&
|
|
24
|
+
Array.isArray(value.links) &&
|
|
25
|
+
(!value.links.length || Boolean(value.origin)) &&
|
|
26
|
+
value.links.every(
|
|
27
|
+
({ id, label, createdAt, token }) =>
|
|
28
|
+
idPattern.test(id) &&
|
|
29
|
+
typeof label === "string" &&
|
|
30
|
+
typeof createdAt === "string" &&
|
|
31
|
+
tokenPattern.test(token),
|
|
32
|
+
)
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createP2pService({
|
|
37
|
+
configDirectory,
|
|
38
|
+
assetsDirectory,
|
|
39
|
+
connectPeer,
|
|
40
|
+
revokeLink,
|
|
41
|
+
runTunnel = runPublicTunnel,
|
|
42
|
+
}) {
|
|
43
|
+
const directory = join(configDirectory, "p2p");
|
|
44
|
+
const settingsFile = join(directory, "links.json");
|
|
45
|
+
let settings = { enabled: false, origin: null, links: [] };
|
|
46
|
+
let state = "disabled";
|
|
47
|
+
let error = null;
|
|
48
|
+
let settingsError = false;
|
|
49
|
+
let stopped = false;
|
|
50
|
+
let active;
|
|
51
|
+
let queue = Promise.resolve();
|
|
52
|
+
let tokens = new Map();
|
|
53
|
+
|
|
54
|
+
function serial(action) {
|
|
55
|
+
const update = queue.then(action);
|
|
56
|
+
queue = update.catch(() => {});
|
|
57
|
+
return update;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function apply(next) {
|
|
61
|
+
settings = next;
|
|
62
|
+
tokens = new Map(next.links.map(({ token, id }) => [token, id]));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function save(next) {
|
|
66
|
+
await writePrivateJson(settingsFile, next);
|
|
67
|
+
apply(next);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function publicLink({ id, label, createdAt, token }) {
|
|
71
|
+
return { id, label, createdAt, url: `${settings.origin}/p2p#${token}` };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function status() {
|
|
75
|
+
return {
|
|
76
|
+
enabled: settings.enabled,
|
|
77
|
+
state,
|
|
78
|
+
origin: settings.origin,
|
|
79
|
+
error,
|
|
80
|
+
links: settings.links.map(publicLink),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function serve(lifetime) {
|
|
85
|
+
const signal = lifetime.controller.signal;
|
|
86
|
+
const current = () => settings.enabled && !signal.aborted && !stopped;
|
|
87
|
+
let local;
|
|
88
|
+
try {
|
|
89
|
+
const sdk = await import("node-datachannel").catch(() => {
|
|
90
|
+
throw new Error("当前安装缺少可用的 WebRTC 原生组件");
|
|
91
|
+
});
|
|
92
|
+
if (!current()) return;
|
|
93
|
+
lifetime.peers = createPeerRegistry(sdk.PeerConnection, connectPeer);
|
|
94
|
+
local = await openSignalingServer({
|
|
95
|
+
assetsDirectory,
|
|
96
|
+
getOrigin: () => (current() ? lifetime.origin : null),
|
|
97
|
+
negotiate({ token, sdp }, requestSignal) {
|
|
98
|
+
const id = typeof token === "string" && tokens.get(token);
|
|
99
|
+
if (!current() || !id) throw fail("P2P 链接无效或已撤销", 401);
|
|
100
|
+
return lifetime.peers.offer(id, sdp, requestSignal);
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
if (!current()) return;
|
|
104
|
+
await runTunnel({
|
|
105
|
+
directory,
|
|
106
|
+
port: local.address().port,
|
|
107
|
+
signal,
|
|
108
|
+
onOrigin: (url) =>
|
|
109
|
+
serial(async () => {
|
|
110
|
+
if (!current()) return;
|
|
111
|
+
const origin = asHttpsOrigin(url);
|
|
112
|
+
if (settings.origin !== origin) {
|
|
113
|
+
if (settings.links.length)
|
|
114
|
+
throw new Error("OpenTunnel 域名与已有链接不匹配");
|
|
115
|
+
await save({ ...settings, origin });
|
|
116
|
+
}
|
|
117
|
+
lifetime.origin = origin;
|
|
118
|
+
}),
|
|
119
|
+
onState(next, message = null) {
|
|
120
|
+
if (!current()) return;
|
|
121
|
+
state = next;
|
|
122
|
+
error = message;
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
} catch (cause) {
|
|
126
|
+
if (current()) {
|
|
127
|
+
state = "error";
|
|
128
|
+
error = cause.message;
|
|
129
|
+
}
|
|
130
|
+
} finally {
|
|
131
|
+
lifetime.peers?.close();
|
|
132
|
+
if (local) {
|
|
133
|
+
await new Promise((resolve) => {
|
|
134
|
+
local.close(resolve);
|
|
135
|
+
local.closeAllConnections();
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function startTunnel() {
|
|
142
|
+
if (active || !settings.enabled || stopped) return;
|
|
143
|
+
state = "connecting";
|
|
144
|
+
error = null;
|
|
145
|
+
const lifetime = { controller: new AbortController(), origin: null };
|
|
146
|
+
active = lifetime;
|
|
147
|
+
lifetime.done = serve(lifetime).finally(() => {
|
|
148
|
+
active = undefined;
|
|
149
|
+
if (lifetime.controller.signal.aborted) startTunnel();
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function stopTunnel() {
|
|
154
|
+
active?.peers?.close();
|
|
155
|
+
active?.controller.abort();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
async start() {
|
|
160
|
+
try {
|
|
161
|
+
const stored = await readPrivateJson(settingsFile);
|
|
162
|
+
if (stored !== undefined) {
|
|
163
|
+
if (!validSettings(stored)) throw new Error("P2P 设置格式错误");
|
|
164
|
+
apply(stored);
|
|
165
|
+
}
|
|
166
|
+
} catch {
|
|
167
|
+
settingsError = true;
|
|
168
|
+
state = "error";
|
|
169
|
+
error = "无法读取 P2P 设置文件";
|
|
170
|
+
}
|
|
171
|
+
startTunnel();
|
|
172
|
+
},
|
|
173
|
+
async close() {
|
|
174
|
+
stopped = true;
|
|
175
|
+
stopTunnel();
|
|
176
|
+
await queue;
|
|
177
|
+
await active?.done;
|
|
178
|
+
},
|
|
179
|
+
manage(action, input = {}) {
|
|
180
|
+
return serial(async () => {
|
|
181
|
+
if (action === "status") return status();
|
|
182
|
+
if (stopped || settingsError)
|
|
183
|
+
throw fail(error || "P2P 服务已停止", 503);
|
|
184
|
+
if (action === "enable" || action === "disable") {
|
|
185
|
+
const enabled = action === "enable";
|
|
186
|
+
if (settings.enabled !== enabled)
|
|
187
|
+
await save({ ...settings, enabled });
|
|
188
|
+
if (enabled) {
|
|
189
|
+
if (active?.controller.signal.aborted) state = "connecting";
|
|
190
|
+
startTunnel();
|
|
191
|
+
} else {
|
|
192
|
+
state = "disabled";
|
|
193
|
+
error = null;
|
|
194
|
+
stopTunnel();
|
|
195
|
+
}
|
|
196
|
+
} else if (action === "create") {
|
|
197
|
+
if (!settings.enabled || state !== "online" || !settings.origin)
|
|
198
|
+
throw fail("请在 P2P 已连接后创建链接", 409);
|
|
199
|
+
const label =
|
|
200
|
+
typeof input.label === "string" ? input.label.trim() : "";
|
|
201
|
+
if (
|
|
202
|
+
(input.label !== undefined && typeof input.label !== "string") ||
|
|
203
|
+
[...label].length > 80 ||
|
|
204
|
+
/\p{Cc}/u.test(label)
|
|
205
|
+
)
|
|
206
|
+
throw fail("链接名称须为 80 字以内的文本", 400);
|
|
207
|
+
const link = {
|
|
208
|
+
id: randomUUID(),
|
|
209
|
+
label: label || "远程访问",
|
|
210
|
+
createdAt: new Date().toISOString(),
|
|
211
|
+
token: randomBytes(32).toString("base64url"),
|
|
212
|
+
};
|
|
213
|
+
await save({ ...settings, links: [...settings.links, link] });
|
|
214
|
+
return { ...status(), created: publicLink(link) };
|
|
215
|
+
} else if (action === "revoke") {
|
|
216
|
+
const links = settings.links.filter(({ id }) => id !== input.id);
|
|
217
|
+
if (links.length === settings.links.length)
|
|
218
|
+
throw fail("P2P 链接不存在", 404);
|
|
219
|
+
await save({ ...settings, links });
|
|
220
|
+
active?.peers?.close(input.id);
|
|
221
|
+
await revokeLink?.(input.id);
|
|
222
|
+
} else {
|
|
223
|
+
throw fail("P2P 操作不存在", 404);
|
|
224
|
+
}
|
|
225
|
+
return status();
|
|
226
|
+
});
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { writePrivateFile } from "../private-file.mjs";
|
|
3
|
+
|
|
4
|
+
export async function readPrivateJson(file) {
|
|
5
|
+
try {
|
|
6
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
7
|
+
} catch (error) {
|
|
8
|
+
if (error.code !== "ENOENT") throw error;
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function writePrivateJson(file, data) {
|
|
14
|
+
return writePrivateFile(file, JSON.stringify(data, null, 2) + "\n");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function tunnelStorage(file, api, profile) {
|
|
18
|
+
let state = (await readPrivateJson(file)) ?? { api };
|
|
19
|
+
if (state.api !== api)
|
|
20
|
+
throw new Error("OpenTunnel 服务地址与现有隧道身份不匹配");
|
|
21
|
+
|
|
22
|
+
async function update(next) {
|
|
23
|
+
await writePrivateJson(file, next);
|
|
24
|
+
state = next;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function identity() {
|
|
28
|
+
return (
|
|
29
|
+
state.identity && {
|
|
30
|
+
...state.identity,
|
|
31
|
+
certificateExpiry: new Date(state.identity.certificateExpiry),
|
|
32
|
+
}
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
profiles: async () => (state.identity || state.pending ? [profile] : []),
|
|
38
|
+
load: async () => identity(),
|
|
39
|
+
save: (_, value) => update({ api, identity: value }),
|
|
40
|
+
loadPending: async () => state.pending,
|
|
41
|
+
savePending: (_, pending) => update({ ...state, pending }),
|
|
42
|
+
remove: () => update({ api }),
|
|
43
|
+
list: async () => (state.identity ? [{ profile, tunnel: identity() }] : []),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { setTimeout as wait } from "node:timers/promises";
|
|
3
|
+
import { tunnelStorage } from "./storage.mjs";
|
|
4
|
+
|
|
5
|
+
const profile = "claudex-web";
|
|
6
|
+
const route = "@";
|
|
7
|
+
|
|
8
|
+
export async function runPublicTunnel({
|
|
9
|
+
directory,
|
|
10
|
+
port,
|
|
11
|
+
signal,
|
|
12
|
+
onOrigin,
|
|
13
|
+
onState,
|
|
14
|
+
}) {
|
|
15
|
+
const endpoint = new URL(
|
|
16
|
+
process.env.OPENTUNNEL_API || "https://opentunnel.xyz",
|
|
17
|
+
);
|
|
18
|
+
if (endpoint.protocol !== "https:" || endpoint.href !== `${endpoint.origin}/`)
|
|
19
|
+
throw new Error("OPENTUNNEL_API 须为 HTTPS 来源地址");
|
|
20
|
+
const { create } = await import("@opentunnel/client");
|
|
21
|
+
const store = await tunnelStorage(
|
|
22
|
+
join(directory, "tunnel.json"),
|
|
23
|
+
endpoint.origin,
|
|
24
|
+
profile,
|
|
25
|
+
);
|
|
26
|
+
const client = create({ api: endpoint, store });
|
|
27
|
+
let retry = 1000;
|
|
28
|
+
|
|
29
|
+
async function attach(connection, activeSignal) {
|
|
30
|
+
let accepted = false;
|
|
31
|
+
const events = (async () => {
|
|
32
|
+
for await (const { type } of connection.events) {
|
|
33
|
+
if (!accepted || activeSignal.aborted) continue;
|
|
34
|
+
if (type === "connected") onState("online");
|
|
35
|
+
if (type === "disconnected" || type === "reconnecting")
|
|
36
|
+
onState("connecting");
|
|
37
|
+
}
|
|
38
|
+
})();
|
|
39
|
+
const closed = Promise.all([connection.closed, events]);
|
|
40
|
+
void closed.catch(() => {});
|
|
41
|
+
try {
|
|
42
|
+
if (!activeSignal.aborted) {
|
|
43
|
+
await onOrigin(connection.urls[route]);
|
|
44
|
+
accepted = true;
|
|
45
|
+
onState(
|
|
46
|
+
connection.status().state === "connected" ? "online" : "connecting",
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
await closed;
|
|
50
|
+
} finally {
|
|
51
|
+
await connection.close();
|
|
52
|
+
await closed.catch(() => {});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
while (!signal.aborted) {
|
|
58
|
+
onState("connecting");
|
|
59
|
+
const timeout = new AbortController();
|
|
60
|
+
const activeSignal = AbortSignal.any([signal, timeout.signal]);
|
|
61
|
+
const timer = setTimeout(() => timeout.abort(), 90000);
|
|
62
|
+
timer.unref();
|
|
63
|
+
let routeConflict = false;
|
|
64
|
+
try {
|
|
65
|
+
const connection = await client.tunnel.connect({
|
|
66
|
+
profile,
|
|
67
|
+
routes: { [route]: `127.0.0.1:${port}` },
|
|
68
|
+
signal: activeSignal,
|
|
69
|
+
onRouteConflict: "fail",
|
|
70
|
+
onEvent(event) {
|
|
71
|
+
if (event.type === "route-conflict") routeConflict = true;
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
retry = 1000;
|
|
76
|
+
await attach(connection, activeSignal);
|
|
77
|
+
} catch {
|
|
78
|
+
if (!signal.aborted)
|
|
79
|
+
onState(
|
|
80
|
+
"error",
|
|
81
|
+
routeConflict
|
|
82
|
+
? "OpenTunnel 域名被另一进程占用,正在重试"
|
|
83
|
+
: "OpenTunnel 暂不可用,正在重试",
|
|
84
|
+
);
|
|
85
|
+
} finally {
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
}
|
|
88
|
+
if (signal.aborted) break;
|
|
89
|
+
await wait(retry, undefined, { signal }).catch(() => {});
|
|
90
|
+
retry = Math.min(retry * 2, 30000);
|
|
91
|
+
}
|
|
92
|
+
} finally {
|
|
93
|
+
await client.dispose();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { Readable, Writable } from "node:stream";
|
|
2
|
+
import { P2P_STREAM_CHUNK_BYTES } from "../../shared/p2p-wire.mjs";
|
|
3
|
+
|
|
4
|
+
class PeerResponse extends Writable {
|
|
5
|
+
constructor(send, id, method) {
|
|
6
|
+
super();
|
|
7
|
+
this.send = send;
|
|
8
|
+
this.id = id;
|
|
9
|
+
this.method = method;
|
|
10
|
+
this.headers = {};
|
|
11
|
+
this.headersSent = false;
|
|
12
|
+
this.statusCode = 200;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
setHeader(name, value) {
|
|
16
|
+
this.headers[name.toLowerCase()] = String(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
writeHead(status, headers = {}) {
|
|
20
|
+
if (this.headersSent || this.destroyed) return this;
|
|
21
|
+
for (const [name, value] of Object.entries(headers))
|
|
22
|
+
this.setHeader(name, value);
|
|
23
|
+
this.statusCode = status;
|
|
24
|
+
this.headersSent = true;
|
|
25
|
+
this.headerSent = this.send({
|
|
26
|
+
type: "response",
|
|
27
|
+
id: this.id,
|
|
28
|
+
status,
|
|
29
|
+
headers: this.headers,
|
|
30
|
+
});
|
|
31
|
+
this.headerSent.catch(() => this.destroy());
|
|
32
|
+
return this;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
pull() {
|
|
36
|
+
if (this.destroyed || this.credit) return;
|
|
37
|
+
this.credit = true;
|
|
38
|
+
this.resumeWrite?.();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async _write(chunk, encoding, callback) {
|
|
42
|
+
try {
|
|
43
|
+
this.writeHead(this.statusCode);
|
|
44
|
+
await this.headerSent;
|
|
45
|
+
if (this.method !== "HEAD") {
|
|
46
|
+
for (
|
|
47
|
+
let offset = 0;
|
|
48
|
+
offset < chunk.length;
|
|
49
|
+
offset += P2P_STREAM_CHUNK_BYTES
|
|
50
|
+
) {
|
|
51
|
+
if (!this.credit && !this.destroyed)
|
|
52
|
+
await new Promise((resolve) => {
|
|
53
|
+
this.resumeWrite = resolve;
|
|
54
|
+
});
|
|
55
|
+
this.resumeWrite = null;
|
|
56
|
+
if (this.destroyed) break;
|
|
57
|
+
this.credit = false;
|
|
58
|
+
await this.send(
|
|
59
|
+
{ type: "data", id: this.id },
|
|
60
|
+
chunk.subarray(offset, offset + P2P_STREAM_CHUNK_BYTES),
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
callback();
|
|
65
|
+
} catch (error) {
|
|
66
|
+
callback(error);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
_final(callback) {
|
|
71
|
+
this.writeHead(this.statusCode);
|
|
72
|
+
this.send({ type: "end", id: this.id }).then(() => callback(), callback);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
_destroy(error, callback) {
|
|
76
|
+
this.resumeWrite?.();
|
|
77
|
+
callback(error);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createPeerHttp(handle, wire) {
|
|
82
|
+
const active = new Map();
|
|
83
|
+
|
|
84
|
+
return {
|
|
85
|
+
receive(message, bytes) {
|
|
86
|
+
const { type, id, method, url, headers } = message;
|
|
87
|
+
if (!Number.isSafeInteger(id) || id < 1) throw new Error("无效请求编号");
|
|
88
|
+
const running = active.get(id);
|
|
89
|
+
if (type === "pull") {
|
|
90
|
+
running?.pull();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (type === "cancel") {
|
|
94
|
+
running?.destroy();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (type !== "request" || running) throw new Error("无效直连请求");
|
|
98
|
+
const fail = (message) => {
|
|
99
|
+
wire.send({ type: "error", id, message }).catch(() => {});
|
|
100
|
+
};
|
|
101
|
+
if (
|
|
102
|
+
active.size >= 32 ||
|
|
103
|
+
!["GET", "HEAD", "POST", "PUT"].includes(method) ||
|
|
104
|
+
typeof url !== "string" ||
|
|
105
|
+
!url.startsWith("/api/") ||
|
|
106
|
+
url.length > 16384
|
|
107
|
+
) {
|
|
108
|
+
fail("直连 HTTP 请求无效或过多");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const parsed = new URL(url, "https://localhost");
|
|
112
|
+
if (parsed.origin !== "https://localhost") {
|
|
113
|
+
fail("直连 HTTP 地址无效");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const request = Readable.from(bytes.length ? [Buffer.from(bytes)] : []);
|
|
117
|
+
request.method = method;
|
|
118
|
+
request.url = parsed.pathname + parsed.search;
|
|
119
|
+
request.headers = {};
|
|
120
|
+
for (const name of ["range", "content-type"])
|
|
121
|
+
if (typeof headers?.[name] === "string" && headers[name].length <= 1024)
|
|
122
|
+
request.headers[name] = headers[name];
|
|
123
|
+
const response = new PeerResponse(wire.send, id, method);
|
|
124
|
+
active.set(id, response);
|
|
125
|
+
response.on("close", () => {
|
|
126
|
+
active.delete(id);
|
|
127
|
+
request.destroy();
|
|
128
|
+
});
|
|
129
|
+
response.on("error", () => fail("直连响应传输中断"));
|
|
130
|
+
Promise.resolve()
|
|
131
|
+
.then(() => {
|
|
132
|
+
if (response.destroyed) return;
|
|
133
|
+
return (
|
|
134
|
+
handle(request, response, parsed.pathname) ||
|
|
135
|
+
response.writeHead(404).end()
|
|
136
|
+
);
|
|
137
|
+
})
|
|
138
|
+
.catch(() => {
|
|
139
|
+
if (response.destroyed) return;
|
|
140
|
+
if (response.headersSent) response.destroy(new Error("请求处理失败"));
|
|
141
|
+
else response.writeHead(500).end();
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
close() {
|
|
145
|
+
for (const response of active.values()) response.destroy();
|
|
146
|
+
active.clear();
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { createP2pWire } from "../../shared/p2p-wire.mjs";
|
|
3
|
+
import { createPeerHttp } from "./p2p-http.mjs";
|
|
4
|
+
|
|
5
|
+
export function createPeerClient(
|
|
6
|
+
channel,
|
|
7
|
+
handleBusiness,
|
|
8
|
+
{ authentication, linkId, onAuthenticated, onLogout },
|
|
9
|
+
) {
|
|
10
|
+
const peer = new EventEmitter();
|
|
11
|
+
const lifetime = new AbortController();
|
|
12
|
+
const authorized = () =>
|
|
13
|
+
peer.authSessionId && authentication.valid(peer.authSessionId, linkId);
|
|
14
|
+
let untrack, pendingToken;
|
|
15
|
+
let authenticating = false;
|
|
16
|
+
peer.authLinkId = linkId;
|
|
17
|
+
peer.readyState = 1;
|
|
18
|
+
peer.detach = () => {
|
|
19
|
+
if (peer.readyState === 3) return;
|
|
20
|
+
peer.readyState = 3;
|
|
21
|
+
lifetime.abort();
|
|
22
|
+
authentication.cancelPeer(pendingToken, peer);
|
|
23
|
+
wire.close();
|
|
24
|
+
http.close();
|
|
25
|
+
peer.emit("close");
|
|
26
|
+
};
|
|
27
|
+
peer.close = () => {
|
|
28
|
+
peer.detach();
|
|
29
|
+
channel.close();
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
async function authorize(message) {
|
|
33
|
+
if (authenticating) {
|
|
34
|
+
peer.close();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
authenticating = true;
|
|
38
|
+
try {
|
|
39
|
+
if (message.action === "logout") {
|
|
40
|
+
authentication.cancelPeer(pendingToken, peer);
|
|
41
|
+
pendingToken = undefined;
|
|
42
|
+
const id = peer.authSessionId;
|
|
43
|
+
untrack?.();
|
|
44
|
+
untrack = undefined;
|
|
45
|
+
peer.authSessionId = undefined;
|
|
46
|
+
http.close();
|
|
47
|
+
if (id) onLogout(peer);
|
|
48
|
+
await authentication.logoutPeer(linkId, id);
|
|
49
|
+
await wire.send({
|
|
50
|
+
type: "auth-result",
|
|
51
|
+
session: { authenticated: false },
|
|
52
|
+
});
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const current = authorized();
|
|
56
|
+
if (message.action === "status") {
|
|
57
|
+
await wire.send({
|
|
58
|
+
type: "auth-result",
|
|
59
|
+
session: current
|
|
60
|
+
? authentication.describe(current)
|
|
61
|
+
: (authentication.pendingPeer(pendingToken, peer) ?? {
|
|
62
|
+
authenticated: false,
|
|
63
|
+
}),
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (current || !["login", "resume", "totp"].includes(message.action))
|
|
68
|
+
throw new Error("当前连接无法执行此登录操作。", { cause: 400 });
|
|
69
|
+
const options = { scope: peer, pendingToken, signal: lifetime.signal };
|
|
70
|
+
const {
|
|
71
|
+
id,
|
|
72
|
+
token,
|
|
73
|
+
session,
|
|
74
|
+
pendingToken: nextPending,
|
|
75
|
+
} = message.action === "login"
|
|
76
|
+
? await authentication.loginPeer(linkId, message, options)
|
|
77
|
+
: message.action === "totp"
|
|
78
|
+
? await authentication.verifyPeer(linkId, message, options)
|
|
79
|
+
: authentication.resumePeer(linkId, message.token);
|
|
80
|
+
if (message.action === "resume")
|
|
81
|
+
authentication.cancelPeer(pendingToken, peer);
|
|
82
|
+
pendingToken = nextPending;
|
|
83
|
+
lifetime.signal.throwIfAborted();
|
|
84
|
+
if (id) untrack = authentication.attach(peer, id, linkId);
|
|
85
|
+
await wire.send({
|
|
86
|
+
type: "auth-result",
|
|
87
|
+
session,
|
|
88
|
+
...(token && { token }),
|
|
89
|
+
});
|
|
90
|
+
if (id && authorized()) onAuthenticated(peer);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error.cause === 410) pendingToken = undefined;
|
|
93
|
+
if (!lifetime.signal.aborted)
|
|
94
|
+
await wire
|
|
95
|
+
.send({
|
|
96
|
+
type: "auth-result",
|
|
97
|
+
status: typeof error.cause === "number" ? error.cause : 503,
|
|
98
|
+
error:
|
|
99
|
+
typeof error.cause === "number"
|
|
100
|
+
? error.message
|
|
101
|
+
: "登录暂不可用,请稍后重试。",
|
|
102
|
+
})
|
|
103
|
+
.catch(() => {});
|
|
104
|
+
} finally {
|
|
105
|
+
authenticating = false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const wire = createP2pWire({
|
|
110
|
+
sendFrame: (frame) =>
|
|
111
|
+
channel.sendMessageBinary(
|
|
112
|
+
Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength),
|
|
113
|
+
),
|
|
114
|
+
bufferedAmount: () => channel.bufferedAmount(),
|
|
115
|
+
maxInboundBytes: () => (peer.authSessionId ? undefined : 8192),
|
|
116
|
+
receive(message, bytes) {
|
|
117
|
+
if (message.type === "auth") {
|
|
118
|
+
if (bytes.length) peer.close();
|
|
119
|
+
else void authorize(message);
|
|
120
|
+
} else if (message.type === "rpc") {
|
|
121
|
+
if (authorized()) peer.emit("message", message.text);
|
|
122
|
+
} else http.receive(message, bytes);
|
|
123
|
+
},
|
|
124
|
+
close: peer.close,
|
|
125
|
+
});
|
|
126
|
+
const http = createPeerHttp((request, response, path) => {
|
|
127
|
+
if (!authorized()) return response.writeHead(401).end();
|
|
128
|
+
return handleBusiness(request, response, path);
|
|
129
|
+
}, wire);
|
|
130
|
+
peer.send = (text) => {
|
|
131
|
+
if (authorized()) wire.send({ type: "rpc", text }).catch(() => {});
|
|
132
|
+
};
|
|
133
|
+
channel.onMessage(wire.frame);
|
|
134
|
+
return peer;
|
|
135
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
|
|
5
|
+
export async function writePrivateFile(path, content) {
|
|
6
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
7
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
8
|
+
try {
|
|
9
|
+
await writeFile(temporary, content, { mode: 0o600, flag: "wx" });
|
|
10
|
+
await rename(temporary, path);
|
|
11
|
+
} finally {
|
|
12
|
+
await rm(temporary, { force: true });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
2
|
import { isAbsolute, join } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { writePrivateFile } from "./private-file.mjs";
|
|
4
4
|
|
|
5
5
|
// 网页项目归属与待应用目录由桥接保存;原生会话在下次恢复或开始轮次时应用目录。
|
|
6
6
|
export function createThreadFolders(directory) {
|
|
@@ -36,17 +36,7 @@ export function createThreadFolders(directory) {
|
|
|
36
36
|
folderRevision: (previous?.folderRevision || 0) + 1,
|
|
37
37
|
};
|
|
38
38
|
const next = { ...entries, [thread.id]: entry };
|
|
39
|
-
await
|
|
40
|
-
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
41
|
-
try {
|
|
42
|
-
await writeFile(temporary, JSON.stringify(next, null, 2) + "\n", {
|
|
43
|
-
mode: 0o600,
|
|
44
|
-
flag: "wx",
|
|
45
|
-
});
|
|
46
|
-
await rename(temporary, path);
|
|
47
|
-
} finally {
|
|
48
|
-
await rm(temporary, { force: true });
|
|
49
|
-
}
|
|
39
|
+
await writePrivateFile(path, JSON.stringify(next, null, 2) + "\n");
|
|
50
40
|
entries = next;
|
|
51
41
|
return { ...thread, ...entry };
|
|
52
42
|
});
|