@aivin-labs/cli 1.0.46 → 1.0.50

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 (38) hide show
  1. package/bin/cli.mjs +16 -5
  2. package/bin/lib/auth.mjs +24 -10
  3. package/bin/lib/projectEnv.mjs +27 -0
  4. package/bin/lib/remote/client.mjs +1412 -1162
  5. package/bin/lib/remote/confirmBarrier.mjs +45 -0
  6. package/bin/lib/remote/constants.mjs +7 -1
  7. package/bin/lib/remote/desktop/aivinIco.mjs +696 -0
  8. package/bin/lib/remote/desktop/castAuth.mjs +74 -69
  9. package/bin/lib/remote/desktop/castConsent.mjs +90 -0
  10. package/bin/lib/remote/desktop/castFileDrop.mjs +24 -0
  11. package/bin/lib/remote/desktop/castInput.mjs +89 -24
  12. package/bin/lib/remote/desktop/castTouchViewers.mjs +26 -0
  13. package/bin/lib/remote/desktop/desktopCast.mjs +28 -2
  14. package/bin/lib/remote/desktop/desktopCastSource.mjs +410 -121
  15. package/bin/lib/remote/desktop/desktopWebRtc.mjs +17 -1
  16. package/bin/lib/remote/desktop/index.mjs +5 -3
  17. package/bin/lib/remote/desktop/traySource.mjs +1289 -1274
  18. package/bin/lib/remote/desktop/webrtcWorker.mjs +3 -0
  19. package/bin/lib/remote/deviceProfile.mjs +2 -0
  20. package/bin/lib/remote/gui/index.mjs +485 -480
  21. package/bin/lib/remote/humanInput.mjs +117 -0
  22. package/bin/lib/remote/idempotency.mjs +19 -2
  23. package/bin/lib/remote/keepAwake.mjs +15 -9
  24. package/bin/lib/remote/localConfirm.mjs +26 -7
  25. package/bin/lib/remote/localPolicy.mjs +15 -2
  26. package/bin/lib/remote/mascot/ask.mjs +23 -4
  27. package/bin/lib/remote/mascot/askHostSource.mjs +10 -4
  28. package/bin/lib/remote/mascot/bot.mjs +5 -1
  29. package/bin/lib/remote/mascot/hostSource.mjs +8 -1
  30. package/bin/lib/remote/mascot/index.mjs +55 -51
  31. package/bin/lib/remote/mascot/rigSource.mjs +28 -2
  32. package/bin/lib/remote/policyCommand.mjs +16 -3
  33. package/bin/lib/remote/processes.mjs +231 -230
  34. package/bin/lib/remote/sandbox.mjs +6 -4
  35. package/bin/lib/remote/scheduler.mjs +164 -124
  36. package/bin/lib/remote/toolHandlers.mjs +3 -2
  37. package/bin/lib/remote/winTree.mjs +29 -0
  38. package/package.json +1 -1
@@ -3,75 +3,50 @@ 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';
7
+ import { lockHolder } from '../daemonLock.mjs';
8
+ import { CAST_CONSENT_WINDOW_TITLE, HUMAN_GUARD_PS, humanGuardEnv } from '../humanInput.mjs';
6
9
 
7
10
  export const CAST_SESSION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-session.json');
8
11
  export const CAST_ACTION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-action.json');
9
12
  export const CAST_PERMISSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-permissions.json');
10
13
 
14
+ const CAST_STOP_ACTION = Object.freeze({ action: 'stop_and_block' });
15
+
11
16
  const b64 = (s) => Buffer.from(String(s ?? ''), 'utf8').toString('base64');
12
17
 
13
18
  function loadPermissions() {
14
19
  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: [] };
20
+ const parsed = JSON.parse(fs.readFileSync(CAST_PERMISSIONS_FILE, 'utf8'));
21
+ return parsed && typeof parsed === 'object' ? parsed : {};
19
22
  } catch {
20
- return { blockedViewers: [] };
23
+ return {};
21
24
  }
22
25
  }
23
26
 
24
27
  function savePermissions(data) {
25
28
  try {
26
29
  fs.mkdirSync(path.dirname(CAST_PERMISSIONS_FILE), { recursive: true });
27
- fs.writeFileSync(CAST_PERMISSIONS_FILE, JSON.stringify(data, null, 2), 'utf8');
30
+ fs.writeFileSync(CAST_PERMISSIONS_FILE, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 });
28
31
  } catch { }
29
32
  }
30
33
 
31
34
  /**
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.
35
+ * 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.
36
+ * 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.
37
+ * Tệp từ bản cũ (`blockedViewers` còn phần tử) cũng tính là đang khoá.
33
38
  */
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
- });
39
+ export function isCastLocked() {
40
+ const { locked, blockedViewers } = loadPermissions();
41
+ return locked === true || (Array.isArray(blockedViewers) && blockedViewers.length > 0);
41
42
  }
