@aivin-labs/cli 1.0.43 → 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 +35 -7
- package/bin/lib/auth.mjs +24 -10
- package/bin/lib/openFile.mjs +15 -4
- package/bin/lib/projectEnv.mjs +27 -0
- package/bin/lib/remote/client.mjs +146 -54
- package/bin/lib/remote/constants.mjs +5 -1
- package/bin/lib/remote/desktop/castAuth.mjs +235 -0
- package/bin/lib/remote/desktop/castConsent.mjs +59 -0
- package/bin/lib/remote/desktop/castFileDrop.mjs +12 -1
- package/bin/lib/remote/desktop/castInput.mjs +40 -3
- package/bin/lib/remote/desktop/desktopCast.mjs +3 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +212 -20
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +18 -2
- package/bin/lib/remote/desktop/fileAssociation.mjs +1 -1
- package/bin/lib/remote/desktop/strings.mjs +4 -0
- package/bin/lib/remote/desktop/traySource.mjs +74 -13
- package/bin/lib/remote/localPolicy.mjs +15 -2
- package/bin/lib/remote/mascot/bot.mjs +5 -1
- package/bin/lib/remote/mascot/hostSource.mjs +8 -1
- package/bin/lib/remote/mascot/index.mjs +55 -51
- package/bin/lib/remote/mascot/rigSource.mjs +28 -2
- package/bin/lib/remote/policyCommand.mjs +16 -3
- package/bin/lib/remote/sandbox.mjs +6 -4
- package/package.json +1 -1
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { spawn } from 'child_process';
|
|
4
|
+
import { REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
5
|
+
import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
|
|
6
|
+
import { CastConsentDecision } from './castConsent.mjs';
|
|
7
|
+
|
|
8
|
+
export const CAST_SESSION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-session.json');
|
|
9
|
+
export const CAST_ACTION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-action.json');
|
|
10
|
+
export const CAST_PERMISSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-permissions.json');
|
|
11
|
+
|
|
12
|
+
const CAST_STOP_ACTION = Object.freeze({ action: 'stop_and_block' });
|
|
13
|
+
|
|
14
|
+
const b64 = (s) => Buffer.from(String(s ?? ''), 'utf8').toString('base64');
|
|
15
|
+
|
|
16
|
+
function loadPermissions() {
|
|
17
|
+
try {
|
|
18
|
+
const parsed = JSON.parse(fs.readFileSync(CAST_PERMISSIONS_FILE, 'utf8'));
|
|
19
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
20
|
+
} catch {
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function savePermissions(data) {
|
|
26
|
+
try {
|
|
27
|
+
fs.mkdirSync(path.dirname(CAST_PERMISSIONS_FILE), { recursive: true });
|
|
28
|
+
fs.writeFileSync(CAST_PERMISSIONS_FILE, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 });
|
|
29
|
+
} catch { }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
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á.
|
|
36
|
+
*/
|
|
37
|
+
export function isCastLocked() {
|
|
38
|
+
const { locked, blockedViewers } = loadPermissions();
|
|
39
|
+
return locked === true || (Array.isArray(blockedViewers) && blockedViewers.length > 0);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function lockCast({ viewerDevice = '' } = {}) {
|
|
43
|
+
savePermissions({ locked: true, lockedAt: new Date().toISOString(), lastViewerDevice: String(viewerDevice || '') });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function unlockCast() {
|
|
47
|
+
savePermissions({ locked: false });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Ghi nhận thông tin phiên cast đang chạy để khay hệ thống (tray) đọc và hiển thị.
|
|
52
|
+
*/
|
|
53
|
+
export function recordCastSession({ active = true, sessionId = '', viewerId = '', viewerDevice = '' } = {}) {
|
|
54
|
+
try {
|
|
55
|
+
fs.mkdirSync(path.dirname(CAST_SESSION_FILE), { recursive: true });
|
|
56
|
+
const payload = {
|
|
57
|
+
active: !!active,
|
|
58
|
+
session_id: sessionId,
|
|
59
|
+
viewer_id: viewerId,
|
|
60
|
+
viewer_device: viewerDevice,
|
|
61
|
+
updated_at: new Date().toISOString(),
|
|
62
|
+
};
|
|
63
|
+
fs.writeFileSync(CAST_SESSION_FILE, JSON.stringify(payload, null, 2), 'utf8');
|
|
64
|
+
} catch { }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Xoá thông tin phiên cast khi đã ngắt kết nối.
|
|
69
|
+
*/
|
|
70
|
+
export function clearCastSession() {
|
|
71
|
+
try {
|
|
72
|
+
if (fs.existsSync(CAST_SESSION_FILE)) {
|
|
73
|
+
fs.unlinkSync(CAST_SESSION_FILE);
|
|
74
|
+
}
|
|
75
|
+
} catch { }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Kiểm tra xem khay hệ thống có gửi lệnh ngắt / chặn thiết bị cast không.
|
|
80
|
+
*/
|
|
81
|
+
export function checkCastAction() {
|
|
82
|
+
let content;
|
|
83
|
+
try {
|
|
84
|
+
if (!fs.existsSync(CAST_ACTION_FILE)) return null;
|
|
85
|
+
content = fs.readFileSync(CAST_ACTION_FILE, 'utf8');
|
|
86
|
+
fs.unlinkSync(CAST_ACTION_FILE);
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
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;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
108
|
+
Width="500" SizeToContent="Height" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize"
|
|
109
|
+
Topmost="True" ShowInTaskbar="True" WindowStartupLocation="CenterScreen" FontFamily="Segoe UI" UseLayoutRounding="True">
|
|
110
|
+
<Window.Resources>
|
|
111
|
+
<Style x:Key="Btn" TargetType="Button">
|
|
112
|
+
<Setter Property="FontSize" Value="14"/><Setter Property="FontWeight" Value="SemiBold"/><Setter Property="Cursor" Value="Hand"/>
|
|
113
|
+
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
|
114
|
+
<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button">
|
|
115
|
+
<Grid x:Name="root" RenderTransformOrigin="0.5,0.5" Background="Transparent">
|
|
116
|
+
<Border x:Name="b" CornerRadius="10" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"/>
|
|
117
|
+
<ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
|
|
118
|
+
</Grid>
|
|
119
|
+
</ControlTemplate></Setter.Value></Setter>
|
|
120
|
+
</Style>
|
|
121
|
+
<Style x:Key="IconBtn" TargetType="Button">
|
|
122
|
+
<Setter Property="FontSize" Value="12"/><Setter Property="Cursor" Value="Hand"/><Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
|
123
|
+
<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button">
|
|
124
|
+
<Border CornerRadius="8" Background="{TemplateBinding Background}">
|
|
125
|
+
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
|
126
|
+
</Border>
|
|
127
|
+
</ControlTemplate></Setter.Value></Setter>
|
|
128
|
+
</Style>
|
|
129
|
+
</Window.Resources>
|
|
130
|
+
<Border Margin="20" CornerRadius="18" Background="White" BorderBrush="#E5E6EB" BorderThickness="1">
|
|
131
|
+
<Border.Effect><DropShadowEffect BlurRadius="30" ShadowDepth="8" Direction="270" Opacity="0.18" Color="#0B1B3F"/></Border.Effect>
|
|
132
|
+
<StackPanel Margin="26,20,22,24">
|
|
133
|
+
<DockPanel x:Name="Head" Background="Transparent" LastChildFill="False">
|
|
134
|
+
<Image x:Name="Logo" Width="26" Height="26" RenderOptions.BitmapScalingMode="HighQuality" VerticalAlignment="Center"/>
|
|
135
|
+
<TextBlock Text="Aivin" FontSize="15" FontWeight="SemiBold" Foreground="#111827" Margin="9,0,0,0" VerticalAlignment="Center"/>
|
|
136
|
+
<TextBlock Text="• Yêu cầu chia sẻ màn hình" FontSize="13" Foreground="#6B7280" Margin="8,1,0,0" VerticalAlignment="Center"/>
|
|
137
|
+
<Button x:Name="Close" DockPanel.Dock="Right" Style="{StaticResource IconBtn}" Content="✕" Width="32" Height="32"
|
|
138
|
+
Background="Transparent" Foreground="#6B7280" ToolTip="Từ chối" IsTabStop="False"/>
|
|
139
|
+
</DockPanel>
|
|
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"/>
|
|
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"/>
|
|
143
|
+
</Border>
|
|
144
|
+
<Border Margin="0,14,0,0" CornerRadius="10" Background="#F4F6FA" BorderBrush="#E8ECF3" BorderThickness="1" Padding="14,12">
|
|
145
|
+
<StackPanel>
|
|
146
|
+
<TextBlock x:Name="DeviceText" FontSize="14" FontWeight="SemiBold" Foreground="#111827" TextWrapping="Wrap"/>
|
|
147
|
+
<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"/>
|
|
148
|
+
</StackPanel>
|
|
149
|
+
</Border>
|
|
150
|
+
<DockPanel Margin="0,22,0,0" LastChildFill="False">
|
|
151
|
+
<TextBlock x:Name="Countdown" VerticalAlignment="Center" FontSize="12" Foreground="#6B7280"/>
|
|
152
|
+
<Button x:Name="Allow" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0" Margin="10,0,0,0"
|
|
153
|
+
Background="#4E46E5" Foreground="White" BorderThickness="0" Content="_Cho phép"/>
|
|
154
|
+
<Button x:Name="Reject" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0"
|
|
155
|
+
Background="White" Foreground="#111827" BorderBrush="#C9CDD4" BorderThickness="1" Content="_Từ chối" IsCancel="True" IsDefault="True"/>
|
|
156
|
+
</DockPanel>
|
|
157
|
+
</StackPanel>
|
|
158
|
+
</Border>
|
|
159
|
+
</Window>`;
|
|
160
|
+
|
|
161
|
+
const CONSENT_SCRIPT = [
|
|
162
|
+
'Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase',
|
|
163
|
+
'function D($n) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Environment]::GetEnvironmentVariable($n))) }',
|
|
164
|
+
"$w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml](D 'AIVIN_CAST_XAML'))))",
|
|
165
|
+
"$w.Title = D 'AIVIN_CAST_TITLE'",
|
|
166
|
+
"$w.FindName('DeviceText').Text = D 'AIVIN_CAST_DEVICE'",
|
|
167
|
+
"if ($env:AIVIN_CAST_WARN -ne '1') { $w.FindName('Warn').Visibility = 'Collapsed' }",
|
|
168
|
+
"$ms = New-Object IO.MemoryStream(, [Convert]::FromBase64String($env:AIVIN_CAST_LOGO)); $img = New-Object Windows.Media.Imaging.BitmapImage",
|
|
169
|
+
"$img.BeginInit(); $img.StreamSource = $ms; $img.CacheOption = 'OnLoad'; $img.EndInit(); $w.FindName('Logo').Source = $img",
|
|
170
|
+
"$script:result = 'No'; $script:closing = $false",
|
|
171
|
+
'$tm = New-Object Windows.Threading.DispatcherTimer; $tm.Interval = [TimeSpan]::FromSeconds(1)',
|
|
172
|
+
"function Finish($r) { if ($script:closing) { return }; $script:closing = $true; $script:result = $r; $tm.Stop(); $w.Close() }",
|
|
173
|
+
"$w.FindName('Allow').Add_Click({ Finish 'Yes' })",
|
|
174
|
+
"$w.FindName('Reject').Add_Click({ Finish 'No' }); $w.FindName('Close').Add_Click({ Finish 'No' })",
|
|
175
|
+
"$w.FindName('Head').Add_MouseLeftButtonDown({ $w.DragMove() })",
|
|
176
|
+
"$script:left = [int]$env:AIVIN_CAST_SECONDS; $fmt = D 'AIVIN_CAST_COUNTDOWN'; $cd = $w.FindName('Countdown'); $cd.Text = $fmt -f $script:left",
|
|
177
|
+
"$tm.Add_Tick({ $script:left--; $cd.Text = $fmt -f $script:left; if ($script:left -le 0) { Finish 'Timeout' } })",
|
|
178
|
+
"$w.Add_ContentRendered({ $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
|
|
179
|
+
'[void]$w.ShowDialog(); $tm.Stop(); $script:result',
|
|
180
|
+
].join('\n');
|
|
181
|
+
|
|
182
|
+
/**
|
|
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`.
|
|
185
|
+
*/
|
|
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);
|
|
188
|
+
return new Promise((resolve) => {
|
|
189
|
+
let out = '';
|
|
190
|
+
let settled = false;
|
|
191
|
+
let timer = null;
|
|
192
|
+
|
|
193
|
+
const done = (answer) => {
|
|
194
|
+
if (settled) return;
|
|
195
|
+
settled = true;
|
|
196
|
+
if (timer) clearTimeout(timer);
|
|
197
|
+
resolve(answer);
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
const env = {
|
|
201
|
+
...process.env,
|
|
202
|
+
AIVIN_CAST_XAML: b64(CONSENT_XAML),
|
|
203
|
+
AIVIN_CAST_LOGO: AIVIN_LOGO_PNG_BASE64,
|
|
204
|
+
AIVIN_CAST_TITLE: b64('Aivin — Xác nhận chia sẻ màn hình'),
|
|
205
|
+
AIVIN_CAST_DEVICE: b64(`Thiết bị yêu cầu: ${viewerDevice}`),
|
|
206
|
+
AIVIN_CAST_COUNTDOWN: b64('Tự từ chối sau {0} giây'),
|
|
207
|
+
AIVIN_CAST_SECONDS: String(timeoutSec),
|
|
208
|
+
AIVIN_CAST_WARN: repeatedAfterBlock ? '1' : '0',
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
let child = null;
|
|
212
|
+
try {
|
|
213
|
+
child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', CONSENT_SCRIPT], {
|
|
214
|
+
env,
|
|
215
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
216
|
+
windowsHide: false,
|
|
217
|
+
});
|
|
218
|
+
} catch {
|
|
219
|
+
return done(CastConsentDecision.UNAVAILABLE);
|
|
220
|
+
}
|
|
221
|
+
|
|
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);
|
|
225
|
+
|
|
226
|
+
child.stdout?.on('data', (chunk) => { out += chunk; });
|
|
227
|
+
child.on('error', () => done(CastConsentDecision.UNAVAILABLE));
|
|
228
|
+
child.on('close', (code) => {
|
|
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);
|
|
233
|
+
});
|
|
234
|
+
});
|
|
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
|
+
}
|
|
@@ -201,7 +201,18 @@ export function createCastFileDrop({
|
|
|
201
201
|
// Ổ không phải NTFS không có luồng phụ: bỏ qua, tệp vẫn nhận xong.
|
|
202
202
|
if (process.platform === 'win32') await fs.promises.writeFile(`${dest}:Zone.Identifier`, ZONE_IDENTIFIER).catch(() => undefined);
|
|
203
203
|
reply(viewerId, { t: 'saved', id: active.id, name: path.basename(dest), path: dest });
|
|
204
|
-
onSaved({
|
|
204
|
+
onSaved({
|
|
205
|
+
viewerId,
|
|
206
|
+
path: dest,
|
|
207
|
+
name: path.basename(dest),
|
|
208
|
+
bytes: active.size,
|
|
209
|
+
reveal: msg.reveal === true && !msg.paste,
|
|
210
|
+
paste: msg.paste === true,
|
|
211
|
+
x: msg.x,
|
|
212
|
+
y: msg.y,
|
|
213
|
+
rx: msg.rx,
|
|
214
|
+
ry: msg.ry,
|
|
215
|
+
});
|
|
205
216
|
}
|
|
206
217
|
|
|
207
218
|
function message(viewerId, msg) {
|
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
* giao diện, hoặc gửi quá dồn. Thao tác qua kênh WebRTC cũng đi qua đây.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
export const CAST_INPUT_ACTIONS = Object.freeze([
|
|
7
|
+
export const CAST_INPUT_ACTIONS = Object.freeze([
|
|
8
|
+
'move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'paste', 'clipboard', 'key', 'hotkey',
|
|
9
|
+
'paste_image'
|
|
10
|
+
]);
|
|
8
11
|
|
|
9
12
|
export const CastInputRejection = Object.freeze({
|
|
10
13
|
INVALID: 'invalid',
|
|
@@ -57,6 +60,13 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
|
|
|
57
60
|
if (keys) cmd.keys = keys;
|
|
58
61
|
const modifiers = shortStrings(raw.modifiers, 4);
|
|
59
62
|
if (modifiers) cmd.modifiers = modifiers;
|
|
63
|
+
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
|
|
66
|
+
if (typeof raw.mime === 'string') cmd.mime = raw.mime.slice(0, 64);
|
|
67
|
+
if (raw.click) cmd.click = true;
|
|
68
|
+
return cmd;
|
|
69
|
+
}
|
|
60
70
|
if ((action === 'type' || action === 'paste' || action === 'clipboard') && !cmd.text) return null;
|
|
61
71
|
if (action === 'key' && !cmd.key) return null;
|
|
62
72
|
if (action === 'hotkey' && !cmd.keys) return null;
|
|
@@ -69,6 +79,7 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
|
|
|
69
79
|
*/
|
|
70
80
|
export function createCastInputGate({ isPaused = () => false, isAiBusy = () => false, maxPerSec = 120, now = Date.now, sleep } = {}) {
|
|
71
81
|
let lastHumanAt = null;
|
|
82
|
+
let takeover = null;
|
|
72
83
|
let accepted = 0;
|
|
73
84
|
let window = { start: 0, count: 0 };
|
|
74
85
|
/** 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. */
|
|
@@ -96,11 +107,37 @@ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => f
|
|
|
96
107
|
return { ok: true, cmd };
|
|
97
108
|
}
|
|
98
109
|
|
|
99
|
-
|
|
110
|
+
/** 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. */
|
|
111
|
+
function setHumanTakeover(opts) {
|
|
112
|
+
takeover = opts?.idleMs > 0 ? { idleMs: opts.idleMs, maxWaitMs: opts.maxWaitMs > 0 ? opts.maxWaitMs : opts.idleMs, at: now() } : null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 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. */
|
|
116
|
+
function humanTakeoverHeld() {
|
|
117
|
+
if (!takeover) return false;
|
|
118
|
+
if (now() - Math.max(takeover.at, lastHumanAt ?? 0) < takeover.idleMs) return true;
|
|
119
|
+
takeover = null;
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 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. */
|
|
124
|
+
function takeoverWaitMs() { return humanTakeoverHeld() ? takeover.maxWaitMs : 0; }
|
|
125
|
+
|
|
126
|
+
/** `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. */
|
|
127
|
+
async function waitHumanIdle({ idleMs = 1500, maxWaitMs = 3000, signal } = {}) {
|
|
128
|
+
if (humanTakeoverHeld()) {
|
|
129
|
+
const takeoverDeadline = now() + takeover.maxWaitMs;
|
|
130
|
+
while (humanTakeoverHeld()) {
|
|
131
|
+
if (signal?.aborted || now() >= takeoverDeadline) return false;
|
|
132
|
+
await wait(250);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (signal?.aborted) return false;
|
|
100
136
|
const deadline = now() + maxWaitMs;
|
|
101
137
|
while (lastHumanAt !== null && now() - lastHumanAt < idleMs && now() < deadline) {
|
|
102
138
|
await wait(Math.min(250, Math.max(10, idleMs - (now() - lastHumanAt))));
|
|
103
139
|
}
|
|
140
|
+
return !signal?.aborted;
|
|
104
141
|
}
|
|
105
142
|
|
|
106
143
|
/** 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. */
|
|
@@ -109,5 +146,5 @@ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => f
|
|
|
109
146
|
/** 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ả. */
|
|
110
147
|
function takeHeldInput() { const had = heldButtons.size > 0; heldButtons.clear(); return had; }
|
|
111
148
|
|
|
112
|
-
return { accept, waitHumanIdle, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
|
|
149
|
+
return { accept, waitHumanIdle, setHumanTakeover, takeoverWaitMs, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
|
|
113
150
|
}
|
|
@@ -189,6 +189,7 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
|
|
|
189
189
|
});
|
|
190
190
|
|
|
191
191
|
let rl = readline.createInterface({ input: child.stdout });
|
|
192
|
+
let packetSeq = 0;
|
|
192
193
|
|
|
193
194
|
rl.on('line', (line) => {
|
|
194
195
|
let msg;
|
|
@@ -203,6 +204,7 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
|
|
|
203
204
|
} else if (msg.t === 'frame') {
|
|
204
205
|
onFrame?.({
|
|
205
206
|
sessionId: session.sessionId,
|
|
207
|
+
seq: ++packetSeq,
|
|
206
208
|
image: msg.image,
|
|
207
209
|
width: msg.width,
|
|
208
210
|
height: msg.height,
|
|
@@ -219,6 +221,7 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
|
|
|
219
221
|
} else if (msg.t === 'meta') {
|
|
220
222
|
onMeta?.({
|
|
221
223
|
sessionId: session.sessionId,
|
|
224
|
+
seq: ++packetSeq,
|
|
222
225
|
width: msg.width,
|
|
223
226
|
height: msg.height,
|
|
224
227
|
screenWidth: msg.screenWidth,
|