@aivin-labs/cli 1.0.46 → 1.0.47

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/bin/cli.mjs CHANGED
@@ -7,7 +7,8 @@ import path from 'path';
7
7
  import inquirer from 'inquirer';
8
8
  import { spawn } from 'child_process';
9
9
  import axios from 'axios';
10
- import dotenv from 'dotenv';
10
+ import { loadProjectEnv } from './lib/projectEnv.mjs';
11
+ import { requestCastStop } from './lib/remote/desktop/castAuth.mjs';
11
12
  import { fileURLToPath, pathToFileURL } from 'url';
12
13
  import { dirname } from 'path';
13
14
  import { createRequire } from 'module';
@@ -131,9 +132,8 @@ import {
131
132
  // didn't set them. `dotenv.config()` never overrides a variable that's already set, so a project's
132
133
  // own `.env` (or a real shell env var) always wins over the global context, exactly like before -
133
134
  // but nothing requires a project to have a `.env` at all anymore for the common single-context case.
134
- // `quiet: true` - otherwise dotenv prints an "injected env" tip line to stdout on every run, which
135
- // would corrupt `--json-output` mode (meant for clean, parseable JSON on stdout).
136
- dotenv.config({ quiet: true });
135
+ // Chỉ các lệnh làm việc trên dự án plugin mới đọc `.env` (xem projectEnv.mjs).
136
+ loadProjectEnv();
137
137
 
138
138
  {
139
139
  const selectedServer = process.env.AIVIN_BASE_URL
@@ -1447,6 +1447,17 @@ remoteCommand
1447
1447
  console.log(chalk.yellow('⏸ Đã tạm dừng — máy này từ chối mọi việc từ xa.'));
1448
1448
  });
1449
1449
 
1450
+ remoteCommand
1451
+ .command('disconnect')
1452
+ .description('Cut off whoever is viewing or controlling this screen; the next session must be allowed on this computer')
1453
+ .action(() => {
1454
+ if (!requestCastStop()) {
1455
+ console.log(chalk.gray('Không có ai đang xem màn hình máy này.'));
1456
+ return;
1457
+ }
1458
+ console.log(chalk.yellow('⏹ Đã gửi lệnh ngắt. Phiên xem sau phải bấm "Cho phép" trên máy này.'));
1459
+ });
1460
+
1450
1461
  remoteCommand
1451
1462
  .command('mascot [action] [combo]')
1452
1463
  .description('The Aivin mascot floating on screen while the listener runs (Windows): on | off — no argument shows the current setting; hotkey [combo|off|default] — the key combination for voice (default Alt+Shift+Space; off turns off both keys), with --chat the one that opens the ask box to type (default Alt+Space)')
@@ -1537,7 +1548,7 @@ remoteCommand
1537
1548
 
1538
1549
  remoteCommand
1539
1550
  .command('policy [action] [value]')
