@aivin-labs/cli 1.0.51 → 1.0.60

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.
Files changed (32) hide show
  1. package/bin/cli.mjs +2215 -2211
  2. package/bin/lib/auth.mjs +119 -88
  3. package/bin/lib/context.mjs +58 -5
  4. package/bin/lib/loginHandoff.mjs +87 -0
  5. package/bin/lib/openFile.mjs +29 -4
  6. package/bin/lib/remote/agentContract.mjs +370 -0
  7. package/bin/lib/remote/agentEvidence.mjs +409 -0
  8. package/bin/lib/remote/autoStart.mjs +640 -623
  9. package/bin/lib/remote/client.mjs +55 -17
  10. package/bin/lib/remote/codingAgents.mjs +594 -293
  11. package/bin/lib/remote/constants.mjs +1 -1
  12. package/bin/lib/remote/credentials.mjs +131 -125
  13. package/bin/lib/remote/desktop/castAuth.mjs +44 -19
  14. package/bin/lib/remote/desktop/castConsent.mjs +79 -14
  15. package/bin/lib/remote/desktop/castInput.mjs +3 -0
  16. package/bin/lib/remote/desktop/castTrust.mjs +221 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
  21. package/bin/lib/remote/desktop/strings.mjs +26 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
  23. package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
  24. package/bin/lib/remote/dpapiHelper.mjs +91 -0
  25. package/bin/lib/remote/gui/index.mjs +422 -68
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
  27. package/bin/lib/remote/humanInput.mjs +7 -0
  28. package/bin/lib/remote/localConfirm.mjs +2 -2
  29. package/bin/lib/remote/tokenStore.mjs +19 -2
  30. package/bin/lib/remote/toolHandlers.mjs +861 -859
  31. package/docs/CLI.md +1606 -1602
  32. package/package.json +1 -1