42
43
 
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);
44
+ export function lockCast({ viewerDevice = '' } = {}) {
45
+ savePermissions({ locked: true, lockedAt: new Date().toISOString(), lastViewerDevice: String(viewerDevice || '') });
61
46
  }
62
47
 
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);
48
+ export function unlockCast() {
49
+ savePermissions({ locked: false });
75
50
  }
76
51
 
77
52
  /**
@@ -82,6 +57,8 @@ export function recordCastSession({ active = true, sessionId = '', viewerId = ''
82
57
  fs.mkdirSync(path.dirname(CAST_SESSION_FILE), { recursive: true });
83
58
  const payload = {
84
59
  active: !!active,
60
+ // Daemon đang giữ phiên: khay / `aivin remote disconnect` biết tệp còn sót sau khi daemon chết (không còn ai để ngắt).
61
+ pid: process.pid,
85
62
  session_id: sessionId,
86
63
  viewer_id: viewerId,
87
64
  viewer_device: viewerDevice,
@@ -106,17 +83,39 @@ export function clearCastSession() {
106
83
  * Kiểm tra xem khay hệ thống có gửi lệnh ngắt / chặn thiết bị cast không.
107
84
  */
108
85
  export function checkCastAction() {
86
+ let content;
109
87
  try {
110
88
  if (!fs.existsSync(CAST_ACTION_FILE)) return null;
111
- const content = fs.readFileSync(CAST_ACTION_FILE, 'utf8');
89
+ content = fs.readFileSync(CAST_ACTION_FILE, 'utf8');
112
90
  fs.unlinkSync(CAST_ACTION_FILE);
113
- return JSON.parse(content);
114
91
  } catch {
115
92
  return null;
116
93
  }
94
+ // 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.
95
+ try {
96
+ const action = JSON.parse(content);
97
+ return action && typeof action === 'object' ? action : CAST_STOP_ACTION;
98
+ } catch {
99
+ return CAST_STOP_ACTION;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * 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 — kể cả khi tệp phiên còn sót lại
105
+ * sau khi daemon chết (dọn luôn, không báo "đã ngắt" cho một phiên không tồn tại).
106
+ */
107
+ export function requestCastStop({ daemonAlive = () => lockHolder() !== null } = {}) {
108
+ if (!fs.existsSync(CAST_SESSION_FILE)) return false;
109
+ if (!daemonAlive()) {
110
+ clearCastSession();
111
+ return false;
112
+ }
113
+ fs.mkdirSync(path.dirname(CAST_ACTION_FILE), { recursive: true });
114
+ fs.writeFileSync(CAST_ACTION_FILE, JSON.stringify(CAST_STOP_ACTION), 'utf8');
115
+ return true;
117
116
  }
118
117
 
119
- const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
118
+ export const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
120
119
  Width="500" SizeToContent="Height" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize"
121
120
  Topmost="True" ShowInTaskbar="True" WindowStartupLocation="CenterScreen" FontFamily="Segoe UI" UseLayoutRounding="True">
122
121
  <Window.Resources>
@@ -150,8 +149,8 @@ const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
150
149
  Background="Transparent" Foreground="#6B7280" ToolTip="Từ chối" IsTabStop="False"/>
151
150
  </DockPanel>
152
151
  <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"/>
152
+ <Border x:Name="Warn" Margin="0,12,0,0" HorizontalAlignment="Left" CornerRadius="10" Background="#FEF3C7" Padding="12,6">
153
+ <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
154
  </Border>
156
155
  <Border Margin="0,14,0,0" CornerRadius="10" Background="#F4F6FA" BorderBrush="#E8ECF3" BorderThickness="1" Padding="14,12">
157
156
  <StackPanel>
@@ -159,12 +158,12 @@ const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
159
158
  <TextBlock Text="Thiết bị này đang gửi yêu cầu xem màn hình và thao tác chuột, bàn phím trên máy tính của bạn." Margin="0,6,0,0" FontSize="12.5" Foreground="#4B5563" TextWrapping="Wrap"/>
160
159
  </StackPanel>
161
160
  </Border>
162
- <DockPanel Margin="0,22,0,0" LastChildFill="False">
163
- <TextBlock x:Name="Countdown" VerticalAlignment="Center" FontSize="12" Foreground="#6B7280"/>
161
+ <DockPanel Margin="0,22,0,0" LastChildFill="True">
164
162
  <Button x:Name="Allow" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0" Margin="10,0,0,0"
165
163
  Background="#4E46E5" Foreground="White" BorderThickness="0" Content="_Cho phép"/>
166
164
  <Button x:Name="Reject" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0"
167
165
  Background="White" Foreground="#111827" BorderBrush="#C9CDD4" BorderThickness="1" Content="_Từ chối" IsCancel="True" IsDefault="True"/>
166
+ <TextBlock x:Name="Countdown" VerticalAlignment="Center" Margin="0,0,12,0" FontSize="12" Foreground="#6B7280" TextWrapping="Wrap"/>
168
167
  </DockPanel>
169
168
  </StackPanel>
170
169
  </Border>
@@ -173,49 +172,54 @@ const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
173
172
  const CONSENT_SCRIPT = [
174
173
  'Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase',
175
174
  'function D($n) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Environment]::GetEnvironmentVariable($n))) }',
175
+ // Đồng ý cho xem màn hình chỉ từ phím / chuột thật trên máy — không nhận cả thao tác từ phiên điều khiển từ xa khác (humanInput.mjs).
176
+ ...HUMAN_GUARD_PS,
176
177
  "$w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml](D 'AIVIN_CAST_XAML'))))",
177
178
  "$w.Title = D 'AIVIN_CAST_TITLE'",
178
179
  "$w.FindName('DeviceText').Text = D 'AIVIN_CAST_DEVICE'",
180
+ "if ($env:AIVIN_CAST_WARN -ne '1') { $w.FindName('Warn').Visibility = 'Collapsed' }",
179
181
  "$ms = New-Object IO.MemoryStream(, [Convert]::FromBase64String($env:AIVIN_CAST_LOGO)); $img = New-Object Windows.Media.Imaging.BitmapImage",
180
182
  "$img.BeginInit(); $img.StreamSource = $ms; $img.CacheOption = 'OnLoad'; $img.EndInit(); $w.FindName('Logo').Source = $img",
181
183
  "$script:result = 'No'; $script:closing = $false",
182
184
  '$tm = New-Object Windows.Threading.DispatcherTimer; $tm.Interval = [TimeSpan]::FromSeconds(1)',
183
185
  "function Finish($r) { if ($script:closing) { return }; $script:closing = $true; $script:result = $r; $tm.Stop(); $w.Close() }",
184
- "$w.FindName('Allow').Add_Click({ Finish 'Yes' })",
186
+ "$w.FindName('Allow').Add_Click({ if (Test-Human) { Finish 'Yes' } else { $script:hintLeft = 3; $cd.Text = $script:hint } })",
185
187
  "$w.FindName('Reject').Add_Click({ Finish 'No' }); $w.FindName('Close').Add_Click({ Finish 'No' })",
186
188
  "$w.FindName('Head').Add_MouseLeftButtonDown({ $w.DragMove() })",
187
189
  "$script:left = [int]$env:AIVIN_CAST_SECONDS; $fmt = D 'AIVIN_CAST_COUNTDOWN'; $cd = $w.FindName('Countdown'); $cd.Text = $fmt -f $script:left",
188
- "$tm.Add_Tick({ $script:left--; $cd.Text = $fmt -f $script:left; if ($script:left -le 0) { Finish 'Timeout' } })",
189
- "$w.Add_ContentRendered({ $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
190
+ "$tm.Add_Tick({ $script:left--; if ($script:hintLeft -gt 0) { $script:hintLeft--; $cd.Text = $script:hint } else { $cd.Text = $fmt -f $script:left }; if ($script:left -le 0) { Finish 'Timeout' } })",
191
+ "$w.Add_ContentRendered({ Install-Guard $w; $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
190
192
  '[void]$w.ShowDialog(); $tm.Stop(); $script:result',
191
193
  ].join('\n');
192
194
 
193
195
  /**
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ờ.
196
+ * 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.
197
+ * `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
198
  */
197
- export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutSec = 30 } = {}) {
198
- if (process.platform !== 'win32') return Promise.resolve(false);
199
+ export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutSec = 45, repeatedAfterBlock = false, signal } = {}) {
200
+ if (process.platform !== 'win32') return Promise.resolve(CastConsentDecision.UNAVAILABLE);
199
201
  return new Promise((resolve) => {
200
202
  let out = '';
201
203
  let settled = false;
202
204
  let timer = null;
203
205
 
204
- const done = (allowed) => {
206
+ const done = (answer) => {
205
207
  if (settled) return;
206
208
  settled = true;
207
209
  if (timer) clearTimeout(timer);
208
- resolve(allowed);
210
+ resolve(answer);
209
211
  };
210
212
 
211
213
  const env = {
212
214
  ...process.env,
213
215
  AIVIN_CAST_XAML: b64(CONSENT_XAML),
214
216
  AIVIN_CAST_LOGO: AIVIN_LOGO_PNG_BASE64,
215
- AIVIN_CAST_TITLE: b64('Aivin — Xác nhận chia sẻ màn hình'),
217
+ AIVIN_CAST_TITLE: b64(CAST_CONSENT_WINDOW_TITLE),
216
218
  AIVIN_CAST_DEVICE: b64(`Thiết bị yêu cầu: ${viewerDevice}`),
217
219
  AIVIN_CAST_COUNTDOWN: b64('Tự từ chối sau {0} giây'),
218
220
  AIVIN_CAST_SECONDS: String(timeoutSec),
221
+ AIVIN_CAST_WARN: repeatedAfterBlock ? '1' : '0',
222
+ ...humanGuardEnv(null),
219
223
  };
220
224
 
221
225
  let child = null;
@@ -226,19 +230,20 @@ export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutS
226
230
  windowsHide: false,
227
231
  });
228
232
  } catch {
229
- return done(false);
233
+ return done(CastConsentDecision.UNAVAILABLE);
230
234
  }
231
235
 
232
- timer = setTimeout(() => {
233
- try { child.kill(); } catch { }
234
- done(false);
235
- }, (timeoutSec + 5) * 1000);
236
+ const kill = () => { try { child.kill(); } catch { } };
237
+ signal?.addEventListener('abort', () => { kill(); done(CastConsentDecision.CANCELLED); }, { once: true });
238
+ timer = setTimeout(() => { kill(); done(CastConsentDecision.TIMEOUT); }, (timeoutSec + 5) * 1000);
236
239
 
237
240
  child.stdout?.on('data', (chunk) => { out += chunk; });
238
- child.on('error', () => done(false));
241
+ child.on('error', () => done(CastConsentDecision.UNAVAILABLE));
239
242
  child.on('close', (code) => {
240
- const allowed = code === 0 && /\bYes\b/.test(out);
241
- done(allowed);
243
+ if (code === 0 && /\bYes\b/.test(out)) return done(CastConsentDecision.ALLOW);
244
+ if (/\bTimeout\b/.test(out)) return done(CastConsentDecision.TIMEOUT);
245
+ if (/\bNo\b/.test(out)) return done(CastConsentDecision.REJECTED);
246
+ return done(CastConsentDecision.UNAVAILABLE);
242
247
  });
243
248
  });
