odant-work 1.0.19 → 1.0.21
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/#system/package-manifest.json +35 -22
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +21 -2
- package/$server/$folder/lib/chat-item/chat-item.js +17 -1
- package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +972 -0
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +427 -106
- package/MODELS/Local/$provider/handlers/methods/transfer/$handler/class.js +41 -0
- package/package.json +1 -1
- package/rules/threats.md +117 -116
- package/sources/client.js +1 -0
- package/sources/data/progress.md +15 -0
- package/sources/host/auto-updater.js +30 -2
- package/sources/host/http-server.js +23 -0
- package/sources/host/websocket.js +127 -120
- package/sources/modules/agent/index.js +6 -1
- package/sources/modules/agent/readme.md +217 -216
- package/sources/modules/agent/tools/chrome.js +263 -0
- package/sources/modules/bridge/chrome.js +673 -0
- package/sources/modules/bridge/hub.js +395 -361
- package/sources/modules/chrome-extension/background.js +299 -0
- package/sources/modules/chrome-extension/manifest.json +25 -0
- package/sources/modules/chrome-extension/options.html +48 -0
- package/sources/modules/chrome-extension/options.js +104 -0
- package/sources/modules/chrome-extension/popup.html +25 -0
- package/sources/modules/chrome-extension/popup.js +32 -0
- package/sources/modules/trainer/halogen.js +16 -4
- package/sources/modules/trainer/huggingface.js +471 -95
- package/sources/modules/trainer/index.js +288 -1
- package/sources/modules/trainer/runner.js +54 -4
- package/sources/modules/trainer/tar-stream.js +458 -0
- package/sources/modules/trainer/transfer.js +1570 -0
- package/sources/modules/user-profile/user-profile.js +34 -10
- package/sources/modules/user-profile/user-token.js +168 -0
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Серверный хаб и CDP-движок для настоящего Chrome пользователя через расширение MV3 (chrome_*):
|
|
3
|
+
* - Расширение подключается по WebSocket на `/~chrome` (только localhost/LAN) и авторизуется
|
|
4
|
+
* персональным токеном `wmcp.<uid>.<секрет>` в первом auth-кадре (никаких cookies,
|
|
5
|
+
* никаких токенов в URL, никакой фоновой утилиты в терминале).
|
|
6
|
+
* - Логика снимка (AX-дерево с `[ref]`), кликов, ввода текста и проверки доменов живёт здесь
|
|
7
|
+
* в одном месте на сервере, а расширение — тонкий транспорт поверх `chrome.debugger`.
|
|
8
|
+
* - Безопасность:
|
|
9
|
+
* * По умолчанию при подключении включён режим «только просмотр» (`readOnly: true`);
|
|
10
|
+
* * Реестр операций `CHROME_OPS` с явным булевым признаком `mutates` (fail-closed);
|
|
11
|
+
* * Домен-скоуп на задачу + проверка конечного URL после каждого перехода/клика (защита от редиректов);
|
|
12
|
+
* * Произвольный `Runtime.evaluate` запрещён жёстко (только фиксированные read-only выражения);
|
|
13
|
+
* * Агент работает только в своей сгруппированной вкладке; если человек закрыл или перехватил её —
|
|
14
|
+
* действие немедленно останавливается без переключения на чужие вкладки;
|
|
15
|
+
* * Все действия пишутся в аудит безопасности (`chrome_bridge`) без паролей, текста ввода и токенов.
|
|
16
|
+
*/
|
|
17
|
+
import { randomBytes } from 'node:crypto';
|
|
18
|
+
import { verifyToken } from '../mcp/tokens.js';
|
|
19
|
+
import { clientAllowed } from '../mcp/server.js';
|
|
20
|
+
import { audit } from '../../server/access/audit.js';
|
|
21
|
+
import { assertPageUrl } from '../agent/tools/browse.js';
|
|
22
|
+
|
|
23
|
+
const CMD_TIMEOUT_MS = 30_000;
|
|
24
|
+
const AUTH_TIMEOUT_MS = 5_000;
|
|
25
|
+
const HISTORY_MAX = 50;
|
|
26
|
+
const MAX_SNAPSHOT_CHARS = 9_000;
|
|
27
|
+
const MAX_SNAPSHOT_ITEMS = 400;
|
|
28
|
+
|
|
29
|
+
export const INTERACTIVE_ROLES = new Set([
|
|
30
|
+
'button', 'link', 'textbox', 'searchbox', 'combobox', 'listbox', 'option',
|
|
31
|
+
'checkbox', 'radio', 'switch', 'menuitem', 'menuitemcheckbox', 'menuitemradio',
|
|
32
|
+
'tab', 'spinbutton', 'slider', 'togglebutton',
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
export const EXPR_LOCATION_HREF = 'location.href';
|
|
36
|
+
export const EXPR_DOCUMENT_TITLE = 'document.title';
|
|
37
|
+
export const EXPR_READY_STATE = 'document.readyState';
|
|
38
|
+
|
|
39
|
+
/** Разрешённые выражения для Runtime.evaluate — произвольный JS запрещён жёстко. */
|
|
40
|
+
export const ALLOWED_EVAL_EXPRS = new Set([
|
|
41
|
+
EXPR_LOCATION_HREF,
|
|
42
|
+
EXPR_DOCUMENT_TITLE,
|
|
43
|
+
EXPR_READY_STATE,
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
/** Белый список CDP-методов, которые сервер имеет право отправлять в расширение. */
|
|
47
|
+
export const ALLOWED_CDP_METHODS = new Set([
|
|
48
|
+
'Accessibility.getFullAXTree',
|
|
49
|
+
'DOM.scrollIntoViewIfNeeded',
|
|
50
|
+
'DOM.getBoxModel',
|
|
51
|
+
'DOM.focus',
|
|
52
|
+
'Input.dispatchMouseEvent',
|
|
53
|
+
'Input.insertText',
|
|
54
|
+
'Input.dispatchKeyEvent',
|
|
55
|
+
'Page.navigate',
|
|
56
|
+
'Page.reload',
|
|
57
|
+
'Page.getNavigationHistory',
|
|
58
|
+
'Page.navigateToHistoryEntry',
|
|
59
|
+
'Page.captureScreenshot',
|
|
60
|
+
'Runtime.evaluate',
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
/** Проверка безопасности CDP-вызова (белый список методов + запрет произвольного eval). */
|
|
64
|
+
export function assertSafeCdpCall(method, params = {}) {
|
|
65
|
+
const m = String(method || '');
|
|
66
|
+
if (!ALLOWED_CDP_METHODS.has(m))
|
|
67
|
+
throw new Error('chrome: запрещённый метод CDP «' + m + '»');
|
|
68
|
+
if (m === 'Runtime.evaluate') {
|
|
69
|
+
const expr = String(params?.expression || '');
|
|
70
|
+
if (!ALLOWED_EVAL_EXPRS.has(expr))
|
|
71
|
+
throw new Error('chrome: произвольный Runtime.evaluate запрещён');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Активные подключения Chrome по uid пользователя: uid → ChromeConn. */
|
|
76
|
+
const connections = new Map();
|
|
77
|
+
|
|
78
|
+
function recordChromeLog(conn, entry) {
|
|
79
|
+
const item = { time: new Date().toISOString(), ...entry };
|
|
80
|
+
conn.history.push(item);
|
|
81
|
+
if (conn.history.length > HISTORY_MAX)
|
|
82
|
+
conn.history.shift();
|
|
83
|
+
audit('chrome_bridge', { uid: conn.uid, ...entry });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function hostnameOf(rawUrl) {
|
|
87
|
+
try {
|
|
88
|
+
return new URL(String(rawUrl || '')).hostname.toLowerCase();
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return '';
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Проверка Origin при WS-подключении на `/~chrome`: расширение, без Origin или тот же хост (для тестов). */
|
|
96
|
+
export function chromeOriginAllowed(req) {
|
|
97
|
+
const origin = String(req?.headers?.origin || '').trim();
|
|
98
|
+
if (!origin)
|
|
99
|
+
return true;
|
|
100
|
+
if (/^(chrome|edge)-extension:\/\/[a-z0-9_-]+$/i.test(origin))
|
|
101
|
+
return true;
|
|
102
|
+
try {
|
|
103
|
+
return new URL(origin).host.toLowerCase() === String(req?.headers?.host || '').trim().toLowerCase();
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Построить карту интерактивных [ref] и читаемое дерево из Accessibility.getFullAXTree (как cdp.py). */
|
|
111
|
+
export function buildAxMap(nodes) {
|
|
112
|
+
const refs = new Map();
|
|
113
|
+
const items = [];
|
|
114
|
+
let n = 0;
|
|
115
|
+
for (const node of (Array.isArray(nodes) ? nodes : [])) {
|
|
116
|
+
const role = String(node?.role?.value || '');
|
|
117
|
+
const name = String(node?.name?.value || '');
|
|
118
|
+
const val = String(node?.value?.value || '');
|
|
119
|
+
const checked = String(node?.checked?.value || '').toLowerCase();
|
|
120
|
+
if (INTERACTIVE_ROLES.has(role) && (name || role === 'textbox' || role === 'searchbox' || role === 'combobox')) {
|
|
121
|
+
n += 1;
|
|
122
|
+
refs.set(n, node);
|
|
123
|
+
const state = role === 'checkbox' ? (checked === 'true' ? ' [x]' : ' [ ]') : '';
|
|
124
|
+
items.push({
|
|
125
|
+
ref: n,
|
|
126
|
+
role,
|
|
127
|
+
name,
|
|
128
|
+
value: val,
|
|
129
|
+
state,
|
|
130
|
+
backend: node.backendDOMNodeId,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
else if ((role === 'heading' || role === 'StaticText' || role === 'image' || role === 'link') && name && items.length < MAX_SNAPSHOT_ITEMS) {
|
|
134
|
+
items.push({ role, name: name.slice(0, 160) });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return { refs, items };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Отформатировать текстовый снимок страницы в едином с cdp.py формате. */
|
|
141
|
+
export function formatSnapshotText(url, title, items) {
|
|
142
|
+
const lines = ['Страница: ' + (title || '(без названия)') + ' — ' + (url || '')];
|
|
143
|
+
for (const it of items) {
|
|
144
|
+
if (it.ref != null) {
|
|
145
|
+
const extra = it.value ? ('="' + it.value + '"') : '';
|
|
146
|
+
lines.push('[' + it.ref + '] ' + it.role + ' "' + it.name + '"' + extra + (it.state || ''));
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
lines.push(' ' + it.role + ': "' + it.name + '"');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return lines.join('\n').slice(0, MAX_SNAPSHOT_CHARS);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Реестр операций Chrome-моста с обязательным флагом mutates. */
|
|
156
|
+
export const CHROME_OPS = Object.freeze({
|
|
157
|
+
status: Object.freeze({ mutates: false }),
|
|
158
|
+
snapshot: Object.freeze({ mutates: false }),
|
|
159
|
+
screenshot: Object.freeze({ mutates: false }),
|
|
160
|
+
open: Object.freeze({ mutates: true }),
|
|
161
|
+
click: Object.freeze({ mutates: true }),
|
|
162
|
+
type: Object.freeze({ mutates: true }),
|
|
163
|
+
nav: Object.freeze({ mutates: true }),
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
/** Проверка: изменяет ли операция браузер (неизвестная операция — fail-closed = true). */
|
|
167
|
+
export function isChromeMutatingOp(op) {
|
|
168
|
+
const def = CHROME_OPS[String(op || '')];
|
|
169
|
+
return def ? Boolean(def.mutates) : true;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Зарегистрировать подключение Chrome-расширения пользователя.
|
|
174
|
+
* По умолчанию `readOnly: true` (переключается человеком через `chrome_mode`).
|
|
175
|
+
*/
|
|
176
|
+
export function registerChromeBridge({ uid, transport, browserName = 'Chrome', extensionVersion = '0.1.0', readOnly = true }) {
|
|
177
|
+
if (!uid)
|
|
178
|
+
throw new Error('chrome: нужен uid пользователя');
|
|
179
|
+
const prev = connections.get(String(uid));
|
|
180
|
+
if (prev && prev.transport !== transport) {
|
|
181
|
+
for (const [, p] of prev.pending)
|
|
182
|
+
p.reject(new Error('новое подключение Chrome заменило предыдущее'));
|
|
183
|
+
prev.pending.clear();
|
|
184
|
+
try { prev.transport?.close?.(4000, 'replaced'); } catch { /* уже закрыт */ }
|
|
185
|
+
}
|
|
186
|
+
const conn = {
|
|
187
|
+
uid: String(uid),
|
|
188
|
+
id: prev?.id || ('chr-' + randomBytes(6).toString('hex')),
|
|
189
|
+
transport,
|
|
190
|
+
browserName: String(browserName || 'Chrome'),
|
|
191
|
+
extensionVersion: String(extensionVersion || '0.1.0'),
|
|
192
|
+
readOnly: Boolean(readOnly),
|
|
193
|
+
tabId: null,
|
|
194
|
+
lastUrl: '',
|
|
195
|
+
lastTitle: '',
|
|
196
|
+
connectedAt: Date.now(),
|
|
197
|
+
lastSeen: Date.now(),
|
|
198
|
+
pending: new Map(),
|
|
199
|
+
history: prev?.history || [],
|
|
200
|
+
refsByTab: new Map(),
|
|
201
|
+
allowedDomainsByScope: prev?.allowedDomainsByScope || new Map(),
|
|
202
|
+
};
|
|
203
|
+
connections.set(conn.uid, conn);
|
|
204
|
+
recordChromeLog(conn, { action: 'connect', browser: conn.browserName, readOnly: conn.readOnly, outcome: 'ok' });
|
|
205
|
+
return conn;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Отключить Chrome-мост пользователя. */
|
|
209
|
+
export function unregisterChromeBridge(uid, reason = 'расширение Chrome отключилось') {
|
|
210
|
+
const conn = connections.get(String(uid || ''));
|
|
211
|
+
if (!conn)
|
|
212
|
+
return false;
|
|
213
|
+
for (const [, p] of conn.pending)
|
|
214
|
+
p.reject(new Error(reason));
|
|
215
|
+
conn.pending.clear();
|
|
216
|
+
conn.refsByTab.clear();
|
|
217
|
+
conn.tabId = null;
|
|
218
|
+
connections.delete(conn.uid);
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Получить активное подключение Chrome ТОЛЬКО для владельца uid. */
|
|
223
|
+
export function getChromeForUser(uid) {
|
|
224
|
+
return connections.get(String(uid || '')) || null;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Переключить режим «только просмотр» (readOnly) для Chrome пользователя. */
|
|
228
|
+
export function setChromeReadOnly(uid, readOnly) {
|
|
229
|
+
const conn = getChromeForUser(uid);
|
|
230
|
+
if (!conn)
|
|
231
|
+
throw new Error('расширение WORK Chrome Bridge не подключено');
|
|
232
|
+
conn.readOnly = Boolean(readOnly);
|
|
233
|
+
conn.lastSeen = Date.now();
|
|
234
|
+
recordChromeLog(conn, { action: 'mode', readOnly: conn.readOnly, outcome: 'ok' });
|
|
235
|
+
return { uid: conn.uid, readOnly: conn.readOnly };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function scopeKeyOf(scopeKey) {
|
|
239
|
+
return String(scopeKey || 'default');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function getChromeAllowedDomains(uid, scopeKey) {
|
|
243
|
+
const conn = getChromeForUser(uid);
|
|
244
|
+
if (!conn)
|
|
245
|
+
return [];
|
|
246
|
+
const set = conn.allowedDomainsByScope.get(scopeKeyOf(scopeKey));
|
|
247
|
+
return set ? [...set] : [];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function isChromeDomainAllowed(uid, scopeKey, hostname) {
|
|
251
|
+
const conn = getChromeForUser(uid);
|
|
252
|
+
const h = String(hostname || '').toLowerCase();
|
|
253
|
+
if (!conn || !h)
|
|
254
|
+
return false;
|
|
255
|
+
const set = conn.allowedDomainsByScope.get(scopeKeyOf(scopeKey));
|
|
256
|
+
return Boolean(set && set.has(h));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function approveChromeDomain(uid, scopeKey, hostname) {
|
|
260
|
+
const conn = getChromeForUser(uid);
|
|
261
|
+
const h = String(hostname || '').toLowerCase();
|
|
262
|
+
if (!conn || !h)
|
|
263
|
+
return;
|
|
264
|
+
const key = scopeKeyOf(scopeKey);
|
|
265
|
+
let set = conn.allowedDomainsByScope.get(key);
|
|
266
|
+
if (!set) {
|
|
267
|
+
set = new Set();
|
|
268
|
+
conn.allowedDomainsByScope.set(key, set);
|
|
269
|
+
}
|
|
270
|
+
set.add(h);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function clearChromeDomains(uid, scopeKey) {
|
|
274
|
+
const conn = getChromeForUser(uid);
|
|
275
|
+
if (!conn)
|
|
276
|
+
return;
|
|
277
|
+
conn.allowedDomainsByScope.delete(scopeKeyOf(scopeKey));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function sendRpc(conn, payload) {
|
|
281
|
+
return new Promise((resolve, reject) => {
|
|
282
|
+
const id = 'cr-' + randomBytes(6).toString('hex');
|
|
283
|
+
const timer = setTimeout(() => {
|
|
284
|
+
conn.pending.delete(id);
|
|
285
|
+
reject(new Error('chrome: таймаут ответа от расширения (' + (payload.op || payload.method || '?') + ')'));
|
|
286
|
+
}, CMD_TIMEOUT_MS);
|
|
287
|
+
conn.pending.set(id, {
|
|
288
|
+
resolve: v => { clearTimeout(timer); resolve(v); },
|
|
289
|
+
reject: e => { clearTimeout(timer); reject(e); },
|
|
290
|
+
});
|
|
291
|
+
try {
|
|
292
|
+
conn.transport.send({ id, ...payload });
|
|
293
|
+
}
|
|
294
|
+
catch (e) {
|
|
295
|
+
clearTimeout(timer);
|
|
296
|
+
conn.pending.delete(id);
|
|
297
|
+
reject(e);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function handleTabDetached(conn, tabId, reason) {
|
|
303
|
+
if (conn.tabId != null && tabId != null && conn.tabId !== tabId)
|
|
304
|
+
return;
|
|
305
|
+
const oldTab = conn.tabId;
|
|
306
|
+
conn.tabId = null;
|
|
307
|
+
if (oldTab != null)
|
|
308
|
+
conn.refsByTab.delete(oldTab);
|
|
309
|
+
for (const [, p] of conn.pending)
|
|
310
|
+
p.reject(new Error('пользователь закрыл или перехватил вкладку агента (' + (reason || 'detach') + ')'));
|
|
311
|
+
conn.pending.clear();
|
|
312
|
+
recordChromeLog(conn, { action: 'tab_detach', domain: hostnameOf(conn.lastUrl), outcome: 'human_takeover' });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Принять входящее сообщение от расширения (или тестового транспорта). */
|
|
316
|
+
export function onChromeTransportMessage(conn, msg) {
|
|
317
|
+
if (!conn || !msg || typeof msg !== 'object')
|
|
318
|
+
return;
|
|
319
|
+
conn.lastSeen = Date.now();
|
|
320
|
+
if (msg.type === 'ping') {
|
|
321
|
+
try { conn.transport.send({ type: 'pong' }); } catch { /* закрыт */ }
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (msg.type === 'tab_detached' || msg.type === 'tab_closed') {
|
|
325
|
+
handleTabDetached(conn, msg.tabId, msg.reason || msg.type);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (msg.id && conn.pending.has(msg.id)) {
|
|
329
|
+
const p = conn.pending.get(msg.id);
|
|
330
|
+
conn.pending.delete(msg.id);
|
|
331
|
+
if (msg.ok === false || msg.error)
|
|
332
|
+
p.reject(new Error(String(msg.error || 'ошибка расширения Chrome')));
|
|
333
|
+
else
|
|
334
|
+
p.resolve(msg.result);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async function cdpCall(conn, tabId, method, params = {}) {
|
|
339
|
+
assertSafeCdpCall(method, params);
|
|
340
|
+
return sendRpc(conn, { op: 'cdp', tabId, method, params });
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function evalFixed(conn, tabId, expr) {
|
|
344
|
+
const r = await cdpCall(conn, tabId, 'Runtime.evaluate', { expression: expr, returnByValue: true });
|
|
345
|
+
if (r?.exceptionDetails)
|
|
346
|
+
throw new Error('chrome: ошибка чтения страницы');
|
|
347
|
+
return r?.result?.value;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function waitReady(conn, tabId, timeoutMs = 15_000) {
|
|
351
|
+
const t0 = Date.now();
|
|
352
|
+
while (Date.now() - t0 < timeoutMs) {
|
|
353
|
+
try {
|
|
354
|
+
if (await evalFixed(conn, tabId, EXPR_READY_STATE) === 'complete')
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
// страница может перезагружаться в этот момент
|
|
359
|
+
}
|
|
360
|
+
await new Promise(r => setTimeout(r, 250));
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function requireConn(uid) {
|
|
365
|
+
const conn = getChromeForUser(uid);
|
|
366
|
+
if (!conn)
|
|
367
|
+
throw new Error('Расширение WORK Chrome Bridge не подключено для вашей учётной записи.');
|
|
368
|
+
return conn;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function assertWritable(conn, op) {
|
|
372
|
+
if (conn.readOnly && isChromeMutatingOp(op)) {
|
|
373
|
+
recordChromeLog(conn, { action: op, domain: hostnameOf(conn.lastUrl), readOnly: true, outcome: 'denied_readonly' });
|
|
374
|
+
throw new Error('Chrome в режиме «только просмотр» (readOnly): вызовите chrome_mode { readOnly: false } для разрешения действий.');
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function assertAllowedDomain(conn, scopeKey, url, action) {
|
|
379
|
+
const host = hostnameOf(url);
|
|
380
|
+
if (!host || !isChromeDomainAllowed(conn.uid, scopeKey, host)) {
|
|
381
|
+
if (conn.tabId != null)
|
|
382
|
+
conn.refsByTab.delete(conn.tabId);
|
|
383
|
+
recordChromeLog(conn, { action, domain: host || 'unknown', outcome: 'denied_domain' });
|
|
384
|
+
throw new Error(
|
|
385
|
+
'Переход или действие на домене «' + (host || url || '?') + '» остановлено: '
|
|
386
|
+
+ 'домен не входит в список разрешённых для этой задачи. '
|
|
387
|
+
+ 'Подтвердите новый домен вызовом chrome_open или спросите человека.'
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
return host;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function takeSnapshotOnTab(conn, tabId) {
|
|
394
|
+
const url = String(await evalFixed(conn, tabId, EXPR_LOCATION_HREF) || '');
|
|
395
|
+
const title = String(await evalFixed(conn, tabId, EXPR_DOCUMENT_TITLE) || '');
|
|
396
|
+
const tree = await cdpCall(conn, tabId, 'Accessibility.getFullAXTree', {});
|
|
397
|
+
const { refs, items } = buildAxMap(tree?.nodes || []);
|
|
398
|
+
conn.refsByTab.set(tabId, refs);
|
|
399
|
+
conn.lastUrl = url;
|
|
400
|
+
conn.lastTitle = title;
|
|
401
|
+
return { url, title, text: formatSnapshotText(url, title, items), refCount: refs.size };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function requireTab(conn) {
|
|
405
|
+
if (conn.tabId == null)
|
|
406
|
+
throw new Error('Вкладка агента в Chrome ещё не открыта (или была закрыта человеком) — сначала вызовите chrome_open.');
|
|
407
|
+
return conn.tabId;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Открыть URL в собственной сгруппированной вкладке агента (чужие вкладки не трогаются). */
|
|
411
|
+
export async function chromeOpen(uid, scopeKey, rawUrl) {
|
|
412
|
+
const conn = requireConn(uid);
|
|
413
|
+
const href = assertPageUrl(rawUrl);
|
|
414
|
+
const targetHost = hostnameOf(href);
|
|
415
|
+
assertWritable(conn, 'open');
|
|
416
|
+
approveChromeDomain(uid, scopeKey, targetHost);
|
|
417
|
+
|
|
418
|
+
try {
|
|
419
|
+
if (conn.tabId == null) {
|
|
420
|
+
const tab = await sendRpc(conn, { op: 'ensure_tab', url: 'about:blank' });
|
|
421
|
+
if (!tab?.tabId)
|
|
422
|
+
throw new Error('не удалось создать вкладку агента в Chrome');
|
|
423
|
+
conn.tabId = tab.tabId;
|
|
424
|
+
}
|
|
425
|
+
await cdpCall(conn, conn.tabId, 'Page.navigate', { url: href });
|
|
426
|
+
await waitReady(conn, conn.tabId);
|
|
427
|
+
const snap = await takeSnapshotOnTab(conn, conn.tabId);
|
|
428
|
+
const finalHost = assertAllowedDomain(conn, scopeKey, snap.url, 'open');
|
|
429
|
+
recordChromeLog(conn, { action: 'open', domain: finalHost, outcome: 'ok' });
|
|
430
|
+
return snap;
|
|
431
|
+
}
|
|
432
|
+
catch (e) {
|
|
433
|
+
recordChromeLog(conn, { action: 'open', domain: targetHost, outcome: 'error', error: String(e?.message || e).slice(0, 160) });
|
|
434
|
+
throw e;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Снять текстовый снимок [ref] текущей вкладки агента (разрешено и в readOnly). */
|
|
439
|
+
export async function chromeSnapshot(uid) {
|
|
440
|
+
const conn = requireConn(uid);
|
|
441
|
+
const tabId = requireTab(conn);
|
|
442
|
+
const snap = await takeSnapshotOnTab(conn, tabId);
|
|
443
|
+
recordChromeLog(conn, { action: 'snapshot', domain: hostnameOf(snap.url), outcome: 'ok' });
|
|
444
|
+
return snap;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Клик по [ref] на текущей вкладке агента + проверка домена после возможного перехода. */
|
|
448
|
+
export async function chromeClick(uid, scopeKey, refNum) {
|
|
449
|
+
const conn = requireConn(uid);
|
|
450
|
+
assertWritable(conn, 'click');
|
|
451
|
+
const tabId = requireTab(conn);
|
|
452
|
+
const curUrl = String(await evalFixed(conn, tabId, EXPR_LOCATION_HREF) || conn.lastUrl || '');
|
|
453
|
+
const curHost = assertAllowedDomain(conn, scopeKey, curUrl, 'click');
|
|
454
|
+
|
|
455
|
+
const n = Number(refNum);
|
|
456
|
+
const refs = conn.refsByTab.get(tabId);
|
|
457
|
+
const node = refs?.get(n);
|
|
458
|
+
if (!node || !node.backendDOMNodeId)
|
|
459
|
+
throw new Error('нет элемента [' + n + '] — обновите chrome_snapshot');
|
|
460
|
+
|
|
461
|
+
try {
|
|
462
|
+
await cdpCall(conn, tabId, 'DOM.scrollIntoViewIfNeeded', { backendNodeId: node.backendDOMNodeId }).catch(() => {});
|
|
463
|
+
const box = await cdpCall(conn, tabId, 'DOM.getBoxModel', { backendNodeId: node.backendDOMNodeId });
|
|
464
|
+
const q = box?.model?.content || [];
|
|
465
|
+
if (q.length < 8)
|
|
466
|
+
throw new Error('элемент [' + n + '] без координат (скрыт?)');
|
|
467
|
+
const x = (q[0] + q[4]) / 2;
|
|
468
|
+
const y = (q[1] + q[5]) / 2;
|
|
469
|
+
for (const type of ['mousePressed', 'mouseReleased']) {
|
|
470
|
+
await cdpCall(conn, tabId, 'Input.dispatchMouseEvent', {
|
|
471
|
+
type, x, y, button: 'left', buttons: 1, clickCount: 1,
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
const t0 = Date.now();
|
|
475
|
+
let finalUrl = curUrl;
|
|
476
|
+
while (Date.now() - t0 < 4_000) {
|
|
477
|
+
await new Promise(r => setTimeout(r, 250));
|
|
478
|
+
try {
|
|
479
|
+
const nowUrl = String(await evalFixed(conn, tabId, EXPR_LOCATION_HREF) || '');
|
|
480
|
+
if (nowUrl && nowUrl !== curUrl) {
|
|
481
|
+
finalUrl = nowUrl;
|
|
482
|
+
await waitReady(conn, tabId, 10_000);
|
|
483
|
+
finalUrl = String(await evalFixed(conn, tabId, EXPR_LOCATION_HREF) || nowUrl);
|
|
484
|
+
break;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
catch { /* ждём навигацию */ }
|
|
488
|
+
}
|
|
489
|
+
conn.lastUrl = finalUrl;
|
|
490
|
+
assertAllowedDomain(conn, scopeKey, finalUrl, 'click');
|
|
491
|
+
const role = String(node?.role?.value || '');
|
|
492
|
+
const name = String(node?.name?.value || '');
|
|
493
|
+
recordChromeLog(conn, { action: 'click', domain: curHost, ref: n, outcome: 'ok' });
|
|
494
|
+
return {
|
|
495
|
+
label: 'клик [' + n + '] ' + role + ' "' + name + '"',
|
|
496
|
+
x: Math.round(x),
|
|
497
|
+
y: Math.round(y),
|
|
498
|
+
url: finalUrl,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
catch (e) {
|
|
502
|
+
recordChromeLog(conn, { action: 'click', domain: curHost, ref: n, outcome: 'error', error: String(e?.message || e).slice(0, 160) });
|
|
503
|
+
throw e;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Ввести текст в поле [ref] (пароли запрещены — используйте chrome_handoff). */
|
|
508
|
+
export async function chromeType(uid, scopeKey, refNum, text, submit = false) {
|
|
509
|
+
const conn = requireConn(uid);
|
|
510
|
+
assertWritable(conn, 'type');
|
|
511
|
+
const tabId = requireTab(conn);
|
|
512
|
+
const curUrl = String(await evalFixed(conn, tabId, EXPR_LOCATION_HREF) || conn.lastUrl || '');
|
|
513
|
+
const curHost = assertAllowedDomain(conn, scopeKey, curUrl, 'type');
|
|
514
|
+
|
|
515
|
+
const str = String(text ?? '');
|
|
516
|
+
if (!str)
|
|
517
|
+
throw new Error('пустой ввод');
|
|
518
|
+
const n = Number(refNum);
|
|
519
|
+
const refs = conn.refsByTab.get(tabId);
|
|
520
|
+
const node = refs?.get(n);
|
|
521
|
+
if (!node || !node.backendDOMNodeId)
|
|
522
|
+
throw new Error('нет элемента [' + n + '] — обновите chrome_snapshot');
|
|
523
|
+
|
|
524
|
+
try {
|
|
525
|
+
await cdpCall(conn, tabId, 'DOM.focus', { backendNodeId: node.backendDOMNodeId });
|
|
526
|
+
await cdpCall(conn, tabId, 'Input.insertText', { text: str });
|
|
527
|
+
if (submit) {
|
|
528
|
+
for (const type of ['keyDown', 'keyUp']) {
|
|
529
|
+
await cdpCall(conn, tabId, 'Input.dispatchKeyEvent', {
|
|
530
|
+
type,
|
|
531
|
+
key: 'Enter',
|
|
532
|
+
code: 'Enter',
|
|
533
|
+
windowsVirtualKeyCode: 13,
|
|
534
|
+
text: type === 'keyDown' ? '\r' : '',
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
await new Promise(r => setTimeout(r, 400));
|
|
538
|
+
const finalUrl = String(await evalFixed(conn, tabId, EXPR_LOCATION_HREF) || curUrl);
|
|
539
|
+
conn.lastUrl = finalUrl;
|
|
540
|
+
assertAllowedDomain(conn, scopeKey, finalUrl, 'type');
|
|
541
|
+
}
|
|
542
|
+
// Важно: в аудит никогда не пишем введённый текст
|
|
543
|
+
recordChromeLog(conn, { action: 'type', domain: curHost, ref: n, chars: str.length, outcome: 'ok' });
|
|
544
|
+
const preview = str.slice(0, 40) + (str.length > 40 ? '…' : '');
|
|
545
|
+
return { label: 'ввод «' + preview + '» в [' + n + ']', chars: str.length };
|
|
546
|
+
}
|
|
547
|
+
catch (e) {
|
|
548
|
+
recordChromeLog(conn, { action: 'type', domain: curHost, ref: n, outcome: 'error', error: String(e?.message || e).slice(0, 160) });
|
|
549
|
+
throw e;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Навигация (back | forward | reload) по истории вкладки агента + проверка домена. */
|
|
554
|
+
export async function chromeNav(uid, scopeKey, action = 'reload') {
|
|
555
|
+
const conn = requireConn(uid);
|
|
556
|
+
assertWritable(conn, 'nav');
|
|
557
|
+
const tabId = requireTab(conn);
|
|
558
|
+
const curUrl = String(await evalFixed(conn, tabId, EXPR_LOCATION_HREF) || conn.lastUrl || '');
|
|
559
|
+
const curHost = assertAllowedDomain(conn, scopeKey, curUrl, 'nav');
|
|
560
|
+
|
|
561
|
+
try {
|
|
562
|
+
if (action === 'back' || action === 'forward') {
|
|
563
|
+
const hist = await cdpCall(conn, tabId, 'Page.getNavigationHistory', {});
|
|
564
|
+
const idx = Number(hist?.currentIndex ?? -1);
|
|
565
|
+
const entries = Array.isArray(hist?.entries) ? hist.entries : [];
|
|
566
|
+
const nextIdx = action === 'back' ? idx - 1 : idx + 1;
|
|
567
|
+
const target = entries[nextIdx];
|
|
568
|
+
if (!target)
|
|
569
|
+
throw new Error(action === 'back' ? 'назад идти некуда' : 'вперёд идти некуда');
|
|
570
|
+
assertAllowedDomain(conn, scopeKey, target.url, 'nav');
|
|
571
|
+
await cdpCall(conn, tabId, 'Page.navigateToHistoryEntry', { entryId: target.id });
|
|
572
|
+
}
|
|
573
|
+
else {
|
|
574
|
+
await cdpCall(conn, tabId, 'Page.reload', {});
|
|
575
|
+
}
|
|
576
|
+
await waitReady(conn, tabId);
|
|
577
|
+
const snap = await takeSnapshotOnTab(conn, tabId);
|
|
578
|
+
const finalHost = assertAllowedDomain(conn, scopeKey, snap.url, 'nav');
|
|
579
|
+
recordChromeLog(conn, { action: 'nav:' + action, domain: finalHost, outcome: 'ok' });
|
|
580
|
+
return snap;
|
|
581
|
+
}
|
|
582
|
+
catch (e) {
|
|
583
|
+
recordChromeLog(conn, { action: 'nav:' + action, domain: curHost, outcome: 'error', error: String(e?.message || e).slice(0, 160) });
|
|
584
|
+
throw e;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Скриншот текущей вкладки агента (PNG Buffer, для chrome_handoff; работает и в readOnly). */
|
|
589
|
+
export async function chromeScreenshot(uid) {
|
|
590
|
+
const conn = getChromeForUser(uid);
|
|
591
|
+
if (!conn || conn.tabId == null)
|
|
592
|
+
return null;
|
|
593
|
+
try {
|
|
594
|
+
const res = await cdpCall(conn, conn.tabId, 'Page.captureScreenshot', { format: 'png' });
|
|
595
|
+
return res?.data ? Buffer.from(res.data, 'base64') : null;
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Обработчик WebSocket `/~chrome` (подключается из `sources/host/websocket.js`).
|
|
604
|
+
* Проверяет LAN/localhost, допустимость Origin (extension/empty/same-host) и auth-кадр с токеном `wmcp.`.
|
|
605
|
+
*/
|
|
606
|
+
export function handleChromeSocket(ws, request) {
|
|
607
|
+
if (!clientAllowed(request)) {
|
|
608
|
+
try { ws.close(4403, 'Chrome bridge available only from localhost or LAN'); } catch { /* уже закрыт */ }
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
if (!chromeOriginAllowed(request)) {
|
|
612
|
+
try { ws.close(4403, 'Forbidden origin'); } catch { /* уже закрыт */ }
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
let authedConn = null;
|
|
616
|
+
const authTimer = setTimeout(() => {
|
|
617
|
+
if (!authedConn) {
|
|
618
|
+
try { ws.close(4401, 'Auth timeout'); } catch { /* уже закрыт */ }
|
|
619
|
+
}
|
|
620
|
+
}, AUTH_TIMEOUT_MS);
|
|
621
|
+
|
|
622
|
+
const transport = {
|
|
623
|
+
send: obj => {
|
|
624
|
+
if (ws.readyState === 1)
|
|
625
|
+
ws.send(JSON.stringify(obj));
|
|
626
|
+
},
|
|
627
|
+
close: (code, reason) => {
|
|
628
|
+
try { ws.close(code, reason); } catch { /* уже закрыт */ }
|
|
629
|
+
},
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
ws.on('message', async raw => {
|
|
633
|
+
let msg;
|
|
634
|
+
try {
|
|
635
|
+
const text = typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf-8');
|
|
636
|
+
msg = JSON.parse(text);
|
|
637
|
+
}
|
|
638
|
+
catch {
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
if (!authedConn) {
|
|
642
|
+
if (msg?.type !== 'auth') {
|
|
643
|
+
try { ws.close(4401, 'Auth required'); } catch { /* уже закрыт */ }
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
const auth = await verifyToken(String(msg.token || '')).catch(() => null);
|
|
647
|
+
if (!auth) {
|
|
648
|
+
try { ws.close(4401, 'Invalid token'); } catch { /* уже закрыт */ }
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
clearTimeout(authTimer);
|
|
652
|
+
authedConn = registerChromeBridge({
|
|
653
|
+
uid: auth.uid,
|
|
654
|
+
transport,
|
|
655
|
+
browserName: msg.browserName || 'Chrome',
|
|
656
|
+
extensionVersion: msg.extensionVersion || '0.1.0',
|
|
657
|
+
readOnly: true,
|
|
658
|
+
});
|
|
659
|
+
transport.send({ type: 'auth_ok', uid: authedConn.uid, readOnly: authedConn.readOnly });
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
onChromeTransportMessage(authedConn, msg);
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
ws.on('close', () => {
|
|
666
|
+
clearTimeout(authTimer);
|
|
667
|
+
if (authedConn && getChromeForUser(authedConn.uid) === authedConn)
|
|
668
|
+
unregisterChromeBridge(authedConn.uid);
|
|
669
|
+
});
|
|
670
|
+
ws.on('error', () => {
|
|
671
|
+
clearTimeout(authTimer);
|
|
672
|
+
});
|
|
673
|
+
}
|