@aivin-labs/cli 1.0.75 → 1.0.78

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.
@@ -1,341 +1,345 @@
1
- import { createHmac, randomBytes, timingSafeEqual } from 'crypto';
2
- import fs from 'fs';
3
- import path from 'path';
4
- import { DeviceErrorCode, REMOTE_CONFIG_DIR } from './constants.mjs';
5
- import { DeviceToolError } from './sandbox.mjs';
6
- import { openToken, sealToken } from './tokenStore.mjs';
7
- import { notePolicySealed, policySealedNoted } from './credentials.mjs';
8
-
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
11
- * quyết định duyệt nằm ở BE — BE / tài khoản admin bị chiếm hoặc agent bị prompt injection là chạy được lệnh trên mọi máy đã ghép (máy
12
- * toàn quyền còn không hỏi). Tệp `~/.aivin/remote-policy.json` do CHỦ MÁY đặt (`aivin remote policy …`).
13
- *
14
- * Chống agent tự nới luật (29/10/2026): thư mục `.aivin` chỉ được che bằng khớp chuỗi với lệnh shell — ghép chuỗi / chạy tệp script là ghi
15
- * đè được tệp luật. Nên tệp luật mang chữ ký HMAC bằng khoá cất trong kho bí mật của hệ điều hành (tokenStore.mjs), chỉ `aivin remote policy`
16
- * ký. Daemon (`createPolicyGuard`) chỉ nhận bản có chữ ký đúng; bản không ký / ký sai chỉ được SIẾT thêm so với bản đúng gần nhất, không
17
- * được nới. Không chống được mã độc cùng tài khoản biết cách gọi DPAPI / Keychain để ký lại — cách ly thật cần tài khoản hệ điều hành riêng
18
- * (policy-approval.md mục 8 ở repo be).
19
- *
20
- * - `deny_tools`: công cụ tắt hẳn trên máy này (không vào danh mục, gọi tới bị từ chối).
21
- * - `blocked_commands`: regex chặn thêm cho lệnh shell / tiến trình nền / lịch.
22
- * - `confirm`: việc nào phải có người bấm "Cho phép" NGAY TRÊN MÁY — `risky` (mặc định: lệnh nguy hiểm, xoá hẳn, gửi thư, đặt lịch),
23
- * `always` (mọi việc có tác dụng), `never` (chỉ luật phía Aivin).
24
- */
25
-
26
- export const REMOTE_POLICY_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-policy.json');
27
-
28
- export const ConfirmMode = Object.freeze({ NEVER: 'never', RISKY: 'risky', ALWAYS: 'always' });
29
-
30
- /** Ai được xem + điều khiển màn hình: `ask` hỏi người ở máy mỗi phiên (mặc định), `unattended` không cần người ở máy, `off` tắt hẳn. */
31
- export const CastConsentMode = Object.freeze({ OFF: 'off', ASK: 'ask', UNATTENDED: 'unattended' });
32
- /** Số lớn hơn là chặt hơn. */
33
- export const CAST_CONSENT_RANK = Object.freeze({ [CastConsentMode.UNATTENDED]: 0, [CastConsentMode.ASK]: 1, [CastConsentMode.OFF]: 2 });
34
-
35
- export const DEFAULT_LOCAL_POLICY = Object.freeze({ confirm: ConfirmMode.RISKY, deny_tools: [], blocked_commands: [], confirm_timeout_sec: 120, cast_consent: CastConsentMode.ASK });
36
-
37
- /** Mức chặt của chế độ xác nhận — số lớn hơn là chặt hơn. */
38
- export const CONFIRM_RANK = Object.freeze({ [ConfirmMode.NEVER]: 0, [ConfirmMode.RISKY]: 1, [ConfirmMode.ALWAYS]: 2 });
39
-
40
- /** Khoá ký tệp luật (bản mã của kho bí mật hệ điều hành, như token máy). */
41
- export const REMOTE_POLICY_KEY_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-policy.key.json');
42
- const POLICY_KEY_ACCOUNT = 'remote-policy-key';
43
-
44
- /**
45
- * 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 —
46
- * xét cùng mẫu lệnh rủi ro / luật chặn của chủ máy.
47
- */
48
- const COMMAND_ARG = Object.freeze({
49
- 'shell.exec': 'command', 'proc.start': 'command', 'proc.write': 'text', 'sys.schedule': 'command',
50
- 'gui.act': 'text', 'gui.do': 'value',
51
- });
52
-
53
- /** 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). */
54
- // 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).
55
- const ALWAYS_RISKY_TOOLS = new Set(['office.outlook.send', 'sys.schedule', 'meeting.start']);
56
- const ALWAYS_RISKY_REASON = {
57
- 'office.outlook.send': 'Gửi thư thay bạn',
58
- 'sys.schedule': 'Đặt việc chạy định kỳ trên máy',
59
- 'meeting.start': 'Ghi âm cuộc họp (micro + âm thanh máy) và chụp màn hình',
60
- };
61
-
62
- /**
63
- * 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
64
- * công cụ nội bộ khác (đọc khúc tệp, ghi nhớ, báo…) (02/11/2026).
65
- */
66
- const INTERNAL_WRITE_TOOLS = new Set(['fs.download']);
67
-
68
- /** Công cụ ghi tệp → tham số chứa đường ĐÍCH (`fs.move_many`: `moves[].to`). */
69
- const WRITE_TARGET_ARGS = Object.freeze({
70
- 'fs.write': 'path', 'fs.edit': 'path', 'fs.download': 'path', 'fs.copy': 'destinationPath', 'fs.move': 'destinationPath',
71
- });
72
-
73
- /**
74
- * 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`
75
- * 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.
76
- */
77
- const AUTOSTART_PATH_PATTERNS = [
78
- /\/start menu\/programs\/startup(\/|$)/, // Windows: thư mục Startup (người dùng / mọi người dùng)
79
- /\/(windows)?powershell\/([^/]*_)?profile\.ps1$/, // hồ sơ PowerShell (chạy mỗi lần mở PowerShell)
80
- /\/\.(bashrc|bash_profile|bash_login|profile|zshrc|zshenv|zprofile|zlogin|login|cshrc|tcshrc|xprofile|xinitrc)$/,
81
- /\/\.config\/fish\/config\.fish$/,
82
- /\/library\/(launchagents|launchdaemons)(\/|$)/, // macOS
83
- /\/\.config\/(autostart|systemd\/user)(\/|$)/, // Linux desktop / systemd người dùng
84
- /\/\.git\/hooks(\/|$)/, // chạy ở lần git commit / checkout kế tiếp
85
- /\/\.vscode\/tasks\.json$/, // VS Code: task "runOn: folderOpen" chạy khi mở thư mục
86
- ];
87
-
88
- /** Đường đích (trong tham số) rơi vào chỗ tự chạy — trả đường đó, không thì null. */
89
- export function autostartTarget(toolName, args = {}) {
90
- const key = WRITE_TARGET_ARGS[toolName];
91
- const targets = key ? [args?.[key]] : toolName === 'fs.move_many' && Array.isArray(args?.moves) ? args.moves.map((m) => m?.to) : [];
92
- return targets.find((t) => {
93
- if (typeof t !== 'string' || !t.trim()) return false;
94
- const p = `/${t.trim().replace(/\\/g, '/').toLowerCase()}`;
95
- return AUTOSTART_PATH_PATTERNS.some((re) => re.test(p));
96
- }) || null;
97
- }
98
-
99
- /**
100
- * 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
101
- * (`-EncodedCommand`, `iex`, `| sh`) cũng nằm trong danh sách.
102
- */
103
- const RISKY_COMMAND_PATTERNS = [
104
- // Xoá đệ quy / xoá hẳn
105
- /\brm\s+-[a-z]*r/i, /remove-item\b[^|;]*-recurse/i, /\b(rd|rmdir)\s+\/s/i, /\bdel\s+(\/[a-z]\s+)*\/s/i, /\bshred\b/i,
106
- // Registry, dịch vụ, khởi động, tường lửa, chính sách hệ thống
107
- /\breg(\.exe)?\s+(add|delete|import)\b/i, /(set|new|remove)-itemproperty\b[^|;]*\bhk(lm|cu)/i,
108
- /\bsc(\.exe)?\s+(config|delete|create|stop)\b/i, /\b(stop|set|new)-service\b/i, /\bsystemctl\s+(disable|stop|mask)\b/i,
109
- /\bbcdedit\b/i, /\bnetsh\b/i, /\bschtasks\b/i, /\bcrontab\s+-r\b/i, /\b(shutdown|restart-computer|stop-computer)\b/i, /\breboot\b/i,
110
- // Tắt bảo vệ / đổi quyền hàng loạt / nâng quyền
111
- /\b(set|add)-mppreference\b/i, /\bdisable-?(windows)?defender/i, /\btakeown\b/i, /\bicacls\b[^|;]*\/grant/i,
112
- /\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,
113
- // Kho mật khẩu / khoá đăng nhập
114
- /\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,
115
- // 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
116
- /\.upload(file|string|data|values)(async)?\s*\(/i, /(^|[\s"'=(])\\\\(?!localhost\\|127\.0\.0\.1\\|\?\\|\.\\)[\w.-]+\\/, /\bnet\s+use\b/i,
117
- // Tải về rồi chạy / chạy chuỗi mã hoá
118
- /\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,
119
- /\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,
120
- // Đẩy đè lịch sử git
121
- /\bgit\s+push\b[^|;]*(--force\b|\s-f\b)/i,
122
- ];
123
-
124
- function normalize(raw) {
125
- const p = raw && typeof raw === 'object' ? raw : {};
126
- const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()) : []);
127
- const confirm = Object.values(ConfirmMode).includes(p.confirm) ? p.confirm : DEFAULT_LOCAL_POLICY.confirm;
128
- const timeout = Number(p.confirm_timeout_sec);
129
- return {
130
- confirm,
131
- deny_tools: list(p.deny_tools),
132
- blocked_commands: list(p.blocked_commands).filter((re) => { try { new RegExp(re, 'i'); return true; } catch { return false; } }),
133
- confirm_timeout_sec: Number.isFinite(timeout) && timeout >= 15 && timeout <= 900 ? Math.round(timeout) : DEFAULT_LOCAL_POLICY.confirm_timeout_sec,
134
- cast_consent: Object.hasOwn(CAST_CONSENT_RANK, String(p.cast_consent)) ? p.cast_consent : DEFAULT_LOCAL_POLICY.cast_consent,
135
- };
136
- }
137
-
138
- /** Đọc luật trong tệp (không có tệp → mặc định), KHÔNG xét chữ ký — để hiện cho chủ máy. Daemon đọc qua `createPolicyGuard`. */
139
- export function loadLocalPolicy(file = REMOTE_POLICY_FILE) {
140
- try {
141
- return normalize(JSON.parse(fs.readFileSync(file, 'utf8')));
142
- } catch {
143
- return normalize(null);
144
- }
145
- }
146
-
147
- /** Khoá đã giải theo bản mã trong tệp khoá — giải DPAPI tốn một tiến trình con, daemon đọc luật ở mỗi lời gọi. */
148
- const keyCache = new Map();
149
-
150
- function readKeyRecord(keyFile) {
151
- try { return JSON.parse(fs.readFileSync(keyFile, 'utf8')); } catch { return null; }
152
- }
153
-
154
- function writeKeyRecord(keyFile, record) {
155
- fs.mkdirSync(path.dirname(keyFile), { recursive: true });
156
- fs.writeFileSync(keyFile, JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
157
- }
158
-
159
- /** Khoá ký luật; `create` → chưa có thì sinh + cất vào kho bí mật. `null` khi không có / không giải được. */
160
- function policyKey(keyFile, { create = false } = {}) {
161
- const record = readKeyRecord(keyFile);
162
- const fingerprint = record ? `${record.token_store || ''}:${record.token_enc || record.device_token || ''}` : null;
163
- if (fingerprint && keyCache.get(keyFile)?.fingerprint === fingerprint) return keyCache.get(keyFile).key;
164
- let key = record ? openToken(record) : null;
165
- let fp = fingerprint;
166
- if (!key && create) {
167
- key = randomBytes(32).toString('hex');
168
- const { fallback_reason: _why, ...sealed } = sealToken(key, { account: POLICY_KEY_ACCOUNT });
169
- writeKeyRecord(keyFile, { device_id: POLICY_KEY_ACCOUNT, ...sealed });
170
- fp = `${sealed.token_store || ''}:${sealed.token_enc || sealed.device_token || ''}`;
171
- }
172
- if (key) keyCache.set(keyFile, { fingerprint: fp, key });
173
- return key;
174
- }
175
-
176
- /** Giá trị mặc định của trường mới không vào chữ ký: tệp luật đã ký từ bản CLI trước vẫn khớp. */
177
- function signedForm(clean) {
178
- const { cast_consent: consent, ...rest } = normalize(clean);
179
- return consent === DEFAULT_LOCAL_POLICY.cast_consent ? rest : { ...rest, cast_consent: consent };
180
- }
181
-
182
- const signPolicy = (clean, key) => createHmac('sha256', key).update(JSON.stringify(signedForm(clean))).digest('hex');
183
-
184
- function sealMatches(clean, seal, key) {
185
- if (typeof seal !== 'string' || !key) return false;
186
- const expected = Buffer.from(signPolicy(clean, key), 'hex');
187
- const actual = Buffer.from(seal, 'hex');
188
- return actual.length === expected.length && timingSafeEqual(actual, expected);
189
- }
190
-
191
- /**
192
- * Lưu luật + ký (chỉ `aivin remote policy` gọi). Bản có chữ ký được chép thêm vào tệp khoá (`policy`): tệp luật bị ghi đè trước khi daemon kịp
193
- * đọc bản đúng (hoặc daemon khởi động lại sau đó) thì vẫn có bản đúng làm gốc — chạy thật 29/10/2026: chỉ nhớ trong RAM là agent bật lại
194
- * được công cụ chủ máy vừa tắt.
195
- */
196
- export function saveLocalPolicy(policy, file = REMOTE_POLICY_FILE, { keyFile = REMOTE_POLICY_KEY_FILE } = {}) {
197
- const clean = normalize(policy);
198
- const key = policyKey(keyFile, { create: true });
199
- const signed = { ...clean, ...(key ? { seal: signPolicy(clean, key) } : {}) };
200
- fs.mkdirSync(path.dirname(file), { recursive: true });
201
- fs.writeFileSync(file, JSON.stringify(signed, null, 2) + '\n', { mode: 0o600 });
202
- const record = key ? readKeyRecord(keyFile) : null;
203
- if (record) writeKeyRecord(keyFile, { ...record, policy: signed });
204
- if (key) { try { notePolicySealed(); } catch { /* dấu bền chỉ để phát hiện bị xoá — xem createPolicyGuard */ } }
205
- return clean;
206
- }
207
-
208
- /** Bản có chữ ký đúng chép trong tệp khoá — `null` khi không có / sai chữ ký. */
209
- function signedBackup(keyFile, key) {
210
- const saved = readKeyRecord(keyFile)?.policy;
211
- if (!saved || !key) return null;
212
- const policy = normalize(saved);
213
- return sealMatches(policy, saved.seal, key) ? policy : null;
214
- }
215
-
216
- /**
217
- * Luật trong tệp + có đúng chữ ký không + `base`: bản có chữ ký gần nhất (chép trong tệp khoá) để làm gốc khi tệp không đúng. Chưa từng đặt
218
- * luật (không có tệp lẫn khoá) → mặc định, coi là đúng. Có khoá mà mất tệp luật → bị xoá ngoài lệnh policy: không đúng.
219
- */
220
- export function verifyLocalPolicy(file = REMOTE_POLICY_FILE, { keyFile = REMOTE_POLICY_KEY_FILE } = {}) {
221
- let raw;
222
- try {
223
- raw = JSON.parse(fs.readFileSync(file, 'utf8'));
224
- } catch (e) {
225
- const keyExists = fs.existsSync(keyFile);
226
- // `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).
227
- const pristine = e?.code === 'ENOENT' && !keyExists;
228
- return { policy: normalize(null), trusted: pristine, pristine, base: keyExists ? signedBackup(keyFile, policyKey(keyFile)) : null };
229
- }
230
- const policy = normalize(raw);
231
- const key = policyKey(keyFile);
232
- if (sealMatches(policy, raw?.seal, key)) return { policy, trusted: true, base: null };
233
- return { policy, trusted: false, base: signedBackup(keyFile, key) };
234
- }
235
-
236
- /** Bản chặt hơn của hai luật: xác nhận mức cao hơn, cộng dồn công cụ tắt / lệnh chặn; giờ chờ giữ theo bản đúng. */
237
- export function stricterPolicy(trusted, other) {
238
- return {
239
- confirm: CONFIRM_RANK[other.confirm] > CONFIRM_RANK[trusted.confirm] ? other.confirm : trusted.confirm,
240
- deny_tools: [...new Set([...trusted.deny_tools, ...other.deny_tools])],
241
- blocked_commands: [...new Set([...trusted.blocked_commands, ...other.blocked_commands])],
242
- confirm_timeout_sec: trusted.confirm_timeout_sec,
243
- cast_consent: CAST_CONSENT_RANK[other.cast_consent] > CAST_CONSENT_RANK[trusted.cast_consent] ? other.cast_consent : trusted.cast_consent,
244
- };
245
- }
246
-
247
- /**
248
- * 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;
249
- * 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,
250
- * 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.
251
- *
252
- * 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.
253
- * 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)
254
- * 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ả
255
- * 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.
256
- */
257
- export function createPolicyGuard({
258
- file = REMOTE_POLICY_FILE, keyFile = REMOTE_POLICY_KEY_FILE, onTamper, sealedMarker = { seen: policySealedNoted, note: notePolicySealed },
259
- } = {}) {
260
- const safe = (fn) => { try { return fn?.(); } catch { return undefined; } };
261
- const first = verifyLocalPolicy(file, { keyFile });
262
- let everSigned = (first.trusted && !first.pristine) || !!first.base || !!safe(sealedMarker?.seen);
263
- const noteSigned = () => {
264
- if (everSigned && safe(sealedMarker?.seen)) return;
265
- everSigned = true;
266
- safe(sealedMarker?.note);
267
- };
268
- if (first.trusted && !first.pristine) noteSigned();
269
- let lastTrusted = first.trusted && !(first.pristine && everSigned) ? first.policy : first.base || normalize(null);
270
- let reported = null;
271
- return {
272
- read() {
273
- const verdict = verifyLocalPolicy(file, { keyFile });
274
- const { policy, base } = verdict;
275
- const trusted = verdict.trusted && !(verdict.pristine && everSigned);
276
- if (trusted) {
277
- if (!verdict.pristine && !everSigned) noteSigned();
278
- lastTrusted = policy;
279
- reported = null;
280
- return policy;
281
- }
282
- if (base) lastTrusted = base;
283
- const effective = stricterPolicy(lastTrusted, policy);
284
- const fingerprint = JSON.stringify(policy);
285
- if (reported !== fingerprint) {
286
- reported = fingerprint;
287
- onTamper?.(effective);
288
- }
289
- return effective;
290
- },
291
- };
292
- }
293
-
294
- const commandOf = (toolName, args) => (COMMAND_ARG[toolName] ? String(args?.[COMMAND_ARG[toolName]] ?? '') : '');
295
-
296
- /** Vì sao một lời gọi rủi ro (chuỗi ngắn để hiện cho người dùng) — `null` = không rủi ro. */
297
- export function riskReason(tool, args = {}) {
298
- if (ALWAYS_RISKY_TOOLS.has(tool.name)) return ALWAYS_RISKY_REASON[tool.name];
299
- if (tool.destructive && args.permanent === true) return 'Xoá hẳn, không lấy lại được';
300
- if (autostartTarget(tool.name, args)) return 'Ghi vào chỗ tự chạy (khởi động máy / mở terminal / mở dự án)';
301
- const command = commandOf(tool.name, args);
302
- 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';
303
- return null;
304
- }
305
-
306
- /**
307
- * 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.
308
- * 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
309
- * 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
310
- * (`INTERNAL_WRITE_TOOLS`) xét như `fs.write`.
311
- */
312
- export function evaluateLocalPolicy(policy, tool, args = {}) {
313
- // gui.do is only a compact route into the same GUI actuator. A device owner who disabled the
314
- // lower-level actuator must not get it back merely because a newer CLI advertised the fast path.
315
- const deniedByAlias = tool.name === 'gui.do' && policy.deny_tools.includes('gui.act');
316
- if (policy.deny_tools.includes(tool.name) || deniedByAlias) {
317
- throw new DeviceToolError(DeviceErrorCode.LOCAL_DENIED, `The owner of this computer turned off ${tool.name} here`);
318
- }
319
- const command = commandOf(tool.name, args);
320
- if (command && policy.blocked_commands.some((re) => new RegExp(re, 'i').test(command))) {
321
- throw new DeviceToolError(DeviceErrorCode.LOCAL_DENIED, 'Command blocked by a rule the owner of this computer set');
322
- }
323
- const confirmExempt = tool.read_only || (tool.internal && !INTERNAL_WRITE_TOOLS.has(tool.name));
324
- if (confirmExempt || policy.confirm === ConfirmMode.NEVER) return { action: 'allow' };
325
- 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)' };
326
- const reason = riskReason(tool, args);
327
- return reason ? { action: 'confirm', reason } : { action: 'allow' };
328
- }
329
-
330
- /** Một dòng mô tả lời gọi cho hộp xác nhận (lệnh / người nhận / đường dẫn), cắt gọn. */
331
- export function describeCall(tool, args = {}) {
332
- const cut = (s, n = 500) => (String(s).length > n ? `${String(s).slice(0, n)}…` : String(s));
333
- const command = commandOf(tool.name, args);
334
- if (command) return cut(command);
335
- if (tool.name === 'office.outlook.send') return cut(`Tới: ${args.to || '?'} — ${args.subject || ''}`, 300);
336
- if (tool.name === 'meeting.start') return cut(`${args.title || 'Cuộc họp'}${args.then ? ` — sau đó: ${args.then}` : ''}`, 300);
337
- if (args.path) return cut(args.path, 300);
338
- if (args.destinationPath) return cut(`${args.sourcePath || '?'} → ${args.destinationPath}`, 300);
339
- if (Array.isArray(args.paths)) return cut(args.paths.join(', '), 300);
340
- return tool.name;
341
- }
1
+ import { createHmac, randomBytes, timingSafeEqual } from 'crypto';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { DeviceErrorCode, REMOTE_CONFIG_DIR } from './constants.mjs';
5
+ import { DeviceToolError } from './sandbox.mjs';
6
+ import { openToken, sealToken } from './tokenStore.mjs';
7
+ import { notePolicySealed, policySealedNoted } from './credentials.mjs';
8
+
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
11
+ * quyết định duyệt nằm ở BE — BE / tài khoản admin bị chiếm hoặc agent bị prompt injection là chạy được lệnh trên mọi máy đã ghép (máy
12
+ * toàn quyền còn không hỏi). Tệp `~/.aivin/remote-policy.json` do CHỦ MÁY đặt (`aivin remote policy …`).
13
+ *
14
+ * Chống agent tự nới luật (29/10/2026): thư mục `.aivin` chỉ được che bằng khớp chuỗi với lệnh shell — ghép chuỗi / chạy tệp script là ghi
15
+ * đè được tệp luật. Nên tệp luật mang chữ ký HMAC bằng khoá cất trong kho bí mật của hệ điều hành (tokenStore.mjs), chỉ `aivin remote policy`
16
+ * ký. Daemon (`createPolicyGuard`) chỉ nhận bản có chữ ký đúng; bản không ký / ký sai chỉ được SIẾT thêm so với bản đúng gần nhất, không
17
+ * được nới. Không chống được mã độc cùng tài khoản biết cách gọi DPAPI / Keychain để ký lại — cách ly thật cần tài khoản hệ điều hành riêng
18
+ * (policy-approval.md mục 8 ở repo be).
19
+ *
20
+ * - `deny_tools`: công cụ tắt hẳn trên máy này (không vào danh mục, gọi tới bị từ chối).
21
+ * - `blocked_commands`: regex chặn thêm cho lệnh shell / tiến trình nền / lịch.
22
+ * - `confirm`: việc nào phải có người bấm "Cho phép" NGAY TRÊN MÁY — `risky` (mặc định: lệnh nguy hiểm, xoá hẳn, gửi thư, đặt lịch),
23
+ * `always` (mọi việc có tác dụng), `never` (chỉ luật phía Aivin).
24
+ */
25
+
26
+ export const REMOTE_POLICY_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-policy.json');
27
+
28
+ export const ConfirmMode = Object.freeze({ NEVER: 'never', RISKY: 'risky', ALWAYS: 'always' });
29
+
30
+ /** Ai được xem + điều khiển màn hình: `ask` hỏi người ở máy mỗi phiên (mặc định), `unattended` không cần người ở máy, `off` tắt hẳn. */
31
+ export const CastConsentMode = Object.freeze({ OFF: 'off', ASK: 'ask', UNATTENDED: 'unattended' });
32
+ /** Số lớn hơn là chặt hơn. */
33
+ export const CAST_CONSENT_RANK = Object.freeze({ [CastConsentMode.UNATTENDED]: 0, [CastConsentMode.ASK]: 1, [CastConsentMode.OFF]: 2 });
34
+
35
+ export const DEFAULT_LOCAL_POLICY = Object.freeze({ confirm: ConfirmMode.RISKY, deny_tools: [], blocked_commands: [], confirm_timeout_sec: 120, cast_consent: CastConsentMode.ASK });
36
+
37
+ /** Mức chặt của chế độ xác nhận — số lớn hơn là chặt hơn. */
38
+ export const CONFIRM_RANK = Object.freeze({ [ConfirmMode.NEVER]: 0, [ConfirmMode.RISKY]: 1, [ConfirmMode.ALWAYS]: 2 });
39
+
40
+ /** Khoá ký tệp luật (bản mã của kho bí mật hệ điều hành, như token máy). */
41
+ export const REMOTE_POLICY_KEY_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-policy.key.json');
42
+ const POLICY_KEY_ACCOUNT = 'remote-policy-key';
43
+
44
+ /**
45
+ * 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 —
46
+ * xét cùng mẫu lệnh rủi ro / luật chặn của chủ máy.
47
+ */
48
+ const COMMAND_ARG = Object.freeze({
49
+ 'shell.exec': 'command', 'proc.start': 'command', 'proc.write': 'text', 'sys.schedule': 'command',
50
+ 'gui.act': 'text', 'gui.do': 'value',
51
+ });
52
+
53
+ /** 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). */
54
+ // 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).
55
+ // lightcode.install: cài phần mềm mới lên máy (20/11/2026) — người ở máy phải tự bấm đồng ý.
56
+ // lightcode.deploy: phát hành sản phẩm lên môi trường qua LightCode (20/11/2026) — luôn cần người ở máy xác nhận.
57
+ const ALWAYS_RISKY_TOOLS = new Set(['office.outlook.send', 'sys.schedule', 'meeting.start', 'lightcode.install', 'lightcode.deploy']);
58
+ const ALWAYS_RISKY_REASON = {
59
+ 'office.outlook.send': 'Gửi thư thay bạn',
60
+ 'sys.schedule': 'Đặt việc chạy định kỳ trên máy',
61
+ 'meeting.start': 'Ghi âm cuộc họp (micro + âm thanh máy) và chụp màn hình',
62
+ 'lightcode.install': 'Cài ứng dụng LightCode (lightcode.live) để thực thi việc lập trình Aivin giao',
63
+ 'lightcode.deploy': 'Phát hành sản phẩm lên môi trường qua quy trình LightCode',
64
+ };
65
+
66
+ /**
67
+ * 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
68
+ * công cụ nội bộ khác (đọc khúc tệp, ghi nhớ, báo…) (02/11/2026).
69
+ */
70
+ const INTERNAL_WRITE_TOOLS = new Set(['fs.download']);
71
+
72
+ /** Công cụ ghi tệp → tham số chứa đường ĐÍCH (`fs.move_many`: `moves[].to`). */
73
+ const WRITE_TARGET_ARGS = Object.freeze({
74
+ 'fs.write': 'path', 'fs.edit': 'path', 'fs.download': 'path', 'fs.copy': 'destinationPath', 'fs.move': 'destinationPath',
75
+ });
76
+
77
+ /**
78
+ * 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`
79
+ * 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.
80
+ */
81
+ const AUTOSTART_PATH_PATTERNS = [
82
+ /\/start menu\/programs\/startup(\/|$)/, // Windows: thư mục Startup (người dùng / mọi người dùng)
83
+ /\/(windows)?powershell\/([^/]*_)?profile\.ps1$/, // hồ sơ PowerShell (chạy mỗi lần mở PowerShell)
84
+ /\/\.(bashrc|bash_profile|bash_login|profile|zshrc|zshenv|zprofile|zlogin|login|cshrc|tcshrc|xprofile|xinitrc)$/,
85
+ /\/\.config\/fish\/config\.fish$/,
86
+ /\/library\/(launchagents|launchdaemons)(\/|$)/, // macOS
87
+ /\/\.config\/(autostart|systemd\/user)(\/|$)/, // Linux desktop / systemd người dùng
88
+ /\/\.git\/hooks(\/|$)/, // chạy ở lần git commit / checkout kế tiếp
89
+ /\/\.vscode\/tasks\.json$/, // VS Code: task "runOn: folderOpen" chạy khi mở thư mục
90
+ ];
91
+
92
+ /** Đường đích (trong tham số) rơi vào chỗ tự chạy — trả đường đó, không thì null. */
93
+ export function autostartTarget(toolName, args = {}) {
94
+ const key = WRITE_TARGET_ARGS[toolName];
95
+ const targets = key ? [args?.[key]] : toolName === 'fs.move_many' && Array.isArray(args?.moves) ? args.moves.map((m) => m?.to) : [];
96
+ return targets.find((t) => {
97
+ if (typeof t !== 'string' || !t.trim()) return false;
98
+ const p = `/${t.trim().replace(/\\/g, '/').toLowerCase()}`;
99
+ return AUTOSTART_PATH_PATTERNS.some((re) => re.test(p));
100
+ }) || null;
101
+ }
102
+
103
+ /**
104
+ * 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
105
+ * (`-EncodedCommand`, `iex`, `| sh`) cũng nằm trong danh sách.
106
+ */
107
+ const RISKY_COMMAND_PATTERNS = [
108
+ // Xoá đệ quy / xoá hẳn
109
+ /\brm\s+-[a-z]*r/i, /remove-item\b[^|;]*-recurse/i, /\b(rd|rmdir)\s+\/s/i, /\bdel\s+(\/[a-z]\s+)*\/s/i, /\bshred\b/i,
110
+ // Registry, dịch vụ, khởi động, tường lửa, chính sách hệ thống
111
+ /\breg(\.exe)?\s+(add|delete|import)\b/i, /(set|new|remove)-itemproperty\b[^|;]*\bhk(lm|cu)/i,
112
+ /\bsc(\.exe)?\s+(config|delete|create|stop)\b/i, /\b(stop|set|new)-service\b/i, /\bsystemctl\s+(disable|stop|mask)\b/i,
113
+ /\bbcdedit\b/i, /\bnetsh\b/i, /\bschtasks\b/i, /\bcrontab\s+-r\b/i, /\b(shutdown|restart-computer|stop-computer)\b/i, /\breboot\b/i,
114
+ // Tắt bảo vệ / đổi quyền hàng loạt / nâng quyền
115
+ /\b(set|add)-mppreference\b/i, /\bdisable-?(windows)?defender/i, /\btakeown\b/i, /\bicacls\b[^|;]*\/grant/i,
116
+ /\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,
117
+ // Kho mật khẩu / khoá đăng nhập
118
+ /\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,
119
+ // 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
120
+ /\.upload(file|string|data|values)(async)?\s*\(/i, /(^|[\s"'=(])\\\\(?!localhost\\|127\.0\.0\.1\\|\?\\|\.\\)[\w.-]+\\/, /\bnet\s+use\b/i,
121
+ // Tải về rồi chạy / chạy chuỗi mã hoá
122
+ /\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,
123
+ /\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,
124
+ // Đẩy đè lịch sử git
125
+ /\bgit\s+push\b[^|;]*(--force\b|\s-f\b)/i,
126
+ ];
127
+
128
+ function normalize(raw) {
129
+ const p = raw && typeof raw === 'object' ? raw : {};
130
+ const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()) : []);
131
+ const confirm = Object.values(ConfirmMode).includes(p.confirm) ? p.confirm : DEFAULT_LOCAL_POLICY.confirm;
132
+ const timeout = Number(p.confirm_timeout_sec);
133
+ return {
134
+ confirm,
135
+ deny_tools: list(p.deny_tools),
136
+ blocked_commands: list(p.blocked_commands).filter((re) => { try { new RegExp(re, 'i'); return true; } catch { return false; } }),
137
+ confirm_timeout_sec: Number.isFinite(timeout) && timeout >= 15 && timeout <= 900 ? Math.round(timeout) : DEFAULT_LOCAL_POLICY.confirm_timeout_sec,
138
+ cast_consent: Object.hasOwn(CAST_CONSENT_RANK, String(p.cast_consent)) ? p.cast_consent : DEFAULT_LOCAL_POLICY.cast_consent,
139
+ };
140
+ }
141
+
142
+ /** Đọc luật trong tệp (không có tệp → mặc định), KHÔNG xét chữ ký — để hiện cho chủ máy. Daemon đọc qua `createPolicyGuard`. */
143
+ export function loadLocalPolicy(file = REMOTE_POLICY_FILE) {
144
+ try {
145
+ return normalize(JSON.parse(fs.readFileSync(file, 'utf8')));
146
+ } catch {
147
+ return normalize(null);
148
+ }
149
+ }
150
+
151
+ /** Khoá đã giải theo bản mã trong tệp khoá — giải DPAPI tốn một tiến trình con, daemon đọc luật ở mỗi lời gọi. */
152
+ const keyCache = new Map();
153
+
154
+ function readKeyRecord(keyFile) {
155
+ try { return JSON.parse(fs.readFileSync(keyFile, 'utf8')); } catch { return null; }
156
+ }
157
+
158
+ function writeKeyRecord(keyFile, record) {
159
+ fs.mkdirSync(path.dirname(keyFile), { recursive: true });
160
+ fs.writeFileSync(keyFile, JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
161
+ }
162
+
163
+ /** Khoá ký luật; `create` → chưa có thì sinh + cất vào kho bí mật. `null` khi không có / không giải được. */
164
+ function policyKey(keyFile, { create = false } = {}) {
165
+ const record = readKeyRecord(keyFile);
166
+ const fingerprint = record ? `${record.token_store || ''}:${record.token_enc || record.device_token || ''}` : null;
167
+ if (fingerprint && keyCache.get(keyFile)?.fingerprint === fingerprint) return keyCache.get(keyFile).key;
168
+ let key = record ? openToken(record) : null;
169
+ let fp = fingerprint;
170
+ if (!key && create) {
171
+ key = randomBytes(32).toString('hex');
172
+ const { fallback_reason: _why, ...sealed } = sealToken(key, { account: POLICY_KEY_ACCOUNT });
173
+ writeKeyRecord(keyFile, { device_id: POLICY_KEY_ACCOUNT, ...sealed });
174
+ fp = `${sealed.token_store || ''}:${sealed.token_enc || sealed.device_token || ''}`;
175
+ }
176
+ if (key) keyCache.set(keyFile, { fingerprint: fp, key });
177
+ return key;
178
+ }
179
+
180
+ /** Giá trị mặc định của trường mới không vào chữ ký: tệp luật đã ký từ bản CLI trước vẫn khớp. */
181
+ function signedForm(clean) {
182
+ const { cast_consent: consent, ...rest } = normalize(clean);
183
+ return consent === DEFAULT_LOCAL_POLICY.cast_consent ? rest : { ...rest, cast_consent: consent };
184
+ }
185
+
186
+ const signPolicy = (clean, key) => createHmac('sha256', key).update(JSON.stringify(signedForm(clean))).digest('hex');
187
+
188
+ function sealMatches(clean, seal, key) {
189
+ if (typeof seal !== 'string' || !key) return false;
190
+ const expected = Buffer.from(signPolicy(clean, key), 'hex');
191
+ const actual = Buffer.from(seal, 'hex');
192
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
193
+ }
194
+
195
+ /**
196
+ * Lưu luật + ký (chỉ `aivin remote policy` gọi). Bản có chữ ký được chép thêm vào tệp khoá (`policy`): tệp luật bị ghi đè trước khi daemon kịp
197
+ * đọc bản đúng (hoặc daemon khởi động lại sau đó) thì vẫn có bản đúng làm gốc — chạy thật 29/10/2026: chỉ nhớ trong RAM là agent bật lại
198
+ * được công cụ chủ máy vừa tắt.
199
+ */
200
+ export function saveLocalPolicy(policy, file = REMOTE_POLICY_FILE, { keyFile = REMOTE_POLICY_KEY_FILE } = {}) {
201
+ const clean = normalize(policy);
202
+ const key = policyKey(keyFile, { create: true });
203
+ const signed = { ...clean, ...(key ? { seal: signPolicy(clean, key) } : {}) };
204
+ fs.mkdirSync(path.dirname(file), { recursive: true });
205
+ fs.writeFileSync(file, JSON.stringify(signed, null, 2) + '\n', { mode: 0o600 });
206
+ const record = key ? readKeyRecord(keyFile) : null;
207
+ if (record) writeKeyRecord(keyFile, { ...record, policy: signed });
208
+ if (key) { try { notePolicySealed(); } catch { /* dấu bền chỉ để phát hiện bị xoá — xem createPolicyGuard */ } }
209
+ return clean;
210
+ }
211
+
212
+ /** Bản có chữ ký đúng chép trong tệp khoá — `null` khi không có / sai chữ ký. */
213
+ function signedBackup(keyFile, key) {
214
+ const saved = readKeyRecord(keyFile)?.policy;
215
+ if (!saved || !key) return null;
216
+ const policy = normalize(saved);
217
+ return sealMatches(policy, saved.seal, key) ? policy : null;
218
+ }
219
+
220
+ /**
221
+ * Luật trong tệp + có đúng chữ ký không + `base`: bản có chữ ký gần nhất (chép trong tệp khoá) để làm gốc khi tệp không đúng. Chưa từng đặt
222
+ * luật (không có tệp lẫn khoá) → mặc định, coi là đúng. Có khoá mà mất tệp luật → bị xoá ngoài lệnh policy: không đúng.
223
+ */
224
+ export function verifyLocalPolicy(file = REMOTE_POLICY_FILE, { keyFile = REMOTE_POLICY_KEY_FILE } = {}) {
225
+ let raw;
226
+ try {
227
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
228
+ } catch (e) {
229
+ const keyExists = fs.existsSync(keyFile);
230
+ // `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).
231
+ const pristine = e?.code === 'ENOENT' && !keyExists;
232
+ return { policy: normalize(null), trusted: pristine, pristine, base: keyExists ? signedBackup(keyFile, policyKey(keyFile)) : null };
233
+ }
234
+ const policy = normalize(raw);
235
+ const key = policyKey(keyFile);
236
+ if (sealMatches(policy, raw?.seal, key)) return { policy, trusted: true, base: null };
237
+ return { policy, trusted: false, base: signedBackup(keyFile, key) };
238
+ }
239
+
240
+ /** Bản chặt hơn của hai luật: xác nhận mức cao hơn, cộng dồn công cụ tắt / lệnh chặn; giờ chờ giữ theo bản đúng. */
241
+ export function stricterPolicy(trusted, other) {
242
+ return {
243
+ confirm: CONFIRM_RANK[other.confirm] > CONFIRM_RANK[trusted.confirm] ? other.confirm : trusted.confirm,
244
+ deny_tools: [...new Set([...trusted.deny_tools, ...other.deny_tools])],
245
+ blocked_commands: [...new Set([...trusted.blocked_commands, ...other.blocked_commands])],
246
+ confirm_timeout_sec: trusted.confirm_timeout_sec,
247
+ cast_consent: CAST_CONSENT_RANK[other.cast_consent] > CAST_CONSENT_RANK[trusted.cast_consent] ? other.cast_consent : trusted.cast_consent,
248
+ };
249
+ }
250
+
251
+ /**
252
+ * 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;
253
+ * 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,
254
+ * 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.
255
+ *
256
+ * 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.
257
+ * 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)
258
+ * 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ả
259
+ * 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.
260
+ */
261
+ export function createPolicyGuard({
262
+ file = REMOTE_POLICY_FILE, keyFile = REMOTE_POLICY_KEY_FILE, onTamper, sealedMarker = { seen: policySealedNoted, note: notePolicySealed },
263
+ } = {}) {
264
+ const safe = (fn) => { try { return fn?.(); } catch { return undefined; } };
265
+ const first = verifyLocalPolicy(file, { keyFile });
266
+ let everSigned = (first.trusted && !first.pristine) || !!first.base || !!safe(sealedMarker?.seen);
267
+ const noteSigned = () => {
268
+ if (everSigned && safe(sealedMarker?.seen)) return;
269
+ everSigned = true;
270
+ safe(sealedMarker?.note);
271
+ };
272
+ if (first.trusted && !first.pristine) noteSigned();
273
+ let lastTrusted = first.trusted && !(first.pristine && everSigned) ? first.policy : first.base || normalize(null);
274
+ let reported = null;
275
+ return {
276
+ read() {
277
+ const verdict = verifyLocalPolicy(file, { keyFile });
278
+ const { policy, base } = verdict;
279
+ const trusted = verdict.trusted && !(verdict.pristine && everSigned);
280
+ if (trusted) {
281
+ if (!verdict.pristine && !everSigned) noteSigned();
282
+ lastTrusted = policy;
283
+ reported = null;
284
+ return policy;
285
+ }
286
+ if (base) lastTrusted = base;
287
+ const effective = stricterPolicy(lastTrusted, policy);
288
+ const fingerprint = JSON.stringify(policy);
289
+ if (reported !== fingerprint) {
290
+ reported = fingerprint;
291
+ onTamper?.(effective);
292
+ }
293
+ return effective;
294
+ },
295
+ };
296
+ }
297
+
298
+ const commandOf = (toolName, args) => (COMMAND_ARG[toolName] ? String(args?.[COMMAND_ARG[toolName]] ?? '') : '');
299
+
300
+ /** Vì sao một lời gọi rủi ro (chuỗi ngắn để hiện cho người dùng) — `null` = không rủi ro. */
301
+ export function riskReason(tool, args = {}) {
302
+ if (ALWAYS_RISKY_TOOLS.has(tool.name)) return ALWAYS_RISKY_REASON[tool.name];
303
+ if (tool.destructive && args.permanent === true) return 'Xoá hẳn, không lấy lại được';
304
+ if (autostartTarget(tool.name, args)) return 'Ghi vào chỗ tự chạy (khởi động máy / mở terminal / mở dự án)';
305
+ const command = commandOf(tool.name, args);
306
+ 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';
307
+ return null;
308
+ }
309
+
310
+ /**
311
+ * 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.
312
+ * 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
313
+ * 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
314
+ * (`INTERNAL_WRITE_TOOLS`) xét như `fs.write`.
315
+ */
316
+ export function evaluateLocalPolicy(policy, tool, args = {}) {
317
+ // gui.do is only a compact route into the same GUI actuator. A device owner who disabled the
318
+ // lower-level actuator must not get it back merely because a newer CLI advertised the fast path.
319
+ const deniedByAlias = tool.name === 'gui.do' && policy.deny_tools.includes('gui.act');
320
+ if (policy.deny_tools.includes(tool.name) || deniedByAlias) {
321
+ throw new DeviceToolError(DeviceErrorCode.LOCAL_DENIED, `The owner of this computer turned off ${tool.name} here`);
322
+ }
323
+ const command = commandOf(tool.name, args);
324
+ if (command && policy.blocked_commands.some((re) => new RegExp(re, 'i').test(command))) {
325
+ throw new DeviceToolError(DeviceErrorCode.LOCAL_DENIED, 'Command blocked by a rule the owner of this computer set');
326
+ }
327
+ const confirmExempt = tool.read_only || (tool.internal && !INTERNAL_WRITE_TOOLS.has(tool.name));
328
+ if (confirmExempt || policy.confirm === ConfirmMode.NEVER) return { action: 'allow' };
329
+ 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)' };
330
+ const reason = riskReason(tool, args);
331
+ return reason ? { action: 'confirm', reason } : { action: 'allow' };
332
+ }
333
+
334
+ /** Một dòng mô tả lời gọi cho hộp xác nhận (lệnh / người nhận / đường dẫn), cắt gọn. */
335
+ export function describeCall(tool, args = {}) {
336
+ const cut = (s, n = 500) => (String(s).length > n ? `${String(s).slice(0, n)}…` : String(s));
337
+ const command = commandOf(tool.name, args);
338
+ if (command) return cut(command);
339
+ if (tool.name === 'office.outlook.send') return cut(`Tới: ${args.to || '?'} — ${args.subject || ''}`, 300);
340
+ if (tool.name === 'meeting.start') return cut(`${args.title || 'Cuộc họp'}${args.then ? ` — sau đó: ${args.then}` : ''}`, 300);
341
+ if (args.path) return cut(args.path, 300);
342
+ if (args.destinationPath) return cut(`${args.sourcePath || '?'} → ${args.destinationPath}`, 300);
343
+ if (Array.isArray(args.paths)) return cut(args.paths.join(', '), 300);
344
+ return tool.name;
345
+ }