@@ -0,0 +1,221 @@
1
+ import { createHash, createHmac, createPublicKey, randomBytes, timingSafeEqual, verify } from 'crypto';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { writeFileAtomic } from '../atomicFile.mjs';
5
+ import { CastState, REMOTE_CONFIG_DIR } from '../constants.mjs';
6
+ import { openToken, sealToken } from '../tokenStore.mjs';
7
+
8
+ /**
9
+ * Thiết bị người ở máy đã bấm "Luôn cho phép" (09/11/2026): lần sau vào xem không phải hỏi lại.
10
+ *
11
+ * Trình duyệt giữ khoá riêng không xuất ra được, máy chỉ lưu khoá công khai và mỗi lần vào bắt ký một chuỗi ngẫu nhiên do chính máy sinh —
12
+ * máy chủ chuyển tin nhưng không tự chứng minh thay được, nghe lén một lần cũng không dùng lại được. Danh sách có chữ ký bằng khoá cất trong
13
+ * kho bí mật của hệ điều hành: AI hay script trên máy ghi thêm vào tệp thì chữ ký sai, cả danh sách coi như rỗng (lại hỏi người ở máy).
14
+ * Giới hạn như `humanInput.mjs`: mã độc cùng tài khoản hệ điều hành gọi được kho bí mật thì vẫn lách được.
15
+ */
16
+ export const CAST_TRUST_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-trusted-devices.json');
17
+ export const CAST_TRUST_KEY_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-trusted-devices.key');
18
+ /** Không dùng quá ngần này thì thiết bị hết được tin. */
19
+ export const CAST_TRUST_TTL_MS = 30 * 86_400_000;
20
+
21
+ const MAX_DEVICES = 20;
22
+ const KEY_ACCOUNT = 'cast-trusted-devices';
23
+ const PROOF_PREFIX = 'aivin-cast-device-proof';
24
+ const MAX_KEY_CHARS = 300;
25
+ const MAX_NAME_CHARS = 60;
26
+ const PROOF_TIMEOUT_MS = 8000;
27
+
28
+ /** Khoá công khai P-256 (SPKI, base64) hợp lệ → đối tượng khoá; khác đi → `null`. */
29
+ function parseDeviceKey(deviceKey) {
30
+ if (typeof deviceKey !== 'string' || !deviceKey || deviceKey.length > MAX_KEY_CHARS) return null;
31
+ try {
32
+ const key = createPublicKey({ key: Buffer.from(deviceKey, 'base64'), format: 'der', type: 'spki' });
33
+ return key.asymmetricKeyType === 'ec' && key.asymmetricKeyDetails?.namedCurve === 'prime256v1' ? key : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /** Tên do trình duyệt tự khai, chỉ để hiện: bỏ ký tự lạ để khay đọc tệp không vỡ. */
40
+ const safeName = (name) => String(name ?? '').replace(/[^\p{L}\p{N} ._·-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, MAX_NAME_CHARS) || 'Thiết bị';
41
+
42
+ /** Nơi / IP / tài khoản máy chủ gửi kèm, chỉ để hiện: lọc như tên (khay đọc tệp bằng regex, không được có `"` hay `\`). */
43
+ const safePlace = (text) => String(text ?? '').replace(/[^\p{L}\p{N} .,'’&-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 80);
44
+ export const safeViewerIp = (ip) => (typeof ip === 'string' && /^[0-9A-Fa-f:.]{2,45}$/.test(ip) ? ip : '');
45
+ export const safeViewerAccount = (account) => (typeof account === 'string' ? account.replace(/[^A-Za-z0-9._@•+-]/g, '').slice(0, 80) : '');
46
+
47
+ /**
48
+ * Vị trí gần đúng theo IP (BE tra từ Cloudflare / bộ dữ liệu quốc gia), ví dụ `{ city: 'Hanoi', country: 'VN' }` → "Hanoi, Việt Nam".
49
+ * Chỉ để chủ máy nhận ra thiết bị lạ; không bao giờ dùng để quyết định cho vào.
50
+ */
51
+ export function castViewerPlace(location, lang = 'vi') {
52
+ if (!location || typeof location !== 'object') return '';
53
+ const local = safePlace(location.city) || safePlace(location.region);
54
+ const code = String(location.country || '').toUpperCase();
55
+ let country = '';
56
+ if (/^[A-Z]{2}$/.test(code)) {
57
+ try { country = new Intl.DisplayNames([lang, 'en'], { type: 'region' }).of(code) || code; } catch { country = code; }
58
+ }
59
+ return safePlace([local, country].filter(Boolean).join(', '));
60
+ }
61
+
62
+ /** Thông tin người xem để hiện cho chủ máy, đã lọc: `{ place, ip, account }` (trường rỗng = không biết). */
63
+ export function castViewerInfo(payload, lang = 'vi') {
64
+ return {
65
+ place: castViewerPlace(payload?.viewer_location, lang),
66
+ ip: safeViewerIp(payload?.viewer_ip),
67
+ account: safeViewerAccount(payload?.viewer_account),
68
+ };
69
+ }
70
+
71
+ /** Thông tin người xem chỉ lưu khi có giá trị — bản ghi cũ / máy chủ đời cũ không có thì giữ nguyên trường cũ. */
72
+ const infoFields = ({ place, ip, account } = {}) => ({
73
+ ...(safePlace(place) ? { place: safePlace(place) } : {}),
74
+ ...(safeViewerIp(ip) ? { ip: safeViewerIp(ip) } : {}),
75
+ ...(safeViewerAccount(account) ? { account: safeViewerAccount(account) } : {}),
76
+ });
77
+
78
+ const VIEWER_CODE_CHARS = 6;
79
+ /** Chừa chỗ cho " - <mã>" để cắt theo `MAX_NAME_CHARS` khi lưu không làm mất mã. */
80
+ const VIEWER_NAME_CHARS = MAX_NAME_CHARS - VIEWER_CODE_CHARS - 3;
81
+
82
+ /**
83
+ * Tên hiện cho chủ máy: FE khai loại máy + model (chỉ Android có) + trình duyệt, vẫn có thể trùng giữa hai máy nên ghép thêm mã suy ra từ khoá
84
+ * của thiết bị, ví dụ "Android SM-S918B · Chrome - 7F3A9C".
85
+ * Trình duyệt không có khoá (ẩn danh, chặn IndexedDB) thì lấy `viewerKey`: vẫn phân biệt được nhưng đổi mạng là đổi mã.
86
+ * Chỉ để hiện: danh tính thật vẫn là khoá, và loại máy gốc vẫn dùng riêng cho `isTouchViewerDevice` (so khớp đúng chuỗi).
87
+ */
88
+ export function castViewerLabel(viewerDevice, deviceKey, viewerKey) {
89
+ const identity = deviceKey || viewerKey;
90
+ if (!identity) return viewerDevice;
91
+ const code = createHash('sha256').update(String(identity)).digest('hex').slice(0, VIEWER_CODE_CHARS).toUpperCase();
92
+ return `${safeName(viewerDevice).slice(0, VIEWER_NAME_CHARS).trim()} - ${code}`;
93
+ }
94
+
95
+ /** `signature`: base64 của chữ ký ECDSA dạng WebCrypto (r || s) trên `aivin-cast-device-proof\n<mã phiên>\n<chuỗi ngẫu nhiên>`. */
96
+ export function verifyDeviceProof({ deviceKey, sessionId, nonce, signature }) {
97
+ const key = parseDeviceKey(deviceKey);
98
+ if (!key || typeof signature !== 'string' || !signature) return false;
99
+ try {
100
+ return verify('sha256', Buffer.from(`${PROOF_PREFIX}\n${sessionId}\n${nonce}`), { key, dsaEncoding: 'ieee-p1363' }, Buffer.from(signature, 'base64'));
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ export function createCastTrust({ file = CAST_TRUST_FILE, keyFile = CAST_TRUST_KEY_FILE, now = Date.now } = {}) {
107
+ /** Giải kho bí mật tốn một tiến trình con: nhớ theo bản mã trong tệp khoá. */
108
+ let cached = null;
109
+
110
+ function secret({ create = false } = {}) {
111
+ let record = null;
112
+ try { record = JSON.parse(fs.readFileSync(keyFile, 'utf8')); } catch { /* chưa có */ }
113
+ const fingerprint = record ? `${record.token_store || ''}:${record.token_enc || record.device_token || ''}` : null;
114
+ if (fingerprint && cached?.fingerprint === fingerprint) return cached.key;
115
+ let key = record ? openToken(record) : null;
116
+ if (!key && create) {
117
+ key = randomBytes(32).toString('hex');
118
+ const { fallback_reason: _why, ...sealed } = sealToken(key, { account: KEY_ACCOUNT });
119
+ writeFileAtomic(keyFile, `${JSON.stringify({ device_id: KEY_ACCOUNT, ...sealed }, null, 2)}\n`);
120
+ cached = { fingerprint: `${sealed.token_store || ''}:${sealed.token_enc || sealed.device_token || ''}`, key };
121
+ return key;
122
+ }
123
+ if (key) cached = { fingerprint, key };
124
+ return key;
125
+ }
126
+
127
+ const sign = (devices, key) => createHmac('sha256', key).update(JSON.stringify(devices)).digest('hex');
128
+
129
+ function sealMatches(devices, seal, key) {
130
+ if (typeof seal !== 'string' || !key) return false;
131
+ const expected = Buffer.from(sign(devices, key), 'hex');
132
+ const actual = Buffer.from(seal, 'hex');
133
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
134
+ }
135
+
136
+ /** Thiết bị còn hạn trong danh sách đúng chữ ký; sai chữ ký / hỏng tệp → rỗng (lại hỏi người ở máy, không bao giờ tự cho vào). */
137
+ function list() {
138
+ let raw;
139
+ try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return []; }
140
+ const devices = Array.isArray(raw?.devices) ? raw.devices : [];
141
+ if (!devices.length || !sealMatches(devices, raw.seal, secret())) return [];
142
+ return devices.filter((d) => d?.expires_at >= now());
143
+ }
144
+
145
+ function save(devices) {
146
+ const key = secret({ create: devices.length > 0 });
147
+ writeFileAtomic(file, `${JSON.stringify({ devices, ...(key ? { seal: sign(devices, key) } : {}) }, null, 2)}\n`);
148
+ }
149
+
150
+ return {
151
+ list,
152
+ /** Khoá này đủ điều kiện để lưu (trình duyệt cũ / khoá hỏng thì hộp hỏi không hiện nút "Luôn cho phép"). */
153
+ accepts: (deviceKey) => parseDeviceKey(deviceKey) !== null,
154
+ has: (deviceKey) => list().some((d) => d.key === deviceKey),
155
+ /** `info`: `{ place, ip, account }` lúc bấm "Luôn cho phép" — khay hiện để chủ máy nhận ra thiết bị (và tài khoản bị lộ nếu thấy lạ). */
156
+ add({ key, name, info }) {
157
+ if (!parseDeviceKey(key)) return false;
158
+ const t = now();
159
+ const others = list().filter((d) => d.key !== key).sort((a, b) => b.last_used_at - a.last_used_at).slice(0, MAX_DEVICES - 1);
160
+ save([{ key, name: safeName(name), ...infoFields(info), added_at: new Date(t).toISOString(), last_used_at: t, expires_at: t + CAST_TRUST_TTL_MS }, ...others]);
161
+ return true;
162
+ },
163
+ /** Vừa vào bằng quyền tin: tính lại hạn từ lần dùng này, ghi lại nơi / IP lần dùng này. */
164
+ touch(key, info) {
165
+ const t = now();
166
+ const devices = list();
167
+ if (devices.some((d) => d.key === key)) save(devices.map((d) => (d.key === key ? { ...d, ...infoFields(info), last_used_at: t, expires_at: t + CAST_TRUST_TTL_MS } : d)));
168
+ },
169
+ remove(key) {
170
+ const devices = list();
171
+ const kept = devices.filter((d) => d.key !== key);
172
+ if (kept.length !== devices.length) save(kept);
173
+ },
174
+ removeAll: () => save([]),
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Bắt thiết bị chứng minh có khoá riêng: gửi chuỗi ngẫu nhiên, chờ chữ ký quay lại. `prove` trả `true` / `false` (sai, quá giờ),
180
+ * `null` khi người xem đã rời trong lúc chờ.
181
+ */
182
+ export function createDeviceProver({ send, timeoutMs = PROOF_TIMEOUT_MS }) {
183
+ const pending = new Map();
184
+
185
+ const settle = (viewerId, result) => {
186
+ const open = pending.get(viewerId);
187
+ if (!open) return;
188
+ pending.delete(viewerId);
189
+ clearTimeout(open.timer);
190
+ open.resolve(result);
191
+ };
192
+
193
+ return {
194
+ prove({ sessionId, viewerId, deviceKey }) {
195
+ const viewer = String(viewerId);
196
+ settle(viewer, null);
197
+ const nonce = randomBytes(32).toString('base64');
198
+ return new Promise((resolve) => {
199
+ const timer = setTimeout(() => settle(viewer, false), timeoutMs);
200
+ timer.unref?.();
201
+ pending.set(viewer, { sessionId, deviceKey, nonce, resolve, timer });
202
+ try {
203
+ send({ session_id: sessionId, viewer_id: viewer, state: CastState.DEVICE_CHALLENGE, nonce });
204
+ } catch {
205
+ settle(viewer, false);
206
+ }
207
+ });
208
+ },
209
+ /** Chữ ký người xem gửi về (tin `device_proof` trên đường tín hiệu; `sdp` mang chữ ký). */
210
+ answer({ viewer_id: viewerId, session_id: sessionId, sdp: signature }) {
211
+ const viewer = String(viewerId);
212
+ const open = pending.get(viewer);
213
+ if (!open || open.sessionId !== sessionId) return;
214
+ settle(viewer, verifyDeviceProof({ deviceKey: open.deviceKey, sessionId, nonce: open.nonce, signature }));
215
+ },
216
+ /** Không truyền `viewerId` = huỷ tất cả. */
217
+ cancel(viewerId) {
218
+ for (const viewer of viewerId === undefined ? [...pending.keys()] : [String(viewerId)]) settle(viewer, null);
219
+ },
220
+ };
221
+ }