244
249
  }
@@ -0,0 +1,90 @@
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
+ /**
10
+ * Phiên dừng vì máy rớt mạng (không phải chủ máy hay người xem kết thúc): giữ đồng ý bấy nhiêu lâu. Máy chủ giữ phiên
11
+ * chờ máy nối lại rồi mời phát lại đúng phiên đó — hỏi lại thì chủ máy đang điều khiển từ xa bị khoá ngoài (không ai ở máy để bấm).
12
+ */
13
+ export const CONSENT_RESUME_MS = 10 * 60_000;
14
+ /** `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ị. */
15
+ const key = (sessionId, viewerKey, viewerDevice) => `${sessionId}\n${viewerKey || viewerDevice || ''}`;
16
+
17
+ /**
18
+ * 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 đó
19
+ * (người xem rớt mạng nối lại không hỏi lại). Phiên kết thúc hẳn (`forget`) là quên; phiên chỉ gián đoạn (`suspend`: máy rớt mạng) thì giữ thêm
20
+ * `CONSENT_RESUME_MS`. 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.
21
+ */
22
+ export function createCastConsent({ ask, getMode, isLocked = () => false, unlock = () => {}, onWaiting = () => {}, now = Date.now }) {
23
+ /** khoá → hạn (Infinity khi phiên đang chạy). */
24
+ const approved = new Map();
25
+ const pending = new Map();
26
+
27
+ const valid = (k) => {
28
+ const until = approved.get(k);
29
+ if (until === undefined) return false;
30
+ if (until >= now()) return true;
31
+ approved.delete(k);
32
+ return false;
33
+ };
34
+ const keysOf = (sessionId) => [...approved.keys()].filter((k) => k.startsWith(`${sessionId}\n`));
35
+
36
+ function request({ sessionId, viewerId, viewerDevice, viewerKey, locked }) {
37
+ const k = key(sessionId, viewerKey, viewerDevice);
38
+ const open = pending.get(k);
39
+ if (open) return open.promise;
40
+ const controller = new AbortController();
41
+ onWaiting({ sessionId, viewerId, viewerDevice });
42
+ const promise = new Promise((resolve) => resolve(ask({ viewerDevice, locked, signal: controller.signal })))
43
+ .catch(() => CastConsentDecision.UNAVAILABLE)
44
+ .then((answer) => {
45
+ pending.delete(k);
46
+ if (answer === CastConsentDecision.ALLOW) {
47
+ if (approved.size >= MAX_REMEMBERED) approved.clear();
48
+ approved.set(k, Infinity);
49
+ if (locked) unlock();
50
+ }
51
+ return answer;
52
+ });
53
+ pending.set(k, { promise, controller, sessionId, viewerId });
54
+ return promise;
55
+ }
56
+
57
+ return {
58
+ async decide({ sessionId, viewerId, viewerDevice = '', viewerKey = '' }) {
59
+ const mode = getMode();
60
+ if (mode === CastConsentMode.OFF) return CastConsentDecision.DISABLED;
61
+ const locked = isLocked();
62
+ const k = key(sessionId, viewerKey, viewerDevice);
63
+ if (!locked && mode === CastConsentMode.UNATTENDED) return CastConsentDecision.ALLOW;
64
+ if (!locked && valid(k)) {
65
+ // Phiên gián đoạn được mời phát lại: đồng ý cũ có hiệu lực lại cho tới khi phiên kết thúc.
66
+ approved.set(k, Infinity);
67
+ return CastConsentDecision.ALLOW;
68
+ }
69
+ return request({ sessionId, viewerId, viewerDevice, viewerKey, locked });
70
+ },
71
+ /** Người xem rời / huỷ trong lúc đang hỏi: đóng hộp, không bắt đầu chụp. */
72
+ cancel({ sessionId, viewerId, final = true }) {
73
+ for (const open of pending.values()) {
74
+ if (open.sessionId === sessionId && (final || open.viewerId === viewerId)) open.controller.abort();
75
+ }
76
+ },
77
+ /** Tạm dừng / tắt daemon / chủ máy bấm ngắt: đóng mọi hộp đang hỏi (bấm "Cho phép" muộn cũng không còn tác dụng). */
78
+ cancelAll() {
79
+ for (const open of pending.values()) open.controller.abort();
80
+ },
81
+ /** Phiên kết thúc hẳn: quên đồng ý. */
82
+ forget(sessionId) {
83
+ for (const k of keysOf(sessionId)) approved.delete(k);
84
+ },
85
+ /** Phiên chỉ gián đoạn (máy rớt mạng): giữ đồng ý thêm `ms` để phát lại không phải hỏi lại. */
86
+ suspend(sessionId, ms = CONSENT_RESUME_MS) {
87
+ for (const k of keysOf(sessionId)) approved.set(k, Math.min(approved.get(k), now() + ms));
88
+ },
89
+ };
90
+ }
@@ -84,6 +84,26 @@ export function revealInExplorer(file, spawnImpl = spawn) {
84
84
  } catch { /* không mở được thì tệp vẫn đã lưu, FE báo đường dẫn */ }
