@aivin-labs/cli 1.0.11 → 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/README.md +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import axios from 'axios';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
|
+
import { Transform } from 'stream';
|
|
4
5
|
import { pipeline } from 'stream/promises';
|
|
5
6
|
import { DEVICE_API_PREFIX, DeviceErrorCode, ToolGroup } from './constants.mjs';
|
|
6
7
|
import { DeviceToolError, displayPath, resolveInRoots } from './sandbox.mjs';
|
|
@@ -9,6 +10,8 @@ import { DeviceToolError, displayPath, resolveInRoots } from './sandbox.mjs';
|
|
|
9
10
|
const DEVICE_TOKEN_HEADER = 'x-aivin-device-token';
|
|
10
11
|
const TICKET_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
11
12
|
const PART_RETRIES = 2;
|
|
13
|
+
/** Trần cỡ một tệp tải về qua HTTP thẳng (02/11/2026) — tránh đầy ổ khi vé / máy chủ trả dữ liệu không dứt. */
|
|
14
|
+
export const MAX_DOWNLOAD_BYTES = 8 * 1024 ** 3;
|
|
12
15
|
|
|
13
16
|
/**
|
|
14
17
|
* Tệp lớn hơn trần socket đi HTTP thẳng giữa máy và kho Aivin (be DeviceDirectTransferService). Chỉ BE gọi (internal, Planner không thấy):
|
|
@@ -40,18 +43,38 @@ export function buildTransferTools({ serverUrl, deviceToken }) {
|
|
|
40
43
|
return { path: displayPath(env.roots, abs), bytes: size, parts };
|
|
41
44
|
}
|
|
42
45
|
|
|
46
|
+
/**
|
|
47
|
+
* Tải về (02/11/2026): ghi ra `<đích>.part` trước, đủ + đúng cỡ mới thay đích (bản cũ vào kho hoàn tác như fs.write) — trước đây ghi thẳng
|
|
48
|
+
* đè đích: đứt giữa chừng là tệp gốc bị cắt cụt, không lấy lại được, và không có trần dung lượng (đầy ổ).
|
|
49
|
+
*/
|
|
43
50
|
async function download(args, ctx, env) {
|
|
44
51
|
if (env.runAs) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Direct transfer is not available on a shared computer');
|
|
45
52
|
const abs = resolveInRoots(env.roots, args.path || '');
|
|
53
|
+
const limit = downloadLimit(args);
|
|
54
|
+
const expected = Number.isFinite(Number(args.size)) && args.size !== null && args.size !== '' ? Number(args.size) : null;
|
|
55
|
+
if (expected !== null && expected > limit) throw tooLarge(limit);
|
|
46
56
|
await fs.promises.mkdir(path.dirname(abs), { recursive: true });
|
|
47
57
|
const res = await axios.get(urlOf(args.ticket), { headers: headers(), signal: ctx.signal, responseType: 'stream', validateStatus: () => true });
|
|
48
58
|
if (res.status !== 200) {
|
|
49
59
|
res.data?.destroy?.();
|
|
50
60
|
throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Download failed (HTTP ${res.status})`);
|
|
51
61
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
62
|
+
if (Number(res.headers?.['content-length']) > limit) {
|
|
63
|
+
res.data?.destroy?.();
|
|
64
|
+
throw tooLarge(limit);
|
|
65
|
+
}
|
|
66
|
+
const part = `${abs}.part`;
|
|
67
|
+
let bytes = 0;
|
|
68
|
+
try {
|
|
69
|
+
await pipeline(res.data, byteCap(limit, (n) => { bytes = n; }), fs.createWriteStream(part), { signal: ctx.signal });
|
|
70
|
+
if (expected !== null && bytes !== expected) {
|
|
71
|
+
throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Download incomplete (${bytes} of ${expected} bytes) — the file was not changed`);
|
|
72
|
+
}
|
|
73
|
+
} catch (e) {
|
|
74
|
+
await fs.promises.rm(part, { force: true }).catch(() => undefined);
|
|
75
|
+
throw e;
|
|
76
|
+
}
|
|
77
|
+
return { path: displayPath(env.roots, abs), bytes, ...(await commitPart(part, abs, args, env)) };
|
|
55
78
|
}
|
|
56
79
|
|
|
57
80
|
return [
|
|
@@ -62,6 +85,44 @@ export function buildTransferTools({ serverUrl, deviceToken }) {
|
|
|
62
85
|
];
|
|
63
86
|
}
|
|
64
87
|
|
|
88
|
+
/** Trần một lần tải về: `args.max_bytes` (BE) chỉ được hạ, không vượt `MAX_DOWNLOAD_BYTES`. */
|
|
89
|
+
function downloadLimit(args) {
|
|
90
|
+
const asked = Number(args?.max_bytes);
|
|
91
|
+
return asked > 0 ? Math.min(asked, MAX_DOWNLOAD_BYTES) : MAX_DOWNLOAD_BYTES;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const tooLarge = (limit) => new DeviceToolError(DeviceErrorCode.OUTPUT_TOO_LARGE, `File is larger than the ${Math.round(limit / 1024 ** 2)} MB limit for one download — nothing was written`);
|
|
95
|
+
|
|
96
|
+
/** Đếm byte đi qua; quá `limit` → huỷ cả đường ống (tệp .part bị xoá ở nơi gọi). */
|
|
97
|
+
function byteCap(limit, onCount) {
|
|
98
|
+
let seen = 0;
|
|
99
|
+
return new Transform({
|
|
100
|
+
transform(chunk, _enc, cb) {
|
|
101
|
+
seen += chunk.length;
|
|
102
|
+
onCount(seen);
|
|
103
|
+
if (seen > limit) return cb(tooLarge(limit));
|
|
104
|
+
cb(null, chunk);
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Đổi `.part` thành đích: đích có sẵn → lưu bản cũ vào kho hoàn tác trước; tệp mới → ghi lại để hoàn tác thì bỏ đi. */
|
|
110
|
+
async function commitPart(part, abs, args, env) {
|
|
111
|
+
const undo = env.undo ? env.undo.begin(args.undo_group, 'write') : null;
|
|
112
|
+
const exists = fs.existsSync(abs);
|
|
113
|
+
try {
|
|
114
|
+
const backup = exists ? await undo?.backupFile(abs) : undefined;
|
|
115
|
+
await fs.promises.rename(part, abs);
|
|
116
|
+
if (!exists) undo?.created(abs);
|
|
117
|
+
return { created: !exists, ...(exists && undo ? { previous_version_kept: !!backup } : {}) };
|
|
118
|
+
} catch (e) {
|
|
119
|
+
await fs.promises.rm(part, { force: true }).catch(() => undefined);
|
|
120
|
+
throw e;
|
|
121
|
+
} finally {
|
|
122
|
+
undo?.commit();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
65
126
|
/** Một khúc = một PUT có Content-Length cố định (BE đối chiếu cỡ khúc theo vé; stream từ đĩa, không nạp cả khúc vào RAM). */
|
|
66
127
|
async function putPart({ url, abs, start, length, signal, headers }) {
|
|
67
128
|
const body = length ? fs.createReadStream(abs, { start, end: start + length - 1 }) : Buffer.alloc(0);
|
|
@@ -39,17 +39,11 @@ const interruptedOutcome = () => ({
|
|
|
39
39
|
export function createIdemLog(file, { now = () => Date.now() } = {}) {
|
|
40
40
|
const entries = new Map();
|
|
41
41
|
let lines = 0;
|
|
42
|
+
const pendingLines = [];
|
|
43
|
+
let writeChain = Promise.resolve();
|
|
44
|
+
let dirEnsured = false;
|
|
42
45
|
|
|
43
|
-
|
|
44
|
-
try {
|
|
45
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
46
|
-
fs.appendFileSync(file, JSON.stringify(record) + '\n');
|
|
47
|
-
lines++;
|
|
48
|
-
if (lines > COMPACT_LINES) compact();
|
|
49
|
-
} catch { /* ổ đầy / không ghi được: chống trùng vẫn chạy trong bộ nhớ */ }
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
function compact() {
|
|
46
|
+
function compactSync() {
|
|
53
47
|
const keep = [...entries.entries()].slice(-PERSIST_MAX);
|
|
54
48
|
entries.clear();
|
|
55
49
|
keep.forEach(([k, v]) => entries.set(k, v));
|
|
@@ -59,6 +53,35 @@ export function createIdemLog(file, { now = () => Date.now() } = {}) {
|
|
|
59
53
|
lines = keep.length;
|
|
60
54
|
}
|
|
61
55
|
|
|
56
|
+
async function compactAsync() {
|
|
57
|
+
const keep = [...entries.entries()].slice(-PERSIST_MAX);
|
|
58
|
+
entries.clear();
|
|
59
|
+
keep.forEach(([k, v]) => entries.set(k, v));
|
|
60
|
+
const tmp = `${file}.tmp`;
|
|
61
|
+
const body = keep.map(([k, v]) => JSON.stringify({ k, s: v.state, at: v.at, ...(v.outcome ? { o: v.outcome } : {}) }) + '\n').join('');
|
|
62
|
+
await fs.promises.writeFile(tmp, body);
|
|
63
|
+
await fs.promises.rename(tmp, file);
|
|
64
|
+
lines = keep.length;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const write = (record) => {
|
|
68
|
+
pendingLines.push(JSON.stringify(record) + '\n');
|
|
69
|
+
writeChain = writeChain.then(async () => {
|
|
70
|
+
if (!pendingLines.length) return;
|
|
71
|
+
const batch = pendingLines.splice(0, pendingLines.length);
|
|
72
|
+
try {
|
|
73
|
+
if (!dirEnsured) {
|
|
74
|
+
await fs.promises.mkdir(path.dirname(file), { recursive: true });
|
|
75
|
+
dirEnsured = true;
|
|
76
|
+
}
|
|
77
|
+
await fs.promises.appendFile(file, batch.join(''));
|
|
78
|
+
lines += batch.length;
|
|
79
|
+
if (lines > COMPACT_LINES) await compactAsync();
|
|
80
|
+
} catch { /* ổ đầy / không ghi được: chống trùng vẫn chạy trong bộ nhớ */ }
|
|
81
|
+
});
|
|
82
|
+
return writeChain;
|
|
83
|
+
};
|
|
84
|
+
|
|
62
85
|
/** Đọc sổ cũ: trả các khoá còn hạn (đã xong / bị ngắt), viết gọn tệp. */
|
|
63
86
|
function load() {
|
|
64
87
|
let raw;
|
|
@@ -73,19 +96,20 @@ export function createIdemLog(file, { now = () => Date.now() } = {}) {
|
|
|
73
96
|
if (r.s === IdemState.FAIL) continue;
|
|
74
97
|
entries.set(r.k, { state: r.s === IdemState.START ? IdemState.INTERRUPTED : r.s, at: Number(r.at), ...(r.o ? { outcome: r.o } : {}) });
|
|
75
98
|
}
|
|
76
|
-
try {
|
|
99
|
+
try { compactSync(); dirEnsured = true; } catch { /* giữ tệp cũ */ }
|
|
77
100
|
return entries;
|
|
78
101
|
}
|
|
79
102
|
|
|
80
103
|
return {
|
|
81
104
|
load,
|
|
82
|
-
|
|
105
|
+
flush: () => writeChain,
|
|
106
|
+
started: (k) => { entries.set(k, { state: IdemState.START, at: now() }); return write({ k, s: IdemState.START, at: now() }); },
|
|
83
107
|
done: (k, outcome) => {
|
|
84
108
|
const o = keptOutcome(outcome);
|
|
85
109
|
entries.set(k, { state: IdemState.DONE, at: now(), outcome: o });
|
|
86
|
-
write({ k, s: IdemState.DONE, at: now(), o });
|
|
110
|
+
return write({ k, s: IdemState.DONE, at: now(), o });
|
|
87
111
|
},
|
|
88
|
-
failed: (k) => { entries.delete(k); write({ k, s: IdemState.FAIL, at: now() }); },
|
|
112
|
+
failed: (k) => { entries.delete(k); return write({ k, s: IdemState.FAIL, at: now() }); },
|
|
89
113
|
};
|
|
90
114
|
}
|
|
91
115
|
|
|
@@ -122,14 +146,19 @@ export function createIdempotentRunner(run, isReadOnly, { onDuplicate, now = ()
|
|
|
122
146
|
return hit.promise.then(markDeduplicated);
|
|
123
147
|
}
|
|
124
148
|
let marked = false;
|
|
125
|
-
const started = () => { if (!marked) { marked = true; log?.started(key); } };
|
|
149
|
+
const started = () => { if (!marked) { marked = true; void log?.started(key); } };
|
|
126
150
|
if (!deferStart) started();
|
|
127
|
-
const
|
|
151
|
+
const rawPromise = run(call, ...rest, ...(deferStart ? [{ started }] : []));
|
|
152
|
+
const promise = rawPromise.then(async (r) => {
|
|
153
|
+
if (r.outcome.ok) await log?.done(key, r.outcome);
|
|
154
|
+
else { seen.delete(key); await log?.failed(key); }
|
|
155
|
+
return r;
|
|
156
|
+
}, async (err) => {
|
|
157
|
+
seen.delete(key);
|
|
158
|
+
await log?.failed(key);
|
|
159
|
+
throw err;
|
|
160
|
+
});
|
|
128
161
|
seen.set(key, { promise, at: t });
|
|
129
|
-
promise.then((r) => {
|
|
130
|
-
if (r.outcome.ok) log?.done(key, r.outcome);
|
|
131
|
-
else { seen.delete(key); log?.failed(key); }
|
|
132
|
-
}, () => { seen.delete(key); log?.failed(key); });
|
|
133
162
|
return promise;
|
|
134
163
|
};
|
|
135
164
|
}
|
|
@@ -4,6 +4,7 @@ import path from 'path';
|
|
|
4
4
|
import { DeviceErrorCode, REMOTE_CONFIG_DIR } from './constants.mjs';
|
|
5
5
|
import { DeviceToolError } from './sandbox.mjs';
|
|
6
6
|
import { openToken, sealToken } from './tokenStore.mjs';
|
|
7
|
+
import { notePolicySealed, policySealedNoted } from './credentials.mjs';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Sàn luật TẠI MÁY (29/10/2026). Trước đây máy tin BE gần như tuyệt đối: ngoài thư mục được phép + công tắc ngắt + vài lệnh thảm hoạ, mọi
|
|
@@ -39,7 +40,10 @@ const POLICY_KEY_ACCOUNT = 'remote-policy-key';
|
|
|
39
40
|
* Công cụ mang lệnh để chạy → tham số chứa lệnh. `gui.act`: chữ gõ vào cửa sổ (hộp Run, terminal đang mở) cũng là một cách chạy lệnh —
|
|
40
41
|
* xét cùng mẫu lệnh rủi ro / luật chặn của chủ máy.
|
|
41
42
|
*/
|
|
42
|
-
const COMMAND_ARG = Object.freeze({
|
|
43
|
+
const COMMAND_ARG = Object.freeze({
|
|
44
|
+
'shell.exec': 'command', 'proc.start': 'command', 'proc.write': 'text', 'sys.schedule': 'command',
|
|
45
|
+
'gui.act': 'text', 'gui.do': 'value',
|
|
46
|
+
});
|
|
43
47
|
|
|
44
48
|
/** Công cụ luôn xét là rủi ro: gửi ra ngoài thay người dùng, cài việc chạy định kỳ (cách bám trụ kinh điển của mã độc). */
|
|
45
49
|
// meeting.start: ghi âm micro + âm thanh máy — AI không tự bật ghi âm khi không ai ngồi trước máy biết (29/10/2026).
|
|
@@ -50,6 +54,43 @@ const ALWAYS_RISKY_REASON = {
|
|
|
50
54
|
'meeting.start': 'Ghi âm cuộc họp (micro + âm thanh máy) và chụp màn hình',
|
|
51
55
|
};
|
|
52
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Công cụ NỘI BỘ (BE tự gọi, Planner không thấy) mà vẫn ghi tệp lên máy — xét rủi ro / hỏi xác nhận như `fs.write`, không được miễn như các
|
|
59
|
+
* công cụ nội bộ khác (đọc khúc tệp, ghi nhớ, báo…) (02/11/2026).
|
|
60
|
+
*/
|
|
61
|
+
const INTERNAL_WRITE_TOOLS = new Set(['fs.download']);
|
|
62
|
+
|
|
63
|
+
/** Công cụ ghi tệp → tham số chứa đường ĐÍCH (`fs.move_many`: `moves[].to`). */
|
|
64
|
+
const WRITE_TARGET_ARGS = Object.freeze({
|
|
65
|
+
'fs.write': 'path', 'fs.edit': 'path', 'fs.download': 'path', 'fs.copy': 'destinationPath', 'fs.move': 'destinationPath',
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Chỗ TỰ CHẠY (02/11/2026): ghi tệp vào đây là cài được lệnh chạy khi đăng nhập / mở terminal / mở dự án — cùng loại bám trụ với `sys.schedule`
|
|
70
|
+
* nên buộc hỏi tại máy. Khớp trên đường dẫn đã chuẩn hoá (`/`, chữ thường); đường tương đối (theo thư mục nhà) cũng khớp.
|
|
71
|
+
*/
|
|
72
|
+
const AUTOSTART_PATH_PATTERNS = [
|
|
73
|
+
/\/start menu\/programs\/startup(\/|$)/, // Windows: thư mục Startup (người dùng / mọi người dùng)
|
|
74
|
+
/\/(windows)?powershell\/([^/]*_)?profile\.ps1$/, // hồ sơ PowerShell (chạy mỗi lần mở PowerShell)
|
|
75
|
+
/\/\.(bashrc|bash_profile|bash_login|profile|zshrc|zshenv|zprofile|zlogin|login|cshrc|tcshrc|xprofile|xinitrc)$/,
|
|
76
|
+
/\/\.config\/fish\/config\.fish$/,
|
|
77
|
+
/\/library\/(launchagents|launchdaemons)(\/|$)/, // macOS
|
|
78
|
+
/\/\.config\/(autostart|systemd\/user)(\/|$)/, // Linux desktop / systemd người dùng
|
|
79
|
+
/\/\.git\/hooks(\/|$)/, // chạy ở lần git commit / checkout kế tiếp
|
|
80
|
+
/\/\.vscode\/tasks\.json$/, // VS Code: task "runOn: folderOpen" chạy khi mở thư mục
|
|
81
|
+
];
|
|
82
|
+
|
|
83
|
+
/** Đường đích (trong tham số) rơi vào chỗ tự chạy — trả đường đó, không thì null. */
|
|
84
|
+
export function autostartTarget(toolName, args = {}) {
|
|
85
|
+
const key = WRITE_TARGET_ARGS[toolName];
|
|
86
|
+
const targets = key ? [args?.[key]] : toolName === 'fs.move_many' && Array.isArray(args?.moves) ? args.moves.map((m) => m?.to) : [];
|
|
87
|
+
return targets.find((t) => {
|
|
88
|
+
if (typeof t !== 'string' || !t.trim()) return false;
|
|
89
|
+
const p = `/${t.trim().replace(/\\/g, '/').toLowerCase()}`;
|
|
90
|
+
return AUTOSTART_PATH_PATTERNS.some((re) => re.test(p));
|
|
91
|
+
}) || null;
|
|
92
|
+
}
|
|
93
|
+
|
|
53
94
|
/**
|
|
54
95
|
* Lệnh có hậu quả khó lấy lại / chạm bảo mật — khớp chuỗi nên lách được (ghép chuỗi, mã hoá), nhưng chính các cách lách thông dụng
|
|
55
96
|
* (`-EncodedCommand`, `iex`, `| sh`) cũng nằm trong danh sách.
|
|
@@ -65,7 +106,9 @@ const RISKY_COMMAND_PATTERNS = [
|
|
|
65
106
|
/\b(set|add)-mppreference\b/i, /\bdisable-?(windows)?defender/i, /\btakeown\b/i, /\bicacls\b[^|;]*\/grant/i,
|
|
66
107
|
/\bchmod\s+(-[a-z]*r[a-z]*\s+)?[0-7]*7{2,}/i, /\bchown\s+-[a-z]*r/i, /\bsudo\b/i, /\brunas\b/i, /-verb\s+runas/i,
|
|
67
108
|
// Kho mật khẩu / khoá đăng nhập
|
|
68
|
-
/\bcmdkey\b/i, /\bsecurity\s+(find|dump|export)-/i, /\bvaultcmd\b/i, /login data|cookies\.sqlite|keychain-db|\.ssh[\\/]id_/i,
|
|
109
|
+
/\bcmdkey\b/i, /\bsecurity\s+(find|dump|export)-/i, /\bvaultcmd\b/i, /login data|cookies\.sqlite|keychain-db|\.ssh[\\/]id_|\bid_(rsa|dsa|ecdsa|ed25519)\b/i,
|
|
110
|
+
// Gửi dữ liệu ra ngoài bằng lớp .NET / chép ra thư mục mạng (UNC) — không có cờ nào của curl để nhận ra
|
|
111
|
+
/\.upload(file|string|data|values)(async)?\s*\(/i, /(^|[\s"'=(])\\\\(?!localhost\\|127\.0\.0\.1\\|\?\\|\.\\)[\w.-]+\\/, /\bnet\s+use\b/i,
|
|
69
112
|
// Tải về rồi chạy / chạy chuỗi mã hoá
|
|
70
113
|
/\b(curl|wget)\b[^|;]*\|\s*(sudo\s+)?(ba|z)?sh\b/i, /\b(iwr|irm|invoke-webrequest|invoke-restmethod)\b[^|;]*\|\s*(iex|invoke-expression)\b/i,
|
|
71
114
|
/\b(iex|invoke-expression)\b/i, /-e(nc(odedcommand)?)?\s+[a-z0-9+/=]{20,}/i, /\bbase64\s+(-d|--decode)\b[^|;]*\|\s*(ba|z)?sh\b/i,
|
|
@@ -146,6 +189,7 @@ export function saveLocalPolicy(policy, file = REMOTE_POLICY_FILE, { keyFile = R
|
|
|
146
189
|
fs.writeFileSync(file, JSON.stringify(signed, null, 2) + '\n', { mode: 0o600 });
|
|
147
190
|
const record = key ? readKeyRecord(keyFile) : null;
|
|
148
191
|
if (record) writeKeyRecord(keyFile, { ...record, policy: signed });
|
|
192
|
+
if (key) { try { notePolicySealed(); } catch { /* dấu bền chỉ để phát hiện bị xoá — xem createPolicyGuard */ } }
|
|
149
193
|
return clean;
|
|
150
194
|
}
|
|
151
195
|
|
|
@@ -167,7 +211,9 @@ export function verifyLocalPolicy(file = REMOTE_POLICY_FILE, { keyFile = REMOTE_
|
|
|
167
211
|
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
168
212
|
} catch (e) {
|
|
169
213
|
const keyExists = fs.existsSync(keyFile);
|
|
170
|
-
|
|
214
|
+
// `pristine`: không có tệp luật lẫn tệp khoá — có thể là chưa từng đặt luật, HOẶC cả hai vừa bị xoá (createPolicyGuard phân biệt).
|
|
215
|
+
const pristine = e?.code === 'ENOENT' && !keyExists;
|
|
216
|
+
return { policy: normalize(null), trusted: pristine, pristine, base: keyExists ? signedBackup(keyFile, policyKey(keyFile)) : null };
|
|
171
217
|
}
|
|
172
218
|
const policy = normalize(raw);
|
|
173
219
|
const key = policyKey(keyFile);
|
|
@@ -189,15 +235,33 @@ export function stricterPolicy(trusted, other) {
|
|
|
189
235
|
* Luật daemon dùng (đọc lại mỗi lời gọi — chủ máy đổi ở cửa sổ khác thì có hiệu lực ngay). Tệp có chữ ký đúng → dùng và nhớ làm bản đúng;
|
|
190
236
|
* tệp bị sửa ngoài `aivin remote policy` → chặt hơn của (bản có chữ ký gần nhất — chép trong tệp khoá, không có thì bản đúng daemon đã thấy,
|
|
191
237
|
* tệp): siết thì nhận, nới thì bỏ. `onTamper(policy)` báo một lần mỗi lần nội dung tệp đổi.
|
|
238
|
+
*
|
|
239
|
+
* Xoá CẢ tệp luật lẫn tệp khoá (02/11/2026): trước đây trông y như "chưa từng đặt luật" → tin, luật về mặc định ngay cả khi daemon đang chạy.
|
|
240
|
+
* Nay daemon đã từng thấy luật có chữ ký (trong phiên này, hoặc theo dấu bền `sealedMarker` — mặc định ghi trong tệp ghép máy, credentials.mjs)
|
|
241
|
+
* thì coi trạng thái "không có gì" là bị can thiệp: giữ bản đúng gần nhất, báo `onTamper`. Giới hạn: daemon khởi động lại sau khi bị xoá cả
|
|
242
|
+
* ba (luật, khoá, dấu) thì không còn gì để phân biệt — nhưng xoá tệp ghép máy cũng làm máy mất kết nối với Aivin.
|
|
192
243
|
*/
|
|
193
|
-
export function createPolicyGuard({
|
|
244
|
+
export function createPolicyGuard({
|
|
245
|
+
file = REMOTE_POLICY_FILE, keyFile = REMOTE_POLICY_KEY_FILE, onTamper, sealedMarker = { seen: policySealedNoted, note: notePolicySealed },
|
|
246
|
+
} = {}) {
|
|
247
|
+
const safe = (fn) => { try { return fn?.(); } catch { return undefined; } };
|
|
194
248
|
const first = verifyLocalPolicy(file, { keyFile });
|
|
195
|
-
let
|
|
249
|
+
let everSigned = (first.trusted && !first.pristine) || !!first.base || !!safe(sealedMarker?.seen);
|
|
250
|
+
const noteSigned = () => {
|
|
251
|
+
if (everSigned && safe(sealedMarker?.seen)) return;
|
|
252
|
+
everSigned = true;
|
|
253
|
+
safe(sealedMarker?.note);
|
|
254
|
+
};
|
|
255
|
+
if (first.trusted && !first.pristine) noteSigned();
|
|
256
|
+
let lastTrusted = first.trusted && !(first.pristine && everSigned) ? first.policy : first.base || normalize(null);
|
|
196
257
|
let reported = null;
|
|
197
258
|
return {
|
|
198
259
|
read() {
|
|
199
|
-
const
|
|
260
|
+
const verdict = verifyLocalPolicy(file, { keyFile });
|
|
261
|
+
const { policy, base } = verdict;
|
|
262
|
+
const trusted = verdict.trusted && !(verdict.pristine && everSigned);
|
|
200
263
|
if (trusted) {
|
|
264
|
+
if (!verdict.pristine && !everSigned) noteSigned();
|
|
201
265
|
lastTrusted = policy;
|
|
202
266
|
reported = null;
|
|
203
267
|
return policy;
|
|
@@ -220,6 +284,7 @@ const commandOf = (toolName, args) => (COMMAND_ARG[toolName] ? String(args?.[COM
|
|
|
220
284
|
export function riskReason(tool, args = {}) {
|
|
221
285
|
if (ALWAYS_RISKY_TOOLS.has(tool.name)) return ALWAYS_RISKY_REASON[tool.name];
|
|
222
286
|
if (tool.destructive && args.permanent === true) return 'Xoá hẳn, không lấy lại được';
|
|
287
|
+
if (autostartTarget(tool.name, args)) return 'Ghi vào chỗ tự chạy (khởi động máy / mở terminal / mở dự án)';
|
|
223
288
|
const command = commandOf(tool.name, args);
|
|
224
289
|
if (command && RISKY_COMMAND_PATTERNS.some((re) => re.test(command))) return 'Lệnh có thể thay đổi hệ thống hoặc cài đặt bảo mật';
|
|
225
290
|
return null;
|
|
@@ -227,17 +292,23 @@ export function riskReason(tool, args = {}) {
|
|
|
227
292
|
|
|
228
293
|
/**
|
|
229
294
|
* Quyết định của sàn luật cho một lời gọi: `{ action: 'allow' }`, `{ action: 'confirm', reason }` hoặc ném `DeviceToolError` khi bị cấm.
|
|
230
|
-
* Lời gọi nội bộ (BE tự dùng: đọc khúc tệp, ghi nhớ…) và chỉ đọc không bao giờ cần xác nhận
|
|
295
|
+
* Lời gọi nội bộ (BE tự dùng: đọc khúc tệp, ghi nhớ…) và chỉ đọc không bao giờ cần xác nhận — nhưng phần CẤM (`deny_tools`, lệnh bị chặn) áp
|
|
296
|
+
* cho mọi công cụ, kể cả nội bộ (02/11/2026: trước đó daemon bỏ qua sàn luật với công cụ nội bộ). Công cụ nội bộ có ghi tệp
|
|
297
|
+
* (`INTERNAL_WRITE_TOOLS`) xét như `fs.write`.
|
|
231
298
|
*/
|
|
232
299
|
export function evaluateLocalPolicy(policy, tool, args = {}) {
|
|
233
|
-
|
|
300
|
+
// gui.do is only a compact route into the same GUI actuator. A device owner who disabled the
|
|
301
|
+
// lower-level actuator must not get it back merely because a newer CLI advertised the fast path.
|
|
302
|
+
const deniedByAlias = tool.name === 'gui.do' && policy.deny_tools.includes('gui.act');
|
|
303
|
+
if (policy.deny_tools.includes(tool.name) || deniedByAlias) {
|
|
234
304
|
throw new DeviceToolError(DeviceErrorCode.LOCAL_DENIED, `The owner of this computer turned off ${tool.name} here`);
|
|
235
305
|
}
|
|
236
306
|
const command = commandOf(tool.name, args);
|
|
237
307
|
if (command && policy.blocked_commands.some((re) => new RegExp(re, 'i').test(command))) {
|
|
238
308
|
throw new DeviceToolError(DeviceErrorCode.LOCAL_DENIED, 'Command blocked by a rule the owner of this computer set');
|
|
239
309
|
}
|
|
240
|
-
|
|
310
|
+
const confirmExempt = tool.read_only || (tool.internal && !INTERNAL_WRITE_TOOLS.has(tool.name));
|
|
311
|
+
if (confirmExempt || policy.confirm === ConfirmMode.NEVER) return { action: 'allow' };
|
|
241
312
|
if (policy.confirm === ConfirmMode.ALWAYS) return { action: 'confirm', reason: riskReason(tool, args) || 'Thay đổi trên máy (bạn đặt luật hỏi mọi việc)' };
|
|
242
313
|
const reason = riskReason(tool, args);
|
|
243
314
|
return reason ? { action: 'confirm', reason } : { action: 'allow' };
|
|
@@ -251,6 +322,7 @@ export function describeCall(tool, args = {}) {
|
|
|
251
322
|
if (tool.name === 'office.outlook.send') return cut(`Tới: ${args.to || '?'} — ${args.subject || ''}`, 300);
|
|
252
323
|
if (tool.name === 'meeting.start') return cut(`${args.title || 'Cuộc họp'}${args.then ? ` — sau đó: ${args.then}` : ''}`, 300);
|
|
253
324
|
if (args.path) return cut(args.path, 300);
|
|
325
|
+
if (args.destinationPath) return cut(`${args.sourcePath || '?'} → ${args.destinationPath}`, 300);
|
|
254
326
|
if (Array.isArray(args.paths)) return cut(args.paths.join(', '), 300);
|
|
255
327
|
return tool.name;
|
|
256
328
|
}
|