@aivin-labs/cli 1.0.4 → 1.0.8
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/README.md +263 -216
- package/bin/cli.mjs +1780 -1361
- package/bin/lib/browserAutomation.mjs +655 -648
- package/bin/lib/browserTui.mjs +276 -245
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/codegen.mjs +61 -5
- package/bin/lib/connectors.mjs +55 -21
- package/bin/lib/deploy.mjs +25 -2
- package/bin/lib/mcpProxy.mjs +869 -773
- package/bin/lib/mission.mjs +13 -1
- package/bin/lib/missionStream.mjs +696 -660
- package/bin/lib/pluginAuthResolve.mjs +127 -0
- package/bin/lib/pluginTrigger.mjs +207 -90
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +457 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +292 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +66 -0
- package/bin/lib/remote/client.mjs +726 -0
- package/bin/lib/remote/constants.mjs +173 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +245 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +249 -0
- package/bin/lib/remote/mascot/assets.mjs +218 -0
- package/bin/lib/remote/mascot/hostSource.mjs +362 -0
- package/bin/lib/remote/mascot/index.mjs +322 -0
- package/bin/lib/remote/mascot/labels.mjs +83 -0
- package/bin/lib/remote/mascot/strings.mjs +189 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +726 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/store.mjs +16 -2
- package/bin/lib/tasks.mjs +52 -8
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/bin/lib/util.mjs +8 -0
- package/docs/CLI.md +1353 -1274
- package/package.json +71 -62
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { RELEASE_PUBLIC_KEYS } from './releaseKeys.mjs';
|
|
5
|
+
import {
|
|
6
|
+
UPDATE_INSTALLED_FILE, UPDATE_LOCK_FILE, UPDATE_PENDING_FILE, UPDATE_SETTINGS_FILE, UPDATE_STATE_FILE, UpdateStatus,
|
|
7
|
+
} from './update/constants.mjs';
|
|
8
|
+
import { replaceBinary } from './update/binarySwap.mjs';
|
|
9
|
+
import { downloadRelease, downloadRoot, fetchLatestVersion, fetchRollout, verifyStarts } from './update/download.mjs';
|
|
10
|
+
import { loadUpdateSettings, recordInstalled, withUpdateLock } from './update/state.mjs';
|
|
11
|
+
import { compareVersions, currentCliVersion, isStandaloneBinary, parseVersion, releaseAsset, rolloutBucket, tagOf, versionList } from './update/versions.mjs';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Tự cập nhật CLI (29/10/2026) — chỉ bản tệp chạy đóng gói (bộ cài install.ps1 / install.sh); bản npm cập nhật bằng npm. Tệp này điều phối
|
|
15
|
+
* một lần cập nhật + gom lại API của `update/` (giữ nguyên chỗ import cũ):
|
|
16
|
+
* - `update/versions.mjs` phiên bản, tên bản build, đợt phát hành
|
|
17
|
+
* - `update/signature.mjs` chữ ký Ed25519 của bản phát hành (khoá công khai trong releaseKeys.mjs)
|
|
18
|
+
* - `update/download.mjs` nguồn tải (chỉ https, chỉ từ biến môi trường), tải stream có trần, chạy thử
|
|
19
|
+
* - `update/binarySwap.mjs` thay / trả tệp chạy, giữ `.prev`
|
|
20
|
+
* - `update/state.mjs` cài đặt, khoá, bản chờ xác nhận, tự lùi bản, tình trạng gửi máy chủ
|
|
21
|
+
* Mô hình đe doạ: docs/official/device-agent/cli-self-update.md (repo be) mục 4.3.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export * from './update/constants.mjs';
|
|
25
|
+
export * from './update/versions.mjs';
|
|
26
|
+
export * from './update/signature.mjs';
|
|
27
|
+
export * from './update/download.mjs';
|
|
28
|
+
export * from './update/binarySwap.mjs';
|
|
29
|
+
export * from './update/state.mjs';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Kiểm + cài bản mới nhất (hoặc `version` chỉ định — được lùi bản, bỏ qua danh sách bỏ qua, bản bị hoãn và đợt phát hành). `check` = chỉ báo
|
|
33
|
+
* có bản mới. `deviceId` (daemon) → tôn trọng `rollout.json` trừ khi `urgent` (máy chủ đòi bản tối thiểu). `holdVersions` (máy chủ báo, chỉ
|
|
34
|
+
* hoãn được, không cài được) → không cài các bản đó. Trả `{ status, current, latest }`. `binary` / `target` / `verify` / `keys` / các tệp: cho test.
|
|
35
|
+
*/
|
|
36
|
+
export async function installUpdate({
|
|
37
|
+
version, root = downloadRoot(), check = false, force = false, urgent = false, deviceId, holdVersions = [], signal,
|
|
38
|
+
binary = isStandaloneBinary(), target = process.execPath, current = currentCliVersion(), verify = verifyStarts, keys = RELEASE_PUBLIC_KEYS,
|
|
39
|
+
markerFile = UPDATE_INSTALLED_FILE, stateFile = UPDATE_STATE_FILE, lockFile = UPDATE_LOCK_FILE, settingsFile = UPDATE_SETTINGS_FILE,
|
|
40
|
+
pendingFile = UPDATE_PENDING_FILE,
|
|
41
|
+
} = {}) {
|
|
42
|
+
const latest = version ? tagOf(version) : await fetchLatestVersion({ root, signal });
|
|
43
|
+
if (!parseVersion(latest)) throw new Error(`Phiên bản không hợp lệ: ${version}`);
|
|
44
|
+
const result = { current: tagOf(current), latest };
|
|
45
|
+
if (!force && compareVersions(latest, current) <= 0) return { ...result, status: UpdateStatus.UP_TO_DATE };
|
|
46
|
+
if (!binary) return { ...result, status: UpdateStatus.NOT_BINARY };
|
|
47
|
+
if (!version && loadUpdateSettings(settingsFile).skip.includes(latest)) return { ...result, status: UpdateStatus.SKIPPED };
|
|
48
|
+
if (!version && versionList(holdVersions).includes(latest)) return { ...result, status: UpdateStatus.HELD };
|
|
49
|
+
if (check) return { ...result, status: UpdateStatus.AVAILABLE };
|
|
50
|
+
if (deviceId && !urgent && !version) {
|
|
51
|
+
const rollout = await fetchRollout({ root, signal });
|
|
52
|
+
if (rollout && rollout.version === latest && rolloutBucket(deviceId, latest) >= rollout.percent) return { ...result, status: UpdateStatus.DEFERRED };
|
|
53
|
+
}
|
|
54
|
+
return withUpdateLock(async () => {
|
|
55
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'aivin-update-'));
|
|
56
|
+
try {
|
|
57
|
+
const file = await downloadRelease({ root, version: latest, asset: releaseAsset(), destDir: tmp, signal, keys });
|
|
58
|
+
await verify(file, latest);
|
|
59
|
+
let backup;
|
|
60
|
+
try {
|
|
61
|
+
backup = replaceBinary({ newFile: file, target });
|
|
62
|
+
} catch (e) {
|
|
63
|
+
throw new Error(`Không thay được ${target} (${e?.code || e?.message}) — cài lại bằng bộ cài: https://get.aivin.vn`, { cause: e });
|
|
64
|
+
}
|
|
65
|
+
recordInstalled({ version: latest, current, target, backup, stateFile, markerFile, pendingFile });
|
|
66
|
+
return { ...result, status: UpdateStatus.INSTALLED };
|
|
67
|
+
} finally {
|
|
68
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
69
|
+
}
|
|
70
|
+
}, lockFile);
|
|
71
|
+
}
|
package/bin/lib/store.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import path from 'path';
|
|
|
4
4
|
import chalk from 'chalk';
|
|
5
5
|
import axios from 'axios';
|
|
6
6
|
import inquirer from 'inquirer';
|
|
7
|
-
import { withSpinner, requireArg } from './util.mjs';
|
|
7
|
+
import { withSpinner, requireArg, DEFAULT_API_TIMEOUT_MS } from './util.mjs';
|
|
8
8
|
|
|
9
9
|
// ── Plugin store (self-host aivin-service worker) — attach/create/ls/enable/disable/detach ──────
|
|
10
10
|
//
|
|
@@ -19,7 +19,11 @@ export function storeAuthHeaders() {
|
|
|
19
19
|
if (!apiKey) {
|
|
20
20
|
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
21
21
|
}
|
|
22
|
-
|
|
22
|
+
// ✅ FIX: every axios call in this file passes this object straight through as its request config
|
|
23
|
+
// (never overriding timeout) - none of them had a `timeout` before, so a hung/overloaded backend
|
|
24
|
+
// left the spinner spinning forever with no way out short of Ctrl+C. Setting it once here covers
|
|
25
|
+
// every call site instead of patching each individually.
|
|
26
|
+
return { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` }, timeout: DEFAULT_API_TIMEOUT_MS };
|
|
23
27
|
}
|
|
24
28
|
|
|
25
29
|
export function storeBaseUrl() {
|
|
@@ -51,7 +55,17 @@ function writeWorkerIdentity(dataDir, { beEndpoint, orgId, storeId, storeName, n
|
|
|
51
55
|
...(sdkGrpcEndpoint ? { sdk_grpc_endpoint: sdkGrpcEndpoint } : {}),
|
|
52
56
|
paired_at: new Date().toISOString(),
|
|
53
57
|
};
|
|
58
|
+
// `mode: 0o600` only actually restricts access on POSIX (Linux/macOS) - Node's `mode` option maps
|
|
59
|
+
// to very little on Windows NTFS (no real per-user read restriction the way POSIX permission bits
|
|
60
|
+
// do), so on Windows this file's `worker_token` is effectively readable by any account that can
|
|
61
|
+
// read this directory at all. Encrypting it at rest would need a real key-management decision
|
|
62
|
+
// (where does the encryption key itself live, without just moving the same problem one level
|
|
63
|
+
// down?) - out of scope for a CLI-side fix, so surfacing the risk explicitly instead of silently
|
|
64
|
+
// relying on a permission bit that doesn't do what it looks like it does on this platform.
|
|
54
65
|
fs.writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n', { mode: 0o600 });
|
|
66
|
+
if (process.platform === 'win32') {
|
|
67
|
+
console.log(chalk.gray(` Note: on Windows, "${filePath}" is only as protected as the folder it's in (0o600 has no POSIX-style effect here) - keep this machine/account access appropriately restricted.`));
|
|
68
|
+
}
|
|
55
69
|
return filePath;
|
|
56
70
|
}
|
|
57
71
|
|
package/bin/lib/tasks.mjs
CHANGED
|
@@ -161,10 +161,26 @@ export async function updateTaskById(id, options) {
|
|
|
161
161
|
console.log(chalk.gray(` Status: ${task.status}`));
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
|
|
164
|
+
// ✅ FIX: had no confirmation at all before - unlike every other destructive command in this CLI
|
|
165
|
+
// (`plugin delete`, `pluginstore rm`/`rm-node`), a typo'd id here deleted immediately with nothing
|
|
166
|
+
// to catch it. Same `-y/--yes` escape hatch for scripts/CI as those commands.
|
|
167
|
+
export async function deleteTaskById(id, options = {}) {
|
|
165
168
|
const serverUrl = missionServerUrl();
|
|
166
169
|
const authHeaders = missionAuthHeaders();
|
|
167
170
|
|
|
171
|
+
if (!options.yes) {
|
|
172
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
173
|
+
throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
|
|
174
|
+
}
|
|
175
|
+
const { confirm } = await inquirer.prompt([
|
|
176
|
+
{ type: 'confirm', name: 'confirm', message: `Delete task "${id}"? This can't be undone.`, default: false },
|
|
177
|
+
]);
|
|
178
|
+
if (!confirm) {
|
|
179
|
+
console.log(chalk.gray('Cancelled.'));
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
168
184
|
try {
|
|
169
185
|
await axios.delete(`${serverUrl}/task/${id}/delete`, authHeaders);
|
|
170
186
|
} catch (error) {
|
|
@@ -175,6 +191,23 @@ export async function deleteTaskById(id) {
|
|
|
175
191
|
console.log(chalk.green(`✅ Task ${id} deleted.`));
|
|
176
192
|
}
|
|
177
193
|
|
|
194
|
+
/**
|
|
195
|
+
* Pure assembly of `POST /task/create`'s body, split out of createTask() so it's unit-testable
|
|
196
|
+
* without stubbing axios/inquirer. Backend's TaskService._sanitizeCreateTaskInput whitelists
|
|
197
|
+
* `description`, not `content` - sending the wrong key here used to look like success (200 + a
|
|
198
|
+
* task id back) while silently dropping the user's actual text, which is exactly the kind of drift
|
|
199
|
+
* a regression test on this function's output shape catches going forward.
|
|
200
|
+
*/
|
|
201
|
+
export function buildCreateTaskPayload(description, workspaceId, options = {}) {
|
|
202
|
+
return {
|
|
203
|
+
title: description.length > 80 ? `${description.slice(0, 77)}...` : description,
|
|
204
|
+
description,
|
|
205
|
+
workspace_id: workspaceId,
|
|
206
|
+
project_id: options.project,
|
|
207
|
+
assign_id: options.assignee,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
178
211
|
export async function createTask(description, options) {
|
|
179
212
|
const serverUrl = missionServerUrl();
|
|
180
213
|
const authHeaders = missionAuthHeaders();
|
|
@@ -188,13 +221,7 @@ export async function createTask(description, options) {
|
|
|
188
221
|
try {
|
|
189
222
|
response = await axios.post(
|
|
190
223
|
`${serverUrl}/task/create`,
|
|
191
|
-
|
|
192
|
-
title: description.length > 80 ? `${description.slice(0, 77)}...` : description,
|
|
193
|
-
content: description,
|
|
194
|
-
workspace_id: workspace.id || workspace._id,
|
|
195
|
-
project_id: options.project,
|
|
196
|
-
assign_id: options.assignee,
|
|
197
|
-
},
|
|
224
|
+
buildCreateTaskPayload(description, workspace.id || workspace._id, options),
|
|
198
225
|
authHeaders,
|
|
199
226
|
);
|
|
200
227
|
} catch (error) {
|
|
@@ -336,9 +363,26 @@ export async function updateProjectCmd(projectId, options) {
|
|
|
336
363
|
console.log(chalk.green(`✅ Project ${projectId} updated.`));
|
|
337
364
|
}
|
|
338
365
|
|
|
366
|
+
// ✅ FIX: had no confirmation at all before, and deleting a project is more consequential than
|
|
367
|
+
// deleting a single task (its tasks go with it) - same missing-protection issue as deleteTaskById
|
|
368
|
+
// above, same `-y/--yes` fix.
|
|
339
369
|
export async function deleteProjectCmd(projectId, options) {
|
|
340
370
|
const serverUrl = missionServerUrl();
|
|
341
371
|
const authHeaders = missionAuthHeaders();
|
|
372
|
+
|
|
373
|
+
if (!options.yes) {
|
|
374
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
375
|
+
throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
|
|
376
|
+
}
|
|
377
|
+
const { confirm } = await inquirer.prompt([
|
|
378
|
+
{ type: 'confirm', name: 'confirm', message: `Delete project "${projectId}"? Its tasks go with it. This can't be undone.`, default: false },
|
|
379
|
+
]);
|
|
380
|
+
if (!confirm) {
|
|
381
|
+
console.log(chalk.gray('Cancelled.'));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
342
386
|
const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
|
|
343
387
|
await deleteProjectById(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, projectId });
|
|
344
388
|
console.log(chalk.green(`✅ Project ${projectId} deleted.`));
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
|
|
4
|
+
/** Thay / trả tệp chạy trên đĩa. Bản cũ giữ ở `<tệp>.prev` để tự lùi (trong tệp chạy hoặc ở trình giữ chạy — xem autoStart.mjs). */
|
|
5
|
+
|
|
6
|
+
/** Xoá; Windows không xoá được tệp còn đang chạy nhưng đổi tên được → `<tệp>-<thời điểm>.trash`, dọn ở lần chạy sau. */
|
|
7
|
+
export function retire(file) {
|
|
8
|
+
try {
|
|
9
|
+
fs.rmSync(file, { force: true });
|
|
10
|
+
} catch {
|
|
11
|
+
fs.renameSync(file, `${file}-${Date.now()}.trash`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Thay tệp chạy, giữ bản cũ ở `<tệp>.prev`. Windows: đổi tên bản đang chạy thành `.prev` rồi chép bản mới (chép hỏng thì trả tên cũ lại).
|
|
17
|
+
* macOS / Linux: chép bản cũ ra `.prev`, chép bản mới cạnh bên rồi đổi tên nguyên khối. Trả đường dẫn bản cũ (null nếu chưa có).
|
|
18
|
+
*/
|
|
19
|
+
export function replaceBinary({ newFile, target, platform = process.platform }) {
|
|
20
|
+
const backup = `${target}.prev`;
|
|
21
|
+
if (fs.existsSync(backup)) retire(backup);
|
|
22
|
+
const had = fs.existsSync(target);
|
|
23
|
+
if (platform === 'win32') {
|
|
24
|
+
if (had) fs.renameSync(target, backup);
|
|
25
|
+
try {
|
|
26
|
+
fs.copyFileSync(newFile, target);
|
|
27
|
+
} catch (e) {
|
|
28
|
+
if (had) {
|
|
29
|
+
fs.rmSync(target, { force: true });
|
|
30
|
+
fs.renameSync(backup, target);
|
|
31
|
+
}
|
|
32
|
+
throw e;
|
|
33
|
+
}
|
|
34
|
+
return had ? backup : null;
|
|
35
|
+
}
|
|
36
|
+
if (had) {
|
|
37
|
+
fs.copyFileSync(target, backup);
|
|
38
|
+
fs.chmodSync(backup, 0o755);
|
|
39
|
+
}
|
|
40
|
+
const staged = `${target}.new`;
|
|
41
|
+
fs.copyFileSync(newFile, staged);
|
|
42
|
+
fs.chmodSync(staged, 0o755);
|
|
43
|
+
fs.renameSync(staged, target);
|
|
44
|
+
return had ? backup : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Trả bản cũ về chỗ (bản mới đang chạy trên Windows bị khoá → đổi tên đi trước). */
|
|
48
|
+
export function restoreBackup({ target, backup, platform = process.platform }) {
|
|
49
|
+
if (platform === 'win32' && fs.existsSync(target)) retire(target);
|
|
50
|
+
fs.renameSync(backup, target);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Dọn bản cũ đã bỏ: `.old` (bản đầu của tính năng) + `*.trash`. Không đụng `.prev` — còn cần để tự lùi tới khi bản mới được xác nhận. */
|
|
54
|
+
export function cleanupRetired(target = process.execPath) {
|
|
55
|
+
const dir = path.dirname(target);
|
|
56
|
+
const base = path.basename(target);
|
|
57
|
+
let names;
|
|
58
|
+
try { names = fs.readdirSync(dir); } catch { return; }
|
|
59
|
+
for (const name of names) {
|
|
60
|
+
if (name !== `${base}.old` && !(name.startsWith(base) && name.endsWith('.trash'))) continue;
|
|
61
|
+
try { fs.rmSync(path.join(dir, name), { force: true }); } catch { /* bản cũ còn đang chạy — lần sau */ }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import { REMOTE_CONFIG_DIR } from '../remote/constants.mjs';
|
|
3
|
+
|
|
4
|
+
/** Tự cập nhật CLI — đường dẫn, mã, trạng thái dùng chung giữa các module trong `update/` (xem selfUpdate.mjs). */
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_DOWNLOAD_ROOT = 'https://get.aivin.vn';
|
|
7
|
+
export const UPDATE_SETTINGS_FILE = path.join(REMOTE_CONFIG_DIR, 'update.json');
|
|
8
|
+
/** Bản vừa cài xuống đĩa (`aivin update` ở cửa sổ khác hoặc daemon tự cài) — daemon đang chạy bản cũ đọc tệp này để biết cần chạy lại. */
|
|
9
|
+
export const UPDATE_INSTALLED_FILE = path.join(REMOTE_CONFIG_DIR, 'update-installed.json');
|
|
10
|
+
/** Bản vừa cài chưa được xác nhận chạy ổn (nối được máy chủ / chạy đủ lâu) + số lần đã khởi động. */
|
|
11
|
+
export const UPDATE_STATE_FILE = path.join(REMOTE_CONFIG_DIR, 'update-state.json');
|
|
12
|
+
export const UPDATE_LOCK_FILE = path.join(REMOTE_CONFIG_DIR, 'update.lock');
|
|
13
|
+
/**
|
|
14
|
+
* Dấu chờ xác nhận dạng chữ thường (một dòng: phiên bản) cho TRÌNH GIỮ CHẠY (VBS / kịch bản sh) — tự lùi bản cả khi bản mới sập ngay lúc nạp
|
|
15
|
+
* mã, trước khi đoạn kiểm trong tệp chạy kịp chạy. Trình giữ chạy không đọc JSON được dễ dàng nên tách riêng.
|
|
16
|
+
*/
|
|
17
|
+
export const UPDATE_PENDING_FILE = path.join(REMOTE_CONFIG_DIR, 'update-pending.txt');
|
|
18
|
+
/** Trình giữ chạy đã tự lùi bản (một dòng: phiên bản bị lùi) — tệp chạy (bản cũ) đọc ở lần khởi động sau, đưa bản đó vào danh sách bỏ qua. */
|
|
19
|
+
export const UPDATE_ROLLBACK_FILE = path.join(REMOTE_CONFIG_DIR, 'update-rollback.txt');
|
|
20
|
+
/** Kết quả lần kiểm gần nhất (giờ, lỗi, bản trang tải báo, bản đã tự lùi) — gửi máy chủ trong hồ sơ máy để biết cả đội máy đang ra sao. */
|
|
21
|
+
export const UPDATE_STATUS_FILE = path.join(REMOTE_CONFIG_DIR, 'update-status.json');
|
|
22
|
+
|
|
23
|
+
/** Mã thoát "chạy lại tôi" (EX_TEMPFAIL): Task Scheduler + VBS / launchd / systemd chạy lại mọi mã khác 0. */
|
|
24
|
+
export const RESTART_EXIT_CODE = 75;
|
|
25
|
+
export const MAX_BOOTS_BEFORE_ROLLBACK = 3;
|
|
26
|
+
/** Bản mới chạy liền chừng này không sập → coi là ổn, bỏ bản cũ. */
|
|
27
|
+
export const UPDATE_CONFIRM_AFTER_MS = 10 * 60_000;
|
|
28
|
+
/** Mã lỗi `aivin remote start` khi vừa tự lùi bản: trình giữ chạy → thoát 75 (mở lại bằng bản cũ), cửa sổ tay → báo + thoát 1. */
|
|
29
|
+
export const UPDATE_ROLLED_BACK = 'UPDATE_ROLLED_BACK';
|
|
30
|
+
|
|
31
|
+
export const UpdateStatus = Object.freeze({
|
|
32
|
+
UP_TO_DATE: 'up_to_date',
|
|
33
|
+
AVAILABLE: 'available',
|
|
34
|
+
INSTALLED: 'installed',
|
|
35
|
+
NOT_BINARY: 'not_binary',
|
|
36
|
+
/** Bản mới nhất là bản máy này đã tự lùi khỏi (khởi động hỏng) — chỉ cài lại khi người dùng chỉ định `--to`. */
|
|
37
|
+
SKIPPED: 'skipped',
|
|
38
|
+
/** Máy chủ báo bản này đang bị hoãn (nhiều máy tự lùi khỏi nó) — daemon không cài, `aivin update` chạy tay vẫn cài được. */
|
|
39
|
+
HELD: 'held',
|
|
40
|
+
/** Phát hành theo đợt (`rollout.json`): máy này chưa tới lượt. */
|
|
41
|
+
DEFERRED: 'deferred',
|
|
42
|
+
/** Một tiến trình khác đang cập nhật. */
|
|
43
|
+
BUSY: 'busy',
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
export const BootAction = Object.freeze({ NONE: 'none', PENDING: 'pending', ROLLED_BACK: 'rolled_back' });
|
|
47
|
+
/** Ai đã tự lùi bản: đoạn kiểm trong tệp chạy, hay trình giữ chạy (bản mới sập trước khi kiểm được). */
|
|
48
|
+
export const RollbackBy = Object.freeze({ BINARY: 'binary', SUPERVISOR: 'supervisor' });
|
|
49
|
+
|
|
50
|
+
export const HTTP_TIMEOUT_MS = 15_000;
|
|
51
|
+
export const DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
|
|
52
|
+
export const MAX_DOWNLOAD_BYTES = 300 * 1024 * 1024;
|
|
53
|
+
export const MAX_BINARY_BYTES = 512 * 1024 * 1024;
|
|
54
|
+
export const MAX_TEXT_BYTES = 64 * 1024;
|
|
55
|
+
export const VERIFY_TIMEOUT_MS = 30_000;
|
|
56
|
+
export const LOCK_STALE_MS = 15 * 60_000;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { execFile } from 'child_process';
|
|
6
|
+
import { Transform } from 'stream';
|
|
7
|
+
import { pipeline } from 'stream/promises';
|
|
8
|
+
import { promisify } from 'util';
|
|
9
|
+
import { createGunzip } from 'zlib';
|
|
10
|
+
import { RELEASE_PUBLIC_KEYS } from '../releaseKeys.mjs';
|
|
11
|
+
import {
|
|
12
|
+
DEFAULT_DOWNLOAD_ROOT, DOWNLOAD_TIMEOUT_MS, HTTP_TIMEOUT_MS, MAX_BINARY_BYTES, MAX_DOWNLOAD_BYTES, MAX_TEXT_BYTES, VERIFY_TIMEOUT_MS,
|
|
13
|
+
} from './constants.mjs';
|
|
14
|
+
import { checksumFor, verifyReleaseSignature } from './signature.mjs';
|
|
15
|
+
import { compareVersions, parseVersion, tagOf } from './versions.mjs';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Tải từ trang tải: nguồn chỉ từ biến môi trường của máy (không từ máy chủ Aivin, không từ tệp trong `~/.aivin` — một lần ghi được tệp đó
|
|
19
|
+
* không được trở thành chỗ cài lại mã độc sau mỗi lần cài sạch), chỉ https (http chỉ cho máy này), chuyển hướng cũng phải https, trần dung
|
|
20
|
+
* lượng mọi tệp. Bản build đi thẳng ra đĩa (tính SHA-256 + giải nén trong lúc tải) — không giữ ~50 MB tệp nén + ~110 MB tệp chạy trong RAM.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const execFileAsync = promisify(execFile);
|
|
24
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
25
|
+
/** Biến môi trường bản mới được thấy khi chạy thử — không API key, token, mật khẩu proxy. */
|
|
26
|
+
const VERIFY_ENV_KEYS = ['PATH', 'Path', 'PATHEXT', 'SystemRoot', 'SYSTEMROOT', 'windir', 'ComSpec', 'TEMP', 'TMP', 'TMPDIR', 'HOME', 'USERPROFILE', 'LOCALAPPDATA', 'APPDATA', 'LANG', 'LC_ALL'];
|
|
27
|
+
|
|
28
|
+
/** https, hoặc http chỉ tới chính máy này (gương thử tại chỗ). */
|
|
29
|
+
export function assertSafeUrl(url) {
|
|
30
|
+
let u;
|
|
31
|
+
try { u = new URL(url); } catch { throw new Error(`Nguồn tải không hợp lệ: ${url}`); }
|
|
32
|
+
if (u.protocol === 'https:' || (u.protocol === 'http:' && LOOPBACK_HOSTS.has(u.hostname))) return;
|
|
33
|
+
throw new Error(`Nguồn tải phải là https (${u.protocol}//${u.host})`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Nguồn tải: AIVIN_DOWNLOAD_ROOT (máy dùng gương nội bộ) → get.aivin.vn. */
|
|
37
|
+
export function downloadRoot({ env = process.env } = {}) {
|
|
38
|
+
const root = String(env.AIVIN_DOWNLOAD_ROOT || DEFAULT_DOWNLOAD_ROOT).replace(/\/+$/, '');
|
|
39
|
+
assertSafeUrl(root);
|
|
40
|
+
return root;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const requestOptions = ({ timeout, signal }) => ({
|
|
44
|
+
timeout, signal, maxRedirects: 3, headers: { 'Cache-Control': 'no-cache' },
|
|
45
|
+
// Chuyển hướng sang http (follow-redirects mặc định cho phép, chỉ bỏ header nhạy cảm) → dừng.
|
|
46
|
+
beforeRedirect: (options) => assertSafeUrl(`${options.protocol}//${options.hostname}${options.port ? `:${options.port}` : ''}/`),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
async function fetchBytes(url, { maxBytes, timeout = HTTP_TIMEOUT_MS, signal }) {
|
|
50
|
+
assertSafeUrl(url);
|
|
51
|
+
const res = await axios.get(url, { ...requestOptions({ timeout, signal }), responseType: 'arraybuffer', maxContentLength: maxBytes });
|
|
52
|
+
return Buffer.from(res.data);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const fetchText = async (url, opts) => (await fetchBytes(url, { maxBytes: MAX_TEXT_BYTES, ...opts })).toString('utf8');
|
|
56
|
+
|
|
57
|
+
/** Đếm byte qua luồng, quá trần thì dừng cả đường ống; `onChunk` thấy từng khúc (tính mã băm). */
|
|
58
|
+
function byteCap(max, label, onChunk) {
|
|
59
|
+
let seen = 0;
|
|
60
|
+
return new Transform({
|
|
61
|
+
transform(chunk, _enc, cb) {
|
|
62
|
+
seen += chunk.length;
|
|
63
|
+
if (seen > max) return cb(new Error(`${label} vượt trần ${Math.round(max / 1048576)} MB — dừng cập nhật`));
|
|
64
|
+
onChunk?.(chunk);
|
|
65
|
+
cb(null, chunk);
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Tải `url` (tệp .gz) thẳng ra `file` đã giải nén; trả SHA-256 của các byte NÉN đã tải (so với danh sách mã băm đã ký). */
|
|
71
|
+
async function downloadGzToFile({ url, file, signal, maxBinaryBytes }) {
|
|
72
|
+
assertSafeUrl(url);
|
|
73
|
+
const res = await axios.get(url, { ...requestOptions({ timeout: DOWNLOAD_TIMEOUT_MS, signal }), responseType: 'stream' });
|
|
74
|
+
const hash = createHash('sha256');
|
|
75
|
+
await pipeline(
|
|
76
|
+
res.data,
|
|
77
|
+
byteCap(MAX_DOWNLOAD_BYTES, 'Tệp tải về', (chunk) => hash.update(chunk)),
|
|
78
|
+
createGunzip(),
|
|
79
|
+
byteCap(maxBinaryBytes, 'Tệp giải nén'),
|
|
80
|
+
fs.createWriteStream(file, { mode: 0o755 }),
|
|
81
|
+
{ signal },
|
|
82
|
+
);
|
|
83
|
+
return hash.digest('hex');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function fetchLatestVersion({ root = downloadRoot(), signal } = {}) {
|
|
87
|
+
const version = (await fetchText(`${root}/latest.txt`, { signal })).trim();
|
|
88
|
+
if (!parseVersion(version)) throw new Error(`Không đọc được phiên bản mới nhất từ ${root}/latest.txt`);
|
|
89
|
+
return tagOf(version);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Phát hành theo đợt: `<root>/rollout.json` = `{ version, percent }`. Không có / hỏng → cả đội máy. Tệp này chỉ hoãn được, không cài được gì. */
|
|
93
|
+
export async function fetchRollout({ root = downloadRoot(), signal } = {}) {
|
|
94
|
+
try {
|
|
95
|
+
const data = JSON.parse(await fetchText(`${root}/rollout.json`, { signal }));
|
|
96
|
+
const percent = Number(data?.percent);
|
|
97
|
+
return parseVersion(data?.version) && Number.isFinite(percent) ? { version: tagOf(data.version), percent: Math.max(0, Math.min(100, percent)) } : null;
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Tải chữ ký + danh sách mã băm trước (nhỏ), kiểm chữ ký, rồi mới tải bản build ra `destDir` (giải nén trong lúc tải, có trần) và so SHA-256.
|
|
105
|
+
* Mã băm lệch → xoá tệp vừa ghi, ném.
|
|
106
|
+
*/
|
|
107
|
+
export async function downloadRelease({ root, version, asset, destDir, signal, keys = RELEASE_PUBLIC_KEYS, maxBinaryBytes = MAX_BINARY_BYTES }) {
|
|
108
|
+
const base = `${root}/${tagOf(version)}`;
|
|
109
|
+
const [sums, sigText] = await Promise.all([
|
|
110
|
+
fetchBytes(`${base}/SHA256SUMS`, { maxBytes: MAX_TEXT_BYTES, signal }),
|
|
111
|
+
fetchText(`${base}/SHA256SUMS.sig`, { signal }).catch((e) => { if (e?.response?.status === 404) return null; throw e; }),
|
|
112
|
+
]);
|
|
113
|
+
if (!sigText) throw new Error(`Bản ${tagOf(version)} không có chữ ký (SHA256SUMS.sig) — dừng cập nhật`);
|
|
114
|
+
verifyReleaseSignature({ version, sums, sigText, keys });
|
|
115
|
+
const expected = checksumFor(sums.toString('utf8'), `${asset}.gz`);
|
|
116
|
+
if (!expected) throw new Error(`SHA256SUMS của ${tagOf(version)} không có ${asset}.gz`);
|
|
117
|
+
const file = path.join(destDir, asset);
|
|
118
|
+
let actual;
|
|
119
|
+
try {
|
|
120
|
+
actual = await downloadGzToFile({ url: `${base}/${asset}.gz`, file, signal, maxBinaryBytes });
|
|
121
|
+
} catch (e) {
|
|
122
|
+
fs.rmSync(file, { force: true });
|
|
123
|
+
throw e;
|
|
124
|
+
}
|
|
125
|
+
if (actual !== expected) {
|
|
126
|
+
fs.rmSync(file, { force: true });
|
|
127
|
+
throw new Error(`Tệp tải về không khớp mã kiểm tra (${asset}.gz) — dừng cập nhật để an toàn`);
|
|
128
|
+
}
|
|
129
|
+
return file;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function verifyEnv(env = process.env) {
|
|
133
|
+
return Object.fromEntries(VERIFY_ENV_KEYS.filter((k) => env[k] !== undefined).map((k) => [k, env[k]]));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Bản mới phải chạy được trên máy này và đúng phiên bản đã hứa, trước khi thay bản đang dùng (bất đồng bộ: daemon vẫn nhận việc). */
|
|
137
|
+
export async function verifyStarts(file, version) {
|
|
138
|
+
let out;
|
|
139
|
+
try {
|
|
140
|
+
({ stdout: out } = await execFileAsync(file, ['--version'], { timeout: VERIFY_TIMEOUT_MS, windowsHide: true, maxBuffer: 64 * 1024, env: verifyEnv(), cwd: path.dirname(file) }));
|
|
141
|
+
} catch (e) {
|
|
142
|
+
throw new Error(`Bản ${tagOf(version)} không chạy được trên máy này (${e?.message || e})`, { cause: e });
|
|
143
|
+
}
|
|
144
|
+
if (compareVersions(String(out).trim(), version) !== 0) throw new Error(`Bản tải về báo phiên bản "${String(out).trim()}", không phải ${tagOf(version)}`);
|
|
145
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createHash, createPublicKey, verify as verifySignature } from 'crypto';
|
|
2
|
+
import { RELEASE_PUBLIC_KEYS } from '../releaseKeys.mjs';
|
|
3
|
+
import { compareVersions, tagOf } from './versions.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Chữ ký bản phát hành (Ed25519): ký trên số phiên bản + nguyên văn `SHA256SUMS`; khoá công khai nhúng trong CLI (releaseKeys.mjs), khoá bí
|
|
7
|
+
* mật không nằm trên trang tải → chiếm được get.aivin.vn cũng không đẩy được tệp chạy lạ. Mã băm cùng trang tải chỉ bắt tệp tải hỏng.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const SPKI_ED25519_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
|
|
11
|
+
|
|
12
|
+
/** Dòng `<sha256> <tệp>` (dấu `*` chế độ nhị phân tuỳ ý) → mã của đúng tệp. */
|
|
13
|
+
export function checksumFor(sumsText, file) {
|
|
14
|
+
for (const line of String(sumsText).split(/\r?\n/)) {
|
|
15
|
+
const m = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line.trim());
|
|
16
|
+
if (m && m[2].trim() === file) return m[1].toLowerCase();
|
|
17
|
+
}
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Nội dung được ký: số phiên bản + nguyên văn SHA256SUMS — chữ ký của bản này không dùng lại được cho bản khác. */
|
|
22
|
+
export const signedMessage = (version, sums) => Buffer.concat([Buffer.from(`aivin-release ${tagOf(version)}\n`), Buffer.from(sums)]);
|
|
23
|
+
|
|
24
|
+
const publicKeyOf = (raw) => createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, Buffer.from(raw, 'base64')]), format: 'der', type: 'spki' });
|
|
25
|
+
|
|
26
|
+
/** Mã khoá = 16 ký tự hex đầu SHA-256 của khoá công khai thô (32 byte). */
|
|
27
|
+
export function releaseKeyId(key) {
|
|
28
|
+
const pub = key.type === 'private' ? createPublicKey(key) : key;
|
|
29
|
+
return createHash('sha256').update(pub.export({ format: 'der', type: 'spki' }).subarray(-32)).digest('hex').slice(0, 16);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** `SHA256SUMS.sig` = `{ alg: 'ed25519', key_id, version, sig }`. Khoá không có trong danh sách / chữ ký sai / lệch phiên bản → ném. */
|
|
33
|
+
export function verifyReleaseSignature({ version, sums, sigText, keys = RELEASE_PUBLIC_KEYS }) {
|
|
34
|
+
let sig;
|
|
35
|
+
try { sig = JSON.parse(String(sigText)); } catch { throw new Error(`Chữ ký của ${tagOf(version)} hỏng — dừng cập nhật để an toàn`); }
|
|
36
|
+
const key = keys.find((k) => k.id === sig?.key_id);
|
|
37
|
+
if (sig?.alg !== 'ed25519' || !key) throw new Error(`Bản ${tagOf(version)} không ký bằng khoá máy này tin (${sig?.key_id || 'không rõ khoá'}) — dừng cập nhật`);
|
|
38
|
+
if (sig.version !== undefined && compareVersions(sig.version, version) !== 0) throw new Error(`Chữ ký dành cho ${sig.version}, không phải ${tagOf(version)} — dừng cập nhật`);
|
|
39
|
+
let ok;
|
|
40
|
+
try { ok = verifySignature(null, signedMessage(version, sums), publicKeyOf(key.key), Buffer.from(String(sig.sig || ''), 'base64')); } catch { ok = false; }
|
|
41
|
+
if (!ok) throw new Error(`Chữ ký của ${tagOf(version)} không hợp lệ — dừng cập nhật để an toàn`);
|
|
42
|
+
}
|