85
85
  }
86
86
 
87
+ /**
88
+ * Thả nhiều tệp là một thao tác: gom theo lô của từng người xem, tệp cuối tới thì trả cả lô. Lô mới thay lô dở (một tệp giữa chừng bị hỏng).
89
+ */
90
+ export function createDropBatches({ maxFiles = 200 } = {}) {
91
+ const open = new Map();
92
+ return {
93
+ add({ viewerId, batch, path: file, last }) {
94
+ const current = open.get(viewerId);
95
+ const paths = current?.batch === batch ? current.paths : [];
96
+ if (paths.length < maxFiles) paths.push(file);
97
+ if (last) {
98
+ open.delete(viewerId);
99
+ return paths;
100
+ }
101
+ open.set(viewerId, { batch, paths });
102
+ return null;
103
+ },
104
+ };
105
+ }
106
+
87
107
  export function createCastFileDrop({
88
108
  dir = DEFAULT_DIR, reply = () => {}, checkAllowed = () => null, onSaved = () => {},
89
109
  maxBytes = MAX_DROP_BYTES, idleMs = IDLE_TIMEOUT_MS, statfs = fs.promises.statfs, now = Date.now,
@@ -208,6 +228,10 @@ export function createCastFileDrop({
208
228
  bytes: active.size,
209
229
  reveal: msg.reveal === true && !msg.paste,
210
230
  paste: msg.paste === true,
231
+ image: msg.image === true,
232
+ drop: msg.drop === true,
233
+ batch: typeof msg.batch === 'string' ? msg.batch.slice(0, MAX_ID_CHARS) : '',
234
+ last: msg.last === true,
211
235
  x: msg.x,
212
236
  y: msg.y,
213
237
  rx: msg.rx,
@@ -6,7 +6,7 @@
6
6
 
7
7
  export const CAST_INPUT_ACTIONS = Object.freeze([
8
8
  'move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'paste', 'clipboard', 'key', 'hotkey',
9
- 'paste_image', 'paste_file'
9
+ 'paste_image', 'paste_html'
10
10
  ]);
11
11
 
12
12
  export const CastInputRejection = Object.freeze({
@@ -14,6 +14,8 @@ export const CastInputRejection = Object.freeze({
14
14
  PAUSED: 'paused',
15
15
  AI_ACTIVE: 'ai_active',
16
16
  RATE_LIMITED: 'rate_limited',
17
+ /** Người xem khác đang cầm lái (vừa thao tác / đang giữ nút) — hai người không giành chuột cùng lúc. */
18
+ OTHER_VIEWER: 'other_viewer',
17
19
  });
18
20
 
19
21
  const ACTIONS = new Set(CAST_INPUT_ACTIONS);
@@ -23,6 +25,8 @@ const MAX_SCROLL = 10_000;
23
25
  const RATIO_SCALE = 65_535;
24
26
  const MAX_KEY_CHARS = 24;
25
27
  const MAX_PASTE_CHARS = 65_536;
28
+ const MAX_PASTE_IMAGE_CHARS = 25_000_000;
29
+ const MAX_PASTE_HTML_CHARS = 12_000_000;
26
30
 
27
31
  function finiteIn(value, limit) {
28
32
  const n = Number(value);
@@ -53,7 +57,7 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
53
57
  const deltaY = finiteIn(raw.deltaY, MAX_SCROLL);
54
58
  if (deltaX !== undefined) cmd.deltaX = Math.round(deltaX);
55
59
  if (deltaY !== undefined) cmd.deltaY = Math.round(deltaY);
56
- const charLimit = action === 'paste' || action === 'clipboard' ? MAX_PASTE_CHARS : maxTypeChars;
60
+ const charLimit = action === 'paste' || action === 'clipboard' || action === 'paste_html' ? MAX_PASTE_CHARS : maxTypeChars;
57
61
  if (typeof raw.text === 'string' && raw.text) cmd.text = raw.text.slice(0, charLimit);
58
62
  if (typeof raw.key === 'string' && raw.key && raw.key.length <= MAX_KEY_CHARS) cmd.key = raw.key;
59
63
  const keys = shortStrings(raw.keys, 6);
@@ -61,16 +65,16 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
61
65
  const modifiers = shortStrings(raw.modifiers, 4);
62
66
  if (modifiers) cmd.modifiers = modifiers;
63
67
  if (action === 'paste_image') {
64
- if (typeof raw.data !== 'string' || !raw.data) return null;
65
- cmd.data = raw.data.slice(0, 25_000_000); // Tối đa ~18MB ảnh base64
68
+ // Quá trần thì bỏ hẳn: cắt ngắn base64 là ảnh hỏng.
69
+ if (typeof raw.data !== 'string' || !raw.data || raw.data.length > MAX_PASTE_IMAGE_CHARS) return null;
70
+ cmd.data = raw.data;
66
71
  if (typeof raw.mime === 'string') cmd.mime = raw.mime.slice(0, 64);
67
72
  if (raw.click) cmd.click = true;
68
73
  return cmd;
69
74
  }
70
- if (action === 'paste_file') {
71
- if (typeof raw.path !== 'string' || !raw.path) return null;
72
- cmd.path = raw.path;
73
- if (raw.click) cmd.click = true;
75
+ if (action === 'paste_html') {
76
+ if (typeof raw.html !== 'string' || !raw.html || raw.html.length > MAX_PASTE_HTML_CHARS) return null;
77
+ cmd.html = raw.html;
74
78
  return cmd;
75
79
  }
76
80
  if ((action === 'type' || action === 'paste' || action === 'clipboard') && !cmd.text) return null;
@@ -80,50 +84,111 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
80
84
  }
81
85
 
82
86
  /**
83
- * `isPaused()`: công tắc ngắt của chủ máy. `isAiBusy()`: AI đang chạy công cụ GUI ghi. `accept(raw)` → `{ ok, cmd }` hoặc `{ ok: false, reason }`.
84
- * `waitHumanIdle()`: công cụ GUI của AI chờ người thôi thao tác (tối đa `maxWaitMs`) trước khi bấm — hai bên không giành chuột cùng lúc.
87
+ * `isPaused()`: công tắc ngắt của chủ máy. `isAiBusy()`: AI đang chạy công cụ GUI ghi. `accept(raw, viewerId)` → `{ ok, cmd }` hoặc
88
+ * `{ ok: false, reason }`. `waitHumanIdle()`: công cụ GUI của AI chờ người thôi thao tác (tối đa `maxWaitMs`) trước khi bấm — hai bên không
89
+ * giành chuột cùng lúc.
90
+ *
91
+ * Nhiều người xem (09/11/2026): mỗi lúc một người cầm lái — người khác vừa thao tác trong `exclusiveMs` hoặc đang giữ nút thì thao tác của
92
+ * mình bị bỏ (`OTHER_VIEWER`). Nút đang giữ theo dõi theo từng người: một người rời phiên chỉ nhả nút của người đó (`releaseViewer`).
85
93
  */
86
- export function createCastInputGate({ isPaused = () => false, isAiBusy = () => false, maxPerSec = 120, now = Date.now, sleep } = {}) {
94
+ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => false, maxPerSec = 120, exclusiveMs = 1000, now = Date.now, sleep } = {}) {
87
95
  let lastHumanAt = null;
96
+ let takeover = null;
88
97
  let accepted = 0;
89
98
  let window = { start: 0, count: 0 };
90
- /** Nút chuột người xem đang giữ trên máy: gói nhả của chúng luôn được qua cổng, không thì nút kẹt xuống tới hết phiên. */
91
- const heldButtons = new Set();
99
+ /** Người xem đang cầm lái + lúc thao tác cuối của họ. */
100
+ let driver = null;
101
+ let driverAt = -Infinity;
102
+ /** Nút chuột từng người xem đang giữ trên máy: gói nhả của chúng luôn được qua cổng, không thì nút kẹt xuống tới hết phiên. */
103
+ const heldButtons = new Map();
104
+ const heldOf = (viewer) => {
105
+ if (!heldButtons.has(viewer)) heldButtons.set(viewer, new Set());
106
+ return heldButtons.get(viewer);
107
+ };
108
+ const othersHolding = (viewer) => [...heldButtons].some(([v, set]) => v !== viewer && set.size > 0);
92
109
  const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
93
110
 
94
- function accept(raw) {
95
- const releasing = raw?.action === 'mouseup' && heldButtons.has(Number(raw.button) || 0);
96
- const blocked = isPaused() ? CastInputRejection.PAUSED : isAiBusy() ? CastInputRejection.AI_ACTIVE : null;
97
- if (blocked && !releasing) return { ok: false, reason: blocked };
111
+ function accept(raw, viewerId = '') {
112
+ const viewer = String(viewerId ?? '');
113
+ const releasing = raw?.action === 'mouseup' && !!heldButtons.get(viewer)?.has(Number(raw.button) || 0);
98
114
  const t = now();
115
+ const blocked = isPaused() ? CastInputRejection.PAUSED : isAiBusy() ? CastInputRejection.AI_ACTIVE
116
+ : driver !== null && driver !== viewer && (t - driverAt < exclusiveMs || othersHolding(viewer)) ? CastInputRejection.OTHER_VIEWER : null;
117
+ if (blocked && !releasing) return { ok: false, reason: blocked };
99
118
  if (t - window.start >= 1000) window = { start: t, count: 0 };
100
119
  if (++window.count > maxPerSec && !releasing) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
101
120
  const cmd = sanitizeCastInput(raw);
102
121
  if (!cmd) return { ok: false, reason: CastInputRejection.INVALID };
103
- if (cmd.action === 'mousedown') heldButtons.add(cmd.button ?? 0);
104
- if (cmd.action === 'mouseup') heldButtons.delete(cmd.button ?? 0);
122
+ if (cmd.action === 'mousedown') heldOf(viewer).add(cmd.button ?? 0);
123
+ if (cmd.action === 'mouseup') heldButtons.get(viewer)?.delete(cmd.button ?? 0);
105
124
  if (blocked) {
106
- // Chỉ nhả nút, không kéo con trỏ khỏi chỗ AI đang bấm; không tính là người đang thao tác.
125
+ // Chỉ nhả nút, không kéo con trỏ khỏi chỗ AI / người khác đang bấm; không tính là đang thao tác.
107
126
  const { x: _x, y: _y, rx: _rx, ry: _ry, ...release } = cmd;
108
127
  return { ok: true, cmd: release };
109
128
  }
110
129
  lastHumanAt = t;
130
+ driver = viewer;
131
+ driverAt = t;
111
132
  accepted++;
112
133
  return { ok: true, cmd };
113
134
  }
114
135
 
115
- async function waitHumanIdle({ idleMs = 1500, maxWaitMs = 3000 } = {}) {
136
+ /**
137
+ * Người xem rời phiên: trả các nút người đó còn giữ (nơi gọi gửi `mouseup` từng nút) và thả quyền cầm lái của họ. Thao tác đi qua máy chủ
138
+ * (đường JPEG) không mang mã người xem, gộp vào `''`: không biết của ai nên nhả luôn — thà nhả nhầm một lần kéo còn hơn nút kẹt tới hết phiên.
139
+ */
140
+ function releaseViewer(viewerId = '') {
141
+ const buttons = new Set();
142
+ for (const viewer of new Set([String(viewerId ?? ''), ''])) {
143
+ for (const button of heldButtons.get(viewer) || []) buttons.add(button);
144
+ heldButtons.delete(viewer);
145
+ if (driver === viewer) { driver = null; driverAt = -Infinity; }
146
+ }
147
+ return [...buttons];
148
+ }
149
+
150
+ /** Người xem bấm "Bạn" lúc AI đang chạy: `{ idleMs, maxWaitMs }` = bắt đầu tạm cầm lái, `null` = trả lại AI. */
151
+ function setHumanTakeover(opts) {
152
+ takeover = opts?.idleMs > 0 ? { idleMs: opts.idleMs, maxWaitMs: opts.maxWaitMs > 0 ? opts.maxWaitMs : opts.idleMs, at: now() } : null;
153
+ }
154
+
155
+ /** Còn đang tạm cầm lái không — người ngừng thao tác đủ lâu thì quyền tự về AI. */
156
+ function humanTakeoverHeld() {
157
+ if (!takeover) return false;
158
+ if (now() - Math.max(takeover.at, lastHumanAt ?? 0) < takeover.idleMs) return true;
159
+ takeover = null;
160
+ return false;
161
+ }
162
+
163
+ /** Bước GUI kế tiếp có thể phải chờ người tối đa bao lâu (0 = không ai đang cầm lái) — để xin BE lùi hạn của lời gọi. */
164
+ function takeoverWaitMs() { return humanTakeoverHeld() ? takeover.maxWaitMs : 0; }
165
+
166
+ /** `false` = AI chưa được bấm: bị huỷ khi đang chờ, hoặc người vẫn cầm lái tới hết `maxWaitMs` của lần tạm cầm lái. */
167
+ async function waitHumanIdle({ idleMs = 1500, maxWaitMs = 3000, signal } = {}) {
168
+ if (humanTakeoverHeld()) {
169
+ const takeoverDeadline = now() + takeover.maxWaitMs;
170
+ while (humanTakeoverHeld()) {
171
+ if (signal?.aborted || now() >= takeoverDeadline) return false;
172
+ await wait(250);
173
+ }
174
+ }
175
+ if (signal?.aborted) return false;
116
176
  const deadline = now() + maxWaitMs;
117
177
  while (lastHumanAt !== null && now() - lastHumanAt < idleMs && now() < deadline) {
118
178
  await wait(Math.min(250, Math.max(10, idleMs - (now() - lastHumanAt))));
119
179
  }
180
+ return !signal?.aborted;
120
181
  }
121
182
 
122
183
  /** Số thao tác đã nhận từ lần gọi trước (nhật ký phiên trên máy) — đọc xong đặt lại 0. */
123
184
  function takeAcceptedCount() { const n = accepted; accepted = 0; return n; }
124
185
 
125
- /** Máy vừa nhả hết nút (`release_all`): AI sắp bấm hoặc người xem đã rời. Trả có đang giữ nút nào không để nơi gọi biết cần gửi lệnh nhả. */
126
- function takeHeldInput() { const had = heldButtons.size > 0; heldButtons.clear(); return had; }
186
+ /** Máy vừa nhả hết nút (`release_all`): AI sắp bấm hoặc phiên dừng. Trả có đang giữ nút nào không để nơi gọi biết cần gửi lệnh nhả. */
187
+ function takeHeldInput() {
188
+ const had = [...heldButtons.values()].some((set) => set.size > 0);
189
+ heldButtons.clear();
190
+ return had;
191
+ }
127
192
 
128
- return { accept, waitHumanIdle, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
193
+ return { accept, releaseViewer, waitHumanIdle, setHumanTakeover, takeoverWaitMs, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
129
194
  }
@@ -0,0 +1,26 @@
1
+ /** Nhãn thiết bị FE khai lúc xin xem (`detectViewerDevice`) — các nhãn này là màn hình cảm ứng, không có con trỏ để nhìn theo. */
2
+ const TOUCH_DEVICES = new Set(['iphone', 'ipad', 'android']);
3
+
4
+ export function isTouchViewerDevice(device) {
5
+ return typeof device === 'string' && TOUCH_DEVICES.has(device.trim().toLowerCase());
6
+ }
7
+
8
+ /** Theo dõi người xem trong phiên có phải màn hình cảm ứng không. Một người xem không rõ thiết bị được tính là không cảm ứng. */
9
+ export function createCastTouchViewers() {
10
+ const viewers = new Map();
11
+ return {
12
+ add: (viewerId, device) => { viewers.set(viewerId, isTouchViewerDevice(device)); },
13
+ remove: (viewerId) => { viewers.delete(viewerId); },
14
+ clear: () => { viewers.clear(); },
15
+ allTouch: () => viewers.size > 0 && [...viewers.values()].every(Boolean),
16
+ };
17
+ }
18
+
19
+ /**
20
+ * Bộ quay có vẽ con trỏ vào khung hình không.
21
+ * Đường JPEG: chỉ bỏ khi mọi người xem đều cảm ứng, còn người dùng chuột thì họ cần thấy con trỏ.
22
+ * Đường video: theo từng người xem báo tự vẽ hay chưa, để lúc đang ghi hình con trỏ vẫn nằm trong bản ghi.
23
+ */
24
+ export function shouldDrawCursorInFrame({ jpeg, localCursor, allTouch }) {
25
+ return jpeg ? !allTouch : !localCursor;
26
+ }