1540
- .description('Rules enforced on this computer itself (Aivin cannot change them): which steps need a click on this computer, tools turned off, extra blocked commands')
1551
+ .description('Rules enforced on this computer itself (Aivin cannot change them): which steps need a click on this computer, tools turned off, extra blocked commands, whether viewing this screen needs a click here (cast ask|unattended|off)')
1541
1552
  .action(async (action, value) => {
1542
1553
  try {
1543
1554
  await runPolicyCommand(action, value);
package/bin/lib/auth.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- import { exec } from 'child_process';
2
+ import { execFile } from 'child_process';
3
3
  import http from 'http';
4
4
  import os from 'os';
5
5
  import { randomBytes } from 'crypto';
@@ -21,16 +21,30 @@ export function saveGlobalApiKey(apiKey, baseUrl = process.env.AIVIN_BASE_URL ||
21
21
  return saveActiveContext(baseUrl, apiKey, identity);
22
22
  }
23
23
 
24
+ /**
25
+ * Lệnh mở trình duyệt, không qua shell: URL có thể do máy chủ trả về nên không được ghép vào chuỗi lệnh. Chỉ http(s); sai thì null.
26
+ */
27
+ export function browserCommand(url, platform = process.platform, systemRoot = process.env.SystemRoot || 'C:\\Windows') {
28
+ let href;
29
+ try {
30
+ const parsed = new URL(url);
31
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
32
+ href = parsed.href;
33
+ } catch {
34
+ return null;
35
+ }
36
+ if (platform === 'win32') return { file: `${systemRoot}\\System32\\rundll32.exe`, args: ['url.dll,FileProtocolHandler', href] };
37
+ return { file: platform === 'darwin' ? 'open' : 'xdg-open', args: [href] };
38
+ }
39
+
24
40
  export function openBrowser(url) {
25
- const platform = process.platform;
26
- const command =
27
- platform === 'win32' ? `start "" "${url}"` : platform === 'darwin' ? `open "${url}"` : `xdg-open "${url}"`;
28
- exec(command, (error) => {
29
- if (error) {
30
- console.log(chalk.yellow('Could not open a browser automatically - open this URL manually:'));
31
- console.log(chalk.cyan(` ${url}`));
32
- }
33
- });
41
+ const showManually = () => {
42
+ console.log(chalk.yellow('Could not open a browser automatically - open this URL manually:'));
43
+ console.log(chalk.cyan(` ${url}`));
44
+ };
45
+ const command = browserCommand(url);
46
+ if (!command) return showManually();
47
+ execFile(command.file, command.args, (error) => { if (error) showManually(); });
34
48
  }
35
49
 
36
50
  /**
@@ -0,0 +1,27 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import dotenv from 'dotenv';
4
+
5
+ /** Chỉ lệnh làm việc trên một dự án plugin mới đọc `.env` của thư mục hiện tại. Tệp này có thể đến từ repo vừa tải về hay tệp zip vừa giải nén. */
6
+ const PROJECT_COMMANDS = new Set(['create', 'init', 'validate', 'start', 'deploy', 'test', 'plugin', 'connector', 'pluginstore', 'mcp']);
7
+ /** Biến đổi cách CLI tin cậy mạng, chỗ lưu khoá, nguồn cập nhật: chỉ nhận từ môi trường thật, không nhận từ tệp trong dự án. */
8
+ const NEVER_FROM_PROJECT = /^(NODE_|AIVIN_(?!BASE_URL$|CLI_SDK_VERSION$|TRIGGER_TIMEOUT_MS$)|(HTTP|HTTPS|ALL|NO)_PROXY$)/i;
9
+
10
+ export function projectEnvEntries(argv, parsed) {
11
+ const command = argv.find((arg) => !arg.startsWith('-'));
12
+ if (!PROJECT_COMMANDS.has(command)) return {};
13
+ return Object.fromEntries(Object.entries(parsed).filter(([key]) => !NEVER_FROM_PROJECT.test(key)));
14
+ }
15
+
16
+ /** Không đè biến đã có sẵn trong môi trường thật. */
17
+ export function loadProjectEnv({ argv = process.argv.slice(2), env = process.env, file = path.resolve('.env') } = {}) {
18
+ let text;
19
+ try {
20
+ text = fs.readFileSync(file, 'utf8');
21
+ } catch {
22
+ return;
23
+ }
24
+ for (const [key, value] of Object.entries(projectEnvEntries(argv, dotenv.parse(text)))) {
25
+ if (env[key] === undefined) env[key] = value;
26
+ }
27
+ }
@@ -47,10 +47,11 @@ import { createAutoUpdater } from './autoUpdate.mjs';
47
47
  import { createDesktopCastManager } from './desktop/desktopCast.mjs';
48
48
  import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
49
49
  import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
50
- import { createCastFileDrop, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
51
- import {
52
- askCastConsent, blockViewer, checkCastAction, clearCastSession, isViewerBlocked, recordCastSession, unblockViewer,
50
+ import { createCastFileDrop, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
51
+ import {
52
+ askCastConsent, checkCastAction, clearCastSession, isCastLocked, lockCast, recordCastSession, unlockCast,
53
53
  } from './desktop/castAuth.mjs';
54
+ import { CastConsentDecision, createCastConsent } from './desktop/castConsent.mjs';
54
55
  import {
55
56
  BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
56
57
  confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
@@ -459,6 +460,16 @@ export async function startRemoteClient(options = {}) {
459
460
  };
460
461
  /** AI sắp bấm / người xem rời giữa lúc đang kéo: nhả nút + phím bổ trợ trên máy, gói nhả của người xem có thể không bao giờ tới. */
461
462
  const releaseCastInput = () => { if (castGate.takeHeldInput()) desktopCast.sendInput({ action: 'release_all' }); };
463
+ const castConsent = createCastConsent({
464
+ ask: ({ viewerDevice, locked, signal }) => askCastConsent({ viewerDevice: viewerDevice || 'Thiết bị từ xa', repeatedAfterBlock: locked, signal }),
465
+ getMode: () => policyGuard.read().cast_consent,
466
+ isLocked: isCastLocked,
467
+ unlock: unlockCast,
468
+ onWaiting: ({ sessionId, viewerId, viewerDevice }) => {
469
+ say(chalk.yellow(` ⚠️ Thiết bị "${viewerDevice || viewerId}" xin xem màn hình — chờ bấm "Cho phép" trên máy này`));
470
+ emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.AWAITING_CONSENT });
471
+ },
472
+ });
462
473
  const castFileDrop = createCastFileDrop({
463
474
  reply: (viewerId, msg) => desktopWebRtc.replyFile(viewerId, msg),
464
475
  checkAllowed: () => (isRemotePaused() ? FileDropReason.PAUSED : aiGuiBusy > 0 ? FileDropReason.AI_ACTIVE : null),
@@ -504,9 +515,10 @@ export async function startRemoteClient(options = {}) {
504
515
  desktopCast.setAudio(desktopWebRtc.needsAudio());
505
516
  };
506
517
  /** Dừng hẳn phiên trên máy (tạm dừng / mất kết nối / tắt daemon); `notify` = báo BE kết thúc phiên. */
507
- const stopDesktopCast = (reason, notify = true) => {
518
+ const stopDesktopCast = (reason, notify = true) => {
508
519
  clearCastSession();
509
520
  const sessionId = desktopCast.sessionId();
521
+ if (sessionId) castConsent.forget(sessionId);
510
522
  clearTimeout(castDisconnectTimer);
511
523
  castDisconnectTimer = null;
512
524
  desktopWebRtc.closeAll();
@@ -519,17 +531,15 @@ export async function startRemoteClient(options = {}) {
519
531
  if (notify && sessionId) emitCastStatus({ session_id: sessionId, state: CastState.STOPPED, reason, final: true });
520
532
  };
521
533
  let mascotChat = null;
522
- let castDisconnectTimer = null;
523
- const castActionTimer = setInterval(() => {
524
- const action = checkCastAction();
525
- if (action && action.action === 'stop_and_block') {
526
- const viewerId = action.viewer_id;
527
- const viewerDevice = action.viewer_device;
528
- blockViewer({ viewerId, viewerDevice });
529
- say(chalk.yellow(` ⏹ Người dùng đã ngắt kết nối và chặn cast từ: ${viewerDevice || viewerId}`));
530
- stopDesktopCast('user_revoked');
531
- }
532
- }, 1000);
534
+ let castDisconnectTimer = null;
535
+ const castActionTimer = setInterval(() => {
536
+ const action = checkCastAction();
537
+ if (action?.action === 'stop_and_block') {
538
+ lockCast({ viewerDevice: action.viewer_device });
539
+ say(chalk.yellow(' ⏹ Đã ngắt người đang xem. Phiên sau phải bấm "Cho phép" trên máy này.'));
540
+ stopDesktopCast('user_revoked');
541
+ }
542
+ }, 1000);
533
543
  castActionTimer.unref?.();
534
544
 
535
545
  say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
@@ -860,6 +870,28 @@ export async function startRemoteClient(options = {}) {
860
870
  onDuplicate: (call) => say(chalk.gray(` ↺ ${callLabel(call)}: đã làm ở lần gửi trước — trả lại kết quả cũ`)),
861
871
  });
862
872
 
873
+ /**
874
+ * Trước khi AI bấm: chờ người thôi tay. Người đang tạm cầm lái từ web thì chờ lâu hơn hạn của lời gọi nên xin BE lùi hạn, và đăng ký vào
875
+ * `gating` để lệnh huỷ dừng được lúc đang chờ. Không thì người vừa trả quyền xong là bước đã huỷ vẫn bấm.
876
+ */
877
+ const waitForHumanToYield = async (call) => {
878
+ const holdMs = castGate.takeoverWaitMs();
879
+ if (!holdMs) return void await castGate.waitHumanIdle();
880
+ const hold = (extraMs, phase) => { if (socket.connected) socket.emit(DeviceEvent.HOLD, { call_id: call.call_id, extra_ms: extraMs, phase }); };
881
+ hold(holdMs, HoldPhase.WAITING);
882
+ const controller = new AbortController();
883
+ gating.set(call.call_id, controller);
884
+ let yielded;
885
+ try {
886
+ yielded = await castGate.waitHumanIdle({ signal: controller.signal });
887
+ } finally {
888
+ gating.delete(call.call_id);
889
+ }
890
+ if (controller.signal.aborted) throw new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled while waiting for the person controlling this computer — the step did not run');
891
+ if (!yielded) throw new DeviceToolError(DeviceErrorCode.NOT_STARTED, 'The person is still controlling this computer from the web — the step did not run, try again later');
892
+ hold(0, HoldPhase.STARTED);
893
+ };
894
+
863
895
  /** Không bao giờ ném / để lọt promise bị từ chối: lỗi bất ngờ vẫn trả kết quả lỗi cho BE. */
864
896
  const handleCall = async (call) => {
865
897
  const streamer = createStreamer(socket, call.call_id);
@@ -871,18 +903,20 @@ export async function startRemoteClient(options = {}) {
871
903
  keepAwake.hold();
872
904
  const def = byName.get(call.tool);
873
905
  const guiWrite = def?.group === ToolGroup.GUI && !def?.read_only;
906
+ let guiBusyHeld = false;
874
907
  try {
875
908
  if (guiWrite) {
876
- // Người đang điều khiển từ web → AI chờ người thôi tay (tối đa 3 s) rồi mới bấm; trong lúc AI bấm, thao tác từ web bị bỏ.
877
- await castGate.waitHumanIdle();
909
+ // Người đang điều khiển từ web → AI chờ người thôi tay rồi mới bấm; trong lúc AI bấm, thao tác từ web bị bỏ.
910
+ await waitForHumanToYield(call);
878
911
  releaseCastInput();
879
912
  aiGuiBusy++;
913
+ guiBusyHeld = true;
880
914
  }
881
915
  ({ tool, outcome } = await runOnce(call, streamer));
882
916
  } catch (e) {
883
917
  outcome = { ok: false, error: e?.message || String(e), error_code: e?.code || DeviceErrorCode.EXECUTION_FAILED, duration_ms: 0 };
884
918
  } finally {
885
- if (guiWrite) aiGuiBusy--;
919
+ if (guiBusyHeld) aiGuiBusy--;
886
920
  keepAwake.release();
887
921
  syncProcAwake();
888
922
  }
@@ -1021,17 +1055,21 @@ export async function startRemoteClient(options = {}) {
1021
1055
  emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
1022
1056
  return;
1023
1057
  }
1024
- if (isViewerBlocked({ viewerId, viewerDevice })) {
1025
- say(chalk.yellow(` ⚠️ Thiết bị "${viewerDevice || viewerId}" đang yêu cầu xem màn hình sau khi bị ngắt kết nối. Đang mở hộp thoại xác thực...`));
1026
- const allowed = await askCastConsent({ viewerDevice: viewerDevice || 'Thiết bị từ xa', timeoutSec: 30 });
1027
- if (!allowed) {
1028
- say(chalk.red(` ✕ Người dùng đã từ chối yêu cầu xem màn hình từ: ${viewerDevice || viewerId}`));
1029
- emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'rejected_by_user' });
1030
- return;
1031
- }
1032
- say(chalk.green(` ✓ Người dùng đã cho phép thiết bị "${viewerDevice || viewerId}" xem màn hình`));
1033
- unblockViewer({ viewerId, viewerDevice });
1034
- }
1058
+ // Quyết định trước khi chụp bất cứ thứ gì; chỉ máy này trả lời được, máy chủ không trả lời thay.
1059
+ const decision = await castConsent.decide({ sessionId, viewerId, viewerDevice, viewerKey: payload?.viewer_key });
1060
+ if (decision !== CastConsentDecision.ALLOW) {
1061
+ logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, result: decision });
1062
+ if (decision === CastConsentDecision.CANCELLED) return;
1063
+ say(chalk.red(` ✕ Không cho xem màn hình (${decision}): ${viewerDevice || viewerId}`));
1064
+ emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: decision });
1065
+ return;
1066
+ }
1067
+ // Chủ máy có thể bấm tạm dừng trong lúc hộp đang mở.
1068
+ if (isRemotePaused()) {
1069
+ emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
1070
+ return;
1071
+ }
1072
+ logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, result: decision });
1035
1073
  const castConfig = {
1036
1074
  max_fps: payload?.max_fps || 15,
1037
1075
  max_width: payload?.max_width || 1366,
@@ -1049,11 +1087,19 @@ export async function startRemoteClient(options = {}) {
1049
1087
  onFrame: (frame) => {
1050
1088
  desktopWebRtc.push(frame);
1051
1089
  // Còn người xem chưa có kênh WebRTC (đang nối / runtime native không có) → JPEG qua máy chủ; BE chỉ chuyển cho những người đó.
1052
- if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, frame);
1090
+ // Binary thay base64: nhẹ hơn khoảng một phần ba; JPEG đã nén nên không nén thêm.
1091
+ if (desktopWebRtc.needsFallback() && socket.connected) {
1092
+ socket.volatile.compress(false).emit(DeviceEvent.DESKTOP_CAST_FRAME, { ...frame, image: Buffer.from(frame.image, 'base64') });
1093
+ }
1053
1094
  syncCastJpeg();
1054
1095
  },
1055
1096
  // Mọi người xem đã có video → tiến trình quay thôi nén JPEG, chỉ gửi meta (toạ độ) + khung thô cho bộ mã hoá video.
1056
- onMeta: (meta) => { desktopWebRtc.push(meta); syncCastJpeg(); },
1097
+ onMeta: (meta) => {
1098
+ desktopWebRtc.push(meta);
1099
+ // Màn hình đứng yên không có ảnh: người xem qua máy chủ vẫn cần gói giữ nhịp để biết máy còn sống.
1100
+ if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, meta);
1101
+ syncCastJpeg();
1102
+ },
1057
1103
  onCursor: (cursor) => desktopWebRtc.pushCursor(cursor),
1058
1104
  onCursorShape: (shape) => desktopWebRtc.pushCursorShape(shape),
1059
1105
  onInputFocus: (focus) => {
@@ -1072,7 +1118,7 @@ export async function startRemoteClient(options = {}) {
1072
1118
  rawPipe: true,
1073
1119
  onReady: (meta) => {
1074
1120
  say(chalk.cyan(` 🖥️ Đang có người xem + điều khiển màn hình máy này từ web (${meta.bounds?.width}x${meta.bounds?.height})`));
1075
- mascot.remoteView(true, { device: viewerDevice });
1121
+ mascot.remoteView(true, { device: viewerDevice });
1076
1122
  recordCastSession({ active: true, sessionId, viewerId, viewerDevice });
1077
1123
  emitCastStatus({ session_id: sessionId, state: CastState.READY, bounds: meta.bounds });
1078
1124
  },
@@ -1081,13 +1127,15 @@ export async function startRemoteClient(options = {}) {
1081
1127
  },
1082
1128
  onStop: () => {
1083
1129
  say(chalk.gray(' ⏹ Đã ngừng xem màn hình từ web'));
1084
- mascot.remoteView(false);
1130
+ mascot.remoteView(false);
1085
1131
  clearCastSession();
1086
1132
  },
1087
1133
  });
1088
1134
  if (!started) return;
1089
1135
  } else {
1090
1136
  desktopCast.config(castConfig);
1137
+ // Màn hình đứng yên thì ảnh thưa: người mới vào cần một ảnh ngay.
1138
+ desktopCast.refresh();
1091
1139
  }
1092
1140
  const webRtcStarted = payload?.transport === 'webrtc'
1093
1141
  ? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null, audio: payload?.audio !== false }).catch(() => false)
