livedesk 0.1.500 → 0.1.502
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/livedesk.js +21 -18
- package/bootstrap/hub-auth-handoff.js +3 -3
- package/bootstrap/legacy-client-update.js +46 -15
- package/bootstrap/npm-update-cache.mjs +158 -0
- package/bootstrap/update-host-client.mjs +69 -3
- package/bootstrap/update-host.mjs +28 -7
- package/client/package.json +5 -5
- package/hub/package.json +1 -1
- package/hub/src/http/hub-ui-session.js +119 -0
- package/hub/src/remote-hub.js +34 -5
- package/hub/src/server.js +151 -47
- package/package.json +7 -7
- package/web/dist/assets/index-DqXhTKiG.js +188 -0
- package/web/dist/index.html +1 -1
- package/web/dist/livedesk-build-evidence.json +11 -11
- package/web/dist/assets/index-9p6M3oJV.js +0 -186
package/bin/livedesk.js
CHANGED
|
@@ -34,6 +34,7 @@ import {
|
|
|
34
34
|
import { runLegacyClientUpdateSupervisorCli } from '../bootstrap/legacy-client-update.js';
|
|
35
35
|
import { transferSavedClientSessionToHub } from '../bootstrap/hub-auth-handoff.js';
|
|
36
36
|
import {
|
|
37
|
+
buildUpdateHostWorkerEnvironment,
|
|
37
38
|
cancelUpdateHostJob,
|
|
38
39
|
ensureUpdateHost,
|
|
39
40
|
getUpdateHostJob,
|
|
@@ -2680,8 +2681,7 @@ async function runManager(args, resolvedRole = null, runtimeLock = null, updateH
|
|
|
2680
2681
|
reportLauncherUpdate(`[LiveDesk Hub] Could not persist the restart supervisor state: ${error instanceof Error ? error.message : String(error)}.`, true);
|
|
2681
2682
|
throw error;
|
|
2682
2683
|
}
|
|
2683
|
-
const workerEnvironment = {
|
|
2684
|
-
...process.env,
|
|
2684
|
+
const workerEnvironment = buildUpdateHostWorkerEnvironment(process.env, {
|
|
2685
2685
|
LIVEDESK_RESTART_WAIT_PID: String(process.pid),
|
|
2686
2686
|
LIVEDESK_RESTART_PREVIOUS_RUNTIME_PID: String(request?.pid || 0),
|
|
2687
2687
|
LIVEDESK_RESTART_OPERATION_ID: operationId,
|
|
@@ -2701,7 +2701,7 @@ async function runManager(args, resolvedRole = null, runtimeLock = null, updateH
|
|
|
2701
2701
|
LIVEDESK_RESTART_FALLBACK_CWD: originalCwd,
|
|
2702
2702
|
LIVEDESK_UPDATE_ORIGINAL_CWD: originalCwd,
|
|
2703
2703
|
LIVEDESK_RESTART_LOG_PATH: hubLogPath
|
|
2704
|
-
};
|
|
2704
|
+
});
|
|
2705
2705
|
const hostJobId = `hub-${safeUpdatePathSegment(operationId)}`;
|
|
2706
2706
|
let hostJob;
|
|
2707
2707
|
try {
|
|
@@ -3034,21 +3034,24 @@ async function runManager(args, resolvedRole = null, runtimeLock = null, updateH
|
|
|
3034
3034
|
updatePollId = setInterval(pollUpdateRequest, HUB_UPDATE_POLL_MS);
|
|
3035
3035
|
|
|
3036
3036
|
const hubReady = waitForManager(hubProbeBaseUrl);
|
|
3037
|
-
const hubStartup = hubReady.then(
|
|
3038
|
-
if (!ok) {
|
|
3039
|
-
return false;
|
|
3040
|
-
}
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3037
|
+
const hubStartup = hubReady.then(ok => {
|
|
3038
|
+
if (!ok) {
|
|
3039
|
+
return false;
|
|
3040
|
+
}
|
|
3041
|
+
void transferSavedClientSessionToHub(hubProbeBaseUrl, MANAGER_STATE_DIR).then(handoff => {
|
|
3042
|
+
if (handoff.ok) {
|
|
3043
|
+
reportLauncherUpdate('[LiveDesk Hub] Saved Client sign-in adopted by the Hub.');
|
|
3044
|
+
if (!handoff.hostTargetOk) {
|
|
3045
|
+
reportLauncherUpdate('[LiveDesk Hub] Sign-in was adopted; host publication will continue through lease renewal.', true);
|
|
3046
|
+
}
|
|
3047
|
+
} else if (!handoff.skipped) {
|
|
3048
|
+
reportLauncherUpdate(`[LiveDesk Hub] Saved Client sign-in could not be adopted: ${handoff.reason}. Continue sign-in in the Hub page.`, true);
|
|
3049
|
+
}
|
|
3050
|
+
}).catch(error => {
|
|
3051
|
+
reportLauncherUpdate(`[LiveDesk Hub] Saved Client sign-in could not be adopted: ${error instanceof Error ? error.message : String(error)}. Continue sign-in in the Hub page.`, true);
|
|
3052
|
+
});
|
|
3053
|
+
return true;
|
|
3054
|
+
});
|
|
3052
3055
|
|
|
3053
3056
|
if (options.openBrowserOnStart) {
|
|
3054
3057
|
void hubStartup.then(ok => {
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
PRODUCTION_SUPABASE_PUBLISHABLE_KEY,
|
|
13
13
|
PRODUCTION_SUPABASE_URL
|
|
14
14
|
} from '../runtime-core/src/auth-config.js';
|
|
15
|
-
import { fetchAuthResponse } from '../runtime-core/src/auth-http.js';
|
|
15
|
+
import { AUTH_REQUEST_TIMEOUT_MS, fetchAuthResponse } from '../runtime-core/src/auth-http.js';
|
|
16
16
|
import { normalizeRuntimeAuthSession } from '../runtime-core/src/auth-session.js';
|
|
17
17
|
|
|
18
18
|
const CLIENT_AUTH_STORAGE_KEY = 'livedesk.client.supabase.auth';
|
|
@@ -103,7 +103,7 @@ async function refreshSavedClientSessionForHub(
|
|
|
103
103
|
Accept: 'application/json'
|
|
104
104
|
},
|
|
105
105
|
body: JSON.stringify({ refresh_token: session.refresh_token })
|
|
106
|
-
},
|
|
106
|
+
}, AUTH_REQUEST_TIMEOUT_MS);
|
|
107
107
|
const data = await response.json().catch(() => null);
|
|
108
108
|
if (!response.ok) {
|
|
109
109
|
throw new Error(`saved-client-session-refresh-failed:${response.status}`);
|
|
@@ -163,7 +163,7 @@ export async function transferSavedClientSessionToHub(
|
|
|
163
163
|
refreshToken: resolved.session.refresh_token,
|
|
164
164
|
expiresAt: resolved.session.expires_at
|
|
165
165
|
})
|
|
166
|
-
},
|
|
166
|
+
}, AUTH_REQUEST_TIMEOUT_MS);
|
|
167
167
|
const data = await response.json().catch(() => null);
|
|
168
168
|
if (!response.ok || data?.authenticated !== true) {
|
|
169
169
|
return {
|
|
@@ -20,6 +20,12 @@ import {
|
|
|
20
20
|
createWindowsProcessTreeTracker,
|
|
21
21
|
drainOwnedWindowsAgentTreeUntilStopped
|
|
22
22
|
} from '../client/src/runtime/agent-process-lifecycle.js';
|
|
23
|
+
import {
|
|
24
|
+
addExactNpxRecoveryCacheArgument,
|
|
25
|
+
isInterruptedExactNpxInstallFailure,
|
|
26
|
+
normalizeExactNpxRecoveryCache,
|
|
27
|
+
prepareExactNpxCacheRecovery
|
|
28
|
+
} from './npm-update-cache.mjs';
|
|
23
29
|
|
|
24
30
|
const DEFAULT_RUNTIME_PORT = 5179;
|
|
25
31
|
const TARGET_ATTEMPT_LIMIT = 3;
|
|
@@ -169,8 +175,8 @@ export function buildLegacyClientUpdateNpxEnvironment(baseEnv, neutralCwd) {
|
|
|
169
175
|
return env;
|
|
170
176
|
}
|
|
171
177
|
|
|
172
|
-
function buildExactNpxArgs(neutralCwd, preference, version, args = []) {
|
|
173
|
-
return [
|
|
178
|
+
function buildExactNpxArgs(neutralCwd, preference, version, args = [], recoveryCache = '') {
|
|
179
|
+
return addExactNpxRecoveryCacheArgument([
|
|
174
180
|
'-y',
|
|
175
181
|
preference,
|
|
176
182
|
'--prefix',
|
|
@@ -178,7 +184,7 @@ function buildExactNpxArgs(neutralCwd, preference, version, args = []) {
|
|
|
178
184
|
'--workspaces=false',
|
|
179
185
|
`livedesk@${version}`,
|
|
180
186
|
...args
|
|
181
|
-
];
|
|
187
|
+
], recoveryCache);
|
|
182
188
|
}
|
|
183
189
|
|
|
184
190
|
function positivePid(value) {
|
|
@@ -1018,21 +1024,36 @@ export function prefetchExactNpxRestore(config, env = process.env, options = {})
|
|
|
1018
1024
|
throw new Error('LiveDesk cannot prefetch an exact restore without the current product version.');
|
|
1019
1025
|
}
|
|
1020
1026
|
const neutralCwd = prepareNeutralCwd(config?.neutralCwd);
|
|
1021
|
-
const
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
invocation.command,
|
|
1027
|
-
invocation.args,
|
|
1028
|
-
{
|
|
1027
|
+
const packageSpec = `livedesk@${version}`;
|
|
1028
|
+
const spawnSyncImpl = options.spawnSyncImpl || spawnSync;
|
|
1029
|
+
const runPrefetch = args => {
|
|
1030
|
+
const invocation = resolveNpxInvocation(args, env);
|
|
1031
|
+
return spawnSyncImpl(invocation.command, invocation.args, {
|
|
1029
1032
|
cwd: neutralCwd,
|
|
1030
1033
|
env: buildLegacyClientUpdateNpxEnvironment(env, neutralCwd),
|
|
1031
1034
|
encoding: 'utf8',
|
|
1032
1035
|
timeout: options.timeoutMs ?? 120_000,
|
|
1033
1036
|
windowsHide: true
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1037
|
+
});
|
|
1038
|
+
};
|
|
1039
|
+
let prepared = prepareExactNpxCacheRecovery({
|
|
1040
|
+
args: buildExactNpxArgs(neutralCwd, '--prefer-offline', version, ['--version']),
|
|
1041
|
+
env,
|
|
1042
|
+
operationId: config?.operationId,
|
|
1043
|
+
phase: 'restore-prefetch'
|
|
1044
|
+
});
|
|
1045
|
+
let result = runPrefetch(prepared.args);
|
|
1046
|
+
if (!prepared.recoveryCache
|
|
1047
|
+
&& isInterruptedExactNpxInstallFailure(result, packageSpec, env)) {
|
|
1048
|
+
prepared = prepareExactNpxCacheRecovery({
|
|
1049
|
+
args: prepared.args,
|
|
1050
|
+
env,
|
|
1051
|
+
operationId: config?.operationId,
|
|
1052
|
+
phase: 'restore-prefetch-retry',
|
|
1053
|
+
force: true
|
|
1054
|
+
});
|
|
1055
|
+
result = runPrefetch(prepared.args);
|
|
1056
|
+
}
|
|
1036
1057
|
const output = `${result?.stdout || ''}\n${result?.stderr || ''}`.trim();
|
|
1037
1058
|
if (result?.error || result?.status !== 0) {
|
|
1038
1059
|
throw new Error(
|
|
@@ -1055,7 +1076,8 @@ export function prefetchExactNpxRestore(config, env = process.env, options = {})
|
|
|
1055
1076
|
strategy: 'npx-exact-connected-proof',
|
|
1056
1077
|
productVersion: version,
|
|
1057
1078
|
agentVersion: cleanVersion(config?.currentAgentVersion),
|
|
1058
|
-
preference: '--prefer-offline'
|
|
1079
|
+
preference: '--prefer-offline',
|
|
1080
|
+
recoveryCache: prepared.recoveryCache
|
|
1059
1081
|
};
|
|
1060
1082
|
}
|
|
1061
1083
|
|
|
@@ -1076,9 +1098,15 @@ export function spawnReplacement(version, preference, env = process.env, restart
|
|
|
1076
1098
|
const neutralCwd = isLocalRestore
|
|
1077
1099
|
? ''
|
|
1078
1100
|
: prepareNeutralCwd(env.LIVEDESK_UPDATE_NEUTRAL_CWD);
|
|
1101
|
+
const recoveryCache = isLocalRestore
|
|
1102
|
+
? ''
|
|
1103
|
+
: normalizeExactNpxRecoveryCache(env.LIVEDESK_CLIENT_UPDATE_NPX_CACHE);
|
|
1079
1104
|
const invocation = isLocalRestore
|
|
1080
1105
|
? { command: process.execPath, args: [localRestoreLauncher, ...roleArgs] }
|
|
1081
|
-
: resolveNpxInvocation(
|
|
1106
|
+
: resolveNpxInvocation(
|
|
1107
|
+
buildExactNpxArgs(neutralCwd, preference, version, roleArgs, recoveryCache),
|
|
1108
|
+
env
|
|
1109
|
+
);
|
|
1082
1110
|
const replacementEnv = isLocalRestore
|
|
1083
1111
|
? { ...env }
|
|
1084
1112
|
: buildLegacyClientUpdateNpxEnvironment(env, neutralCwd);
|
|
@@ -1344,6 +1372,9 @@ export async function launchAndVerifyLegacyClientReplacement(
|
|
|
1344
1372
|
LIVEDESK_CLIENT_UPDATE_LOCAL_LAUNCHER: kind === 'restore'
|
|
1345
1373
|
? String(config.localRestoreLauncher?.entryPath || '')
|
|
1346
1374
|
: '',
|
|
1375
|
+
LIVEDESK_CLIENT_UPDATE_NPX_CACHE: kind === 'restore'
|
|
1376
|
+
? String(config.npxRestore?.recoveryCache || '')
|
|
1377
|
+
: '',
|
|
1347
1378
|
LIVEDESK_CLIENT_RUNTIME_PORT: String(config.runtimePort),
|
|
1348
1379
|
LIVEDESK_DEVICE_ID: config.deviceId,
|
|
1349
1380
|
LIVEDESK_SKIP_BROWSER_OPEN: '1'
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { isAbsolute, join, resolve, sep } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const EXACT_LIVEDESK_PACKAGE_PATTERN = /^livedesk@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/;
|
|
7
|
+
|
|
8
|
+
function environmentValue(env, name) {
|
|
9
|
+
const expected = String(name || '').toLowerCase();
|
|
10
|
+
const entry = Object.entries(env || {}).find(([key]) => String(key).toLowerCase() === expected);
|
|
11
|
+
return String(entry?.[1] || '').trim();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function safePathSegment(value, fallback = 'unknown') {
|
|
15
|
+
return String(value || '')
|
|
16
|
+
.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
17
|
+
.slice(0, 100) || fallback;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function pathInside(root, candidate) {
|
|
21
|
+
const base = resolve(root);
|
|
22
|
+
const target = resolve(candidate);
|
|
23
|
+
return target === base || target.startsWith(`${base}${sep}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readJson(filePath) {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(readFileSync(filePath, 'utf8'));
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function parseExactLiveDeskPackageSpec(value) {
|
|
35
|
+
const match = EXACT_LIVEDESK_PACKAGE_PATTERN.exec(String(value || '').trim());
|
|
36
|
+
return match ? { packageSpec: match[0], version: match[1] } : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function getExactNpxInstallHash(packageSpec) {
|
|
40
|
+
return createHash('sha512').update(String(packageSpec || '')).digest('hex').slice(0, 16);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function resolveNpmCacheRoot(env = process.env) {
|
|
44
|
+
const configured = environmentValue(env, 'npm_config_cache');
|
|
45
|
+
if (configured) return resolve(configured);
|
|
46
|
+
if (process.platform === 'win32') {
|
|
47
|
+
const localAppData = environmentValue(env, 'LOCALAPPDATA')
|
|
48
|
+
|| join(os.homedir(), 'AppData', 'Local');
|
|
49
|
+
return resolve(localAppData, 'npm-cache');
|
|
50
|
+
}
|
|
51
|
+
return resolve(os.homedir(), '.npm');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function inspectExactNpxInstall(packageSpec, env = process.env) {
|
|
55
|
+
const exact = parseExactLiveDeskPackageSpec(packageSpec);
|
|
56
|
+
if (!exact) return { state: 'not-exact-livedesk', packageSpec: '', version: '', installDir: '' };
|
|
57
|
+
const installDir = join(resolveNpmCacheRoot(env), '_npx', getExactNpxInstallHash(exact.packageSpec));
|
|
58
|
+
if (!existsSync(installDir)) {
|
|
59
|
+
return { state: 'absent', ...exact, installDir };
|
|
60
|
+
}
|
|
61
|
+
const rootManifest = readJson(join(installDir, 'package.json'));
|
|
62
|
+
const productManifest = readJson(join(installDir, 'node_modules', 'livedesk', 'package.json'));
|
|
63
|
+
const healthy = rootManifest
|
|
64
|
+
&& typeof rootManifest.dependencies?.livedesk === 'string'
|
|
65
|
+
&& productManifest?.name === 'livedesk'
|
|
66
|
+
&& String(productManifest.version || '') === exact.version;
|
|
67
|
+
return {
|
|
68
|
+
state: healthy ? 'healthy' : 'interrupted',
|
|
69
|
+
...exact,
|
|
70
|
+
installDir
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function createExactNpxRecoveryCache(operationId, phase = 'package', options = {}) {
|
|
75
|
+
const root = resolve(
|
|
76
|
+
String(options.tempDirectory || os.tmpdir()),
|
|
77
|
+
'livedesk-update-npm-cache'
|
|
78
|
+
);
|
|
79
|
+
const nonce = safePathSegment(
|
|
80
|
+
options.nonce || `${process.pid}-${Date.now()}-${randomBytes(5).toString('hex')}`,
|
|
81
|
+
String(process.pid)
|
|
82
|
+
);
|
|
83
|
+
return join(
|
|
84
|
+
root,
|
|
85
|
+
`${safePathSegment(operationId, 'operation')}-${safePathSegment(phase, 'package')}-${nonce}`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function normalizeExactNpxRecoveryCache(value, options = {}) {
|
|
90
|
+
const configured = String(value || '').trim();
|
|
91
|
+
if (!configured || !isAbsolute(configured)) return '';
|
|
92
|
+
const root = resolve(
|
|
93
|
+
String(options.tempDirectory || os.tmpdir()),
|
|
94
|
+
'livedesk-update-npm-cache'
|
|
95
|
+
);
|
|
96
|
+
const candidate = resolve(configured);
|
|
97
|
+
return candidate !== root && pathInside(root, candidate) ? candidate : '';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function addExactNpxRecoveryCacheArgument(args, recoveryCache) {
|
|
101
|
+
const values = Array.isArray(args) ? args.map(value => String(value)) : [];
|
|
102
|
+
if (!recoveryCache
|
|
103
|
+
|| values.some(value => value === '--cache' || value.startsWith('--cache='))) {
|
|
104
|
+
return values;
|
|
105
|
+
}
|
|
106
|
+
const packageIndex = values.findIndex(value => parseExactLiveDeskPackageSpec(value));
|
|
107
|
+
if (packageIndex < 0) return values;
|
|
108
|
+
return [
|
|
109
|
+
...values.slice(0, packageIndex),
|
|
110
|
+
'--cache',
|
|
111
|
+
recoveryCache,
|
|
112
|
+
...values.slice(packageIndex)
|
|
113
|
+
];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function prepareExactNpxCacheRecovery({
|
|
117
|
+
args,
|
|
118
|
+
env = process.env,
|
|
119
|
+
operationId,
|
|
120
|
+
phase,
|
|
121
|
+
force = false,
|
|
122
|
+
nonce,
|
|
123
|
+
tempDirectory
|
|
124
|
+
} = {}) {
|
|
125
|
+
const values = Array.isArray(args) ? args.map(value => String(value)) : [];
|
|
126
|
+
const exact = values.map(parseExactLiveDeskPackageSpec).find(Boolean);
|
|
127
|
+
if (!exact || values.some(value => value === '--cache' || value.startsWith('--cache='))) {
|
|
128
|
+
return { args: values, recoveryCache: '', recovered: false, inspection: null };
|
|
129
|
+
}
|
|
130
|
+
const inspection = inspectExactNpxInstall(exact.packageSpec, env);
|
|
131
|
+
if (!force && inspection.state !== 'interrupted') {
|
|
132
|
+
return { args: values, recoveryCache: '', recovered: false, inspection };
|
|
133
|
+
}
|
|
134
|
+
const recoveryCache = createExactNpxRecoveryCache(operationId, phase, {
|
|
135
|
+
nonce,
|
|
136
|
+
tempDirectory
|
|
137
|
+
});
|
|
138
|
+
return {
|
|
139
|
+
args: addExactNpxRecoveryCacheArgument(values, recoveryCache),
|
|
140
|
+
recoveryCache,
|
|
141
|
+
recovered: true,
|
|
142
|
+
inspection
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function isInterruptedExactNpxInstallFailure(result, packageSpec, env = process.env) {
|
|
147
|
+
const exact = parseExactLiveDeskPackageSpec(packageSpec);
|
|
148
|
+
if (!exact) return false;
|
|
149
|
+
const output = `${result?.error?.message || ''}\n${result?.stdout || ''}\n${result?.stderr || ''}`;
|
|
150
|
+
if (!/\bENOENT\b|Could not read package\.json/i.test(output)) return false;
|
|
151
|
+
const expectedPath = join(
|
|
152
|
+
resolveNpmCacheRoot(env),
|
|
153
|
+
'_npx',
|
|
154
|
+
getExactNpxInstallHash(exact.packageSpec),
|
|
155
|
+
'package.json'
|
|
156
|
+
).replaceAll('\\', '/').toLowerCase();
|
|
157
|
+
return output.replaceAll('\\', '/').toLowerCase().includes(expectedPath);
|
|
158
|
+
}
|
|
@@ -1,14 +1,69 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
3
3
|
import net from 'node:net';
|
|
4
4
|
import os from 'node:os';
|
|
5
|
-
import {
|
|
5
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
6
6
|
import { spawn } from 'node:child_process';
|
|
7
7
|
|
|
8
8
|
export const UPDATE_HOST_PROTOCOL_VERSION = 1;
|
|
9
9
|
export const UPDATE_HOST_DEFAULT_START_TIMEOUT_MS = 8_000;
|
|
10
10
|
export const UPDATE_HOST_DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
|
|
11
11
|
export const UPDATE_HOST_MAX_MESSAGE_BYTES = 2 * 1024 * 1024;
|
|
12
|
+
export const UPDATE_HOST_MAX_ENVIRONMENT_KEYS = 512;
|
|
13
|
+
export const UPDATE_HOST_MAX_ENVIRONMENT_VALUE_BYTES = 128 * 1024;
|
|
14
|
+
|
|
15
|
+
const UPDATE_HOST_ENVIRONMENT_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_()]*$/;
|
|
16
|
+
|
|
17
|
+
export function isValidUpdateHostEnvironmentEntry(key, value) {
|
|
18
|
+
return UPDATE_HOST_ENVIRONMENT_KEY_PATTERN.test(String(key || ''))
|
|
19
|
+
&& Buffer.byteLength(String(value ?? ''), 'utf8') <= UPDATE_HOST_MAX_ENVIRONMENT_VALUE_BYTES;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function updateHostEnvironmentPriority(key) {
|
|
23
|
+
const normalized = String(key || '').toUpperCase();
|
|
24
|
+
if (normalized.startsWith('LIVEDESK_')
|
|
25
|
+
|| normalized.startsWith('LIVE_DESK_')
|
|
26
|
+
|| normalized.startsWith('REMOTE_HUB_')) {
|
|
27
|
+
return 0;
|
|
28
|
+
}
|
|
29
|
+
if (/^(PATH|PATHEXT|SYSTEMROOT|WINDIR|COMSPEC|TEMP|TMP|TMPDIR|HOME|HOMEDRIVE|HOMEPATH|USERPROFILE|APPDATA|LOCALAPPDATA|LANG|LC_ALL|TZ|PORT)$/.test(normalized)
|
|
30
|
+
|| normalized.startsWith('NPM_')
|
|
31
|
+
|| normalized.startsWith('NODE_')
|
|
32
|
+
|| normalized.endsWith('_PROXY')
|
|
33
|
+
|| normalized.startsWith('OPENAI_')
|
|
34
|
+
|| normalized.startsWith('CODEX_')) {
|
|
35
|
+
return 1;
|
|
36
|
+
}
|
|
37
|
+
return 2;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function buildUpdateHostWorkerEnvironment(baseEnv = process.env, requiredEnv = {}) {
|
|
41
|
+
const requiredEntries = Object.entries(requiredEnv || {}).map(([key, value]) => [String(key), String(value ?? '')]);
|
|
42
|
+
for (const [key, value] of requiredEntries) {
|
|
43
|
+
if (!isValidUpdateHostEnvironmentEntry(key, value)) {
|
|
44
|
+
throw new Error(`invalid-required-update-host-environment-entry:${key}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (requiredEntries.length > UPDATE_HOST_MAX_ENVIRONMENT_KEYS) {
|
|
48
|
+
throw new Error('invalid-required-update-host-environment-count');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const requiredKeys = new Set(requiredEntries.map(([key]) => key.toUpperCase()));
|
|
52
|
+
const availableBaseEntries = UPDATE_HOST_MAX_ENVIRONMENT_KEYS - requiredEntries.length;
|
|
53
|
+
const baseEntries = Object.entries(baseEnv || {})
|
|
54
|
+
.filter(([key, value]) => value != null
|
|
55
|
+
&& !requiredKeys.has(String(key).toUpperCase())
|
|
56
|
+
&& isValidUpdateHostEnvironmentEntry(key, value))
|
|
57
|
+
.map(([key, value]) => [String(key), String(value)])
|
|
58
|
+
.sort((left, right) => {
|
|
59
|
+
const priorityDifference = updateHostEnvironmentPriority(left[0]) - updateHostEnvironmentPriority(right[0]);
|
|
60
|
+
if (priorityDifference) return priorityDifference;
|
|
61
|
+
return left[0] < right[0] ? -1 : (left[0] > right[0] ? 1 : 0);
|
|
62
|
+
})
|
|
63
|
+
.slice(0, availableBaseEntries);
|
|
64
|
+
|
|
65
|
+
return Object.fromEntries([...baseEntries, ...requiredEntries]);
|
|
66
|
+
}
|
|
12
67
|
|
|
13
68
|
function normalizedStateDir(stateDir) {
|
|
14
69
|
return resolve(String(stateDir || join(os.homedir(), '.livedesk')).trim());
|
|
@@ -31,6 +86,16 @@ export function getUpdateHostPaths(stateDir) {
|
|
|
31
86
|
};
|
|
32
87
|
}
|
|
33
88
|
|
|
89
|
+
export function getUpdateHostWorkingDirectory(stateDir) {
|
|
90
|
+
return join(normalizedStateDir(stateDir), 'update-host-cwd');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function prepareUpdateHostWorkingDirectory(stateDir) {
|
|
94
|
+
const workingDirectory = getUpdateHostWorkingDirectory(stateDir);
|
|
95
|
+
mkdirSync(workingDirectory, { recursive: true, mode: 0o700 });
|
|
96
|
+
return workingDirectory;
|
|
97
|
+
}
|
|
98
|
+
|
|
34
99
|
export function readUpdateHostStatus(statusPath) {
|
|
35
100
|
try {
|
|
36
101
|
const status = JSON.parse(readFileSync(statusPath, 'utf8'));
|
|
@@ -257,8 +322,9 @@ export async function ensureUpdateHost({
|
|
|
257
322
|
];
|
|
258
323
|
let child;
|
|
259
324
|
try {
|
|
325
|
+
const workingDirectory = prepareUpdateHostWorkingDirectory(paths.stateDir);
|
|
260
326
|
child = spawnImpl(process.execPath, args, {
|
|
261
|
-
cwd:
|
|
327
|
+
cwd: workingDirectory,
|
|
262
328
|
env: buildHostEnvironment(env),
|
|
263
329
|
detached: true,
|
|
264
330
|
stdio: 'ignore',
|
|
@@ -8,15 +8,17 @@ import { dirname, isAbsolute, resolve, sep } from 'node:path';
|
|
|
8
8
|
import { spawn } from 'node:child_process';
|
|
9
9
|
import {
|
|
10
10
|
getUpdateHostPaths,
|
|
11
|
+
prepareUpdateHostWorkingDirectory,
|
|
12
|
+
isValidUpdateHostEnvironmentEntry,
|
|
13
|
+
UPDATE_HOST_MAX_ENVIRONMENT_KEYS,
|
|
11
14
|
UPDATE_HOST_MAX_MESSAGE_BYTES,
|
|
12
15
|
UPDATE_HOST_PROTOCOL_VERSION
|
|
13
16
|
} from './update-host-client.mjs';
|
|
17
|
+
import { prepareExactNpxCacheRecovery } from './npm-update-cache.mjs';
|
|
14
18
|
|
|
15
19
|
const MAX_LOG_BYTES = 1024 * 1024;
|
|
16
20
|
const MAX_ARGUMENT_COUNT = 512;
|
|
17
21
|
const MAX_ARGUMENT_BYTES = 1024 * 1024;
|
|
18
|
-
const MAX_ENVIRONMENT_KEYS = 512;
|
|
19
|
-
const MAX_ENVIRONMENT_VALUE_BYTES = 128 * 1024;
|
|
20
22
|
const ALLOWED_JOB_KINDS = new Set(['hub-update', 'client-update']);
|
|
21
23
|
const TERMINAL_RESULT_STAGES = new Set(['updated', 'restored', 'failed', 'connected', 'cancelled']);
|
|
22
24
|
|
|
@@ -36,6 +38,8 @@ const replacePid = Number(argumentValue('--replace-pid') || 0);
|
|
|
36
38
|
const stateDir = decodeStateDir();
|
|
37
39
|
if (!stateDir) throw new Error('LiveDesk Update Host requires a state directory.');
|
|
38
40
|
const paths = getUpdateHostPaths(stateDir);
|
|
41
|
+
const workingDirectory = prepareUpdateHostWorkingDirectory(paths.stateDir);
|
|
42
|
+
process.chdir(workingDirectory);
|
|
39
43
|
const token = randomBytes(32).toString('hex');
|
|
40
44
|
const hostId = randomBytes(24).toString('hex');
|
|
41
45
|
const startedAt = new Date().toISOString();
|
|
@@ -116,6 +120,7 @@ function hostStatus() {
|
|
|
116
120
|
hostId,
|
|
117
121
|
token,
|
|
118
122
|
endpoint: paths.endpoint,
|
|
123
|
+
workingDirectory,
|
|
119
124
|
sourceVersion,
|
|
120
125
|
startedAt,
|
|
121
126
|
state: stopping ? 'stopping' : (currentJob && ['accepted', 'running'].includes(currentJob.state) ? 'busy' : 'idle'),
|
|
@@ -173,9 +178,9 @@ function validateJob(value) {
|
|
|
173
178
|
}
|
|
174
179
|
if (args.length === 0 || args.length > MAX_ARGUMENT_COUNT) throw new Error('invalid-update-host-arguments');
|
|
175
180
|
if (Buffer.byteLength(JSON.stringify(args), 'utf8') > MAX_ARGUMENT_BYTES) throw new Error('update-host-arguments-too-large');
|
|
176
|
-
if (!env || Object.keys(env).length >
|
|
181
|
+
if (!env || Object.keys(env).length > UPDATE_HOST_MAX_ENVIRONMENT_KEYS) throw new Error('invalid-update-host-environment');
|
|
177
182
|
for (const [key, item] of Object.entries(env)) {
|
|
178
|
-
if (
|
|
183
|
+
if (!isValidUpdateHostEnvironmentEntry(key, item)) {
|
|
179
184
|
throw new Error('invalid-update-host-environment-entry');
|
|
180
185
|
}
|
|
181
186
|
}
|
|
@@ -252,7 +257,7 @@ function beginHostReplacement() {
|
|
|
252
257
|
'--source-version', replacement.sourceVersion,
|
|
253
258
|
'--replace-pid', String(process.pid)
|
|
254
259
|
], {
|
|
255
|
-
cwd:
|
|
260
|
+
cwd: workingDirectory,
|
|
256
261
|
env: process.env,
|
|
257
262
|
detached: true,
|
|
258
263
|
stdio: 'ignore',
|
|
@@ -270,13 +275,26 @@ function beginHostReplacement() {
|
|
|
270
275
|
}
|
|
271
276
|
|
|
272
277
|
function startJob(value) {
|
|
273
|
-
const
|
|
278
|
+
const validatedJob = validateJob(value);
|
|
274
279
|
if (currentJob && ['accepted', 'running'].includes(currentJob.state)) {
|
|
275
|
-
if (currentJob.jobId ===
|
|
280
|
+
if (currentJob.jobId === validatedJob.jobId && currentJob.operationId === validatedJob.operationId) return currentJob;
|
|
276
281
|
const error = new Error(`LiveDesk Update Host is busy with ${currentJob.operationId}.`);
|
|
277
282
|
error.code = 'LIVEDESK_UPDATE_HOST_BUSY';
|
|
278
283
|
throw error;
|
|
279
284
|
}
|
|
285
|
+
const cacheRecovery = validatedJob.kind === 'client-update'
|
|
286
|
+
? prepareExactNpxCacheRecovery({
|
|
287
|
+
args: validatedJob.args,
|
|
288
|
+
env: validatedJob.env,
|
|
289
|
+
operationId: validatedJob.operationId,
|
|
290
|
+
phase: 'target-worker'
|
|
291
|
+
})
|
|
292
|
+
: { args: validatedJob.args, recoveryCache: '', recovered: false };
|
|
293
|
+
const job = {
|
|
294
|
+
...validatedJob,
|
|
295
|
+
args: cacheRecovery.args,
|
|
296
|
+
recoveryCache: cacheRecovery.recoveryCache
|
|
297
|
+
};
|
|
280
298
|
currentJob = {
|
|
281
299
|
...job,
|
|
282
300
|
state: 'accepted',
|
|
@@ -307,6 +325,9 @@ function startJob(value) {
|
|
|
307
325
|
currentJob.startedAt = new Date().toISOString();
|
|
308
326
|
currentJob.state = 'running';
|
|
309
327
|
workerSpawnCount += 1;
|
|
328
|
+
if (cacheRecovery.recovered) {
|
|
329
|
+
appendLog(`job=${job.jobId} operation=${job.operationId} npm-cache-recovery=isolated reason=interrupted-exact-npx-install`);
|
|
330
|
+
}
|
|
310
331
|
appendLog(`job=${job.jobId} kind=${job.kind} operation=${job.operationId} state=running workerPid=${currentJob.workerPid}`);
|
|
311
332
|
publishStatus();
|
|
312
333
|
child.once('error', error => finishJob(currentJob, 'failed', { error: error.message }));
|
package/client/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@livedesk/client",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.240",
|
|
4
4
|
"description": "LiveDesk local remote client",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -42,10 +42,10 @@
|
|
|
42
42
|
"ws": "^8.18.3"
|
|
43
43
|
},
|
|
44
44
|
"optionalDependencies": {
|
|
45
|
-
"@livedesk/fast-linux-x64": "0.1.
|
|
46
|
-
"@livedesk/fast-osx-arm64": "0.1.
|
|
47
|
-
"@livedesk/fast-osx-x64": "0.1.
|
|
48
|
-
"@livedesk/fast-win-x64": "0.1.
|
|
45
|
+
"@livedesk/fast-linux-x64": "0.1.439",
|
|
46
|
+
"@livedesk/fast-osx-arm64": "0.1.439",
|
|
47
|
+
"@livedesk/fast-osx-x64": "0.1.439",
|
|
48
|
+
"@livedesk/fast-win-x64": "0.1.439"
|
|
49
49
|
},
|
|
50
50
|
"publishConfig": {
|
|
51
51
|
"access": "public"
|