@aivin-labs/cli 1.0.57 → 1.0.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.mjs +2 -1
- package/bin/lib/auth.mjs +119 -88
- package/bin/lib/context.mjs +58 -5
- package/bin/lib/loginHandoff.mjs +87 -0
- package/bin/lib/openFile.mjs +29 -4
- package/bin/lib/remote/client.mjs +1456 -1454
- package/bin/lib/remote/credentials.mjs +131 -125
- package/bin/lib/remote/desktop/castAuth.mjs +274 -259
- package/bin/lib/remote/desktop/castConsent.mjs +155 -154
- package/bin/lib/remote/desktop/castTrust.mjs +220 -183
- package/bin/lib/remote/desktop/desktopCastSource.mjs +77 -31
- package/bin/lib/remote/desktop/strings.mjs +158 -138
- package/bin/lib/remote/desktop/traySource.mjs +89 -15
- package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
- package/bin/lib/remote/dpapiHelper.mjs +91 -0
- package/bin/lib/remote/gui/index.mjs +839 -567
- package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -2127
- package/bin/lib/remote/tokenStore.mjs +19 -2
- package/package.json +1 -1
|
@@ -1,184 +1,221 @@
|
|
|
1
|
-
import { createHash, createHmac, createPublicKey, randomBytes, timingSafeEqual, verify } from 'crypto';
|
|
2
|
-
import fs from 'fs';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import { writeFileAtomic } from '../atomicFile.mjs';
|
|
5
|
-
import { CastState, REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
6
|
-
import { openToken, sealToken } from '../tokenStore.mjs';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Thiết bị người ở máy đã bấm "Luôn cho phép" (09/11/2026): lần sau vào xem không phải hỏi lại.
|
|
10
|
-
*
|
|
11
|
-
* Trình duyệt giữ khoá riêng không xuất ra được, máy chỉ lưu khoá công khai và mỗi lần vào bắt ký một chuỗi ngẫu nhiên do chính máy sinh —
|
|
12
|
-
* máy chủ chuyển tin nhưng không tự chứng minh thay được, nghe lén một lần cũng không dùng lại được. Danh sách có chữ ký bằng khoá cất trong
|
|
13
|
-
* kho bí mật của hệ điều hành: AI hay script trên máy ghi thêm vào tệp thì chữ ký sai, cả danh sách coi như rỗng (lại hỏi người ở máy).
|
|
14
|
-
* Giới hạn như `humanInput.mjs`: mã độc cùng tài khoản hệ điều hành gọi được kho bí mật thì vẫn lách được.
|
|
15
|
-
*/
|
|
16
|
-
export const CAST_TRUST_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-trusted-devices.json');
|
|
17
|
-
export const CAST_TRUST_KEY_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-trusted-devices.key');
|
|
18
|
-
/** Không dùng quá ngần này thì thiết bị hết được tin. */
|
|
19
|
-
export const CAST_TRUST_TTL_MS = 30 * 86_400_000;
|
|
20
|
-
|
|
21
|
-
const MAX_DEVICES = 20;
|
|
22
|
-
const KEY_ACCOUNT = 'cast-trusted-devices';
|
|
23
|
-
const PROOF_PREFIX = 'aivin-cast-device-proof';
|
|
24
|
-
const MAX_KEY_CHARS = 300;
|
|
25
|
-
const MAX_NAME_CHARS = 60;
|
|
26
|
-
const PROOF_TIMEOUT_MS = 8000;
|
|
27
|
-
|
|
28
|
-
/** Khoá công khai P-256 (SPKI, base64) hợp lệ → đối tượng khoá; khác đi → `null`. */
|
|
29
|
-
function parseDeviceKey(deviceKey) {
|
|
30
|
-
if (typeof deviceKey !== 'string' || !deviceKey || deviceKey.length > MAX_KEY_CHARS) return null;
|
|
31
|
-
try {
|
|
32
|
-
const key = createPublicKey({ key: Buffer.from(deviceKey, 'base64'), format: 'der', type: 'spki' });
|
|
33
|
-
return key.asymmetricKeyType === 'ec' && key.asymmetricKeyDetails?.namedCurve === 'prime256v1' ? key : null;
|
|
34
|
-
} catch {
|
|
35
|
-
return null;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Tên do trình duyệt tự khai, chỉ để hiện: bỏ ký tự lạ để khay đọc tệp không vỡ. */
|
|
40
|
-
const safeName = (name) => String(name ?? '').replace(/[^\p{L}\p{N} ._·-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, MAX_NAME_CHARS) || 'Thiết bị';
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
1
|
+
import { createHash, createHmac, createPublicKey, randomBytes, timingSafeEqual, verify } from 'crypto';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { writeFileAtomic } from '../atomicFile.mjs';
|
|
5
|
+
import { CastState, REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
6
|
+
import { openToken, sealToken } from '../tokenStore.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Thiết bị người ở máy đã bấm "Luôn cho phép" (09/11/2026): lần sau vào xem không phải hỏi lại.
|
|
10
|
+
*
|
|
11
|
+
* Trình duyệt giữ khoá riêng không xuất ra được, máy chỉ lưu khoá công khai và mỗi lần vào bắt ký một chuỗi ngẫu nhiên do chính máy sinh —
|
|
12
|
+
* máy chủ chuyển tin nhưng không tự chứng minh thay được, nghe lén một lần cũng không dùng lại được. Danh sách có chữ ký bằng khoá cất trong
|
|
13
|
+
* kho bí mật của hệ điều hành: AI hay script trên máy ghi thêm vào tệp thì chữ ký sai, cả danh sách coi như rỗng (lại hỏi người ở máy).
|
|
14
|
+
* Giới hạn như `humanInput.mjs`: mã độc cùng tài khoản hệ điều hành gọi được kho bí mật thì vẫn lách được.
|
|
15
|
+
*/
|
|
16
|
+
export const CAST_TRUST_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-trusted-devices.json');
|
|
17
|
+
export const CAST_TRUST_KEY_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-trusted-devices.key');
|
|
18
|
+
/** Không dùng quá ngần này thì thiết bị hết được tin. */
|
|
19
|
+
export const CAST_TRUST_TTL_MS = 30 * 86_400_000;
|
|
20
|
+
|
|
21
|
+
const MAX_DEVICES = 20;
|
|
22
|
+
const KEY_ACCOUNT = 'cast-trusted-devices';
|
|
23
|
+
const PROOF_PREFIX = 'aivin-cast-device-proof';
|
|
24
|
+
const MAX_KEY_CHARS = 300;
|
|
25
|
+
const MAX_NAME_CHARS = 60;
|
|
26
|
+
const PROOF_TIMEOUT_MS = 8000;
|
|
27
|
+
|
|
28
|
+
/** Khoá công khai P-256 (SPKI, base64) hợp lệ → đối tượng khoá; khác đi → `null`. */
|
|
29
|
+
function parseDeviceKey(deviceKey) {
|
|
30
|
+
if (typeof deviceKey !== 'string' || !deviceKey || deviceKey.length > MAX_KEY_CHARS) return null;
|
|
31
|
+
try {
|
|
32
|
+
const key = createPublicKey({ key: Buffer.from(deviceKey, 'base64'), format: 'der', type: 'spki' });
|
|
33
|
+
return key.asymmetricKeyType === 'ec' && key.asymmetricKeyDetails?.namedCurve === 'prime256v1' ? key : null;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Tên do trình duyệt tự khai, chỉ để hiện: bỏ ký tự lạ để khay đọc tệp không vỡ. */
|
|
40
|
+
const safeName = (name) => String(name ?? '').replace(/[^\p{L}\p{N} ._·-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, MAX_NAME_CHARS) || 'Thiết bị';
|
|
41
|
+
|
|
42
|
+
/** Nơi / IP / tài khoản máy chủ gửi kèm, chỉ để hiện: lọc như tên (khay đọc tệp bằng regex, không được có `"` hay `\`). */
|
|
43
|
+
const safePlace = (text) => String(text ?? '').replace(/[^\p{L}\p{N} .,'’&-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 80);
|
|
44
|
+
export const safeViewerIp = (ip) => (typeof ip === 'string' && /^[0-9A-Fa-f:.]{2,45}$/.test(ip) ? ip : '');
|
|
45
|
+
export const safeViewerAccount = (account) => (typeof account === 'string' ? account.replace(/[^A-Za-z0-9._@•+-]/g, '').slice(0, 80) : '');
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Vị trí gần đúng theo IP (BE tra từ Cloudflare / bộ dữ liệu quốc gia), ví dụ `{ city: 'Hanoi', country: 'VN' }` → "Hanoi, Việt Nam".
|
|
49
|
+
* Chỉ để chủ máy nhận ra thiết bị lạ; không bao giờ dùng để quyết định cho vào.
|
|
50
|
+
*/
|
|
51
|
+
export function castViewerPlace(location, lang = 'vi') {
|
|
52
|
+
if (!location || typeof location !== 'object') return '';
|
|
53
|
+
const local = safePlace(location.city) || safePlace(location.region);
|
|
54
|
+
const code = String(location.country || '').toUpperCase();
|
|
55
|
+
let country = '';
|
|
56
|
+
if (/^[A-Z]{2}$/.test(code)) {
|
|
57
|
+
try { country = new Intl.DisplayNames([lang, 'en'], { type: 'region' }).of(code) || code; } catch { country = code; }
|
|
58
|
+
}
|
|
59
|
+
return safePlace([local, country].filter(Boolean).join(', '));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Thông tin người xem để hiện cho chủ máy, đã lọc: `{ place, ip, account }` (trường rỗng = không biết). */
|
|
63
|
+
export function castViewerInfo(payload, lang = 'vi') {
|
|
64
|
+
return {
|
|
65
|
+
place: castViewerPlace(payload?.viewer_location, lang),
|
|
66
|
+
ip: safeViewerIp(payload?.viewer_ip),
|
|
67
|
+
account: safeViewerAccount(payload?.viewer_account),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Thông tin người xem chỉ lưu khi có giá trị — bản ghi cũ / máy chủ đời cũ không có thì giữ nguyên trường cũ. */
|
|
72
|
+
const infoFields = ({ place, ip, account } = {}) => ({
|
|
73
|
+
...(safePlace(place) ? { place: safePlace(place) } : {}),
|
|
74
|
+
...(safeViewerIp(ip) ? { ip: safeViewerIp(ip) } : {}),
|
|
75
|
+
...(safeViewerAccount(account) ? { account: safeViewerAccount(account) } : {}),
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const VIEWER_CODE_CHARS = 6;
|
|
79
|
+
/** Chừa chỗ cho " - <mã>" để cắt theo `MAX_NAME_CHARS` khi lưu không làm mất mã. */
|
|
80
|
+
const VIEWER_NAME_CHARS = MAX_NAME_CHARS - VIEWER_CODE_CHARS - 3;
|
|
81
|
+
|
|
82
|
+
/**
|
|
47
83
|
* Tên hiện cho chủ máy: FE khai loại máy + model (chỉ Android có) + trình duyệt, vẫn có thể trùng giữa hai máy nên ghép thêm mã suy ra từ khoá
|
|
48
|
-
* của thiết bị, ví dụ "Android SM-S918B · Chrome - 7F3A9C".
|
|
49
|
-
* Trình duyệt không có khoá (ẩn danh, chặn IndexedDB) thì lấy `viewerKey`: vẫn phân biệt được nhưng đổi mạng là đổi mã.
|
|
50
|
-
* Chỉ để hiện: danh tính thật vẫn là khoá, và loại máy gốc vẫn dùng riêng cho `isTouchViewerDevice` (so khớp đúng chuỗi).
|
|
51
|
-
*/
|
|
52
|
-
export function castViewerLabel(viewerDevice, deviceKey, viewerKey) {
|
|
53
|
-
const identity = deviceKey || viewerKey;
|
|
54
|
-
if (!identity) return viewerDevice;
|
|
55
|
-
const code = createHash('sha256').update(String(identity)).digest('hex').slice(0, VIEWER_CODE_CHARS).toUpperCase();
|
|
56
|
-
return `${safeName(viewerDevice).slice(0, VIEWER_NAME_CHARS).trim()} - ${code}`;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** `signature`: base64 của chữ ký ECDSA dạng WebCrypto (r || s) trên `aivin-cast-device-proof\n<mã phiên>\n<chuỗi ngẫu nhiên>`. */
|
|
60
|
-
export function verifyDeviceProof({ deviceKey, sessionId, nonce, signature }) {
|
|
61
|
-
const key = parseDeviceKey(deviceKey);
|
|
62
|
-
if (!key || typeof signature !== 'string' || !signature) return false;
|
|
63
|
-
try {
|
|
64
|
-
return verify('sha256', Buffer.from(`${PROOF_PREFIX}\n${sessionId}\n${nonce}`), { key, dsaEncoding: 'ieee-p1363' }, Buffer.from(signature, 'base64'));
|
|
65
|
-
} catch {
|
|
66
|
-
return false;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function createCastTrust({ file = CAST_TRUST_FILE, keyFile = CAST_TRUST_KEY_FILE, now = Date.now } = {}) {
|
|
71
|
-
/** Giải kho bí mật tốn một tiến trình con: nhớ theo bản mã trong tệp khoá. */
|
|
72
|
-
let cached = null;
|
|
73
|
-
|
|
74
|
-
function secret({ create = false } = {}) {
|
|
75
|
-
let record = null;
|
|
76
|
-
try { record = JSON.parse(fs.readFileSync(keyFile, 'utf8')); } catch { /* chưa có */ }
|
|
77
|
-
const fingerprint = record ? `${record.token_store || ''}:${record.token_enc || record.device_token || ''}` : null;
|
|
78
|
-
if (fingerprint && cached?.fingerprint === fingerprint) return cached.key;
|
|
79
|
-
let key = record ? openToken(record) : null;
|
|
80
|
-
if (!key && create) {
|
|
81
|
-
key = randomBytes(32).toString('hex');
|
|
82
|
-
const { fallback_reason: _why, ...sealed } = sealToken(key, { account: KEY_ACCOUNT });
|
|
83
|
-
writeFileAtomic(keyFile, `${JSON.stringify({ device_id: KEY_ACCOUNT, ...sealed }, null, 2)}\n`);
|
|
84
|
-
cached = { fingerprint: `${sealed.token_store || ''}:${sealed.token_enc || sealed.device_token || ''}`, key };
|
|
85
|
-
return key;
|
|
86
|
-
}
|
|
87
|
-
if (key) cached = { fingerprint, key };
|
|
88
|
-
return key;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const sign = (devices, key) => createHmac('sha256', key).update(JSON.stringify(devices)).digest('hex');
|
|
92
|
-
|
|
93
|
-
function sealMatches(devices, seal, key) {
|
|
94
|
-
if (typeof seal !== 'string' || !key) return false;
|
|
95
|
-
const expected = Buffer.from(sign(devices, key), 'hex');
|
|
96
|
-
const actual = Buffer.from(seal, 'hex');
|
|
97
|
-
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/** Thiết bị còn hạn trong danh sách đúng chữ ký; sai chữ ký / hỏng tệp → rỗng (lại hỏi người ở máy, không bao giờ tự cho vào). */
|
|
101
|
-
function list() {
|
|
102
|
-
let raw;
|
|
103
|
-
try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return []; }
|
|
104
|
-
const devices = Array.isArray(raw?.devices) ? raw.devices : [];
|
|
105
|
-
if (!devices.length || !sealMatches(devices, raw.seal, secret())) return [];
|
|
106
|
-
return devices.filter((d) => d?.expires_at >= now());
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function save(devices) {
|
|
110
|
-
const key = secret({ create: devices.length > 0 });
|
|
111
|
-
writeFileAtomic(file, `${JSON.stringify({ devices, ...(key ? { seal: sign(devices, key) } : {}) }, null, 2)}\n`);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
return {
|
|
115
|
-
list,
|
|
116
|
-
/** Khoá này đủ điều kiện để lưu (trình duyệt cũ / khoá hỏng thì hộp hỏi không hiện nút "Luôn cho phép"). */
|
|
117
|
-
accepts: (deviceKey) => parseDeviceKey(deviceKey) !== null,
|
|
118
|
-
has: (deviceKey) => list().some((d) => d.key === deviceKey),
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
* `
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
open.
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
timer
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
84
|
+
* của thiết bị, ví dụ "Android SM-S918B · Chrome - 7F3A9C".
|
|
85
|
+
* Trình duyệt không có khoá (ẩn danh, chặn IndexedDB) thì lấy `viewerKey`: vẫn phân biệt được nhưng đổi mạng là đổi mã.
|
|
86
|
+
* Chỉ để hiện: danh tính thật vẫn là khoá, và loại máy gốc vẫn dùng riêng cho `isTouchViewerDevice` (so khớp đúng chuỗi).
|
|
87
|
+
*/
|
|
88
|
+
export function castViewerLabel(viewerDevice, deviceKey, viewerKey) {
|
|
89
|
+
const identity = deviceKey || viewerKey;
|
|
90
|
+
if (!identity) return viewerDevice;
|
|
91
|
+
const code = createHash('sha256').update(String(identity)).digest('hex').slice(0, VIEWER_CODE_CHARS).toUpperCase();
|
|
92
|
+
return `${safeName(viewerDevice).slice(0, VIEWER_NAME_CHARS).trim()} - ${code}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** `signature`: base64 của chữ ký ECDSA dạng WebCrypto (r || s) trên `aivin-cast-device-proof\n<mã phiên>\n<chuỗi ngẫu nhiên>`. */
|
|
96
|
+
export function verifyDeviceProof({ deviceKey, sessionId, nonce, signature }) {
|
|
97
|
+
const key = parseDeviceKey(deviceKey);
|
|
98
|
+
if (!key || typeof signature !== 'string' || !signature) return false;
|
|
99
|
+
try {
|
|
100
|
+
return verify('sha256', Buffer.from(`${PROOF_PREFIX}\n${sessionId}\n${nonce}`), { key, dsaEncoding: 'ieee-p1363' }, Buffer.from(signature, 'base64'));
|
|
101
|
+
} catch {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function createCastTrust({ file = CAST_TRUST_FILE, keyFile = CAST_TRUST_KEY_FILE, now = Date.now } = {}) {
|
|
107
|
+
/** Giải kho bí mật tốn một tiến trình con: nhớ theo bản mã trong tệp khoá. */
|
|
108
|
+
let cached = null;
|
|
109
|
+
|
|
110
|
+
function secret({ create = false } = {}) {
|
|
111
|
+
let record = null;
|
|
112
|
+
try { record = JSON.parse(fs.readFileSync(keyFile, 'utf8')); } catch { /* chưa có */ }
|
|
113
|
+
const fingerprint = record ? `${record.token_store || ''}:${record.token_enc || record.device_token || ''}` : null;
|
|
114
|
+
if (fingerprint && cached?.fingerprint === fingerprint) return cached.key;
|
|
115
|
+
let key = record ? openToken(record) : null;
|
|
116
|
+
if (!key && create) {
|
|
117
|
+
key = randomBytes(32).toString('hex');
|
|
118
|
+
const { fallback_reason: _why, ...sealed } = sealToken(key, { account: KEY_ACCOUNT });
|
|
119
|
+
writeFileAtomic(keyFile, `${JSON.stringify({ device_id: KEY_ACCOUNT, ...sealed }, null, 2)}\n`);
|
|
120
|
+
cached = { fingerprint: `${sealed.token_store || ''}:${sealed.token_enc || sealed.device_token || ''}`, key };
|
|
121
|
+
return key;
|
|
122
|
+
}
|
|
123
|
+
if (key) cached = { fingerprint, key };
|
|
124
|
+
return key;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const sign = (devices, key) => createHmac('sha256', key).update(JSON.stringify(devices)).digest('hex');
|
|
128
|
+
|
|
129
|
+
function sealMatches(devices, seal, key) {
|
|
130
|
+
if (typeof seal !== 'string' || !key) return false;
|
|
131
|
+
const expected = Buffer.from(sign(devices, key), 'hex');
|
|
132
|
+
const actual = Buffer.from(seal, 'hex');
|
|
133
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Thiết bị còn hạn trong danh sách đúng chữ ký; sai chữ ký / hỏng tệp → rỗng (lại hỏi người ở máy, không bao giờ tự cho vào). */
|
|
137
|
+
function list() {
|
|
138
|
+
let raw;
|
|
139
|
+
try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return []; }
|
|
140
|
+
const devices = Array.isArray(raw?.devices) ? raw.devices : [];
|
|
141
|
+
if (!devices.length || !sealMatches(devices, raw.seal, secret())) return [];
|
|
142
|
+
return devices.filter((d) => d?.expires_at >= now());
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function save(devices) {
|
|
146
|
+
const key = secret({ create: devices.length > 0 });
|
|
147
|
+
writeFileAtomic(file, `${JSON.stringify({ devices, ...(key ? { seal: sign(devices, key) } : {}) }, null, 2)}\n`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
list,
|
|
152
|
+
/** Khoá này đủ điều kiện để lưu (trình duyệt cũ / khoá hỏng thì hộp hỏi không hiện nút "Luôn cho phép"). */
|
|
153
|
+
accepts: (deviceKey) => parseDeviceKey(deviceKey) !== null,
|
|
154
|
+
has: (deviceKey) => list().some((d) => d.key === deviceKey),
|
|
155
|
+
/** `info`: `{ place, ip, account }` lúc bấm "Luôn cho phép" — khay hiện để chủ máy nhận ra thiết bị (và tài khoản bị lộ nếu thấy lạ). */
|
|
156
|
+
add({ key, name, info }) {
|
|
157
|
+
if (!parseDeviceKey(key)) return false;
|
|
158
|
+
const t = now();
|
|
159
|
+
const others = list().filter((d) => d.key !== key).sort((a, b) => b.last_used_at - a.last_used_at).slice(0, MAX_DEVICES - 1);
|
|
160
|
+
save([{ key, name: safeName(name), ...infoFields(info), added_at: new Date(t).toISOString(), last_used_at: t, expires_at: t + CAST_TRUST_TTL_MS }, ...others]);
|
|
161
|
+
return true;
|
|
162
|
+
},
|
|
163
|
+
/** Vừa vào bằng quyền tin: tính lại hạn từ lần dùng này, ghi lại nơi / IP lần dùng này. */
|
|
164
|
+
touch(key, info) {
|
|
165
|
+
const t = now();
|
|
166
|
+
const devices = list();
|
|
167
|
+
if (devices.some((d) => d.key === key)) save(devices.map((d) => (d.key === key ? { ...d, ...infoFields(info), last_used_at: t, expires_at: t + CAST_TRUST_TTL_MS } : d)));
|
|
168
|
+
},
|
|
169
|
+
remove(key) {
|
|
170
|
+
const devices = list();
|
|
171
|
+
const kept = devices.filter((d) => d.key !== key);
|
|
172
|
+
if (kept.length !== devices.length) save(kept);
|
|
173
|
+
},
|
|
174
|
+
removeAll: () => save([]),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Bắt thiết bị chứng minh có khoá riêng: gửi chuỗi ngẫu nhiên, chờ chữ ký quay lại. `prove` trả `true` / `false` (sai, quá giờ),
|
|
180
|
+
* `null` khi người xem đã rời trong lúc chờ.
|
|
181
|
+
*/
|
|
182
|
+
export function createDeviceProver({ send, timeoutMs = PROOF_TIMEOUT_MS }) {
|
|
183
|
+
const pending = new Map();
|
|
184
|
+
|
|
185
|
+
const settle = (viewerId, result) => {
|
|
186
|
+
const open = pending.get(viewerId);
|
|
187
|
+
if (!open) return;
|
|
188
|
+
pending.delete(viewerId);
|
|
189
|
+
clearTimeout(open.timer);
|
|
190
|
+
open.resolve(result);
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
prove({ sessionId, viewerId, deviceKey }) {
|
|
195
|
+
const viewer = String(viewerId);
|
|
196
|
+
settle(viewer, null);
|
|
197
|
+
const nonce = randomBytes(32).toString('base64');
|
|
198
|
+
return new Promise((resolve) => {
|
|
199
|
+
const timer = setTimeout(() => settle(viewer, false), timeoutMs);
|
|
200
|
+
timer.unref?.();
|
|
201
|
+
pending.set(viewer, { sessionId, deviceKey, nonce, resolve, timer });
|
|
202
|
+
try {
|
|
203
|
+
send({ session_id: sessionId, viewer_id: viewer, state: CastState.DEVICE_CHALLENGE, nonce });
|
|
204
|
+
} catch {
|
|
205
|
+
settle(viewer, false);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
},
|
|
209
|
+
/** Chữ ký người xem gửi về (tin `device_proof` trên đường tín hiệu; `sdp` mang chữ ký). */
|
|
210
|
+
answer({ viewer_id: viewerId, session_id: sessionId, sdp: signature }) {
|
|
211
|
+
const viewer = String(viewerId);
|
|
212
|
+
const open = pending.get(viewer);
|
|
213
|
+
if (!open || open.sessionId !== sessionId) return;
|
|
214
|
+
settle(viewer, verifyDeviceProof({ deviceKey: open.deviceKey, sessionId, nonce: open.nonce, signature }));
|
|
215
|
+
},
|
|
216
|
+
/** Không truyền `viewerId` = huỷ tất cả. */
|
|
217
|
+
cancel(viewerId) {
|
|
218
|
+
for (const viewer of viewerId === undefined ? [...pending.keys()] : [String(viewerId)]) settle(viewer, null);
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
}
|
|
@@ -478,7 +478,6 @@ namespace AivinDesktopCast {
|
|
|
478
478
|
static byte[] scaleRaw;
|
|
479
479
|
static byte[] scaleOut;
|
|
480
480
|
static byte[] i420Out;
|
|
481
|
-
static Bitmap cursorBuffer;
|
|
482
481
|
static Bitmap scaleBuffer;
|
|
483
482
|
static Bitmap thumbBmp;
|
|
484
483
|
static byte[] thumbRaw;
|
|
@@ -591,35 +590,71 @@ namespace AivinDesktopCast {
|
|
|
591
590
|
}
|
|
592
591
|
}
|
|
593
592
|
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
593
|
+
const int CURSOR_PATCH = 128;
|
|
594
|
+
static Bitmap cursorPatch;
|
|
595
|
+
static byte[] cursorSaved;
|
|
596
|
+
static Rectangle cursorSavedRect = Rectangle.Empty;
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Vẽ con trỏ thật của Windows thẳng lên khung, chỉ đụng vùng CURSOR_PATCH quanh con trỏ; RestoreCursorPatch trả vùng đó về như cũ sau khi
|
|
600
|
+
* khung đã gửi (khung còn dùng để so thay đổi và lần sau chỉ con trỏ đổi thì không chụp lại). Trước đây chép nguyên khung sang bản sao rồi vẽ:
|
|
601
|
+
* đo 13/11/2026 tốn 19,4 ms mỗi khung 1920×1080, là khâu đắt nhất của bộ quay. Trả về false khi không vẽ gì.
|
|
602
|
+
*/
|
|
603
|
+
public static bool DrawCursorInPlace(Bitmap frame, Rectangle r) {
|
|
604
|
+
cursorSavedRect = Rectangle.Empty;
|
|
605
|
+
try {
|
|
606
|
+
Native.CURSORINFO pci;
|
|
607
|
+
pci.cbSize = Marshal.SizeOf(typeof(Native.CURSORINFO));
|
|
608
|
+
if (!Native.GetCursorInfo(out pci) || (pci.flags & Native.CURSOR_SHOWING) == 0) return false;
|
|
609
|
+
IntPtr shape = SystemCursorHider.ShapeOf(pci.hCursor);
|
|
610
|
+
var hot = CursorTracker.Hotspot(shape);
|
|
611
|
+
int cursorX = pci.ptScreenPos.x - hot.X - r.Left;
|
|
612
|
+
int cursorY = pci.ptScreenPos.y - hot.Y - r.Top;
|
|
613
|
+
var area = Rectangle.Intersect(new Rectangle(cursorX, cursorY, CURSOR_PATCH, CURSOR_PATCH), new Rectangle(0, 0, frame.Width, frame.Height));
|
|
614
|
+
if (area.Width <= 0 || area.Height <= 0) return false;
|
|
615
|
+
if (cursorPatch == null) cursorPatch = new Bitmap(CURSOR_PATCH, CURSOR_PATCH, PixelFormat.Format32bppRgb);
|
|
616
|
+
int rowBytes = area.Width * 4;
|
|
617
|
+
if (cursorSaved == null) cursorSaved = new byte[CURSOR_PATCH * CURSOR_PATCH * 4];
|
|
618
|
+
CopyRegion(frame, area, cursorSaved, true);
|
|
619
|
+
CopyRegion(cursorPatch, new Rectangle(0, 0, area.Width, area.Height), cursorSaved, false);
|
|
620
|
+
using (var g = Graphics.FromImage(cursorPatch)) {
|
|
621
|
+
IntPtr hdc = g.GetHdc();
|
|
622
|
+
try {
|
|
623
|
+
Native.DrawIcon(hdc, cursorX - area.X, cursorY - area.Y, shape);
|
|
624
|
+
} finally {
|
|
625
|
+
g.ReleaseHdc(hdc);
|
|
619
626
|
}
|
|
620
|
-
}
|
|
627
|
+
}
|
|
628
|
+
var drawn = new byte[area.Height * rowBytes];
|
|
629
|
+
CopyRegion(cursorPatch, new Rectangle(0, 0, area.Width, area.Height), drawn, true);
|
|
630
|
+
CopyRegion(frame, area, drawn, false);
|
|
631
|
+
cursorSavedRect = area;
|
|
632
|
+
return true;
|
|
633
|
+
} catch {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** Trả vùng dưới con trỏ về ảnh màn hình thật (xem DrawCursorInPlace). */
|
|
639
|
+
public static void RestoreCursorPatch(Bitmap frame) {
|
|
640
|
+
if (cursorSavedRect.IsEmpty) return;
|
|
641
|
+
try { CopyRegion(frame, cursorSavedRect, cursorSaved, false); } catch { }
|
|
642
|
+
cursorSavedRect = Rectangle.Empty;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** Chép từng hàng giữa một vùng của bitmap 32bpp và mảng liền (hàng nối tiếp, mỗi hàng area.Width * 4 byte). */
|
|
646
|
+
static void CopyRegion(Bitmap bmp, Rectangle area, byte[] buffer, bool toBuffer) {
|
|
647
|
+
var data = bmp.LockBits(area, toBuffer ? ImageLockMode.ReadOnly : ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
|
|
648
|
+
try {
|
|
649
|
+
int rowBytes = area.Width * 4;
|
|
650
|
+
for (int y = 0; y < area.Height; y++) {
|
|
651
|
+
var row = new IntPtr(data.Scan0.ToInt64() + (long)y * data.Stride);
|
|
652
|
+
if (toBuffer) Marshal.Copy(row, buffer, y * rowBytes, rowBytes);
|
|
653
|
+
else Marshal.Copy(buffer, y * rowBytes, row, rowBytes);
|
|
654
|
+
}
|
|
655
|
+
} finally {
|
|
656
|
+
bmp.UnlockBits(data);
|
|
621
657
|
}
|
|
622
|
-
return cursorBuffer;
|
|
623
658
|
}
|
|
624
659
|
|
|
625
660
|
/** Song tuyến tính chia theo hàng trên nhiều nhân: GDI+ DrawImage chỉ chạy một nhân, đo 14 ms mỗi khung từ 1080p xuống 1280, là khâu đắt nhất của bộ quay. */
|
|
@@ -923,6 +958,10 @@ namespace AivinDesktopCast {
|
|
|
923
958
|
|
|
924
959
|
public static void Run(string argsJson) {
|
|
925
960
|
Native.UsePerMonitorDpi();
|
|
961
|
+
// Máy bận (đo 13/11/2026: CPU 50–95 %) thì luồng quay mức thường bị giành CPU, khung tới chậm từng đợt; trên mức thường vẫn nhường ứng dụng
|
|
962
|
+
// người dùng đang dùng (không lên High / Realtime).
|
|
963
|
+
try { System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.AboveNormal; } catch { }
|
|
964
|
+
try { Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; } catch { }
|
|
926
965
|
SystemCursorHider.Init();
|
|
927
966
|
Native.timeBeginPeriod(1);
|
|
928
967
|
var a = Out.Parse(argsJson);
|
|
@@ -1050,10 +1089,17 @@ namespace AivinDesktopCast {
|
|
|
1050
1089
|
static int frameEchoSeq = 0;
|
|
1051
1090
|
|
|
1052
1091
|
static void SendFrame(Bitmap frame, bool cursorInFrame, bool jpegMode, long nowMs, HostStats hostStats) {
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1092
|
+
// Con trỏ vẽ thẳng lên khung rồi trả lại vùng đó ngay sau khi gửi (CastScreen.DrawCursorInPlace).
|
|
1093
|
+
bool drawn = cursorInFrame && CastScreen.DrawCursorInPlace(frame, currentBounds);
|
|
1094
|
+
try {
|
|
1095
|
+
SendFrameCore(frame, jpegMode, nowMs, hostStats);
|
|
1096
|
+
} finally {
|
|
1097
|
+
if (drawn) CastScreen.RestoreCursorPatch(frame);
|
|
1056
1098
|
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
static void SendFrameCore(Bitmap frame, bool jpegMode, long nowMs, HostStats hostStats) {
|
|
1102
|
+
Bitmap encodeBmp = frame;
|
|
1057
1103
|
if (leadInWidth > 0) SendLeadIn(encodeBmp, nowMs);
|
|
1058
1104
|
if (encodeBmp.Width > targetMaxWidth) {
|
|
1059
1105
|
encodeBmp = CastScreen.Scale(encodeBmp, targetMaxWidth);
|