@@ -1098,6 +1146,7 @@ export async function startRemoteClient(options = {}) {
1098
1146
  });
1099
1147
  }));
1100
1148
  socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
1149
+ if (payload?.session_id) castConsent.cancel({ sessionId: payload.session_id, viewerId: payload.viewer_id, final: payload.final !== false });
1101
1150
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
1102
1151
  if (payload?.viewer_id) {
1103
1152
  desktopWebRtc.close(payload.viewer_id);
@@ -1113,6 +1162,10 @@ export async function startRemoteClient(options = {}) {
1113
1162
  desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
1114
1163
  if (typeof audio === 'boolean') desktopWebRtc.setAudio(audio);
1115
1164
  }));
1165
+ socket.on(DeviceEvent.DESKTOP_CAST_TAKEOVER, guarded(DeviceEvent.DESKTOP_CAST_TAKEOVER, (payload) => {
1166
+ if (!payload?.session_id || payload.session_id !== desktopCast.sessionId()) return;
1167
+ castGate.setHumanTakeover(payload.active === true ? { idleMs: Number(payload.idle_ms), maxWaitMs: Number(payload.max_wait_ms) } : null);
1168
+ }));
1116
1169
  socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
1117
1170
  void desktopWebRtc.signal(payload).catch(() => undefined);
