@chendaleiq/dsh-chrome 0.0.0-stage → 0.1.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/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.en.md +98 -0
- package/README.md +85 -2
- package/cordis.patch.yml +23 -0
- package/docs/DETAIL.md +23 -0
- package/docs/TESTING.md +75 -0
- package/extension/_locales/en/messages.json +43 -0
- package/extension/_locales/zh_CN/messages.json +43 -0
- package/extension/manifest.json +16 -0
- package/extension/popup.html +29 -0
- package/extension/popup.js +63 -0
- package/extension/service_worker.js +314 -0
- package/icon.svg +9 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +61 -4
- package/scripts/bridge.mjs +23 -0
- package/scripts/setup.mjs +94 -0
- package/scripts/verify.mjs +50 -0
- package/src/auto-bridge.js +29 -0
- package/src/bridge-client.js +63 -0
- package/src/bridge-server.js +245 -0
- package/src/index.js +117 -0
- package/src/onboard.js +70 -0
- package/src/screenshot.js +35 -0
- package/src/tools.js +440 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chrome — 本地桥服务端。
|
|
3
|
+
*
|
|
4
|
+
* GET /status -> { url, mode, connected, lastSeenAt, clientName, queuedCommands, pendingCommands }
|
|
5
|
+
* POST /command -> 入队,等待扩展经 GET /next 取走、POST /result 回传后返回
|
|
6
|
+
* GET /next -> 扩展长轮询(最长 25s),有命令返回 { type:"command", command },无命令返回 { type:"none" }
|
|
7
|
+
* POST /result -> 扩展回传 { id, ok, result/error }
|
|
8
|
+
*
|
|
9
|
+
* 安全边界:只听 127.0.0.1;/command 仅接受无 Origin 的本机进程请求;
|
|
10
|
+
* /next、/result 仅接受 chrome-extension:// origin 或无 sec-fetch-site 的请求。
|
|
11
|
+
* 无第三方依赖。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { createServer } from "node:http";
|
|
15
|
+
|
|
16
|
+
const VERSION = "0.1.0";
|
|
17
|
+
|
|
18
|
+
function isLocalProcess(req) {
|
|
19
|
+
return !req.headers.origin && !req.headers["sec-fetch-site"];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// 扩展请求判定(关键词:允许无 Origin + 简单 fetch,不允许导航/页面):
|
|
23
|
+
// - MV3 service worker 的 fetch 不带 Origin,带 sec-fetch-site: none + mode: cors;
|
|
24
|
+
// - 带 chrome-extension:// Origin 的直接放行;
|
|
25
|
+
// - 带其它 Origin(如网页)一律拒绝;
|
|
26
|
+
// - 导航模式(地址栏输入)拒绝,只接受 fetch(cors/no-cors)。
|
|
27
|
+
// 注意 /command 仍只认本机进程(isLocalProcess),不受此影响。
|
|
28
|
+
export function isExtensionRequest(req) {
|
|
29
|
+
const origin = req.headers.origin || "";
|
|
30
|
+
if (origin.startsWith("chrome-extension://")) return true;
|
|
31
|
+
if (origin !== "") return false;
|
|
32
|
+
const site = req.headers["sec-fetch-site"];
|
|
33
|
+
if (site !== undefined && site !== "none") return false;
|
|
34
|
+
const mode = req.headers["sec-fetch-mode"];
|
|
35
|
+
if (mode !== undefined && mode !== "cors" && mode !== "no-cors") return false;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function readJson(req, limit = 1024 * 1024) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const chunks = [];
|
|
42
|
+
let size = 0;
|
|
43
|
+
req.on("data", (c) => {
|
|
44
|
+
size += c.length;
|
|
45
|
+
if (size > limit) {
|
|
46
|
+
req.destroy();
|
|
47
|
+
reject(new Error("body too large"));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
chunks.push(c);
|
|
51
|
+
});
|
|
52
|
+
req.on("end", () => {
|
|
53
|
+
if (chunks.length === 0) {
|
|
54
|
+
resolve({});
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
59
|
+
} catch (e) {
|
|
60
|
+
reject(e);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
req.on("error", reject);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function json(res, status, body, extraHeaders = {}) {
|
|
68
|
+
const text = JSON.stringify(body);
|
|
69
|
+
res.writeHead(status, {
|
|
70
|
+
"content-type": "application/json; charset=utf-8",
|
|
71
|
+
"content-length": Buffer.byteLength(text),
|
|
72
|
+
"cache-control": "no-store",
|
|
73
|
+
"x-dsh-chrome-version": VERSION,
|
|
74
|
+
...extraHeaders,
|
|
75
|
+
});
|
|
76
|
+
res.end(text);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function createBridge({ host = "127.0.0.1", port = 17319 } = {}) {
|
|
80
|
+
const queue = [];
|
|
81
|
+
const pending = new Map();
|
|
82
|
+
const waiters = new Set();
|
|
83
|
+
let lastSeenAt = 0;
|
|
84
|
+
let clientName = "";
|
|
85
|
+
let seq = 0;
|
|
86
|
+
|
|
87
|
+
function status() {
|
|
88
|
+
return {
|
|
89
|
+
url: `http://${host}:${port}`,
|
|
90
|
+
mode: "server",
|
|
91
|
+
connected: Date.now() - lastSeenAt < 5 * 60 * 1000,
|
|
92
|
+
lastSeenAt,
|
|
93
|
+
clientName,
|
|
94
|
+
queuedCommands: queue.length,
|
|
95
|
+
pendingCommands: pending.size,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function takeNext() {
|
|
100
|
+
const cmd = queue.shift();
|
|
101
|
+
if (!cmd) return null;
|
|
102
|
+
cmd.deliveredAt = Date.now();
|
|
103
|
+
pending.set(cmd.id, cmd);
|
|
104
|
+
return cmd;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// 发往扩展的线包:只带 id/action/params,内部的 timer/resolve 绝不序列化。
|
|
108
|
+
function wireCommand(cmd) {
|
|
109
|
+
return { id: cmd.id, action: cmd.action, params: cmd.params };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const server = createServer(async (req, res) => {
|
|
113
|
+
try {
|
|
114
|
+
const url = new URL(req.url || "/", `http://${host}:${port}`);
|
|
115
|
+
if (req.method === "GET" && url.pathname === "/status") {
|
|
116
|
+
json(res, 200, status());
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (req.method === "POST" && url.pathname === "/command") {
|
|
120
|
+
if (!isLocalProcess(req)) {
|
|
121
|
+
json(res, 403, { ok: false, error: "local process only" });
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const body = await readJson(req).catch(() => null);
|
|
125
|
+
if (!body || typeof body.action !== "string") {
|
|
126
|
+
json(res, 400, { ok: false, error: "missing action" });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const id = `dsh-${Date.now().toString(36)}-${(seq += 1)}`;
|
|
130
|
+
const timeoutMs = Math.max(1000, Math.min(120000, Number(body.timeoutMs) || 30000));
|
|
131
|
+
const cmd = { id, action: body.action, params: body.params || {} };
|
|
132
|
+
const done = new Promise((resolve, reject) => {
|
|
133
|
+
cmd.resolve = resolve;
|
|
134
|
+
cmd.reject = reject;
|
|
135
|
+
cmd.timer = setTimeout(() => {
|
|
136
|
+
pending.delete(id);
|
|
137
|
+
reject(new Error(`Timed out after ${timeoutMs}ms waiting for Chrome extension`));
|
|
138
|
+
}, timeoutMs);
|
|
139
|
+
});
|
|
140
|
+
queue.push(cmd);
|
|
141
|
+
for (const w of [...waiters]) {
|
|
142
|
+
waiters.delete(w);
|
|
143
|
+
w(takeNext());
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
const result = await done;
|
|
147
|
+
json(res, 200, { ok: true, result });
|
|
148
|
+
} catch (e) {
|
|
149
|
+
json(res, 504, { ok: false, error: e.message });
|
|
150
|
+
}
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (req.method === "GET" && url.pathname === "/next") {
|
|
154
|
+
if (!isExtensionRequest(req)) {
|
|
155
|
+
const observed = {
|
|
156
|
+
origin: req.headers.origin,
|
|
157
|
+
secFetchSite: req.headers["sec-fetch-site"],
|
|
158
|
+
secFetchMode: req.headers["sec-fetch-mode"],
|
|
159
|
+
secFetchDest: req.headers["sec-fetch-dest"],
|
|
160
|
+
};
|
|
161
|
+
console.error(`[dsh-chrome] /next rejected: ${JSON.stringify(observed)}`);
|
|
162
|
+
json(res, 403, { ok: false, error: "extension only", observed });
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
lastSeenAt = Date.now();
|
|
166
|
+
clientName = String(url.searchParams.get("name") || clientName || "");
|
|
167
|
+
const cmd = takeNext();
|
|
168
|
+
if (cmd) {
|
|
169
|
+
json(res, 200, { type: "command", command: wireCommand(cmd), expectedExtensionVersion: VERSION });
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const waiter = await new Promise((resolve) => {
|
|
173
|
+
const wrapped = (c) => {
|
|
174
|
+
clearTimeout(t);
|
|
175
|
+
waiters.delete(wrapped);
|
|
176
|
+
resolve(c);
|
|
177
|
+
};
|
|
178
|
+
const t = setTimeout(() => {
|
|
179
|
+
waiters.delete(wrapped);
|
|
180
|
+
resolve(null);
|
|
181
|
+
}, 25000);
|
|
182
|
+
waiters.add(wrapped);
|
|
183
|
+
});
|
|
184
|
+
if (waiter) json(res, 200, { type: "command", command: wireCommand(waiter), expectedExtensionVersion: VERSION });
|
|
185
|
+
else json(res, 200, { type: "none", expectedExtensionVersion: VERSION });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (req.method === "POST" && url.pathname === "/result") {
|
|
189
|
+
if (!isExtensionRequest(req)) {
|
|
190
|
+
const observed = {
|
|
191
|
+
origin: req.headers.origin,
|
|
192
|
+
secFetchSite: req.headers["sec-fetch-site"],
|
|
193
|
+
secFetchMode: req.headers["sec-fetch-mode"],
|
|
194
|
+
secFetchDest: req.headers["sec-fetch-dest"],
|
|
195
|
+
};
|
|
196
|
+
console.error(`[dsh-chrome] /result rejected: ${JSON.stringify(observed)}`);
|
|
197
|
+
json(res, 403, { ok: false, error: "extension only", observed });
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
lastSeenAt = Date.now();
|
|
201
|
+
const body = await readJson(req).catch(() => null);
|
|
202
|
+
const cmd = body && pending.get(body.id);
|
|
203
|
+
if (!cmd) {
|
|
204
|
+
json(res, 404, { ok: false, error: "unknown command id" });
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
pending.delete(body.id);
|
|
208
|
+
clearTimeout(cmd.timer);
|
|
209
|
+
if (body.ok === false) cmd.reject(new Error(String(body.error || "extension error")));
|
|
210
|
+
else cmd.resolve(body.result);
|
|
211
|
+
json(res, 200, { ok: true });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
json(res, 404, { ok: false, error: "not found" });
|
|
215
|
+
} catch (e) {
|
|
216
|
+
try {
|
|
217
|
+
json(res, 500, { ok: false, error: e.message });
|
|
218
|
+
} catch {
|
|
219
|
+
// ignore
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
server,
|
|
226
|
+
status,
|
|
227
|
+
listen: () =>
|
|
228
|
+
new Promise((resolve, reject) => {
|
|
229
|
+
// EADDRINUSE 是异步 'error' 事件:没人听就变未捕获异常。
|
|
230
|
+
// 必须接住,调用方(apply 的 client 降级)才有机会活。
|
|
231
|
+
const onError = (err) => {
|
|
232
|
+
server.off("listening", onListen);
|
|
233
|
+
reject(err);
|
|
234
|
+
};
|
|
235
|
+
const onListen = () => {
|
|
236
|
+
server.off("error", onError);
|
|
237
|
+
resolve();
|
|
238
|
+
};
|
|
239
|
+
server.once("error", onError);
|
|
240
|
+
server.once("listening", onListen);
|
|
241
|
+
server.listen(port, host);
|
|
242
|
+
}),
|
|
243
|
+
close: () => new Promise((resolve) => server.close(resolve)),
|
|
244
|
+
};
|
|
245
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chrome — Host 侧入口(全新重写)。
|
|
3
|
+
*
|
|
4
|
+
* 工具定义在 src/tools.js(纯模块,可单测),这里只做三件事:
|
|
5
|
+
* 1) 起回环桥(被占则当 client);2) 用 defineTool 包装后注册;
|
|
6
|
+
* 3) 注入一段极简系统提示。defineTool 来自随 DSH 发货的包,
|
|
7
|
+
* bundle 不声明依赖(见 dsh.bundle.patch 说明)。
|
|
8
|
+
*
|
|
9
|
+
* loader 行 id、package 名、本文件的 `name` 三者必须一致。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { bridgeSend, bridgeStatus, bridgeUrlOf } from "./bridge-client.js";
|
|
13
|
+
import { ensureBridge } from "./auto-bridge.js";
|
|
14
|
+
import { saveScreenshot } from "./screenshot.js";
|
|
15
|
+
import { buildTools, compileToolDefinition } from "./tools.js";
|
|
16
|
+
import { alreadyOnboarded, onboard } from "./onboard.js";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { dirname, join } from "node:path";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
|
|
21
|
+
export const name = "@chendaleiq/dsh-chrome";
|
|
22
|
+
|
|
23
|
+
export const inject = ["tools"];
|
|
24
|
+
|
|
25
|
+
const DEFAULTS = {
|
|
26
|
+
enabled: true,
|
|
27
|
+
bridgeHost: "127.0.0.1",
|
|
28
|
+
bridgePort: 17319,
|
|
29
|
+
approvalPolicy: "read-auto",
|
|
30
|
+
requireApprovalFor: ["chrome_navigate", "chrome_evaluate", "chrome_tab_select", "chrome_tab_new", "chrome_tab_close", "chrome_fill"],
|
|
31
|
+
blockPrivateIPs: true,
|
|
32
|
+
snapshotMaxChars: 8000,
|
|
33
|
+
evaluateMaxChars: 4000,
|
|
34
|
+
screenshotMaxBytes: 512000,
|
|
35
|
+
autoStartBridge: true,
|
|
36
|
+
dataDir: "",
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function resolveConfig(raw) {
|
|
40
|
+
const config = { ...DEFAULTS };
|
|
41
|
+
if (raw === null || typeof raw !== "object") return config;
|
|
42
|
+
for (const [key, fallback] of Object.entries(DEFAULTS)) {
|
|
43
|
+
const value = raw[key];
|
|
44
|
+
if (value === undefined) continue;
|
|
45
|
+
if (Array.isArray(fallback)) {
|
|
46
|
+
if (Array.isArray(value)) config[key] = value;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (typeof value !== typeof fallback) continue;
|
|
50
|
+
config[key] = value;
|
|
51
|
+
}
|
|
52
|
+
return config;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function apply(ctx, rawConfig) {
|
|
56
|
+
const config = resolveConfig(rawConfig);
|
|
57
|
+
const baseUrl = bridgeUrlOf(config);
|
|
58
|
+
const disposers = [];
|
|
59
|
+
const SESSION_KEY = "session:dsh-chrome";
|
|
60
|
+
const extensionDir = join(dirname(fileURLToPath(import.meta.url)), "..", "extension");
|
|
61
|
+
const dataDir = config.dataDir && config.dataDir.length > 0 ? config.dataDir : join(homedir(), ".dsh", "chrome");
|
|
62
|
+
const doOnboard = (extra = {}) =>
|
|
63
|
+
onboard({ bridgeStatus: () => bridgeStatus(baseUrl), dataDir, extensionDir, ...extra });
|
|
64
|
+
|
|
65
|
+
if (config.autoStartBridge !== false) {
|
|
66
|
+
try {
|
|
67
|
+
const auto = ensureBridge({ bridgeHost: config.bridgeHost, bridgePort: config.bridgePort });
|
|
68
|
+
disposers.push(() => auto.dispose());
|
|
69
|
+
} catch {
|
|
70
|
+
// 起不了就当纯 client,chrome_status 会如实报告
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const send = (action, params = {}, timeoutMs, exec) =>
|
|
75
|
+
bridgeSend(
|
|
76
|
+
baseUrl,
|
|
77
|
+
action,
|
|
78
|
+
{ sessionKey: SESSION_KEY, background: true, foreground: false, ...params },
|
|
79
|
+
timeoutMs,
|
|
80
|
+
exec?.signal,
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
// 工具使用指引直接写在各工具 description 里,不另起 prompt section
|
|
84
|
+
//(section 需要宿主排序号,硬编码 order 会乱插队)。
|
|
85
|
+
|
|
86
|
+
for (const def of buildTools({
|
|
87
|
+
send,
|
|
88
|
+
bridgeStatus: () => bridgeStatus(baseUrl),
|
|
89
|
+
config,
|
|
90
|
+
saveScreenshot,
|
|
91
|
+
sessionKey: SESSION_KEY,
|
|
92
|
+
doOnboard: () => doOnboard(),
|
|
93
|
+
})) {
|
|
94
|
+
if (!ctx?.tools?.register) throw new Error("dsh-chrome requires ctx.tools.register");
|
|
95
|
+
// 不 import @deepseek-ai/dsh-tools:工作区 bundle 解析不到发货包。
|
|
96
|
+
// compileToolDefinition 按同一契约本地编译(output schema+render、参数校验)。
|
|
97
|
+
const dispose = ctx.tools.register(compileToolDefinition(def));
|
|
98
|
+
if (typeof dispose === "function") disposers.push(dispose);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 首次安装且从没连上过:自动打开文件管理器定位 extension/,只做一次。
|
|
102
|
+
// 之后靠 chrome_onboard 工具按需引导。
|
|
103
|
+
if (!alreadyOnboarded(dataDir)) {
|
|
104
|
+
doOnboard({ markAttempt: true }).catch(() => {});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return () => {
|
|
108
|
+
while (disposers.length > 0) {
|
|
109
|
+
const dispose = disposers.pop();
|
|
110
|
+
try {
|
|
111
|
+
dispose();
|
|
112
|
+
} catch {
|
|
113
|
+
// ignore teardown errors
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
package/src/onboard.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chrome — 首次引导(纯模块,可单测)。
|
|
3
|
+
* 扩展目录藏在包里,用户自己找很烦:连不上时直接把文件管理器打开并选中
|
|
4
|
+
* extension/ 文件夹,用户拖进 chrome://extensions 就行。
|
|
5
|
+
* macOS 用 open -R(定位并选中),Windows 用 explorer /select,Linux 用 xdg-open。
|
|
6
|
+
*/
|
|
7
|
+
import { execFile } from "node:child_process";
|
|
8
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
export function defaultOpener(dir) {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
const plat = process.platform;
|
|
14
|
+
const cmd = plat === "darwin" ? "open" : plat === "win32" ? "explorer" : "xdg-open";
|
|
15
|
+
const args = plat === "darwin" ? ["-R", dir] : plat === "win32" ? [`/select,${dir}`] : [dir];
|
|
16
|
+
execFile(cmd, args, (error) => resolve(!error));
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param deps.bridgeStatus () => Promise<status>
|
|
22
|
+
* @param deps.dataDir 落盘目录(放 .onboarded 标记,避免每次启动都弹)
|
|
23
|
+
* @param deps.extensionDir 扩展绝对路径
|
|
24
|
+
* @param deps.openDir (dir) => Promise<boolean>,默认按平台打开文件管理器
|
|
25
|
+
* @param deps.markAttempt 无论是否打开成功都写标记(自动引导用一次即止)
|
|
26
|
+
* @returns { connected, bridgeUp, extensionDir, opened, steps }
|
|
27
|
+
*/
|
|
28
|
+
export async function onboard({ bridgeStatus, dataDir, extensionDir, openDir = defaultOpener, markAttempt = false }) {
|
|
29
|
+
let status = { connected: false };
|
|
30
|
+
try {
|
|
31
|
+
status = (await bridgeStatus()) || status;
|
|
32
|
+
} catch { /* 桥没起也继续走引导 */ }
|
|
33
|
+
const connected = status.connected === true;
|
|
34
|
+
let opened = false;
|
|
35
|
+
if (!connected) {
|
|
36
|
+
try {
|
|
37
|
+
opened = await openDir(extensionDir);
|
|
38
|
+
} catch {
|
|
39
|
+
opened = false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
if (dataDir) {
|
|
44
|
+
mkdirSync(dataDir, { recursive: true });
|
|
45
|
+
if (opened || markAttempt) writeFileSync(join(dataDir, ".onboarded"), `${new Date().toISOString()}\n`);
|
|
46
|
+
}
|
|
47
|
+
} catch { /* 标记写失败不影响引导 */ }
|
|
48
|
+
return {
|
|
49
|
+
connected,
|
|
50
|
+
bridgeUp: status.mode === "server" || connected,
|
|
51
|
+
extensionDir,
|
|
52
|
+
opened,
|
|
53
|
+
steps: [
|
|
54
|
+
"1. 打开 chrome://extensions,打开右上角「开发者模式」",
|
|
55
|
+
"2. 点「加载已解压的扩展程序」,选择上面的 extensionDir(也可直接从文件管理器拖进去)",
|
|
56
|
+
"3. 点工具栏 DSH Chrome Connector 图标,按「立即连接」",
|
|
57
|
+
"1. Open chrome://extensions, turn on Developer mode",
|
|
58
|
+
"2. Load unpacked and pick extensionDir above (or drag it in from the file manager)",
|
|
59
|
+
"3. Click the toolbar icon and press Connect",
|
|
60
|
+
],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function alreadyOnboarded(dataDir) {
|
|
65
|
+
try {
|
|
66
|
+
return existsSync(join(dataDir || "", ".onboarded"));
|
|
67
|
+
} catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-chrome — 截图落盘(全新重写,无第三方依赖)。
|
|
3
|
+
* 扩展只回 dataUrl,落盘是 Host 的事:文件名带时间戳,PNG 头解析宽高,
|
|
4
|
+
* 失败也不掩盖(width/height 置 null)。
|
|
5
|
+
*/
|
|
6
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
|
|
10
|
+
function pngSize(buf) {
|
|
11
|
+
try {
|
|
12
|
+
if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47 && buf.readUInt32BE(12) === 0x49484452) {
|
|
13
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
14
|
+
}
|
|
15
|
+
} catch {
|
|
16
|
+
// ignore
|
|
17
|
+
}
|
|
18
|
+
return { width: null, height: null };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function saveScreenshot(dataDir, sessionKey, dataUrl) {
|
|
22
|
+
if (typeof dataUrl !== "string" || !dataUrl.startsWith("data:image/")) {
|
|
23
|
+
throw new Error("extension did not return an image dataUrl");
|
|
24
|
+
}
|
|
25
|
+
const base = dataDir && dataDir.length > 0 ? dataDir : join(homedir(), ".dsh", "chrome");
|
|
26
|
+
const safe = String(sessionKey || "session:default").replace(/[^a-zA-Z0-9_-]+/g, "_");
|
|
27
|
+
const dir = join(base, safe);
|
|
28
|
+
mkdirSync(dir, { recursive: true });
|
|
29
|
+
const name = `shot-${Date.now()}.png`;
|
|
30
|
+
const path = join(dir, name);
|
|
31
|
+
const buf = Buffer.from(dataUrl.split(",", 2)[1] || "", "base64");
|
|
32
|
+
writeFileSync(path, buf);
|
|
33
|
+
const { width, height } = pngSize(buf);
|
|
34
|
+
return { path, bytes: buf.length, width, height };
|
|
35
|
+
}
|