@tianacloud/dsh-remote 0.0.0-stage → 0.2.1
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/LICENSE +204 -0
- package/README.md +44 -2
- package/cli.js +347 -0
- package/client.js +1501 -0
- package/cordis.patch.yml +3 -0
- package/host-main.js +628 -0
- package/icon.svg +7 -0
- package/locale/en-US.json +9 -0
- package/locale/zh-CN.json +9 -0
- package/package.json +89 -4
- package/relay-go/go.mod +3 -0
- package/relay-go/main.go +1711 -0
- package/scripts/build-web-dist.mjs +46 -0
- package/src/clipboard.js +94 -0
- package/src/connect.js +599 -0
- package/src/dsh-packages.js +46 -0
- package/src/frontend-assets.js +405 -0
- package/src/host-bridge.js +1412 -0
- package/src/local-transport.js +496 -0
- package/src/protocol.js +124 -0
- package/src/remote-api.js +433 -0
- package/src/state.js +379 -0
- package/src/tiana-cli.js +929 -0
- package/web-src/dsh-remote-entry.mjs +2692 -0
- package/web-src/dsh-remote-sw.js +593 -0
- package/web-src/e2ee.js +460 -0
- package/web-src/frontend-loader.js +450 -0
- package/web-src/multipath.js +375 -0
- package/web-src/peer-path.js +265 -0
- package/web-src/shell-ui.js +280 -0
- package/web-src/ws-fragments.js +46 -0
package/src/connect.js
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline/promises';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { copyToClipboard, maskPairingKey } from './clipboard.js';
|
|
8
|
+
import { formatPairingKey, readRuntimeInfo, resolveDshHome } from './state.js';
|
|
9
|
+
import { bindTianaRemoteWeb, getTianaStatus, tianaBinary } from './tiana-cli.js';
|
|
10
|
+
|
|
11
|
+
const execFileAsync = promisify(execFile);
|
|
12
|
+
|
|
13
|
+
export const MIN_NODE_VERSION = '24.9.0';
|
|
14
|
+
export const MIN_TIANA_CLI_VERSION = '1.0.32';
|
|
15
|
+
const NPM_REGISTRY = 'https://registry.npmjs.org/';
|
|
16
|
+
const TIANA_CLI_PKG = '@tianacloud/cli@latest';
|
|
17
|
+
const TIANA_SKILLS_PKG = '@tianacloud/agent-skills@latest';
|
|
18
|
+
|
|
19
|
+
export function compareSemver(a, b) {
|
|
20
|
+
const pa = String(a || '0.0.0').replace(/^v/u, '').split('-')[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
|
|
21
|
+
const pb = String(b || '0.0.0').replace(/^v/u, '').split('-')[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
|
|
22
|
+
for (let i = 0; i < 3; i += 1) {
|
|
23
|
+
if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
|
|
24
|
+
}
|
|
25
|
+
return 0;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function extractSemver(text) {
|
|
29
|
+
const match = /(\d+\.\d+\.\d+)/u.exec(String(text || ''));
|
|
30
|
+
return match ? match[1] : '';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function checkNodeVersion(current = process.versions.node, required = MIN_NODE_VERSION) {
|
|
34
|
+
const ok = compareSemver(current, required) >= 0;
|
|
35
|
+
if (ok) {
|
|
36
|
+
return { ok: true, current, required, message: '' };
|
|
37
|
+
}
|
|
38
|
+
const message = [
|
|
39
|
+
`[dsh-remote] Node.js >= ${required} is required (current: v${current}).`,
|
|
40
|
+
`DeepSeek Harness (@deepseek-ai/dsh) requires Node.js >= ${required}.`,
|
|
41
|
+
'',
|
|
42
|
+
'Upgrade Node.js and re-run this command:',
|
|
43
|
+
' macOS / Linux (fnm): fnm install 24 && fnm use 24',
|
|
44
|
+
' macOS / Linux (nvm): nvm install 24 && nvm use 24',
|
|
45
|
+
' Windows (winget): winget install OpenJS.NodeJS.LTS',
|
|
46
|
+
' Windows (fnm): fnm install 24 && fnm use 24',
|
|
47
|
+
' Official downloads: https://nodejs.org/',
|
|
48
|
+
].join('\n');
|
|
49
|
+
return { ok: false, current, required, message };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function parseAppArg(raw) {
|
|
53
|
+
const input = String(raw || '').trim();
|
|
54
|
+
if (!input) return '';
|
|
55
|
+
if (/^[a-z][a-z0-9]{11}$/u.test(input)) return input;
|
|
56
|
+
try {
|
|
57
|
+
const url = new URL(input);
|
|
58
|
+
const match = /^\/web\/([a-z][a-z0-9]{11})(?:\/|$)/u.exec(url.pathname);
|
|
59
|
+
if (match) return match[1];
|
|
60
|
+
const hostLabel = url.hostname.split('.')[0];
|
|
61
|
+
if (/^[a-z][a-z0-9]{11}$/u.test(hostLabel)) return hostLabel;
|
|
62
|
+
} catch {
|
|
63
|
+
// not a URL
|
|
64
|
+
}
|
|
65
|
+
return '';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Idempotently ensure plugin entries exist in ~/.dsh/cordis.patch.yml (or profile patch)
|
|
70
|
+
* without overwriting or stripping existing user plugins or configuration.
|
|
71
|
+
*/
|
|
72
|
+
export function mergeCordisPatchYml(existingContent, requiredPlugins = [
|
|
73
|
+
{ id: 'tiana', name: '@tianacloud/dsh-tiana' },
|
|
74
|
+
{ id: 'tiana-remote', name: '@tianacloud/dsh-remote' },
|
|
75
|
+
]) {
|
|
76
|
+
const raw = String(existingContent || '');
|
|
77
|
+
const toAdd = requiredPlugins.filter((plugin) => !raw.includes(plugin.name));
|
|
78
|
+
if (toAdd.length === 0) return raw;
|
|
79
|
+
|
|
80
|
+
const snippet = toAdd.map((p) => ` - id: ${p.id}\n name: '${p.name}'`).join('\n');
|
|
81
|
+
if (!raw.trim()) {
|
|
82
|
+
return `- insert:\n${snippet}\n`;
|
|
83
|
+
}
|
|
84
|
+
const insertMatch = /^([ \t]*-[ \t]+insert:\s*\n)/mu.exec(raw);
|
|
85
|
+
if (insertMatch) {
|
|
86
|
+
const pos = insertMatch.index + insertMatch[0].length;
|
|
87
|
+
return `${raw.slice(0, pos)}${snippet}\n${raw.slice(pos)}`;
|
|
88
|
+
}
|
|
89
|
+
const sep = raw.endsWith('\n') ? '' : '\n';
|
|
90
|
+
return `${raw}${sep}- insert:\n${snippet}\n`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function ensureCordisPatchFile({ dshHome = resolveDshHome(), profile = '' } = {}) {
|
|
94
|
+
const target = profile
|
|
95
|
+
? join(dshHome, 'profiles', profile, 'cordis.patch.yml')
|
|
96
|
+
: join(dshHome, 'cordis.patch.yml');
|
|
97
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
98
|
+
const before = existsSync(target) ? readFileSync(target, 'utf8') : '';
|
|
99
|
+
const after = mergeCordisPatchYml(before);
|
|
100
|
+
if (after !== before) {
|
|
101
|
+
writeFileSync(target, after, 'utf8');
|
|
102
|
+
}
|
|
103
|
+
return { path: target, changed: after !== before };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function platformCmd(name, platform = process.platform) {
|
|
107
|
+
return platform === 'win32' ? `${name}.cmd` : name;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function execQuiet(bin, args, options = {}) {
|
|
111
|
+
return await execFileAsync(bin, args, {
|
|
112
|
+
timeout: options.timeoutMs ?? 15_000,
|
|
113
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
114
|
+
env: options.env ?? process.env,
|
|
115
|
+
shell: process.platform === 'win32',
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function getNpmGlobalBinCandidates(cmdName, execFn = execQuiet, platform = process.platform) {
|
|
120
|
+
const out = [];
|
|
121
|
+
try {
|
|
122
|
+
const { stdout } = await execFn(platformCmd('npm', platform), ['prefix', '-g'], { timeoutMs: 10_000 });
|
|
123
|
+
const prefix = String(stdout || '').trim();
|
|
124
|
+
if (prefix) {
|
|
125
|
+
const cmd = platformCmd(cmdName, platform);
|
|
126
|
+
if (platform === 'win32') {
|
|
127
|
+
out.push(join(prefix, cmd), join(prefix, 'bin', cmd));
|
|
128
|
+
} else {
|
|
129
|
+
out.push(join(prefix, 'bin', cmd));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
} catch {
|
|
133
|
+
// ignore if npm prefix -g is unavailable
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function resolveDshBinary(execFn = execQuiet, platform = process.platform) {
|
|
139
|
+
const candidates = [
|
|
140
|
+
process.env.DSH_BIN,
|
|
141
|
+
platformCmd('dsh', platform),
|
|
142
|
+
join(homedir(), '.local', 'bin', platformCmd('dsh', platform)),
|
|
143
|
+
].filter(Boolean);
|
|
144
|
+
|
|
145
|
+
for (const bin of candidates) {
|
|
146
|
+
try {
|
|
147
|
+
const { stdout } = await execFn(bin, ['--version'], { timeoutMs: 15_000 });
|
|
148
|
+
return { bin, version: String(stdout || '').trim() };
|
|
149
|
+
} catch {
|
|
150
|
+
// try next
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
for (const bin of await getNpmGlobalBinCandidates('dsh', execFn, platform)) {
|
|
154
|
+
if (candidates.includes(bin)) continue;
|
|
155
|
+
try {
|
|
156
|
+
const { stdout } = await execFn(bin, ['--version'], { timeoutMs: 15_000 });
|
|
157
|
+
return { bin, version: String(stdout || '').trim() };
|
|
158
|
+
} catch {
|
|
159
|
+
// try next
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function installNpmGlobalWithFallback(pkg, { execFn = execQuiet, log = console.error, platform = process.platform } = {}) {
|
|
166
|
+
const npmBin = platformCmd('npm', platform);
|
|
167
|
+
try {
|
|
168
|
+
await execFn(npmBin, ['install', '-g', `--registry=${NPM_REGISTRY}`, pkg], {
|
|
169
|
+
timeoutMs: 240_000,
|
|
170
|
+
});
|
|
171
|
+
return { userLocal: false, prefix: null };
|
|
172
|
+
} catch (err) {
|
|
173
|
+
const msg = String(err?.stderr || err?.message || err);
|
|
174
|
+
if (platform === 'win32' || !/EACCES|EPERM|permission/iu.test(msg)) {
|
|
175
|
+
throw new Error(`Failed to install ${pkg}: ${msg}`);
|
|
176
|
+
}
|
|
177
|
+
const prefix = join(homedir(), '.local');
|
|
178
|
+
log(`[dsh-remote] Global npm prefix not writable; falling back to user prefix ${prefix} (no sudo)...`);
|
|
179
|
+
await execFn(npmBin, ['install', '-g', '--prefix', prefix, `--registry=${NPM_REGISTRY}`, pkg], {
|
|
180
|
+
timeoutMs: 240_000,
|
|
181
|
+
});
|
|
182
|
+
return { userLocal: true, prefix };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function installDshPackage(execFn = execQuiet, log = console.error, platform = process.platform) {
|
|
187
|
+
log('[dsh-remote] DeepSeek Harness (dsh) not found. Installing @deepseek-ai/dsh@latest...');
|
|
188
|
+
const { userLocal, prefix } = await installNpmGlobalWithFallback('@deepseek-ai/dsh@latest', { execFn, log, platform });
|
|
189
|
+
if (userLocal && prefix) {
|
|
190
|
+
const localBin = join(prefix, 'bin', platformCmd('dsh', platform));
|
|
191
|
+
const { stdout } = await execFn(localBin, ['--version'], { timeoutMs: 15_000 });
|
|
192
|
+
return { bin: localBin, version: String(stdout || '').trim(), userLocal: true };
|
|
193
|
+
}
|
|
194
|
+
const found = await resolveDshBinary(execFn, platform);
|
|
195
|
+
if (found) return { ...found, userLocal: false };
|
|
196
|
+
throw new Error('Installed @deepseek-ai/dsh@latest but could not locate the `dsh` executable.');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function resolveTianaBinary(execFn = execQuiet, platform = process.platform) {
|
|
200
|
+
const candidates = [
|
|
201
|
+
process.env.TIANA_BIN,
|
|
202
|
+
platformCmd('tiana', platform),
|
|
203
|
+
join(homedir(), '.local', 'bin', platformCmd('tiana', platform)),
|
|
204
|
+
].filter(Boolean);
|
|
205
|
+
|
|
206
|
+
for (const bin of candidates) {
|
|
207
|
+
try {
|
|
208
|
+
const res = await execFn(bin, ['version'], { timeoutMs: 15_000 });
|
|
209
|
+
const ver = extractSemver(`${res?.stdout || ''}\n${res?.stderr || ''}`);
|
|
210
|
+
if (ver) return { bin, version: ver };
|
|
211
|
+
} catch {
|
|
212
|
+
// try next
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
for (const bin of await getNpmGlobalBinCandidates('tiana', execFn, platform)) {
|
|
216
|
+
if (candidates.includes(bin)) continue;
|
|
217
|
+
try {
|
|
218
|
+
const res = await execFn(bin, ['version'], { timeoutMs: 15_000 });
|
|
219
|
+
const ver = extractSemver(`${res?.stdout || ''}\n${res?.stderr || ''}`);
|
|
220
|
+
if (ver) return { bin, version: ver };
|
|
221
|
+
} catch {
|
|
222
|
+
// try next
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Ensure `@tianacloud/cli` >= 1.0.32 and official `@tianacloud/agent-skills` in `$DSH_HOME/skills`.
|
|
230
|
+
* Mirrors `dsh-tiana/install.js` and returns the verified executable path for `tiana`.
|
|
231
|
+
*/
|
|
232
|
+
export async function ensureTianaToolchain({
|
|
233
|
+
execFn = execQuiet,
|
|
234
|
+
log = console.error,
|
|
235
|
+
dshHome = resolveDshHome(),
|
|
236
|
+
platform = process.platform,
|
|
237
|
+
} = {}) {
|
|
238
|
+
let found = await resolveTianaBinary(execFn, platform);
|
|
239
|
+
let installedCli = false;
|
|
240
|
+
let userLocalCli = false;
|
|
241
|
+
|
|
242
|
+
if (!found || compareSemver(found.version, MIN_TIANA_CLI_VERSION) < 0) {
|
|
243
|
+
const reason = found
|
|
244
|
+
? `Tiana CLI v${found.version} is below ${MIN_TIANA_CLI_VERSION}`
|
|
245
|
+
: 'Tiana CLI not found';
|
|
246
|
+
log(`[dsh-remote] ${reason}. Installing ${TIANA_CLI_PKG}...`);
|
|
247
|
+
const installRes = await installNpmGlobalWithFallback(TIANA_CLI_PKG, { execFn, log, platform });
|
|
248
|
+
installedCli = true;
|
|
249
|
+
userLocalCli = installRes.userLocal;
|
|
250
|
+
|
|
251
|
+
if (userLocalCli && installRes.prefix) {
|
|
252
|
+
const localBin = join(installRes.prefix, 'bin', platformCmd('tiana', platform));
|
|
253
|
+
const res = await execFn(localBin, ['version'], { timeoutMs: 15_000 });
|
|
254
|
+
const ver = extractSemver(`${res?.stdout || ''}\n${res?.stderr || ''}`);
|
|
255
|
+
found = ver ? { bin: localBin, version: ver } : null;
|
|
256
|
+
} else {
|
|
257
|
+
found = await resolveTianaBinary(execFn, platform);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (!found || compareSemver(found.version, MIN_TIANA_CLI_VERSION) < 0) {
|
|
262
|
+
throw new Error(
|
|
263
|
+
`Tiana CLI >= ${MIN_TIANA_CLI_VERSION} is required (found: ${found?.version || 'none'}).`,
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Sync official Tiana skills into `$DSH_HOME/skills`
|
|
268
|
+
const skillsDir = join(dshHome, 'skills');
|
|
269
|
+
mkdirSync(skillsDir, { recursive: true });
|
|
270
|
+
log(`[dsh-remote] Syncing ${TIANA_SKILLS_PKG} to ${skillsDir}...`);
|
|
271
|
+
const npxBin = platformCmd('npx', platform);
|
|
272
|
+
const pnpmBin = platformCmd('pnpm', platform);
|
|
273
|
+
let skillsSynced = false;
|
|
274
|
+
let lastSkillsErr = null;
|
|
275
|
+
for (const [cmd, args] of [
|
|
276
|
+
[npxBin, ['--yes', TIANA_SKILLS_PKG, 'install', '--dir', skillsDir]],
|
|
277
|
+
[pnpmBin, ['dlx', TIANA_SKILLS_PKG, 'install', '--dir', skillsDir]],
|
|
278
|
+
]) {
|
|
279
|
+
try {
|
|
280
|
+
await execFn(cmd, args, { timeoutMs: 180_000 });
|
|
281
|
+
skillsSynced = true;
|
|
282
|
+
break;
|
|
283
|
+
} catch (err) {
|
|
284
|
+
lastSkillsErr = err;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (!skillsSynced) {
|
|
288
|
+
throw new Error(
|
|
289
|
+
`Failed to install ${TIANA_SKILLS_PKG} into ${skillsDir}: ${lastSkillsErr instanceof Error ? lastSkillsErr.message : String(lastSkillsErr)}`,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return {
|
|
294
|
+
bin: found.bin,
|
|
295
|
+
version: found.version,
|
|
296
|
+
installedCli,
|
|
297
|
+
userLocalCli,
|
|
298
|
+
skillsDir,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export async function ensureDshPlugins(dshBin, { profile = 'web', execFn = execQuiet, log = console.error } = {}) {
|
|
303
|
+
for (const pkg of ['@tianacloud/dsh-tiana@latest', '@tianacloud/dsh-remote@latest']) {
|
|
304
|
+
log(`[dsh-remote] Ensuring plugin ${pkg} in profile "${profile}"...`);
|
|
305
|
+
try {
|
|
306
|
+
await execFn(dshBin, ['plugin', '--profile', profile, 'add', pkg], { timeoutMs: 180_000 });
|
|
307
|
+
} catch (err) {
|
|
308
|
+
const detail = String(err?.stderr || err?.message || err).trim();
|
|
309
|
+
throw new Error(`Failed to install DSH plugin ${pkg} in profile "${profile}": ${detail}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
ensureCordisPatchFile({ profile: '' });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function ensureTianaLoggedIn({ interactive, tianaBin, log = console.error } = {}) {
|
|
316
|
+
const cliOpts = tianaBin ? { bin: tianaBin } : {};
|
|
317
|
+
try {
|
|
318
|
+
return await getTianaStatus(cliOpts);
|
|
319
|
+
} catch {
|
|
320
|
+
if (!interactive) {
|
|
321
|
+
throw new Error('Not logged in to Tiana. Run `tiana login` first.');
|
|
322
|
+
}
|
|
323
|
+
log('[dsh-remote] Not logged in to Tiana. Launching `tiana login`...');
|
|
324
|
+
await new Promise((resolve, reject) => {
|
|
325
|
+
const child = spawn(tianaBinary(tianaBin), ['login'], {
|
|
326
|
+
stdio: 'inherit',
|
|
327
|
+
shell: process.platform === 'win32',
|
|
328
|
+
});
|
|
329
|
+
child.on('error', reject);
|
|
330
|
+
child.on('exit', (code) => {
|
|
331
|
+
if (code === 0) resolve();
|
|
332
|
+
else reject(new Error(`tiana login exited with code ${code}`));
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
return await getTianaStatus(cliOpts);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function openBrowserUrl(url, { platform = process.platform, spawnFn = spawn } = {}) {
|
|
340
|
+
const parsed = new URL(url);
|
|
341
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
342
|
+
throw new Error('Only http/https URLs may be opened');
|
|
343
|
+
}
|
|
344
|
+
if (parsed.hash.includes('rk=') || parsed.hash.includes('k=') || parsed.href.includes('dshk1_')) {
|
|
345
|
+
throw new Error('Refusing to open URL containing pairing key material');
|
|
346
|
+
}
|
|
347
|
+
let cmd;
|
|
348
|
+
let args;
|
|
349
|
+
if (platform === 'darwin') {
|
|
350
|
+
cmd = 'open';
|
|
351
|
+
args = [parsed.href];
|
|
352
|
+
} else if (platform === 'win32') {
|
|
353
|
+
cmd = 'cmd';
|
|
354
|
+
args = ['/c', 'start', '', parsed.href];
|
|
355
|
+
} else {
|
|
356
|
+
cmd = 'xdg-open';
|
|
357
|
+
args = [parsed.href];
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
const child = spawnFn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true });
|
|
361
|
+
child.on?.('error', () => {});
|
|
362
|
+
child.unref?.();
|
|
363
|
+
return true;
|
|
364
|
+
} catch {
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Probe whether a local DSH web server with `@tianacloud/dsh-remote` mounted is responsive.
|
|
371
|
+
* NEVER treats 404 or 5xx as ready: accepts ONLY 200 with valid public-status JSON (`configured` boolean)
|
|
372
|
+
* or 401/403 from DSH's own local owner auth fence.
|
|
373
|
+
*/
|
|
374
|
+
export async function isLocalDshResponsive(origin, { fetchFn = fetch, timeoutMs = 1500 } = {}) {
|
|
375
|
+
if (!origin) return false;
|
|
376
|
+
try {
|
|
377
|
+
const url = new URL('/api/tiana-remote/public-status', origin);
|
|
378
|
+
const resp = await fetchFn(url, {
|
|
379
|
+
method: 'GET',
|
|
380
|
+
redirect: 'error',
|
|
381
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
382
|
+
});
|
|
383
|
+
if (resp.status === 200) {
|
|
384
|
+
const body = await resp.json().catch(() => null);
|
|
385
|
+
return Boolean(body && typeof body === 'object' && typeof body.configured === 'boolean');
|
|
386
|
+
}
|
|
387
|
+
// 401/403 means DSH's connection.requestRejection fence answered on the mounted route
|
|
388
|
+
if (resp.status === 401 || resp.status === 403) {
|
|
389
|
+
return true;
|
|
390
|
+
}
|
|
391
|
+
return false;
|
|
392
|
+
} catch {
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export async function waitForLocalDshReady(port, timeoutMs = 15_000, { childState = null, fetchFn = fetch } = {}) {
|
|
398
|
+
const deadline = Date.now() + timeoutMs;
|
|
399
|
+
const origin = `http://127.0.0.1:${port}`;
|
|
400
|
+
while (Date.now() < deadline) {
|
|
401
|
+
if (childState?.error) {
|
|
402
|
+
throw new Error(`Failed to spawn local DSH: ${childState.error.message}`);
|
|
403
|
+
}
|
|
404
|
+
if (childState?.exited && childState.exitCode !== 0) {
|
|
405
|
+
throw new Error(`Local DSH exited prematurely with code ${childState.exitCode}`);
|
|
406
|
+
}
|
|
407
|
+
if (await isLocalDshResponsive(origin, { fetchFn })) {
|
|
408
|
+
return true;
|
|
409
|
+
}
|
|
410
|
+
await new Promise((r) => setTimeout(r, 350));
|
|
411
|
+
}
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Full `dsh-remote connect` orchestrator.
|
|
417
|
+
* Supports dependency injection via `deps` for comprehensive offline unit tests.
|
|
418
|
+
*/
|
|
419
|
+
export async function runConnect(options = {}, deps = {}) {
|
|
420
|
+
const log = options.json ? (...args) => console.error(...args) : (deps.log ?? console.log);
|
|
421
|
+
const nodeCheck = checkNodeVersion(deps.nodeVersion ?? process.versions.node);
|
|
422
|
+
if (!nodeCheck.ok) {
|
|
423
|
+
const err = new Error(nodeCheck.message);
|
|
424
|
+
err.exitCode = 2;
|
|
425
|
+
throw err;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const webId = parseAppArg(options.app || options.web);
|
|
429
|
+
if (!webId) {
|
|
430
|
+
throw new Error('Provide --app <appIdOrUrl> (or --web <webId>) for the Tiana DSH Remote app.');
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const profile = options.profile || 'web';
|
|
434
|
+
const port = Number(options.port || process.env.DSH_PORT || 3080);
|
|
435
|
+
const interactive = Boolean(!options.json && process.stdin.isTTY && process.stdout.isTTY);
|
|
436
|
+
const execFn = deps.execFn ?? execQuiet;
|
|
437
|
+
const fetchFn = deps.fetchFn ?? fetch;
|
|
438
|
+
|
|
439
|
+
// Step 2: Detect or install DSH
|
|
440
|
+
let dshInfo = deps.resolveDsh ? await deps.resolveDsh() : await resolveDshBinary(execFn);
|
|
441
|
+
let installedDsh = false;
|
|
442
|
+
if (!dshInfo) {
|
|
443
|
+
dshInfo = deps.installDsh ? await deps.installDsh() : await installDshPackage(execFn, log);
|
|
444
|
+
installedDsh = true;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// Step 3a: Idempotently ensure dsh-tiana + dsh-remote plugins (fail-fast on error!)
|
|
448
|
+
if (deps.ensurePlugins) {
|
|
449
|
+
await deps.ensurePlugins(dshInfo.bin, profile);
|
|
450
|
+
} else {
|
|
451
|
+
await ensureDshPlugins(dshInfo.bin, { profile, execFn, log });
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Step 3b: Ensure `@tianacloud/cli >= 1.0.32` & `@tianacloud/agent-skills` in `$DSH_HOME/skills`
|
|
455
|
+
const tianaToolchain = deps.ensureTianaToolchain
|
|
456
|
+
? await deps.ensureTianaToolchain()
|
|
457
|
+
: await ensureTianaToolchain({ execFn, log });
|
|
458
|
+
const tianaBin = tianaToolchain?.bin;
|
|
459
|
+
|
|
460
|
+
// Step 4: Ensure Tiana CLI login using verified tiana executable
|
|
461
|
+
if (deps.ensureLogin) {
|
|
462
|
+
await deps.ensureLogin(tianaBin);
|
|
463
|
+
} else {
|
|
464
|
+
await ensureTianaLoggedIn({ interactive, tianaBin, log });
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Step 5: Zero-recompile binding (DSH_REMOTE_POLICY + Token + state.json)
|
|
468
|
+
const confirmRebind = async (existingPolicy, target) => {
|
|
469
|
+
if (!interactive) return false;
|
|
470
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
471
|
+
try {
|
|
472
|
+
const answer = await rl.question(
|
|
473
|
+
`App ${webId} is currently bound to "${existingPolicy.hostName || existingPolicy.hostId}" (${existingPolicy.hostId}). Rebind to "${target.hostName}" (${target.hostId})? [y/N] `,
|
|
474
|
+
);
|
|
475
|
+
return /^y(?:es)?$/iu.test(answer.trim());
|
|
476
|
+
} finally {
|
|
477
|
+
rl.close();
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
const bindFn = deps.bindRemoteWeb ?? bindTianaRemoteWeb;
|
|
482
|
+
const state = await bindFn({
|
|
483
|
+
webId,
|
|
484
|
+
spaceId: options.space,
|
|
485
|
+
hostName: options.hostName,
|
|
486
|
+
rebind: Boolean(options.rebind),
|
|
487
|
+
confirmRebind: deps.confirmRebind ?? confirmRebind,
|
|
488
|
+
statePath: options.statePath,
|
|
489
|
+
tianaBin,
|
|
490
|
+
log,
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
// Step 6: Verify local DSH liveness (PID + real health probe) and start if needed
|
|
494
|
+
let dshStarted = false;
|
|
495
|
+
const runtime = deps.readRuntime ? deps.readRuntime() : readRuntimeInfo();
|
|
496
|
+
let runtimeAlive = false;
|
|
497
|
+
if (runtime) {
|
|
498
|
+
if (deps.checkDshResponsive) {
|
|
499
|
+
runtimeAlive = await deps.checkDshResponsive(runtime.origin || `http://127.0.0.1:${port}`);
|
|
500
|
+
} else if (runtime.origin) {
|
|
501
|
+
runtimeAlive = await isLocalDshResponsive(runtime.origin, { fetchFn });
|
|
502
|
+
} else {
|
|
503
|
+
runtimeAlive = await isLocalDshResponsive(`http://127.0.0.1:${port}`, { fetchFn });
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (!options.noStart && !runtimeAlive) {
|
|
508
|
+
if (deps.startDsh) {
|
|
509
|
+
dshStarted = await deps.startDsh(dshInfo.bin, { profile, port });
|
|
510
|
+
} else {
|
|
511
|
+
log(`[dsh-remote] Starting local DSH (${dshInfo.bin} web --port ${port} --no-open)...`);
|
|
512
|
+
const childState = { error: null, exited: false, exitCode: null };
|
|
513
|
+
const child = spawn(dshInfo.bin, ['web', '--profile', profile, '--port', String(port), '--no-open'], {
|
|
514
|
+
stdio: 'ignore',
|
|
515
|
+
detached: true,
|
|
516
|
+
windowsHide: true,
|
|
517
|
+
shell: process.platform === 'win32',
|
|
518
|
+
});
|
|
519
|
+
child.on('error', (err) => {
|
|
520
|
+
childState.error = err;
|
|
521
|
+
});
|
|
522
|
+
child.on('exit', (code) => {
|
|
523
|
+
childState.exited = true;
|
|
524
|
+
childState.exitCode = code;
|
|
525
|
+
});
|
|
526
|
+
child.unref();
|
|
527
|
+
dshStarted = await waitForLocalDshReady(port, 15_000, { childState, fetchFn });
|
|
528
|
+
}
|
|
529
|
+
if (!dshStarted) {
|
|
530
|
+
throw new Error(`Local DSH web server failed to become ready on 127.0.0.1:${port}`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// Step 7: Copy pairing key to clipboard (never in URL!)
|
|
535
|
+
const pairingKey = formatPairingKey(state.e2ee.secret);
|
|
536
|
+
let clipboardResult = { ok: false, skipped: true };
|
|
537
|
+
if (!options.noClipboard && !options.json) {
|
|
538
|
+
const copyFn = deps.copyToClipboard ?? copyToClipboard;
|
|
539
|
+
clipboardResult = await copyFn(pairingKey);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// Step 8: Open clean URL (no #rk= or query key!)
|
|
543
|
+
const cleanUrl = state.web.endpoint;
|
|
544
|
+
let browserOpened = false;
|
|
545
|
+
if (!options.noOpen && !options.json) {
|
|
546
|
+
const openFn = deps.openBrowser ?? openBrowserUrl;
|
|
547
|
+
browserOpened = openFn(cleanUrl);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const summary = {
|
|
551
|
+
ok: true,
|
|
552
|
+
webId: state.web.id,
|
|
553
|
+
hostId: state.host.hostId,
|
|
554
|
+
hostName: state.host.hostName,
|
|
555
|
+
endpoint: cleanUrl,
|
|
556
|
+
fingerprint: state.e2ee.fingerprint,
|
|
557
|
+
clipboardCopied: Boolean(clipboardResult.ok),
|
|
558
|
+
clipboardTool: clipboardResult.tool || null,
|
|
559
|
+
dshInstalled: installedDsh,
|
|
560
|
+
dshStarted: Boolean(dshStarted || runtimeAlive),
|
|
561
|
+
browserOpened,
|
|
562
|
+
...(!options.json && options.printKey ? { pairingKey } : {}),
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
if (options.json) {
|
|
566
|
+
console.log(JSON.stringify(summary, null, 2));
|
|
567
|
+
return summary;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
log('');
|
|
571
|
+
log('============================================================');
|
|
572
|
+
log('DSH Remote connected!');
|
|
573
|
+
log(` Host : ${state.host.hostName} (${state.host.hostId})`);
|
|
574
|
+
log(` Remote URL : ${cleanUrl}`);
|
|
575
|
+
log(` Fingerprint : ${state.e2ee.fingerprint}`);
|
|
576
|
+
if (clipboardResult.ok) {
|
|
577
|
+
log(` Pairing Key : ${maskPairingKey(pairingKey)} (copied to clipboard via ${clipboardResult.tool})`);
|
|
578
|
+
} else if (options.printKey) {
|
|
579
|
+
log(` Pairing Key : ${pairingKey}`);
|
|
580
|
+
} else {
|
|
581
|
+
log(` Pairing Key : ${maskPairingKey(pairingKey)} (clipboard unavailable; run with --print-key or press Enter to reveal)`);
|
|
582
|
+
}
|
|
583
|
+
if (dshInfo.userLocal || tianaToolchain?.userLocalCli) {
|
|
584
|
+
log(' PATH tip : export PATH="$HOME/.local/bin:$PATH"');
|
|
585
|
+
}
|
|
586
|
+
log('============================================================');
|
|
587
|
+
|
|
588
|
+
if (!clipboardResult.ok && !options.printKey && interactive && !deps.skipInteractiveReveal) {
|
|
589
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
590
|
+
try {
|
|
591
|
+
await rl.question('Press Enter to reveal pairing key in this terminal (Ctrl+C to keep hidden): ');
|
|
592
|
+
console.log(` Pairing Key : ${pairingKey}`);
|
|
593
|
+
} finally {
|
|
594
|
+
rl.close();
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
return summary;
|
|
599
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { existsSync, readdirSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export function* resolveDshPackageDirs(packageName) {
|
|
6
|
+
const seen = new Set();
|
|
7
|
+
function unique(path) {
|
|
8
|
+
if (!existsSync(join(path, 'package.json'))) return undefined;
|
|
9
|
+
const real = realpathSync(path);
|
|
10
|
+
if (seen.has(real)) return undefined;
|
|
11
|
+
seen.add(real);
|
|
12
|
+
return real;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const require = createRequire(import.meta.url);
|
|
16
|
+
try {
|
|
17
|
+
const path = unique(dirname(require.resolve(packageName + '/package.json')));
|
|
18
|
+
if (path) yield path;
|
|
19
|
+
} catch {
|
|
20
|
+
// The installed DSH profile normally owns these packages.
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const home = process.env.HOME || '';
|
|
24
|
+
const stores = [
|
|
25
|
+
process.env.DSH_PNPM_STORE,
|
|
26
|
+
join(process.env.DSH_HOME || join(home, '.dsh'), 'profiles/web/node_modules'),
|
|
27
|
+
join(home, '.local/share/pnpm/global/5/.pnpm'),
|
|
28
|
+
];
|
|
29
|
+
const pnpmPrefix = packageName.replace('/', '+') + '@';
|
|
30
|
+
for (const base of stores) {
|
|
31
|
+
if (!base || !existsSync(base)) continue;
|
|
32
|
+
const direct = unique(join(base, packageName));
|
|
33
|
+
if (direct) yield direct;
|
|
34
|
+
for (const entry of readdirSync(base).sort()) {
|
|
35
|
+
if (!entry.startsWith(pnpmPrefix)) continue;
|
|
36
|
+
const path = unique(join(base, entry, 'node_modules', packageName));
|
|
37
|
+
if (path) yield path;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function resolveDshPackageDir(packageName) {
|
|
43
|
+
const first = resolveDshPackageDirs(packageName).next();
|
|
44
|
+
if (first.done) throw new Error('Unable to locate ' + packageName + '. Ensure DSH is installed.');
|
|
45
|
+
return first.value;
|
|
46
|
+
}
|