1118
1171
  }));
@@ -103,11 +103,13 @@ export const DeviceEvent = Object.freeze({
103
103
  DESKTOP_CAST_STATUS: 'device:desktop_cast_status',
104
104
  /** CLI → BE: ô có tiêu điểm sau cú nhấp có phải ô nhập chữ — cho người xem đường JPEG (WebRTC đi kênh thao tác). */
105
105
  DESKTOP_CAST_INPUT_FOCUS: 'device:desktop_cast_input_focus',
106
+ /** BE → CLI: người xem tạm cầm lái khi AI đang chạy / trả lại — `{ session_id, active, idle_ms, max_wait_ms }`. */
107
+ DESKTOP_CAST_TAKEOVER: 'device:desktop_cast_takeover',
106
108
  });
107
109
 
108
110
  /** Trạng thái phiên xem màn hình gửi BE (`device:desktop_cast_status`) — khớp BE `DesktopCastState`. */
109
111
  export const CastState = Object.freeze({
110
- READY: 'ready', CONNECTED: 'connected', DEGRADED: 'degraded', STOPPED: 'stopped', REFUSED: 'refused', INPUT_BLOCKED: 'input_blocked',
112
+ READY: 'ready', CONNECTED: 'connected', DEGRADED: 'degraded', STOPPED: 'stopped', REFUSED: 'refused', INPUT_BLOCKED: 'input_blocked', AWAITING_CONSENT: 'awaiting_consent',
111
113
  });
