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
|
@@ -1,361 +1,395 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Серверный хаб и исполнитель команд агента-«моста» на компьютере пользователя (9.12):
|
|
3
|
-
* - Компьютер пользователя сам подключается к WORK по HTTP (/~bridge/*) с персональным токеном
|
|
4
|
-
* Bearer `wmcp.<uid>.<секрет>` (sources/modules/mcp/tokens.js) — входящие порты на ПК не нужны;
|
|
5
|
-
* - Строгая изоляция по владельцу (uid): задача пользователя U видит и вызывает только мост U;
|
|
6
|
-
* - Режим «только просмотр» (readOnly): при readOnly=true разрешены только status/windows/ls/read,
|
|
7
|
-
* любые изменяющие и активные команды (write, open_app, focus_window) жёстко отклоняются и на сервере,
|
|
8
|
-
* и на самом мосте;
|
|
9
|
-
* - Песочница файлов на ПК (assertBridgePath): доступ только внутри корневой папки моста (--root),
|
|
10
|
-
* запрет выхода через `..` и запрет чувствительных имён (.env, .ssh, id_rsa, credentials, secret…);
|
|
11
|
-
* - Запуск программ (open_app) — только из белого списка имён (allowedApps) через spawn(..., { shell: false }),
|
|
12
|
-
* никакого произвольного шелла;
|
|
13
|
-
* - Полный журнал каждого действия в аудите безопасности WORK (event: 'desktop_bridge') и кольцевом буфере моста.
|
|
14
|
-
*/
|
|
15
|
-
import fsp from 'node:fs/promises';
|
|
16
|
-
import fs from 'node:fs';
|
|
17
|
-
import path from 'node:path';
|
|
18
|
-
import os from 'node:os';
|
|
19
|
-
import { spawn } from 'node:child_process';
|
|
20
|
-
import { randomBytes } from 'node:crypto';
|
|
21
|
-
import { verifyToken } from '../mcp/tokens.js';
|
|
22
|
-
import { clientAllowed } from '../mcp/server.js';
|
|
23
|
-
import { audit } from '../../server/access/audit.js';
|
|
24
|
-
|
|
25
|
-
const BRIDGE_TTL_MS = 2 * 60_000;
|
|
26
|
-
const CMD_TIMEOUT_MS = 30_000;
|
|
27
|
-
const FILE_READ_MAX = 512 * 1024;
|
|
28
|
-
const FILE_WRITE_MAX = 1024 * 1024;
|
|
29
|
-
const HISTORY_MAX = 50;
|
|
30
|
-
const SENSITIVE_FILE = /(^|[\\/])(\.env(\..+)?|\.ssh|\.gnupg|\.aws|id_rsa|id_ed25519|.*credentials.*|.*secret.*|.*\.(pem|pfx|p12|key))$/i;
|
|
31
|
-
const APP_NAME_RE = /^[a-zA-Z0-9._-]{1,40}$/;
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
return {
|
|
134
|
-
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Серверный хаб и исполнитель команд агента-«моста» на компьютере пользователя (9.12):
|
|
3
|
+
* - Компьютер пользователя сам подключается к WORK по HTTP (/~bridge/*) с персональным токеном
|
|
4
|
+
* Bearer `wmcp.<uid>.<секрет>` (sources/modules/mcp/tokens.js) — входящие порты на ПК не нужны;
|
|
5
|
+
* - Строгая изоляция по владельцу (uid): задача пользователя U видит и вызывает только мост U;
|
|
6
|
+
* - Режим «только просмотр» (readOnly): при readOnly=true разрешены только status/windows/ls/read,
|
|
7
|
+
* любые изменяющие и активные команды (write, open_app, focus_window) жёстко отклоняются и на сервере,
|
|
8
|
+
* и на самом мосте;
|
|
9
|
+
* - Песочница файлов на ПК (assertBridgePath): доступ только внутри корневой папки моста (--root),
|
|
10
|
+
* запрет выхода через `..` и запрет чувствительных имён (.env, .ssh, id_rsa, credentials, secret…);
|
|
11
|
+
* - Запуск программ (open_app) — только из белого списка имён (allowedApps) через spawn(..., { shell: false }),
|
|
12
|
+
* никакого произвольного шелла;
|
|
13
|
+
* - Полный журнал каждого действия в аудите безопасности WORK (event: 'desktop_bridge') и кольцевом буфере моста.
|
|
14
|
+
*/
|
|
15
|
+
import fsp from 'node:fs/promises';
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import { spawn } from 'node:child_process';
|
|
20
|
+
import { randomBytes } from 'node:crypto';
|
|
21
|
+
import { verifyToken } from '../mcp/tokens.js';
|
|
22
|
+
import { clientAllowed } from '../mcp/server.js';
|
|
23
|
+
import { audit } from '../../server/access/audit.js';
|
|
24
|
+
|
|
25
|
+
const BRIDGE_TTL_MS = 2 * 60_000;
|
|
26
|
+
const CMD_TIMEOUT_MS = 30_000;
|
|
27
|
+
const FILE_READ_MAX = 512 * 1024;
|
|
28
|
+
const FILE_WRITE_MAX = 1024 * 1024;
|
|
29
|
+
const HISTORY_MAX = 50;
|
|
30
|
+
const SENSITIVE_FILE = /(^|[\\/])(\.env(\..+)?|\.ssh|\.gnupg|\.aws|id_rsa|id_ed25519|.*credentials.*|.*secret.*|.*\.(pem|pfx|p12|key))$/i;
|
|
31
|
+
const APP_NAME_RE = /^[a-zA-Z0-9._-]{1,40}$/;
|
|
32
|
+
|
|
33
|
+
function assertSafeStringArgs(raw) {
|
|
34
|
+
const safeArgs = Array.isArray(raw) ? raw.map(a => String(a)).slice(0, 8) : [];
|
|
35
|
+
for (const a of safeArgs)
|
|
36
|
+
if (a.includes('\0') || /[;&|`$<>]/.test(a))
|
|
37
|
+
throw new Error('bridge: недопустимый аргумент программы: ' + a);
|
|
38
|
+
return safeArgs;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Декларативный реестр операций локального моста.
|
|
43
|
+
* У каждой операции обязателен булев признак mutates (меняет состояние / активно действует) —
|
|
44
|
+
* это гарантирует, что ни одна новая операция не обойдёт режим readOnly по забывчивости.
|
|
45
|
+
*/
|
|
46
|
+
export const BRIDGE_OPS = Object.freeze({
|
|
47
|
+
status: Object.freeze({
|
|
48
|
+
mutates: false,
|
|
49
|
+
async run(cfg, _cmd, rootDir) {
|
|
50
|
+
return {
|
|
51
|
+
hostname: cfg?.hostname || os.hostname(),
|
|
52
|
+
platform: cfg?.platform || process.platform,
|
|
53
|
+
rootDir,
|
|
54
|
+
readOnly: Boolean(cfg?.readOnly),
|
|
55
|
+
allowedApps: Array.isArray(cfg?.allowedApps) ? cfg.allowedApps : [],
|
|
56
|
+
};
|
|
57
|
+
},
|
|
58
|
+
}),
|
|
59
|
+
ls: Object.freeze({
|
|
60
|
+
mutates: false,
|
|
61
|
+
async run(_cfg, cmd, rootDir) {
|
|
62
|
+
const { resolved, rel } = assertBridgePath(rootDir, cmd.path || '.');
|
|
63
|
+
const entries = await fsp.readdir(resolved, { withFileTypes: true });
|
|
64
|
+
const items = [];
|
|
65
|
+
for (const e of entries.slice(0, 200)) {
|
|
66
|
+
if (SENSITIVE_FILE.test(e.name))
|
|
67
|
+
continue;
|
|
68
|
+
items.push({ name: e.name, type: e.isDirectory() ? 'dir' : 'file' });
|
|
69
|
+
}
|
|
70
|
+
return { path: rel, items };
|
|
71
|
+
},
|
|
72
|
+
}),
|
|
73
|
+
read: Object.freeze({
|
|
74
|
+
mutates: false,
|
|
75
|
+
async run(_cfg, cmd, rootDir) {
|
|
76
|
+
const { resolved, rel } = assertBridgePath(rootDir, cmd.path);
|
|
77
|
+
const st = await fsp.stat(resolved);
|
|
78
|
+
if (!st.isFile())
|
|
79
|
+
throw new Error('bridge: это не файл: ' + rel);
|
|
80
|
+
if (st.size > FILE_READ_MAX)
|
|
81
|
+
throw new Error('bridge: файл больше лимита (' + st.size + ' > ' + FILE_READ_MAX + ' байт)');
|
|
82
|
+
const content = await fsp.readFile(resolved, 'utf-8');
|
|
83
|
+
return { path: rel, size: st.size, content };
|
|
84
|
+
},
|
|
85
|
+
}),
|
|
86
|
+
write: Object.freeze({
|
|
87
|
+
mutates: true,
|
|
88
|
+
async run(_cfg, cmd, rootDir) {
|
|
89
|
+
const { resolved, rel } = assertBridgePath(rootDir, cmd.path);
|
|
90
|
+
const text = String(cmd.content ?? '');
|
|
91
|
+
if (Buffer.byteLength(text, 'utf-8') > FILE_WRITE_MAX)
|
|
92
|
+
throw new Error('bridge: текст больше лимита 1 МБ');
|
|
93
|
+
await fsp.mkdir(path.dirname(resolved), { recursive: true });
|
|
94
|
+
await fsp.writeFile(resolved, text, 'utf-8');
|
|
95
|
+
return { path: rel, bytes: Buffer.byteLength(text, 'utf-8'), written: true };
|
|
96
|
+
},
|
|
97
|
+
}),
|
|
98
|
+
windows: Object.freeze({
|
|
99
|
+
mutates: false,
|
|
100
|
+
async run(cfg) {
|
|
101
|
+
if (typeof cfg?.listWindows === 'function')
|
|
102
|
+
return { windows: await cfg.listWindows() };
|
|
103
|
+
return { windows: [{ id: '1', title: 'Рабочий стол (' + os.hostname() + ')', app: 'desktop' }] };
|
|
104
|
+
},
|
|
105
|
+
}),
|
|
106
|
+
focus_window: Object.freeze({
|
|
107
|
+
mutates: true,
|
|
108
|
+
async run(cfg, cmd) {
|
|
109
|
+
const title = String(cmd.title || '').trim();
|
|
110
|
+
if (!title)
|
|
111
|
+
throw new Error('bridge: укажи заголовок окна (title)');
|
|
112
|
+
if (typeof cfg?.focusWindow === 'function')
|
|
113
|
+
return await cfg.focusWindow(title);
|
|
114
|
+
return { focused: title };
|
|
115
|
+
},
|
|
116
|
+
}),
|
|
117
|
+
open_app: Object.freeze({
|
|
118
|
+
mutates: true,
|
|
119
|
+
async run(cfg, cmd, rootDir) {
|
|
120
|
+
const app = String(cmd.app || '').trim();
|
|
121
|
+
if (!APP_NAME_RE.test(app))
|
|
122
|
+
throw new Error('bridge: недопустимое имя программы «' + app + '»');
|
|
123
|
+
const allowed = Array.isArray(cfg?.allowedApps) ? cfg.allowedApps : [];
|
|
124
|
+
if (!allowed.includes(app))
|
|
125
|
+
throw new Error('bridge: программа «' + app + '» не входит в разрешённый список моста (' + (allowed.join(', ') || 'пусто') + ')');
|
|
126
|
+
const safeArgs = assertSafeStringArgs(cmd.args);
|
|
127
|
+
if (typeof cfg?.spawnApp === 'function') {
|
|
128
|
+
const r = await cfg.spawnApp(app, safeArgs);
|
|
129
|
+
return { started: app, args: safeArgs, pid: r?.pid || 0 };
|
|
130
|
+
}
|
|
131
|
+
const child = spawn(app, safeArgs, { cwd: rootDir, shell: false, detached: true, stdio: 'ignore' });
|
|
132
|
+
child.unref();
|
|
133
|
+
return { started: app, args: safeArgs, pid: child.pid || 0 };
|
|
134
|
+
},
|
|
135
|
+
}),
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
/** Изменяющие/активные операции моста (запрещены в режиме readOnly). */
|
|
139
|
+
export const WRITE_OPS = new Set(Object.entries(BRIDGE_OPS).filter(([, d]) => d.mutates).map(([k]) => k));
|
|
140
|
+
export const READ_OPS = new Set(Object.entries(BRIDGE_OPS).filter(([, d]) => !d.mutates).map(([k]) => k));
|
|
141
|
+
|
|
142
|
+
/** Проверка: изменяет ли операция состояние (неизвестная операция — fail-closed = true). */
|
|
143
|
+
export function isBridgeMutatingOp(op) {
|
|
144
|
+
const def = BRIDGE_OPS[String(op || '')];
|
|
145
|
+
return def ? Boolean(def.mutates) : true;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Активные мосты по uid пользователя: uid → BridgeSession. */
|
|
149
|
+
const bridges = new Map();
|
|
150
|
+
|
|
151
|
+
function recordLog(session, entry) {
|
|
152
|
+
const item = { time: new Date().toISOString(), ...entry };
|
|
153
|
+
session.history.push(item);
|
|
154
|
+
if (session.history.length > HISTORY_MAX)
|
|
155
|
+
session.history.shift();
|
|
156
|
+
audit('desktop_bridge', { uid: session.uid, ...entry });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Проверить путь файла внутри корневой папки моста на ПК пользователя.
|
|
161
|
+
* Блокирует выход за пределы rootDir (`..`, чужой диск) и чувствительные файлы (.env, .ssh, ключи).
|
|
162
|
+
*/
|
|
163
|
+
export function assertBridgePath(rootDir, relPath) {
|
|
164
|
+
if (!rootDir)
|
|
165
|
+
throw new Error('bridge: не задана корневая папка моста (rootDir)');
|
|
166
|
+
const base = fs.existsSync(rootDir) ? fs.realpathSync(rootDir) : path.resolve(rootDir);
|
|
167
|
+
const raw = String(relPath ?? '.').trim() || '.';
|
|
168
|
+
if (raw.includes('\0'))
|
|
169
|
+
throw new Error('bridge: недопустимый путь');
|
|
170
|
+
const resolved = path.resolve(base, raw);
|
|
171
|
+
const rel = path.relative(base, resolved);
|
|
172
|
+
if (rel.startsWith('..') || path.isAbsolute(rel))
|
|
173
|
+
throw new Error('bridge: выход за пределы разрешённой папки компьютера запрещён: ' + raw);
|
|
174
|
+
// Ф.1: если файл или его родитель существует — проверяем realpathSync против обхода через символическую ссылку
|
|
175
|
+
const checkReal = fs.existsSync(resolved) ? resolved : (fs.existsSync(path.dirname(resolved)) ? path.dirname(resolved) : null);
|
|
176
|
+
if (checkReal) {
|
|
177
|
+
const realTarget = fs.realpathSync(checkReal);
|
|
178
|
+
const realRel = path.relative(base, realTarget);
|
|
179
|
+
if (realRel.startsWith('..') || path.isAbsolute(realRel))
|
|
180
|
+
throw new Error('bridge: символическая ссылка уводит за пределы разрешённой папки компьютера: ' + raw);
|
|
181
|
+
}
|
|
182
|
+
if (rel && SENSITIVE_FILE.test(rel))
|
|
183
|
+
throw new Error('bridge: доступ к чувствительным файлам и ключам запрещён: ' + rel);
|
|
184
|
+
return { base, resolved, rel: rel.replace(/\\/g, '/') || '.' };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Выполнить операцию локально на стороне моста (используется и CLI-клиентом моста, и in-process мостом в тестах).
|
|
189
|
+
* Повторно проверяет readOnly, белый список программ и границы папки rootDir через реестр BRIDGE_OPS.
|
|
190
|
+
*/
|
|
191
|
+
export async function executeLocalBridgeOp(cfg, cmd) {
|
|
192
|
+
const op = String(cmd?.op || '');
|
|
193
|
+
const def = Object.hasOwn(BRIDGE_OPS, op) ? BRIDGE_OPS[op] : null;
|
|
194
|
+
if (!def)
|
|
195
|
+
throw new Error('bridge: неизвестная операция «' + op + '»');
|
|
196
|
+
const readOnly = Boolean(cfg?.readOnly);
|
|
197
|
+
if (readOnly && isBridgeMutatingOp(op))
|
|
198
|
+
throw new Error('bridge: компьютер в режиме «только просмотр» (readOnly) — операция «' + op + '» запрещена');
|
|
199
|
+
const rootDir = path.resolve(cfg?.rootDir || process.cwd());
|
|
200
|
+
return def.run(cfg, cmd, rootDir);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Зарегистрировать или обновить подключение моста для пользователя uid.
|
|
205
|
+
* localHandler (необязательно) — прямое исполнение (для локального моста или тестов),
|
|
206
|
+
* иначе команды ставятся в очередь queue и забираются клиентом моста по HTTP /~bridge/poll.
|
|
207
|
+
*/
|
|
208
|
+
export function registerBridge({ uid, hostname, platform, rootDir, readOnly = false, allowedApps = [], localHandler = null }) {
|
|
209
|
+
if (!uid)
|
|
210
|
+
throw new Error('bridge: нужен uid пользователя');
|
|
211
|
+
const prev = bridges.get(uid);
|
|
212
|
+
const session = {
|
|
213
|
+
uid: String(uid),
|
|
214
|
+
id: prev?.id || ('br-' + randomBytes(6).toString('hex')),
|
|
215
|
+
hostname: String(hostname || os.hostname()),
|
|
216
|
+
platform: String(platform || process.platform),
|
|
217
|
+
rootDir: String(rootDir || process.cwd()),
|
|
218
|
+
readOnly: prev?.serverReadOnly != null ? Boolean(prev.serverReadOnly) : Boolean(readOnly),
|
|
219
|
+
serverReadOnly: prev?.serverReadOnly ?? null,
|
|
220
|
+
allowedApps: Array.isArray(allowedApps) ? allowedApps.map(String) : [],
|
|
221
|
+
connectedAt: prev?.connectedAt || Date.now(),
|
|
222
|
+
lastSeen: Date.now(),
|
|
223
|
+
localHandler,
|
|
224
|
+
queue: prev?.queue || [],
|
|
225
|
+
pending: prev?.pending || new Map(),
|
|
226
|
+
history: prev?.history || [],
|
|
227
|
+
};
|
|
228
|
+
bridges.set(String(uid), session);
|
|
229
|
+
recordLog(session, { action: 'register', hostname: session.hostname, readOnly: session.readOnly, outcome: 'ok' });
|
|
230
|
+
return session;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Отключить мост пользователя. */
|
|
234
|
+
export function unregisterBridge(uid) {
|
|
235
|
+
const s = bridges.get(String(uid || ''));
|
|
236
|
+
if (!s)
|
|
237
|
+
return false;
|
|
238
|
+
for (const [, p] of s.pending)
|
|
239
|
+
p.reject(new Error('мост отключён'));
|
|
240
|
+
s.pending.clear();
|
|
241
|
+
bridges.delete(String(uid));
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Получить активный мост ТОЛЬКО для владельца uid (строгая изоляция по пользователю). */
|
|
246
|
+
export function getBridgeForUser(uid) {
|
|
247
|
+
const s = bridges.get(String(uid || ''));
|
|
248
|
+
if (!s)
|
|
249
|
+
return null;
|
|
250
|
+
if (Date.now() - s.lastSeen > BRIDGE_TTL_MS) {
|
|
251
|
+
unregisterBridge(uid);
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
return s;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Переключить режим «только просмотр» (readOnly) моста пользователя. */
|
|
258
|
+
export function setBridgeReadOnly(uid, readOnly) {
|
|
259
|
+
const s = getBridgeForUser(uid);
|
|
260
|
+
if (!s)
|
|
261
|
+
throw new Error('мост компьютера не подключён');
|
|
262
|
+
s.readOnly = Boolean(readOnly);
|
|
263
|
+
s.serverReadOnly = s.readOnly;
|
|
264
|
+
s.lastSeen = Date.now();
|
|
265
|
+
recordLog(s, { action: 'mode', readOnly: s.readOnly, outcome: 'ok' });
|
|
266
|
+
return { uid: s.uid, readOnly: s.readOnly };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Отправить команду на мост пользователя uid и дождаться результата.
|
|
271
|
+
* Проверяет владение (uid), активность моста, режим «только просмотр» (readOnly) и пишет в журнал.
|
|
272
|
+
*/
|
|
273
|
+
export async function dispatchBridgeCommand(uid, cmd) {
|
|
274
|
+
const s = getBridgeForUser(uid);
|
|
275
|
+
if (!s)
|
|
276
|
+
throw new Error('На вашем компьютере не запущен агент-«мост» WORK (или связь потеряна). Запустите scripts/work-desktop-bridge.mjs.');
|
|
277
|
+
const op = String(cmd?.op || '');
|
|
278
|
+
const target = String(cmd?.path || cmd?.app || cmd?.title || op);
|
|
279
|
+
if (s.readOnly && isBridgeMutatingOp(op)) {
|
|
280
|
+
recordLog(s, { action: op, target, readOnly: true, outcome: 'denied_readonly' });
|
|
281
|
+
throw new Error('Компьютер в режиме «только просмотр» (readOnly): действие «' + op + '» запрещено.');
|
|
282
|
+
}
|
|
283
|
+
s.lastSeen = Date.now();
|
|
284
|
+
try {
|
|
285
|
+
let res;
|
|
286
|
+
if (typeof s.localHandler === 'function') {
|
|
287
|
+
res = await s.localHandler(cmd, s);
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
const callId = 'cmd-' + randomBytes(6).toString('hex');
|
|
291
|
+
res = await new Promise((resolve, reject) => {
|
|
292
|
+
const timer = setTimeout(() => {
|
|
293
|
+
s.pending.delete(callId);
|
|
294
|
+
reject(new Error('bridge: таймаут ответа от компьютера пользователя (' + op + ')'));
|
|
295
|
+
}, CMD_TIMEOUT_MS);
|
|
296
|
+
s.pending.set(callId, {
|
|
297
|
+
resolve: v => { clearTimeout(timer); resolve(v); },
|
|
298
|
+
reject: e => { clearTimeout(timer); reject(e); },
|
|
299
|
+
});
|
|
300
|
+
s.queue.push({ id: callId, ...cmd });
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
recordLog(s, { action: op, target, readOnly: s.readOnly, outcome: 'ok' });
|
|
304
|
+
return res;
|
|
305
|
+
}
|
|
306
|
+
catch (e) {
|
|
307
|
+
recordLog(s, { action: op, target, readOnly: s.readOnly, outcome: 'error', error: String(e?.message || e).slice(0, 200) });
|
|
308
|
+
throw e;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ── HTTP-транспорт /~bridge/* для удалённого процесса моста ─────────────────
|
|
313
|
+
|
|
314
|
+
function replyJson(res, status, obj) {
|
|
315
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
316
|
+
res.end(JSON.stringify(obj));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function readBodyJson(req) {
|
|
320
|
+
const chunks = [];
|
|
321
|
+
let len = 0;
|
|
322
|
+
for await (const c of req) {
|
|
323
|
+
len += c.length;
|
|
324
|
+
if (len > 2 * 1024 * 1024)
|
|
325
|
+
throw new Error('тело больше 2 МБ');
|
|
326
|
+
chunks.push(c);
|
|
327
|
+
}
|
|
328
|
+
return chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf-8')) : {};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export async function handleBridgeHttp(req, res) {
|
|
332
|
+
const urlPath = String(req.url || '').split('?')[0];
|
|
333
|
+
if (!urlPath.startsWith('/~bridge/'))
|
|
334
|
+
return false;
|
|
335
|
+
if (!clientAllowed(req)) {
|
|
336
|
+
replyJson(res, 403, { error: 'Мост доступен только с этого компьютера или локальной сети' });
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
const hdr = String(req.headers.authorization || '');
|
|
340
|
+
const rawToken = /^Bearer\s+(\S+)$/i.exec(hdr)?.[1] || '';
|
|
341
|
+
const auth = await verifyToken(rawToken);
|
|
342
|
+
if (!auth) {
|
|
343
|
+
replyJson(res, 401, { error: 'Нужен токен Authorization: Bearer wmcp.<uid>.<секрет>' });
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (urlPath === '/~bridge/register' && req.method === 'POST') {
|
|
348
|
+
const body = await readBodyJson(req);
|
|
349
|
+
const s = registerBridge({
|
|
350
|
+
uid: auth.uid,
|
|
351
|
+
hostname: body.hostname,
|
|
352
|
+
platform: body.platform,
|
|
353
|
+
rootDir: body.rootDir,
|
|
354
|
+
readOnly: Boolean(body.readOnly),
|
|
355
|
+
allowedApps: body.allowedApps,
|
|
356
|
+
});
|
|
357
|
+
replyJson(res, 200, { ok: true, id: s.id, uid: s.uid, readOnly: s.readOnly });
|
|
358
|
+
return true;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (urlPath === '/~bridge/poll' && req.method === 'GET') {
|
|
362
|
+
const s = getBridgeForUser(auth.uid);
|
|
363
|
+
if (!s) {
|
|
364
|
+
replyJson(res, 404, { error: 'Мост не зарегистрирован' });
|
|
365
|
+
return true;
|
|
366
|
+
}
|
|
367
|
+
s.lastSeen = Date.now();
|
|
368
|
+
const cmd = s.queue.shift() || null;
|
|
369
|
+
replyJson(res, 200, { ok: true, readOnly: s.readOnly, command: cmd });
|
|
370
|
+
return true;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (urlPath === '/~bridge/result' && req.method === 'POST') {
|
|
374
|
+
const s = getBridgeForUser(auth.uid);
|
|
375
|
+
if (!s) {
|
|
376
|
+
replyJson(res, 404, { error: 'Мост не зарегистрирован' });
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
s.lastSeen = Date.now();
|
|
380
|
+
const body = await readBodyJson(req);
|
|
381
|
+
const p = s.pending.get(String(body.id || ''));
|
|
382
|
+
if (p) {
|
|
383
|
+
s.pending.delete(String(body.id));
|
|
384
|
+
if (body.error)
|
|
385
|
+
p.reject(new Error(String(body.error)));
|
|
386
|
+
else
|
|
387
|
+
p.resolve(body.result);
|
|
388
|
+
}
|
|
389
|
+
replyJson(res, 200, { ok: true });
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
replyJson(res, 404, { error: 'Неизвестный маршрут моста' });
|
|
394
|
+
return true;
|
|
395
|
+
}
|