@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/state.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import {
|
|
2
|
+
closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync,
|
|
3
|
+
readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync,
|
|
4
|
+
} from 'node:fs';
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import { homedir, hostname } from 'node:os';
|
|
7
|
+
import { dirname, join, resolve } from 'node:path';
|
|
8
|
+
import {
|
|
9
|
+
decodeMasterSecret,
|
|
10
|
+
E2EE_ALGORITHM,
|
|
11
|
+
formatPairingKey,
|
|
12
|
+
normalizePairingKey,
|
|
13
|
+
} from '../web-src/e2ee.js';
|
|
14
|
+
|
|
15
|
+
export const STATE_CONFIG_VERSION = 2;
|
|
16
|
+
export const DEFAULT_STUN_URLS = ['stun:stun.cloudflare.com:3478'];
|
|
17
|
+
|
|
18
|
+
export { formatPairingKey, normalizePairingKey };
|
|
19
|
+
|
|
20
|
+
export function resolveDshHome() {
|
|
21
|
+
return process.env.DSH_HOME || join(homedir(), '.dsh');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function defaultStateDir() {
|
|
25
|
+
return join(resolveDshHome(), 'tiana-remote');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function defaultStatePath() {
|
|
29
|
+
return join(defaultStateDir(), 'state.json');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function resolveStatePath(filePath) {
|
|
33
|
+
return resolve(filePath || defaultStatePath());
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function defaultRuntimePath() {
|
|
37
|
+
return join(defaultStateDir(), 'runtime.json');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function verifyPrivate(stat, type) {
|
|
41
|
+
if ((type === 'directory' ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1) ||
|
|
42
|
+
(process.platform !== 'win32' && (stat.mode & 0o077) !== 0) ||
|
|
43
|
+
(typeof process.getuid === 'function' && stat.uid !== process.getuid())) {
|
|
44
|
+
throw new Error(`DSH remote state ${type} must be private and owned by the current user`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function loadRemoteState(filePath = defaultStatePath()) {
|
|
49
|
+
let fd;
|
|
50
|
+
try {
|
|
51
|
+
verifyPrivate(lstatSync(dirname(filePath)), 'directory');
|
|
52
|
+
fd = openSync(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0));
|
|
53
|
+
} catch (err) {
|
|
54
|
+
if (err?.code === 'ENOENT') return null;
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const info = fstatSync(fd);
|
|
59
|
+
verifyPrivate(info, 'file');
|
|
60
|
+
if (info.size > 256 * 1024) throw new Error('DSH remote state file is too large');
|
|
61
|
+
let parsed;
|
|
62
|
+
try { parsed = JSON.parse(readFileSync(fd, 'utf8')); }
|
|
63
|
+
catch { throw new Error('Invalid DSH remote state file'); }
|
|
64
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
65
|
+
throw new Error('Invalid DSH remote state file');
|
|
66
|
+
}
|
|
67
|
+
return parsed;
|
|
68
|
+
} finally {
|
|
69
|
+
closeSync(fd);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function saveRemoteState(state, filePath = defaultStatePath()) {
|
|
74
|
+
const dir = dirname(filePath);
|
|
75
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
76
|
+
verifyPrivate(lstatSync(dir), 'directory');
|
|
77
|
+
const tmp = `${filePath}.tmp.${randomBytes(16).toString('hex')}`;
|
|
78
|
+
const fd = openSync(tmp, 'wx', 0o600);
|
|
79
|
+
try {
|
|
80
|
+
try {
|
|
81
|
+
writeFileSync(fd, `${JSON.stringify(state, null, 2)}\n`);
|
|
82
|
+
} finally {
|
|
83
|
+
closeSync(fd);
|
|
84
|
+
}
|
|
85
|
+
renameSync(tmp, filePath);
|
|
86
|
+
} catch (err) {
|
|
87
|
+
try { unlinkSync(tmp); } catch { /* preserve original error */ }
|
|
88
|
+
throw err;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Lossless v1 -> v2 migration / normalization.
|
|
94
|
+
* Preserves existing hostId, hostSigningKeyPair, e2ee/e2eeKeySeed, tiana/owner/function/web fields,
|
|
95
|
+
* and fills v2 network & security defaults without discarding unknown fields.
|
|
96
|
+
*/
|
|
97
|
+
export function migrateRemoteState(raw) {
|
|
98
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
99
|
+
const stunUrls = Array.isArray(raw.network?.stunUrls)
|
|
100
|
+
? raw.network.stunUrls.map((u) => String(u).trim()).filter(Boolean)
|
|
101
|
+
: [...DEFAULT_STUN_URLS];
|
|
102
|
+
const p2pEnabled = raw.network?.p2pEnabled !== undefined ? Boolean(raw.network.p2pEnabled) : true;
|
|
103
|
+
const rawAllowed = Array.isArray(raw.security?.allowedWebPlugins)
|
|
104
|
+
? raw.security.allowedWebPlugins
|
|
105
|
+
: Array.isArray(raw.allowedWebPlugins)
|
|
106
|
+
? raw.allowedWebPlugins
|
|
107
|
+
: [];
|
|
108
|
+
const allowedWebPlugins = [...new Set(rawAllowed.map((item) => String(item).trim()).filter(Boolean))];
|
|
109
|
+
|
|
110
|
+
const next = {
|
|
111
|
+
...raw,
|
|
112
|
+
version: STATE_CONFIG_VERSION,
|
|
113
|
+
configVersion: STATE_CONFIG_VERSION,
|
|
114
|
+
enabled: raw.enabled !== undefined ? Boolean(raw.enabled) : true,
|
|
115
|
+
network: {
|
|
116
|
+
p2pEnabled,
|
|
117
|
+
stunUrls,
|
|
118
|
+
},
|
|
119
|
+
security: {
|
|
120
|
+
...(raw.security && typeof raw.security === 'object' ? raw.security : {}),
|
|
121
|
+
allowedWebPlugins,
|
|
122
|
+
},
|
|
123
|
+
allowedWebPlugins,
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
if (raw.hostId && !next.host) {
|
|
127
|
+
next.host = {
|
|
128
|
+
hostId: raw.hostId,
|
|
129
|
+
hostName: raw.hostName || raw.hostId,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (raw.e2eeKeySeed && !next.e2ee?.secret) {
|
|
133
|
+
try {
|
|
134
|
+
const normalized = normalizePairingKey(raw.e2eeKeySeed);
|
|
135
|
+
next.e2ee = {
|
|
136
|
+
algorithm: E2EE_ALGORITHM,
|
|
137
|
+
secret: normalized,
|
|
138
|
+
fingerprint: e2eeFingerprint(normalized),
|
|
139
|
+
createdAt: raw.updatedAt || new Date().toISOString(),
|
|
140
|
+
};
|
|
141
|
+
} catch {
|
|
142
|
+
// Leave malformed legacy seed intact in e2eeKeySeed for caller to handle.
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return next;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function loadNormalizedRemoteState(filePath = defaultStatePath()) {
|
|
149
|
+
const raw = loadRemoteState(filePath);
|
|
150
|
+
if (!raw) return null;
|
|
151
|
+
return migrateRemoteState(raw);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function isPidAlive(pid) {
|
|
155
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
156
|
+
try {
|
|
157
|
+
process.kill(pid, 0);
|
|
158
|
+
return true;
|
|
159
|
+
} catch (err) {
|
|
160
|
+
return err?.code === 'EPERM';
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const inProcessLocks = new Map();
|
|
165
|
+
|
|
166
|
+
function ensurePersistentLockFile(lockPath) {
|
|
167
|
+
try {
|
|
168
|
+
const fd = openSync(lockPath, constants.O_CREAT | constants.O_RDWR | (constants.O_NOFOLLOW || 0), 0o600);
|
|
169
|
+
try {
|
|
170
|
+
verifyPrivate(fstatSync(fd), 'file');
|
|
171
|
+
} finally {
|
|
172
|
+
closeSync(fd);
|
|
173
|
+
}
|
|
174
|
+
} catch (err) {
|
|
175
|
+
if (err?.code === 'EEXIST') return;
|
|
176
|
+
throw err;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const ENTERING_RE = /^entering-(\d+)-([0-9a-f]{32})$/u;
|
|
181
|
+
const TICKET_RE = /^ticket-([0-9a-f]{16})-(\d+)-([0-9a-f]{32})$/u;
|
|
182
|
+
|
|
183
|
+
export async function withStateLock(fn, filePath = defaultStatePath(), { timeoutMs = 10_000 } = {}) {
|
|
184
|
+
const targetPath = resolveStatePath(filePath);
|
|
185
|
+
const dir = dirname(targetPath);
|
|
186
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
187
|
+
verifyPrivate(lstatSync(dir), 'directory');
|
|
188
|
+
|
|
189
|
+
const lockPath = `${targetPath}.lock`;
|
|
190
|
+
const claimsDir = `${lockPath}.claims`;
|
|
191
|
+
ensurePersistentLockFile(lockPath);
|
|
192
|
+
mkdirSync(claimsDir, { recursive: true, mode: 0o700 });
|
|
193
|
+
verifyPrivate(lstatSync(claimsDir), 'directory');
|
|
194
|
+
|
|
195
|
+
// Serialize concurrent callers within this Node.js process in FIFO order first.
|
|
196
|
+
const prevTail = inProcessLocks.get(lockPath) ?? Promise.resolve();
|
|
197
|
+
let releaseInProcess;
|
|
198
|
+
const myTurn = new Promise((resolve) => { releaseInProcess = resolve; });
|
|
199
|
+
const nextTail = prevTail.then(() => myTurn, () => myTurn);
|
|
200
|
+
inProcessLocks.set(lockPath, nextTail);
|
|
201
|
+
|
|
202
|
+
const deadline = Date.now() + timeoutMs;
|
|
203
|
+
await prevTail;
|
|
204
|
+
|
|
205
|
+
const idSuffix = `${process.pid}-${randomBytes(16).toString('hex')}`;
|
|
206
|
+
const enteringPath = join(claimsDir, `entering-${idSuffix}`);
|
|
207
|
+
let ticketPath = '';
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
// Lamport Bakery Directory Lock: every attempt uses globally unique filenames, so
|
|
211
|
+
// unlinking a dead PID's file can never affect any live owner even across arbitrary pauses.
|
|
212
|
+
// Phase 1: announce entering before reading max ticket.
|
|
213
|
+
closeSync(openSync(enteringPath, 'wx', 0o600));
|
|
214
|
+
|
|
215
|
+
// Phase 2: pick strictly greater ticket number and create unique ticket file.
|
|
216
|
+
let maxTicket = 0n;
|
|
217
|
+
for (const name of readdirSync(claimsDir)) {
|
|
218
|
+
const m = TICKET_RE.exec(name);
|
|
219
|
+
if (m) {
|
|
220
|
+
const ticket = BigInt(`0x${m[1]}`);
|
|
221
|
+
if (ticket > maxTicket) maxTicket = ticket;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const myTicket = maxTicket + 1n;
|
|
225
|
+
const hex16 = myTicket.toString(16).padStart(16, '0');
|
|
226
|
+
const ticketName = `ticket-${hex16}-${idSuffix}`;
|
|
227
|
+
ticketPath = join(claimsDir, ticketName);
|
|
228
|
+
closeSync(openSync(ticketPath, 'wx', 0o600));
|
|
229
|
+
|
|
230
|
+
// Phase 3: clear entering marker now that our ticket is published.
|
|
231
|
+
try { unlinkSync(enteringPath); } catch { /* ignore */ }
|
|
232
|
+
|
|
233
|
+
// Phase 4: wait until no live process is entering or holds a smaller (ticket, idSuffix).
|
|
234
|
+
while (true) {
|
|
235
|
+
const entries = readdirSync(claimsDir);
|
|
236
|
+
if (!entries.includes(ticketName)) {
|
|
237
|
+
throw new Error(`DSH remote state lock ticket disappeared (${lockPath})`);
|
|
238
|
+
}
|
|
239
|
+
let blocked = false;
|
|
240
|
+
for (const name of entries) {
|
|
241
|
+
if (name === ticketName) continue;
|
|
242
|
+
const em = ENTERING_RE.exec(name);
|
|
243
|
+
if (em) {
|
|
244
|
+
const otherPid = Number(em[1]);
|
|
245
|
+
if (!isPidAlive(otherPid)) {
|
|
246
|
+
try { unlinkSync(join(claimsDir, name)); } catch { /* ignore */ }
|
|
247
|
+
} else {
|
|
248
|
+
blocked = true;
|
|
249
|
+
}
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const tm = TICKET_RE.exec(name);
|
|
253
|
+
if (tm) {
|
|
254
|
+
const otherTicket = BigInt(`0x${tm[1]}`);
|
|
255
|
+
const otherPid = Number(tm[2]);
|
|
256
|
+
const otherSuffix = `${tm[2]}-${tm[3]}`;
|
|
257
|
+
if (!isPidAlive(otherPid)) {
|
|
258
|
+
try { unlinkSync(join(claimsDir, name)); } catch { /* ignore */ }
|
|
259
|
+
} else if (otherTicket < myTicket || (otherTicket === myTicket && otherSuffix < idSuffix)) {
|
|
260
|
+
blocked = true;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (!blocked) break;
|
|
265
|
+
if (Date.now() >= deadline) {
|
|
266
|
+
throw new Error(`Timed out waiting for DSH remote state lock (${lockPath})`);
|
|
267
|
+
}
|
|
268
|
+
await new Promise((r) => setTimeout(r, 8));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Record holder metadata in persistent lock file (file itself is never deleted).
|
|
272
|
+
try {
|
|
273
|
+
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, token: idSuffix, ticket: hex16, ts: Date.now() }) + '\n', { mode: 0o600 });
|
|
274
|
+
} catch { /* non-fatal */ }
|
|
275
|
+
|
|
276
|
+
return await fn();
|
|
277
|
+
} finally {
|
|
278
|
+
try { unlinkSync(enteringPath); } catch { /* ignore */ }
|
|
279
|
+
if (ticketPath) {
|
|
280
|
+
try { unlinkSync(ticketPath); } catch { /* ignore */ }
|
|
281
|
+
}
|
|
282
|
+
releaseInProcess();
|
|
283
|
+
if (inProcessLocks.get(lockPath) === nextTail) {
|
|
284
|
+
inProcessLocks.delete(lockPath);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function writeRuntimeInfo(info, filePath = defaultRuntimePath()) {
|
|
290
|
+
saveRemoteState({
|
|
291
|
+
pid: process.pid,
|
|
292
|
+
startedAt: new Date().toISOString(),
|
|
293
|
+
...info,
|
|
294
|
+
}, filePath);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function readRuntimeInfo(filePath = defaultRuntimePath()) {
|
|
298
|
+
try {
|
|
299
|
+
const info = loadRemoteState(filePath);
|
|
300
|
+
if (!info || !isPidAlive(info.pid)) return null;
|
|
301
|
+
return info;
|
|
302
|
+
} catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function removeRuntimeInfo(filePath = defaultRuntimePath()) {
|
|
308
|
+
try {
|
|
309
|
+
const info = loadRemoteState(filePath);
|
|
310
|
+
if (info && info.pid === process.pid) {
|
|
311
|
+
unlinkSync(filePath);
|
|
312
|
+
}
|
|
313
|
+
} catch {
|
|
314
|
+
// ignore
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function sanitizeHostId(raw) {
|
|
319
|
+
const cleaned = String(raw || '')
|
|
320
|
+
.toLowerCase()
|
|
321
|
+
.replace(/[^a-z0-9_-]+/g, '-')
|
|
322
|
+
.replace(/^-+|-+$/g, '')
|
|
323
|
+
.slice(0, 48);
|
|
324
|
+
return cleaned || `host-${randomBytes(3).toString('hex')}`;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export function defaultHostIdentity() {
|
|
328
|
+
const host = hostname();
|
|
329
|
+
return {
|
|
330
|
+
hostId: sanitizeHostId(host),
|
|
331
|
+
hostName: host || 'dsh-host',
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function generateE2eeSecret() {
|
|
336
|
+
return randomBytes(32).toString('base64url');
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function e2eeFingerprint(secret) {
|
|
340
|
+
const bytes = decodeMasterSecret(secret);
|
|
341
|
+
const digest = createHash('sha256').update(bytes).digest();
|
|
342
|
+
const parts = [];
|
|
343
|
+
for (let i = 0; i < 6; i += 2) {
|
|
344
|
+
parts.push(digest.subarray(i, i + 2).toString('hex'));
|
|
345
|
+
}
|
|
346
|
+
return parts.join(':');
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export function ensureE2eeConfig(state, { rotate = false } = {}) {
|
|
350
|
+
const existing = state?.e2ee?.secret;
|
|
351
|
+
if (!rotate && existing) {
|
|
352
|
+
try {
|
|
353
|
+
const normalized = normalizePairingKey(existing);
|
|
354
|
+
const fingerprint = e2eeFingerprint(normalized);
|
|
355
|
+
const needsMetaUpdate = !state.e2ee.algorithm || state.e2ee.fingerprint !== fingerprint || normalized !== existing;
|
|
356
|
+
return {
|
|
357
|
+
changed: needsMetaUpdate,
|
|
358
|
+
e2ee: {
|
|
359
|
+
algorithm: state.e2ee.algorithm || E2EE_ALGORITHM,
|
|
360
|
+
secret: normalized,
|
|
361
|
+
fingerprint,
|
|
362
|
+
createdAt: state.e2ee.createdAt || state.updatedAt || new Date().toISOString(),
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
} catch {
|
|
366
|
+
// Regenerate if existing key is malformed.
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const secret = generateE2eeSecret();
|
|
370
|
+
return {
|
|
371
|
+
changed: true,
|
|
372
|
+
e2ee: {
|
|
373
|
+
algorithm: E2EE_ALGORITHM,
|
|
374
|
+
secret,
|
|
375
|
+
fingerprint: e2eeFingerprint(secret),
|
|
376
|
+
createdAt: new Date().toISOString(),
|
|
377
|
+
},
|
|
378
|
+
};
|
|
379
|
+
}
|