112
114
 
113
115
  /** Loại báo chủ động (`device:notify`). */
@@ -212,6 +214,8 @@ export const DeviceErrorCode = Object.freeze({
212
214
  CANCELLED: 'CANCELLED',
213
215
  /** Bước có tác dụng đã bắt đầu thì daemon khởi động lại — không biết đã làm tới đâu, không tự làm lại. */
214
216
  INTERRUPTED: 'INTERRUPTED',
217
+ /** Bước CHƯA chạy (vd người đang tạm cầm lái từ web tới hết hạn chờ) — gửi lại an toàn. */
218
+ NOT_STARTED: 'NOT_STARTED',
215
219
  TOOL_UNKNOWN: 'TOOL_UNKNOWN',
216
220
  INVALID_ARGS: 'INVALID_ARGS',
217
221
  NOT_FOUND: 'NOT_FOUND',
@@ -3,75 +3,48 @@ import path from 'path';
3
3
  import { spawn } from 'child_process';
4
4
  import { REMOTE_CONFIG_DIR } from '../constants.mjs';
5
5
  import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
6
+ import { CastConsentDecision } from './castConsent.mjs';
6
7
 
7
8
  export const CAST_SESSION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-session.json');
8
9
  export const CAST_ACTION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-action.json');
9
10
  export const CAST_PERMISSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-permissions.json');
10
11
 
12
+ const CAST_STOP_ACTION = Object.freeze({ action: 'stop_and_block' });
13
+
11
14
  const b64 = (s) => Buffer.from(String(s ?? ''), 'utf8').toString('base64');
12
15
 
13
16
  function loadPermissions() {
14
17
  try {
15
- if (!fs.existsSync(CAST_PERMISSIONS_FILE)) return { blockedViewers: [] };
16
- const content = fs.readFileSync(CAST_PERMISSIONS_FILE, 'utf8');
17
- const parsed = JSON.parse(content);
18
- return parsed && Array.isArray(parsed.blockedViewers) ? parsed : { blockedViewers: [] };
18
+ const parsed = JSON.parse(fs.readFileSync(CAST_PERMISSIONS_FILE, 'utf8'));
19
+ return parsed && typeof parsed === 'object' ? parsed : {};
19
20
  } catch {
20
- return { blockedViewers: [] };
21
+ return {};
21
22
  }
22
23
  }
23
24
 
24
25
  function savePermissions(data) {
25
26
  try {
26
27
  fs.mkdirSync(path.dirname(CAST_PERMISSIONS_FILE), { recursive: true });
27
- fs.writeFileSync(CAST_PERMISSIONS_FILE, JSON.stringify(data, null, 2), 'utf8');
28
+ fs.writeFileSync(CAST_PERMISSIONS_FILE, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 });
28
29
  } catch { }
29
30
  }
30
31
 
31
32
  /**
32
- * Kiểm tra xem người xem / thiết bị này có đang bị chặn hoặc cần xác nhận lại quyền cast không.
33
+ * Chủ máy vừa bấm ngắt: mọi phiên sau đều phải hỏi tới khi chủ máy bấm "Cho phép" một lần, kể cả chế độ không cần người ở máy.
34
+ * Khoá theo cả máy, không theo tên thiết bị: tên do trình duyệt tự khai và mã socket đổi sau mỗi lần nối nên chặn theo chúng lách được.
35
+ * Tệp từ bản cũ (`blockedViewers` còn phần tử) cũng tính là đang khoá.
33
36
  */
34
- export function isViewerBlocked({ viewerId, viewerDevice } = {}) {
35
- const { blockedViewers = [] } = loadPermissions();
36
- return blockedViewers.some((v) => {
37
- if (v.viewerId && viewerId && v.viewerId === viewerId) return true;
38
- if (v.viewerDevice && viewerDevice && v.viewerDevice === viewerDevice) return true;
39
- return false;
40
- });
37
+ export function isCastLocked() {
38
+ const { locked, blockedViewers } = loadPermissions();
39
+ return locked === true || (Array.isArray(blockedViewers) && blockedViewers.length > 0);
41
40
  }
42
41
 
43
- /**
44
- * Thêm thiết bị vào danh sách chặn / thu hồi quyền cast.
45
- */
46
- export function blockViewer({ viewerId, viewerDevice } = {}) {
47
- const data = loadPermissions();
48
- const list = data.blockedViewers || [];
49
- const filtered = list.filter((v) => {
50
- if (viewerId && v.viewerId === viewerId) return false;
51
- if (viewerDevice && v.viewerDevice === viewerDevice) return false;
52
- return true;
53
- });
54
- filtered.push({
55
- viewerId: viewerId || '',
56
- viewerDevice: viewerDevice || '',
57
- blockedAt: new Date().toISOString(),
58
- });
59
- data.blockedViewers = filtered;
60
- savePermissions(data);
42
+ export function lockCast({ viewerDevice = '' } = {}) {
43
+ savePermissions({ locked: true, lockedAt: new Date().toISOString(), lastViewerDevice: String(viewerDevice || '') });
61
44
  }
62
45
 
63
- /**
64
- * Bỏ chặn / cấp quyền cho thiết bị sau khi người dùng đã bấm đồng ý trên modal.
65
- */
66
- export function unblockViewer({ viewerId, viewerDevice } = {}) {
67
- const data = loadPermissions();
68
- if (!data.blockedViewers) return;
69
- data.blockedViewers = data.blockedViewers.filter((v) => {
70
- if (viewerId && v.viewerId === viewerId) return false;
71
- if (viewerDevice && v.viewerDevice === viewerDevice) return false;
72
- return true;
73
- });
74
- savePermissions(data);
46
+ export function unlockCast() {
47
+ savePermissions({ locked: false });
75
48
  }
76
49
 
77
50
  /**
@@ -106,14 +79,29 @@ export function clearCastSession() {
106
79
  * Kiểm tra xem khay hệ thống có gửi lệnh ngắt / chặn thiết bị cast không.
107
80
  */
108
81
  export function checkCastAction() {
82
+ let content;
109
83
  try {
110
84
  if (!fs.existsSync(CAST_ACTION_FILE)) return null;
111
- const content = fs.readFileSync(CAST_ACTION_FILE, 'utf8');
85
+ content = fs.readFileSync(CAST_ACTION_FILE, 'utf8');
112
86
  fs.unlinkSync(CAST_ACTION_FILE);
113
- return JSON.parse(content);
114
87
  } catch {
115
88
  return null;
116
89
  }
90
+ // Có tệp nghĩa là chủ máy đã bấm ngắt: không đọc được nội dung thì vẫn phải ngắt, không được bỏ qua.
91
+ try {
92
+ const action = JSON.parse(content);
93
+ return action && typeof action === 'object' ? action : CAST_STOP_ACTION;
94
+ } catch {
95
+ return CAST_STOP_ACTION;
96
+ }
97
+ }
98
+
99
+ /** Gửi yêu cầu ngắt từ dòng lệnh, cùng đường với nút ở khay. Trả về `false` nếu không có phiên nào đang chạy. */
100
+ export function requestCastStop() {
101
+ if (!fs.existsSync(CAST_SESSION_FILE)) return false;
102
+ fs.mkdirSync(path.dirname(CAST_ACTION_FILE), { recursive: true });
103
+ fs.writeFileSync(CAST_ACTION_FILE, JSON.stringify(CAST_STOP_ACTION), 'utf8');
104
+ return true;
117
105
  }
118
106
 
119
107
  const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
@@ -150,8 +138,8 @@ const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
150
138
  Background="Transparent" Foreground="#6B7280" ToolTip="Từ chối" IsTabStop="False"/>
151
139
  </DockPanel>
152
140
  <TextBlock Text="Cho phép xem và điều khiển màn hình máy tính?" Margin="0,20,0,0" FontSize="18" FontWeight="SemiBold" Foreground="#111827" TextWrapping="Wrap"/>
153
- <Border Margin="0,12,0,0" HorizontalAlignment="Left" CornerRadius="10" Background="#FEF3C7" Padding="12,6">
154
- <TextBlock Text="⚠ Thiết bị trước đó đã bị ngắt kết nối hoặc chưa được cấp quyền" Foreground="#92400E" FontSize="12.5" FontWeight="SemiBold" TextWrapping="Wrap"/>
141
+ <Border x:Name="Warn" Margin="0,12,0,0" HorizontalAlignment="Left" CornerRadius="10" Background="#FEF3C7" Padding="12,6">
142
+ <TextBlock Text="⚠ Thiết bị này trước đó đã bị ngắt kết nối" Foreground="#92400E" FontSize="12.5" FontWeight="SemiBold" TextWrapping="Wrap"/>
155
143
  </Border>
156
144
  <Border Margin="0,14,0,0" CornerRadius="10" Background="#F4F6FA" BorderBrush="#E8ECF3" BorderThickness="1" Padding="14,12">
157
145
  <StackPanel>
@@ -176,6 +164,7 @@ const CONSENT_SCRIPT = [
176
164
  "$w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml](D 'AIVIN_CAST_XAML'))))",
177
165
  "$w.Title = D 'AIVIN_CAST_TITLE'",
178
166
  "$w.FindName('DeviceText').Text = D 'AIVIN_CAST_DEVICE'",
167
+ "if ($env:AIVIN_CAST_WARN -ne '1') { $w.FindName('Warn').Visibility = 'Collapsed' }",
179
168
  "$ms = New-Object IO.MemoryStream(, [Convert]::FromBase64String($env:AIVIN_CAST_LOGO)); $img = New-Object Windows.Media.Imaging.BitmapImage",
180
169
  "$img.BeginInit(); $img.StreamSource = $ms; $img.CacheOption = 'OnLoad'; $img.EndInit(); $w.FindName('Logo').Source = $img",
181
170
  "$script:result = 'No'; $script:closing = $false",
@@ -191,21 +180,21 @@ const CONSENT_SCRIPT = [
191
180
  ].join('\n');
192
181
 
193
182
  /**
194
- * Mở modal hộp thoại xác thực trên màn hình Windows hỏi người dùng có cho phép cast không.
195
- * Trả về true nếu người dùng chọn Cho phép, false nếu Từ chối hoặc hết giờ.
183
+ * Hỏi người ở máy trên chính màn hình Windows. Mặc định là từ chối: Enter, Esc, đóng hộp, hết giờ đều không cho xem.
184
+ * `repeatedAfterBlock`: hiện thêm dòng cảnh báo thiết bị từng bị ngắt. Trả về một giá trị của `CastConsentDecision`.
196
185
  */
197
- export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutSec = 30 } = {}) {
198
- if (process.platform !== 'win32') return Promise.resolve(false);
186
+ export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutSec = 45, repeatedAfterBlock = false, signal } = {}) {
187
+ if (process.platform !== 'win32') return Promise.resolve(CastConsentDecision.UNAVAILABLE);
199
188
  return new Promise((resolve) => {
200
189
  let out = '';
201
190
  let settled = false;
202
191
  let timer = null;
203
192
 
204
- const done = (allowed) => {
193
+ const done = (answer) => {
205
194
  if (settled) return;
206
195
  settled = true;
207
196
  if (timer) clearTimeout(timer);
208
- resolve(allowed);
197
+ resolve(answer);
209
198
  };
210
199
 
211
200
  const env = {
@@ -216,6 +205,7 @@ export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutS
216
205
  AIVIN_CAST_DEVICE: b64(`Thiết bị yêu cầu: ${viewerDevice}`),
217
206
  AIVIN_CAST_COUNTDOWN: b64('Tự từ chối sau {0} giây'),
218
207
  AIVIN_CAST_SECONDS: String(timeoutSec),
208
+ AIVIN_CAST_WARN: repeatedAfterBlock ? '1' : '0',
219
209
  };
220
210
 
221
211
  let child = null;
@@ -226,19 +216,20 @@ export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutS
226
216
  windowsHide: false,
227
217
  });
228
218
  } catch {
229
- return done(false);
219
+ return done(CastConsentDecision.UNAVAILABLE);
230
220
  }
231
221
 
232
- timer = setTimeout(() => {
233
- try { child.kill(); } catch { }
234
- done(false);
235
- }, (timeoutSec + 5) * 1000);
222
+ const kill = () => { try { child.kill(); } catch { } };
223
+ signal?.addEventListener('abort', () => { kill(); done(CastConsentDecision.CANCELLED); }, { once: true });
224
+ timer = setTimeout(() => { kill(); done(CastConsentDecision.TIMEOUT); }, (timeoutSec + 5) * 1000);
236
225
 
237
226
  child.stdout?.on('data', (chunk) => { out += chunk; });
238
- child.on('error', () => done(false));
227
+ child.on('error', () => done(CastConsentDecision.UNAVAILABLE));
239
228
  child.on('close', (code) => {
240
- const allowed = code === 0 && /\bYes\b/.test(out);
241
- done(allowed);
229
+ if (code === 0 && /\bYes\b/.test(out)) return done(CastConsentDecision.ALLOW);
230
+ if (/\bTimeout\b/.test(out)) return done(CastConsentDecision.TIMEOUT);
231
+ if (/\bNo\b/.test(out)) return done(CastConsentDecision.REJECTED);
232
+ return done(CastConsentDecision.UNAVAILABLE);
242
233
  });
243
234
  });
244
235
  }
@@ -0,0 +1,59 @@
1
+ import { CastConsentMode } from '../localPolicy.mjs';
2
+
3
+ /** Kết quả hỏi; khác `ALLOW` / `CANCELLED` thì gửi nguyên giá trị làm lý do từ chối cho người xem. */
4
+ export const CastConsentDecision = Object.freeze({
5
+ ALLOW: 'allow', DISABLED: 'cast_disabled', REJECTED: 'rejected_by_user', TIMEOUT: 'consent_timeout', UNAVAILABLE: 'consent_unavailable', CANCELLED: 'cancelled',
6
+ });
7
+
8
+ const MAX_REMEMBERED = 100;
9
+ /** `viewerKey` do máy chủ tính (tài khoản + IP + trình duyệt); máy chủ đời cũ không gửi thì dùng tên thiết bị. */
10
+ const key = (sessionId, viewerKey, viewerDevice) => `${sessionId}\n${viewerKey || viewerDevice || ''}`;
11
+
12
+ /**
13
+ * Chủ máy đồng ý từng phiên, quyết định ngay trên máy nên máy chủ không trả lời thay được. Đồng ý có hiệu lực cho đúng phiên + đúng người xem đó
14
+ * (rớt mạng nối lại không hỏi lại), phiên kết thúc là quên. Chủ máy vừa bấm ngắt thì `isLocked` đúng: luôn hỏi, kể cả chế độ không cần người ở máy.
15
+ */
16
+ export function createCastConsent({ ask, getMode, isLocked = () => false, unlock = () => {}, onWaiting = () => {} }) {
17
+ const approved = new Set();
18
+ const pending = new Map();
19
+
20
+ function request({ sessionId, viewerId, viewerDevice, viewerKey, locked }) {
21
+ const k = key(sessionId, viewerKey, viewerDevice);
22
+ const open = pending.get(k);
23
+ if (open) return open.promise;
24
+ const controller = new AbortController();
25
+ onWaiting({ sessionId, viewerId, viewerDevice });
26
+ const promise = new Promise((resolve) => resolve(ask({ viewerDevice, locked, signal: controller.signal })))
27
+ .catch(() => CastConsentDecision.UNAVAILABLE)
28
+ .then((answer) => {
29
+ pending.delete(k);
30
+ if (answer === CastConsentDecision.ALLOW) {
31
+ if (approved.size >= MAX_REMEMBERED) approved.clear();
32
+ approved.add(k);
33
+ if (locked) unlock();
34
+ }
35
+ return answer;
36
+ });
37
+ pending.set(k, { promise, controller, sessionId, viewerId });
38
+ return promise;
39
+ }
40
+
41
+ return {
42
+ async decide({ sessionId, viewerId, viewerDevice = '', viewerKey = '' }) {
43
+ const mode = getMode();
44
+ if (mode === CastConsentMode.OFF) return CastConsentDecision.DISABLED;
45
+ const locked = isLocked();
46
+ if (!locked && (mode === CastConsentMode.UNATTENDED || approved.has(key(sessionId, viewerKey, viewerDevice)))) return CastConsentDecision.ALLOW;
47
+ return request({ sessionId, viewerId, viewerDevice, viewerKey, locked });
48
+ },
49
+ /** Người xem rời / huỷ trong lúc đang hỏi: đóng hộp, không bắt đầu chụp. */
50
+ cancel({ sessionId, viewerId, final = true }) {
51
+ for (const open of pending.values()) {
52
+ if (open.sessionId === sessionId && (final || open.viewerId === viewerId)) open.controller.abort();
53
+ }
54
+ },
55
+ forget(sessionId) {
56
+ for (const k of approved) if (k.startsWith(`${sessionId}\n`)) approved.delete(k);
57
+ },
58
+ };
59
+ }