@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/tiana-cli.js
ADDED
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { buildWebDist } from '../scripts/build-web-dist.mjs';
|
|
9
|
+
import {
|
|
10
|
+
defaultHostIdentity,
|
|
11
|
+
DEFAULT_STUN_URLS,
|
|
12
|
+
ensureE2eeConfig,
|
|
13
|
+
generateE2eeSecret,
|
|
14
|
+
loadRemoteState,
|
|
15
|
+
migrateRemoteState,
|
|
16
|
+
resolveStatePath,
|
|
17
|
+
saveRemoteState,
|
|
18
|
+
withStateLock,
|
|
19
|
+
} from './state.js';
|
|
20
|
+
|
|
21
|
+
const execFileAsync = promisify(execFile);
|
|
22
|
+
const PROJECT_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
|
23
|
+
const RELAY_GO_DIR = join(PROJECT_ROOT, 'relay-go');
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_FUNCTION_NAME = 'dsh-remote-relay';
|
|
26
|
+
export const DEFAULT_WEB_NAME = 'DSH Remote';
|
|
27
|
+
export const DEFAULT_TOKEN_NAME = 'dsh-remote-host';
|
|
28
|
+
|
|
29
|
+
export function tianaBinary(overrideBin) {
|
|
30
|
+
if (typeof overrideBin === 'string' && overrideBin.trim()) return overrideBin.trim();
|
|
31
|
+
return process.env.TIANA_BIN || (process.platform === 'win32' ? 'tiana.cmd' : 'tiana');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function runTiana(args, options = {}) {
|
|
35
|
+
const bin = tianaBinary(options.bin || options.tianaBin);
|
|
36
|
+
try {
|
|
37
|
+
const { stdout, stderr } = await execFileAsync(bin, args, {
|
|
38
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
39
|
+
timeout: options.timeoutMs ?? 180_000,
|
|
40
|
+
env: options.env ?? process.env,
|
|
41
|
+
shell: process.platform === 'win32',
|
|
42
|
+
});
|
|
43
|
+
return { stdout, stderr };
|
|
44
|
+
} catch (err) {
|
|
45
|
+
const detail = args[0] === 'token' || args[0] === 'status'
|
|
46
|
+
? 'credential command failed'
|
|
47
|
+
: String(err?.stderr || err?.message || err).trim();
|
|
48
|
+
throw new Error(`tiana ${args.join(' ')} failed: ${detail}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function runTianaJSON(args, options = {}) {
|
|
53
|
+
const { stdout } = await runTiana(args, options);
|
|
54
|
+
const trimmed = stdout.trim();
|
|
55
|
+
let parsed;
|
|
56
|
+
try {
|
|
57
|
+
parsed = JSON.parse(trimmed);
|
|
58
|
+
} catch {
|
|
59
|
+
throw new Error(`tiana ${args.join(' ')} returned invalid JSON`);
|
|
60
|
+
}
|
|
61
|
+
if (parsed?.error) {
|
|
62
|
+
const credentialCommand = args[0] === 'token' || args[0] === 'status';
|
|
63
|
+
const msg = credentialCommand ? 'credential command failed'
|
|
64
|
+
: parsed.error.message || parsed.error.code || 'unknown error';
|
|
65
|
+
throw new Error(`tiana ${args.join(' ')} error: ${msg}`);
|
|
66
|
+
}
|
|
67
|
+
return parsed?.data ?? parsed;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function getTianaStatus(options = {}) {
|
|
71
|
+
const data = await runTianaJSON(['status', '--json'], options);
|
|
72
|
+
if (!data?.logged_in || !data?.user?.user_id || !data?.user?.tenant_id) {
|
|
73
|
+
throw new Error('Not logged in to Tiana. Run `tiana login` first.');
|
|
74
|
+
}
|
|
75
|
+
return data;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function listTianaWebApps(options = {}) {
|
|
79
|
+
const data = await runTianaJSON(['web', 'list', '--json'], options);
|
|
80
|
+
return Array.isArray(data?.items) ? data.items : [];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function getWebFunctionBinding(webId, options = {}) {
|
|
84
|
+
const current = await runTianaJSON(['web', 'functions', 'get', webId, '--json'], options);
|
|
85
|
+
const ids = Array.isArray(current?.function_instance_ids) ? current.function_instance_ids : [];
|
|
86
|
+
return {
|
|
87
|
+
functionInstanceIds: ids,
|
|
88
|
+
projectRevision: current?.project_revision,
|
|
89
|
+
raw: current,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function getFunctionParameters(functionId, options = {}) {
|
|
94
|
+
const data = await runTianaJSON(['function', 'parameters', 'get', functionId, '--json'], options);
|
|
95
|
+
const params = data?.parameters && typeof data.parameters === 'object' ? data.parameters : data;
|
|
96
|
+
if (!params || typeof params !== 'object' || Array.isArray(params)) {
|
|
97
|
+
throw new Error(`Unexpected function parameters response for ${functionId}`);
|
|
98
|
+
}
|
|
99
|
+
return params;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function setFunctionParameters(functionId, paramsObj, options = {}) {
|
|
103
|
+
const temp = mkdtempSync(join(tmpdir(), 'dsh-remote-params-'));
|
|
104
|
+
try {
|
|
105
|
+
const paramsFile = join(temp, 'parameters.json');
|
|
106
|
+
writeFileSync(paramsFile, `${JSON.stringify(paramsObj, null, 2)}\n`, { mode: 0o600 });
|
|
107
|
+
return await runTianaJSON([
|
|
108
|
+
'function', 'parameters', 'set',
|
|
109
|
+
functionId,
|
|
110
|
+
'--file', paramsFile,
|
|
111
|
+
'--json',
|
|
112
|
+
], options);
|
|
113
|
+
} finally {
|
|
114
|
+
rmSync(temp, { recursive: true, force: true });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function buildRemotePolicy({ hostId, hostName, registrationKey, ownerUserId, ownerTenantId, webId, origin }) {
|
|
119
|
+
return {
|
|
120
|
+
version: 1,
|
|
121
|
+
webId,
|
|
122
|
+
origin,
|
|
123
|
+
ownerUserId,
|
|
124
|
+
ownerTenantId,
|
|
125
|
+
hostId,
|
|
126
|
+
hostName: hostName || hostId,
|
|
127
|
+
hostDigest: createHash('sha256').update(registrationKey).digest('hex'),
|
|
128
|
+
updatedAt: new Date().toISOString(),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function parsePolicyFromParameters(params) {
|
|
133
|
+
const entry = params?.DSH_REMOTE_POLICY;
|
|
134
|
+
const raw = typeof entry === 'string' ? entry : entry?.value;
|
|
135
|
+
if (!raw || typeof raw !== 'string') return null;
|
|
136
|
+
try {
|
|
137
|
+
return JSON.parse(raw);
|
|
138
|
+
} catch {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Update `DSH_REMOTE_POLICY` while strictly preserving all other function parameters.
|
|
145
|
+
* NEVER swallows `getFunctionParameters` errors (to prevent clobbering existing bindings or user params).
|
|
146
|
+
*/
|
|
147
|
+
export async function updateRemotePolicy(functionId, policy, { log = console.log, existingParams, ...options } = {}) {
|
|
148
|
+
const existing = existingParams !== undefined
|
|
149
|
+
? existingParams
|
|
150
|
+
: await getFunctionParameters(functionId, options);
|
|
151
|
+
const merged = {
|
|
152
|
+
...existing,
|
|
153
|
+
DSH_REMOTE_POLICY: {
|
|
154
|
+
kind: 'plain',
|
|
155
|
+
value: JSON.stringify(policy),
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
log(`[dsh-remote] Updating DSH_REMOTE_POLICY on Function ${functionId} (zero recompile)...`);
|
|
159
|
+
await setFunctionParameters(functionId, merged, options);
|
|
160
|
+
return policy;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function validateRelayFunctionShown(fnShown) {
|
|
164
|
+
const status = String(
|
|
165
|
+
fnShown?.instance?.product_state ??
|
|
166
|
+
fnShown?.instance?.status ??
|
|
167
|
+
fnShown?.function?.status ??
|
|
168
|
+
fnShown?.product_state ??
|
|
169
|
+
fnShown?.status ??
|
|
170
|
+
'',
|
|
171
|
+
).trim().toUpperCase();
|
|
172
|
+
if (status !== 'ACTIVE') {
|
|
173
|
+
throw new Error(`Relay Function must be ACTIVE (got "${status || 'unknown'}")`);
|
|
174
|
+
}
|
|
175
|
+
if (fnShown?.instance?.enabled === false) {
|
|
176
|
+
throw new Error('Relay Function is disabled');
|
|
177
|
+
}
|
|
178
|
+
if (fnShown?.instance?.deletion_pending === true) {
|
|
179
|
+
throw new Error('Relay Function is pending deletion');
|
|
180
|
+
}
|
|
181
|
+
const fnUrl = fnShown?.instance?.connection?.url || fnShown?.instance?.url || '';
|
|
182
|
+
if (!fnUrl) {
|
|
183
|
+
throw new Error('Relay Function requires an active HTTPS endpoint');
|
|
184
|
+
}
|
|
185
|
+
let parsed;
|
|
186
|
+
try {
|
|
187
|
+
parsed = new URL(fnUrl);
|
|
188
|
+
} catch {
|
|
189
|
+
throw new Error('Relay Function endpoint URL is invalid');
|
|
190
|
+
}
|
|
191
|
+
if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
|
|
192
|
+
throw new Error('Relay Function requires an active HTTPS endpoint without credentials');
|
|
193
|
+
}
|
|
194
|
+
return fnUrl;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function verifyRelayHealth(fnUrl, token, options = {}) {
|
|
198
|
+
if (typeof options.probeRelayHealth === 'function') {
|
|
199
|
+
const res = await options.probeRelayHealth(fnUrl, token);
|
|
200
|
+
if (!res || res.ok !== true || typeof res.paired !== 'boolean') {
|
|
201
|
+
throw new Error('Target Function /healthz did not confirm a valid DSH Remote Relay');
|
|
202
|
+
}
|
|
203
|
+
return res;
|
|
204
|
+
}
|
|
205
|
+
const healthUrl = new URL('/healthz', fnUrl);
|
|
206
|
+
if (healthUrl.protocol !== 'https:' || healthUrl.username || healthUrl.password) {
|
|
207
|
+
throw new Error('Relay health probe requires HTTPS URL');
|
|
208
|
+
}
|
|
209
|
+
const headers = { Accept: 'application/json' };
|
|
210
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
211
|
+
const resp = await fetch(healthUrl, {
|
|
212
|
+
headers,
|
|
213
|
+
redirect: 'error',
|
|
214
|
+
signal: AbortSignal.timeout(options.healthTimeoutMs ?? 10_000),
|
|
215
|
+
});
|
|
216
|
+
if (!resp.ok) {
|
|
217
|
+
throw new Error(`Target Function /healthz returned HTTP ${resp.status}; verify this is a DSH Remote Relay`);
|
|
218
|
+
}
|
|
219
|
+
let body;
|
|
220
|
+
try {
|
|
221
|
+
body = await resp.json();
|
|
222
|
+
} catch {
|
|
223
|
+
throw new Error('Target Function /healthz did not return JSON; verify this is a DSH Remote Relay');
|
|
224
|
+
}
|
|
225
|
+
if (body?.ok !== true || typeof body?.paired !== 'boolean') {
|
|
226
|
+
throw new Error('Target Function /healthz payload does not match DSH Remote Relay contract');
|
|
227
|
+
}
|
|
228
|
+
return body;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function ensureRelayFunction({ functionName, functionId, log = console.log, ...cliOpts }) {
|
|
232
|
+
if (functionId) {
|
|
233
|
+
log(`[dsh-remote] Reusing configured Function ${functionId}`);
|
|
234
|
+
const shown = await runTianaJSON(['function', 'show', functionId, '--json'], cliOpts);
|
|
235
|
+
return { instance: shown.instance };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
log(`[dsh-remote] Creating Function "${functionName}"...`);
|
|
239
|
+
const created = await runTianaJSON([
|
|
240
|
+
'function', 'create', '--wait',
|
|
241
|
+
'-m', 'DSH Remote WebSocket rendezvous relay',
|
|
242
|
+
'--json',
|
|
243
|
+
functionName,
|
|
244
|
+
], { ...cliOpts, timeoutMs: 240_000 });
|
|
245
|
+
const createdId = created?.instance_id || created?.instance?.id || created?.id;
|
|
246
|
+
if (!createdId) {
|
|
247
|
+
throw new Error(`Unexpected function create response: ${JSON.stringify(created)}`);
|
|
248
|
+
}
|
|
249
|
+
const shown = await runTianaJSON(['function', 'show', createdId, '--json'], cliOpts);
|
|
250
|
+
return { instance: shown?.instance ?? { id: createdId, display_name: functionName }, details: shown?.function ?? {}, release: shown?.release };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function syncAndPublishRelayFunction(functionId, webId, { forcePublish = false, log = console.log, ...cliOpts } = {}) {
|
|
254
|
+
const goModPath = join(RELAY_GO_DIR, 'go.mod');
|
|
255
|
+
const desiredGoMod = readFileSync(goModPath, 'utf8');
|
|
256
|
+
const template = readFileSync(join(RELAY_GO_DIR, 'main.go'), 'utf8');
|
|
257
|
+
const marker = 'var defaultWebID = ""';
|
|
258
|
+
const desiredMainGo = webId && template.includes(marker)
|
|
259
|
+
? template.replace(marker, () => `var defaultWebID = ${JSON.stringify(webId)}`)
|
|
260
|
+
: template;
|
|
261
|
+
|
|
262
|
+
const sourceView = await runTianaJSON(['function', 'source', 'list', functionId, '--json'], cliOpts);
|
|
263
|
+
const needsInitial = Boolean(sourceView?.needs_initial_source) || !sourceView?.commit;
|
|
264
|
+
|
|
265
|
+
let sameSource = false;
|
|
266
|
+
if (!needsInitial) {
|
|
267
|
+
try {
|
|
268
|
+
const [curMod, curMain] = await Promise.all([
|
|
269
|
+
runTiana(['function', 'source', 'read', functionId, 'go.mod'], cliOpts),
|
|
270
|
+
runTiana(['function', 'source', 'read', functionId, 'main.go'], cliOpts),
|
|
271
|
+
]);
|
|
272
|
+
sameSource = curMod.stdout === desiredGoMod && curMain.stdout === desiredMainGo;
|
|
273
|
+
} catch {
|
|
274
|
+
sameSource = false;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
let commit = sourceView?.commit || '';
|
|
279
|
+
if (!sameSource) {
|
|
280
|
+
log(`[dsh-remote] Uploading Go relay source to ${functionId}...`);
|
|
281
|
+
const baseCommit = needsInitial ? 'empty' : commit;
|
|
282
|
+
const temp = mkdtempSync(join(tmpdir(), 'dsh-remote-relay-'));
|
|
283
|
+
try {
|
|
284
|
+
const mainGoPath = join(temp, 'main.go');
|
|
285
|
+
writeFileSync(mainGoPath, desiredMainGo, { mode: 0o600 });
|
|
286
|
+
const saved = await runTianaJSON([
|
|
287
|
+
'function', 'source', 'save',
|
|
288
|
+
'--base-commit', baseCommit,
|
|
289
|
+
'--file', `go.mod=${goModPath}`,
|
|
290
|
+
'--file', `main.go=${mainGoPath}`,
|
|
291
|
+
'--json', functionId,
|
|
292
|
+
], cliOpts);
|
|
293
|
+
if (!saved?.commit) throw new Error('Function source save returned no commit');
|
|
294
|
+
commit = saved.commit;
|
|
295
|
+
} finally {
|
|
296
|
+
rmSync(temp, { recursive: true, force: true });
|
|
297
|
+
}
|
|
298
|
+
} else {
|
|
299
|
+
log(`[dsh-remote] Function source is up to date (${commit.slice(0, 8)}).`);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function isPublished(info) {
|
|
303
|
+
const published = info?.release?.published;
|
|
304
|
+
if (!published?.id) return false;
|
|
305
|
+
const builds = await runTianaJSON(['function', 'builds', '--json', functionId], cliOpts);
|
|
306
|
+
return Boolean(builds?.items?.some((build) => build.id === published.id &&
|
|
307
|
+
build.source_commit === commit && build.build_commit === published.build_commit));
|
|
308
|
+
}
|
|
309
|
+
const shown = await runTianaJSON(['function', 'show', functionId, '--json'], cliOpts);
|
|
310
|
+
if (!forcePublish && sameSource && await isPublished(shown)) {
|
|
311
|
+
log('[dsh-remote] The configured relay source is already published');
|
|
312
|
+
return shown;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
log(`[dsh-remote] Building & publishing Function ${functionId}...`);
|
|
316
|
+
await runTianaJSON(['function', 'publish', '--commit', commit, '--wait', '--json', functionId],
|
|
317
|
+
{ ...cliOpts, timeoutMs: 300_000 });
|
|
318
|
+
const deployed = await runTianaJSON(['function', 'show', functionId, '--json'], cliOpts);
|
|
319
|
+
if (!(await isPublished(deployed))) throw new Error('The relay release does not match the configured source');
|
|
320
|
+
return deployed;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export async function ensureHostToken(state, functionId, { rotateToken = false, log = console.log, ...cliOpts } = {}) {
|
|
324
|
+
const now = Math.floor(Date.now() / 1000);
|
|
325
|
+
if (!rotateToken && state?.function?.id === functionId && state?.function?.token &&
|
|
326
|
+
state.function.expiresAt > now + 86400) {
|
|
327
|
+
const { token, tokenId, expiresAt } = state.function;
|
|
328
|
+
return { token, tokenId, expiresAt };
|
|
329
|
+
}
|
|
330
|
+
const expiresAt = now + 30 * 86400;
|
|
331
|
+
const tokenName = `${DEFAULT_TOKEN_NAME}-${Date.now()}`;
|
|
332
|
+
log(`[dsh-remote] Creating instance access token for ${functionId}...`);
|
|
333
|
+
const receipt = await runTianaJSON([
|
|
334
|
+
'token', 'create',
|
|
335
|
+
'--name', tokenName,
|
|
336
|
+
'--expires-at', String(expiresAt),
|
|
337
|
+
'--json',
|
|
338
|
+
functionId,
|
|
339
|
+
], cliOpts);
|
|
340
|
+
if (!receipt?.token) {
|
|
341
|
+
throw new Error('Instance Token receipt was missing its credential');
|
|
342
|
+
}
|
|
343
|
+
return { token: receipt.token, tokenId: receipt.token_id || '', expiresAt };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function ensureWebApp({ webName, webId, log = console.log, ...cliOpts }) {
|
|
347
|
+
if (webId) {
|
|
348
|
+
const items = await listTianaWebApps(cliOpts);
|
|
349
|
+
const existing = items.find((item) => item.id === webId);
|
|
350
|
+
if (!existing) throw new Error('The configured Web app is unavailable in the current Tiana space');
|
|
351
|
+
return existing;
|
|
352
|
+
}
|
|
353
|
+
log(`[dsh-remote] Creating Web app "${webName}"...`);
|
|
354
|
+
const created = await runTianaJSON([
|
|
355
|
+
'web', 'create',
|
|
356
|
+
'--entry', 'dsh-remote-entry.mjs',
|
|
357
|
+
'--description', 'DeepSeek Harness 远程访问入口(由 @tianacloud/dsh-remote 自动编排)',
|
|
358
|
+
'--json',
|
|
359
|
+
webName,
|
|
360
|
+
], cliOpts);
|
|
361
|
+
return created?.project ?? created?.app ?? created;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async function ensureWebFunctionBinding(webId, functionId, { adoptExisting = false, log = console.log, ...cliOpts } = {}) {
|
|
365
|
+
const current = await runTianaJSON(['web', 'functions', 'get', webId, '--json'], cliOpts);
|
|
366
|
+
const bound = Array.isArray(current?.function_instance_ids) ? current.function_instance_ids : [];
|
|
367
|
+
if (bound.length === 1 && bound[0] === functionId) {
|
|
368
|
+
return functionId;
|
|
369
|
+
}
|
|
370
|
+
if (adoptExisting && bound[0]) {
|
|
371
|
+
log(`[dsh-remote] Adopting existing Relay Function ${bound[0]} already bound to Web ${webId}`);
|
|
372
|
+
return bound[0];
|
|
373
|
+
}
|
|
374
|
+
const revision = current?.project_revision;
|
|
375
|
+
if (!revision) {
|
|
376
|
+
throw new Error(`Missing project_revision from web functions get: ${JSON.stringify(current)}`);
|
|
377
|
+
}
|
|
378
|
+
log(`[dsh-remote] Binding Function ${functionId} -> Web ${webId} (rev ${revision})...`);
|
|
379
|
+
try {
|
|
380
|
+
await runTianaJSON([
|
|
381
|
+
'web', 'functions', 'set',
|
|
382
|
+
'--expected-revision', String(revision),
|
|
383
|
+
'--function-id', functionId,
|
|
384
|
+
'--json',
|
|
385
|
+
webId,
|
|
386
|
+
], cliOpts);
|
|
387
|
+
return functionId;
|
|
388
|
+
} catch (err) {
|
|
389
|
+
if (adoptExisting) {
|
|
390
|
+
const rechecked = await getWebFunctionBinding(webId, cliOpts);
|
|
391
|
+
if (rechecked.functionInstanceIds[0]) {
|
|
392
|
+
log(`[dsh-remote] Adopting Relay Function ${rechecked.functionInstanceIds[0]} bound concurrently to Web ${webId}`);
|
|
393
|
+
return rechecked.functionInstanceIds[0];
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
throw err;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function validateWebEndpoint(webApp, webId) {
|
|
401
|
+
const webUrl = new URL(webApp.endpoint || `https://${webId}.tianacloud.site/web/${webId}/`);
|
|
402
|
+
if (webUrl.protocol !== 'https:' || webUrl.username || webUrl.password || webUrl.search ||
|
|
403
|
+
webUrl.hash || webUrl.pathname !== `/web/${webId}/`) {
|
|
404
|
+
throw new Error('Invalid Web app entrypoint');
|
|
405
|
+
}
|
|
406
|
+
return webUrl;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export function hasBindingIdentityConflict(existingPolicy, { hostId, registrationKey, hostPublicKey = '' }) {
|
|
410
|
+
if (!existingPolicy || typeof existingPolicy !== 'object') return false;
|
|
411
|
+
if (!existingPolicy.hostId && !existingPolicy.hostDigest && !existingPolicy.hostPublicKey) return false;
|
|
412
|
+
|
|
413
|
+
if (existingPolicy.hostId && existingPolicy.hostId !== hostId) {
|
|
414
|
+
return true;
|
|
415
|
+
}
|
|
416
|
+
const localDigest = registrationKey
|
|
417
|
+
? createHash('sha256').update(registrationKey).digest('hex')
|
|
418
|
+
: '';
|
|
419
|
+
if (existingPolicy.hostDigest && existingPolicy.hostDigest !== localDigest) {
|
|
420
|
+
return true;
|
|
421
|
+
}
|
|
422
|
+
if (existingPolicy.hostPublicKey && existingPolicy.hostPublicKey !== hostPublicKey) {
|
|
423
|
+
return true;
|
|
424
|
+
}
|
|
425
|
+
return false;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Zero-recompile binding to an existing Tiana Web app (e.g. installed from Tiana Marketplace).
|
|
430
|
+
* Writes DSH_REMOTE_POLICY via `tiana function parameters set` without rebuilding Go or .tweb.
|
|
431
|
+
*
|
|
432
|
+
* Transactional safety:
|
|
433
|
+
* 1. Validates non-empty user_id/tenant_id and strict `webApp.owner_id === status.user.user_id`.
|
|
434
|
+
* 2. Validates Relay Function is ACTIVE, HTTPS, and passes `/healthz` check.
|
|
435
|
+
* 3. Reads existing function parameters strictly (never swallows errors).
|
|
436
|
+
* 4. Checks rebind conflict across hostId + hostDigest + hostPublicKey.
|
|
437
|
+
* 5. Mints/confirms token and writes local checkpoint BEFORE updating cloud `DSH_REMOTE_POLICY`.
|
|
438
|
+
* 6. Commits final state under `withStateLock` while preserving concurrent local settings edits.
|
|
439
|
+
*/
|
|
440
|
+
export async function bindTianaRemoteWeb(options = {}) {
|
|
441
|
+
const log = options.log ?? console.log;
|
|
442
|
+
const webId = String(options.webId || '').trim();
|
|
443
|
+
const statePath = options.statePath;
|
|
444
|
+
const cliOpts = options.tianaBin ? { bin: options.tianaBin } : {};
|
|
445
|
+
|
|
446
|
+
if (!/^[a-z][a-z0-9]{11}$/u.test(webId)) {
|
|
447
|
+
throw new Error(`Invalid Tiana Web app ID: ${webId || '(empty)'}`);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
let status = await getTianaStatus(cliOpts);
|
|
451
|
+
if (options.spaceId && status.user.tenant_id !== options.spaceId) {
|
|
452
|
+
log(`[dsh-remote] Switching Tiana space to ${options.spaceId}...`);
|
|
453
|
+
await runTianaJSON(['space', 'switch', options.spaceId, '--json'], cliOpts);
|
|
454
|
+
status = await getTianaStatus(cliOpts);
|
|
455
|
+
}
|
|
456
|
+
if (!status?.user?.user_id || !status?.user?.tenant_id) {
|
|
457
|
+
throw new Error('Tiana login status is missing user_id or tenant_id.');
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const webApps = await listTianaWebApps(cliOpts);
|
|
461
|
+
const webApp = webApps.find((item) => item.id === webId);
|
|
462
|
+
if (!webApp) {
|
|
463
|
+
throw new Error(`Web app "${webId}" was not found in the current Tiana space.`);
|
|
464
|
+
}
|
|
465
|
+
if (!webApp.owner_id || webApp.owner_id !== status.user.user_id ||
|
|
466
|
+
(webApp.tenant_id && webApp.tenant_id !== status.user.tenant_id)) {
|
|
467
|
+
throw new Error('Only the verified owner of this DSH Remote Web app can bind a host to it.');
|
|
468
|
+
}
|
|
469
|
+
if (webApp.enabled === false) {
|
|
470
|
+
throw new Error(`Web app "${webId}" is disabled.`);
|
|
471
|
+
}
|
|
472
|
+
if (webApp.deletion_pending === true) {
|
|
473
|
+
throw new Error(`Web app "${webId}" is pending deletion.`);
|
|
474
|
+
}
|
|
475
|
+
const webUrl = validateWebEndpoint(webApp, webId);
|
|
476
|
+
|
|
477
|
+
const initialState = await withStateLock(() => {
|
|
478
|
+
const raw = loadRemoteState(statePath);
|
|
479
|
+
return raw ? migrateRemoteState(raw) : {};
|
|
480
|
+
}, statePath);
|
|
481
|
+
|
|
482
|
+
const identity = defaultHostIdentity();
|
|
483
|
+
const initialHostId = options.hostId || initialState.host?.hostId || identity.hostId;
|
|
484
|
+
if (!/^[a-z0-9_-]{1,48}$/u.test(initialHostId)) throw new Error('Invalid host ID');
|
|
485
|
+
|
|
486
|
+
// Locate bound Relay Function or provision one if empty
|
|
487
|
+
const binding = await getWebFunctionBinding(webId, cliOpts);
|
|
488
|
+
let fnId = binding.functionInstanceIds[0] || '';
|
|
489
|
+
let fnShown = null;
|
|
490
|
+
if (fnId) {
|
|
491
|
+
fnShown = await runTianaJSON(['function', 'show', fnId, '--json'], cliOpts);
|
|
492
|
+
} else {
|
|
493
|
+
log(`[dsh-remote] Web app ${webId} has no bound Relay Function; provisioning generic relay-go...`);
|
|
494
|
+
const created = await ensureRelayFunction({
|
|
495
|
+
functionName: options.functionName || DEFAULT_FUNCTION_NAME,
|
|
496
|
+
log,
|
|
497
|
+
...cliOpts,
|
|
498
|
+
});
|
|
499
|
+
fnId = created.instance.id;
|
|
500
|
+
fnShown = await syncAndPublishRelayFunction(fnId, webId, { log, ...cliOpts });
|
|
501
|
+
const boundFnId = await ensureWebFunctionBinding(webId, fnId, { adoptExisting: true, log, ...cliOpts });
|
|
502
|
+
if (boundFnId !== fnId) {
|
|
503
|
+
fnId = boundFnId;
|
|
504
|
+
fnShown = await runTianaJSON(['function', 'show', fnId, '--json'], cliOpts);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
let fnUrl = validateRelayFunctionShown(fnShown);
|
|
509
|
+
|
|
510
|
+
const initialPendingBind = initialState.pendingBind?.functionId === fnId && initialState.pendingBind?.webId === webId
|
|
511
|
+
? initialState.pendingBind
|
|
512
|
+
: null;
|
|
513
|
+
let preLockToken = initialState.function?.id === fnId ? initialState.function : null;
|
|
514
|
+
const tokenSeedState = (initialState.function?.id === fnId && initialState.function?.token &&
|
|
515
|
+
(!initialPendingBind?.tokenInfo?.token || Number(initialState.function.expiresAt) >= Number(initialPendingBind.tokenInfo.expiresAt)))
|
|
516
|
+
? initialState
|
|
517
|
+
: (initialPendingBind?.tokenInfo ? { function: initialPendingBind.tokenInfo } : initialState);
|
|
518
|
+
const seedToken = tokenSeedState?.function?.id === fnId ? tokenSeedState.function : null;
|
|
519
|
+
|
|
520
|
+
// Step A: Mint or confirm Function Instance Token BEFORE mutating cloud policy
|
|
521
|
+
let tokenInfo = await ensureHostToken(
|
|
522
|
+
tokenSeedState,
|
|
523
|
+
fnId,
|
|
524
|
+
{ rotateToken: Boolean(options.rotateToken), log, ...cliOpts },
|
|
525
|
+
);
|
|
526
|
+
let mintedNewToken = tokenInfo.token !== seedToken?.token;
|
|
527
|
+
|
|
528
|
+
// Step B: Verify target Function /healthz confirms a valid DSH Remote Relay
|
|
529
|
+
await verifyRelayHealth(fnUrl, tokenInfo.token, options);
|
|
530
|
+
|
|
531
|
+
// Serialize the cloud-read + conflict-check + pendingBind checkpoint + policy write + state commit
|
|
532
|
+
// across local processes so concurrent binds can never produce a local/cloud hostDigest mismatch.
|
|
533
|
+
const bindLockPath = `${resolveStatePath(statePath)}.bind`;
|
|
534
|
+
return await withStateLock(async () => {
|
|
535
|
+
const prevState = await withStateLock(() => {
|
|
536
|
+
const raw = loadRemoteState(statePath);
|
|
537
|
+
return raw ? migrateRemoteState(raw) : {};
|
|
538
|
+
}, statePath);
|
|
539
|
+
|
|
540
|
+
// Re-verify the Web app's active Relay Function binding under lock
|
|
541
|
+
const activeBinding = await getWebFunctionBinding(webId, cliOpts);
|
|
542
|
+
let activeFnId = activeBinding.functionInstanceIds[0] || '';
|
|
543
|
+
if (!activeFnId) {
|
|
544
|
+
activeFnId = await ensureWebFunctionBinding(webId, fnId, { adoptExisting: true, log, ...cliOpts });
|
|
545
|
+
}
|
|
546
|
+
if (activeFnId && activeFnId !== fnId) {
|
|
547
|
+
fnId = activeFnId;
|
|
548
|
+
fnShown = await runTianaJSON(['function', 'show', fnId, '--json'], cliOpts);
|
|
549
|
+
fnUrl = validateRelayFunctionShown(fnShown);
|
|
550
|
+
preLockToken = prevState.function?.id === fnId ? prevState.function : null;
|
|
551
|
+
tokenInfo = await ensureHostToken(prevState, fnId, {
|
|
552
|
+
rotateToken: Boolean(options.rotateToken),
|
|
553
|
+
log,
|
|
554
|
+
...cliOpts,
|
|
555
|
+
});
|
|
556
|
+
mintedNewToken = tokenInfo.token !== preLockToken?.token;
|
|
557
|
+
await verifyRelayHealth(fnUrl, tokenInfo.token, options);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const hostId = options.hostId || prevState.host?.hostId || identity.hostId;
|
|
561
|
+
const hostName = options.hostName || prevState.host?.hostName || identity.hostName;
|
|
562
|
+
if (!/^[a-z0-9_-]{1,48}$/u.test(hostId)) throw new Error('Invalid host ID');
|
|
563
|
+
|
|
564
|
+
// Strictly read fresh existing function parameters (NEVER swallow failure!)
|
|
565
|
+
const existingParams = await getFunctionParameters(fnId, cliOpts);
|
|
566
|
+
const existingPolicy = parsePolicyFromParameters(existingParams);
|
|
567
|
+
|
|
568
|
+
const pendingBind = prevState.pendingBind?.functionId === fnId && prevState.pendingBind?.webId === webId
|
|
569
|
+
? prevState.pendingBind
|
|
570
|
+
: null;
|
|
571
|
+
|
|
572
|
+
const localPubKey = prevState.host?.publicKey || prevState.hostSigningKeyPair?.publicKey || '';
|
|
573
|
+
const matchesPrevHost = !hasBindingIdentityConflict(existingPolicy, {
|
|
574
|
+
hostId,
|
|
575
|
+
registrationKey: prevState.host?.registrationKey || '',
|
|
576
|
+
hostPublicKey: localPubKey,
|
|
577
|
+
});
|
|
578
|
+
const matchesPendingBind = Boolean(pendingBind) && !hasBindingIdentityConflict(existingPolicy, {
|
|
579
|
+
hostId: pendingBind.hostId || hostId,
|
|
580
|
+
registrationKey: pendingBind.registrationKey || '',
|
|
581
|
+
hostPublicKey: localPubKey,
|
|
582
|
+
});
|
|
583
|
+
const conflict = !matchesPrevHost && !matchesPendingBind;
|
|
584
|
+
|
|
585
|
+
let rotatedRegistration = false;
|
|
586
|
+
if (conflict) {
|
|
587
|
+
if (!options.rebind) {
|
|
588
|
+
if (typeof options.confirmRebind === 'function') {
|
|
589
|
+
const ok = await options.confirmRebind(existingPolicy, { hostId, hostName });
|
|
590
|
+
if (!ok) throw new Error('Rebind cancelled by user.');
|
|
591
|
+
} else {
|
|
592
|
+
throw new Error(
|
|
593
|
+
`Web app ${webId} is already bound to "${existingPolicy.hostName || existingPolicy.hostId}" (${existingPolicy.hostId}). Pass --rebind to switch to this host.`,
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
rotatedRegistration = true;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const reusePending = Boolean(pendingBind) && (matchesPendingBind || !prevState.host?.registrationKey);
|
|
601
|
+
const registrationKey = rotatedRegistration
|
|
602
|
+
? generateE2eeSecret()
|
|
603
|
+
: ((reusePending ? pendingBind?.registrationKey : prevState.host?.registrationKey) ||
|
|
604
|
+
pendingBind?.registrationKey ||
|
|
605
|
+
prevState.host?.registrationKey ||
|
|
606
|
+
generateE2eeSecret());
|
|
607
|
+
const baseE2eeSource = prevState.e2ee?.secret
|
|
608
|
+
? prevState
|
|
609
|
+
: (pendingBind?.e2ee?.secret ? { e2ee: pendingBind.e2ee } : prevState);
|
|
610
|
+
const { e2ee } = ensureE2eeConfig(baseE2eeSource, { rotate: Boolean(options.rotateE2eeKey) });
|
|
611
|
+
|
|
612
|
+
const bindStartToken = prevState.function?.id === fnId ? prevState.function : null;
|
|
613
|
+
let activeTokenInfo = tokenInfo;
|
|
614
|
+
if (!options.rotateToken &&
|
|
615
|
+
prevState.function?.id === fnId &&
|
|
616
|
+
prevState.function?.token &&
|
|
617
|
+
(Number(prevState.function.expiresAt) > Number(tokenInfo.expiresAt) ||
|
|
618
|
+
(Number(prevState.function.expiresAt) === Number(tokenInfo.expiresAt) &&
|
|
619
|
+
(!mintedNewToken || prevState.function.token !== preLockToken?.token)))) {
|
|
620
|
+
activeTokenInfo = {
|
|
621
|
+
token: prevState.function.token,
|
|
622
|
+
tokenId: prevState.function.tokenId,
|
|
623
|
+
expiresAt: prevState.function.expiresAt,
|
|
624
|
+
};
|
|
625
|
+
} else if (!options.rotateToken &&
|
|
626
|
+
pendingBind?.tokenInfo?.token &&
|
|
627
|
+
Number(pendingBind.tokenInfo.expiresAt) > Number(tokenInfo.expiresAt)) {
|
|
628
|
+
activeTokenInfo = {
|
|
629
|
+
token: pendingBind.tokenInfo.token,
|
|
630
|
+
tokenId: pendingBind.tokenInfo.tokenId,
|
|
631
|
+
expiresAt: pendingBind.tokenInfo.expiresAt,
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// Step C: Save local recovery checkpoint under lock BEFORE mutating cloud DSH_REMOTE_POLICY
|
|
636
|
+
await withStateLock(() => {
|
|
637
|
+
const raw = loadRemoteState(statePath) || {};
|
|
638
|
+
saveRemoteState({
|
|
639
|
+
...raw,
|
|
640
|
+
pendingBind: {
|
|
641
|
+
webId,
|
|
642
|
+
functionId: fnId,
|
|
643
|
+
hostId,
|
|
644
|
+
hostName,
|
|
645
|
+
registrationKey,
|
|
646
|
+
e2ee,
|
|
647
|
+
tokenInfo: { ...activeTokenInfo, id: fnId },
|
|
648
|
+
createdAt: new Date().toISOString(),
|
|
649
|
+
},
|
|
650
|
+
}, statePath);
|
|
651
|
+
}, statePath);
|
|
652
|
+
|
|
653
|
+
// Step D: Write DSH_REMOTE_POLICY using verified existingParams (preserving unrelated params)
|
|
654
|
+
const policy = buildRemotePolicy({
|
|
655
|
+
hostId,
|
|
656
|
+
hostName,
|
|
657
|
+
registrationKey,
|
|
658
|
+
ownerUserId: status.user.user_id,
|
|
659
|
+
ownerTenantId: status.user.tenant_id,
|
|
660
|
+
webId,
|
|
661
|
+
origin: webUrl.origin,
|
|
662
|
+
});
|
|
663
|
+
await updateRemotePolicy(fnId, policy, { existingParams, log, ...cliOpts });
|
|
664
|
+
|
|
665
|
+
// Step E: Atomically commit final state under lock, merging concurrent settings, key rotation, and token renewals
|
|
666
|
+
const committedState = await withStateLock(() => {
|
|
667
|
+
const latestRaw = loadRemoteState(statePath);
|
|
668
|
+
const latest = latestRaw ? migrateRemoteState(latestRaw) : prevState;
|
|
669
|
+
const committedE2ee = (!options.rotateE2eeKey && latest.e2ee?.secret && latest.e2ee.secret !== prevState.e2ee?.secret)
|
|
670
|
+
? latest.e2ee
|
|
671
|
+
: e2ee;
|
|
672
|
+
const keepLatestToken = !options.rotateToken &&
|
|
673
|
+
latest.function?.id === fnId &&
|
|
674
|
+
latest.function?.token &&
|
|
675
|
+
(Number(latest.function.expiresAt) > Number(activeTokenInfo.expiresAt) ||
|
|
676
|
+
(Number(latest.function.expiresAt) === Number(activeTokenInfo.expiresAt) &&
|
|
677
|
+
(latest.function.token !== bindStartToken?.token ||
|
|
678
|
+
(!mintedNewToken && latest.function.token !== activeTokenInfo.token))));
|
|
679
|
+
const committedToken = keepLatestToken
|
|
680
|
+
? { token: latest.function.token, tokenId: latest.function.tokenId, expiresAt: latest.function.expiresAt }
|
|
681
|
+
: activeTokenInfo;
|
|
682
|
+
const nextState = {
|
|
683
|
+
version: 2,
|
|
684
|
+
configVersion: 2,
|
|
685
|
+
enabled: latest.enabled !== undefined ? latest.enabled : true,
|
|
686
|
+
updatedAt: new Date().toISOString(),
|
|
687
|
+
owner: {
|
|
688
|
+
userId: status.user.user_id,
|
|
689
|
+
tenantId: status.user.tenant_id,
|
|
690
|
+
email: status.user.email,
|
|
691
|
+
displayName: status.user.display_name,
|
|
692
|
+
spaceName: status.space?.display_name || '',
|
|
693
|
+
},
|
|
694
|
+
host: {
|
|
695
|
+
hostId,
|
|
696
|
+
hostName,
|
|
697
|
+
registrationKey,
|
|
698
|
+
},
|
|
699
|
+
e2ee: committedE2ee,
|
|
700
|
+
function: {
|
|
701
|
+
id: fnId,
|
|
702
|
+
name: fnShown?.instance?.display_name || fnShown?.instance?.name || DEFAULT_FUNCTION_NAME,
|
|
703
|
+
url: fnUrl,
|
|
704
|
+
token: committedToken.token,
|
|
705
|
+
tokenId: committedToken.tokenId,
|
|
706
|
+
expiresAt: committedToken.expiresAt,
|
|
707
|
+
},
|
|
708
|
+
web: {
|
|
709
|
+
id: webId,
|
|
710
|
+
name: webApp.name || DEFAULT_WEB_NAME,
|
|
711
|
+
endpoint: webUrl.href,
|
|
712
|
+
},
|
|
713
|
+
network: latest.network || {
|
|
714
|
+
p2pEnabled: true,
|
|
715
|
+
stunUrls: [...DEFAULT_STUN_URLS],
|
|
716
|
+
},
|
|
717
|
+
security: latest.security || {
|
|
718
|
+
allowedWebPlugins: [],
|
|
719
|
+
},
|
|
720
|
+
allowedWebPlugins: latest.security?.allowedWebPlugins || latest.allowedWebPlugins || [],
|
|
721
|
+
};
|
|
722
|
+
saveRemoteState(nextState, statePath);
|
|
723
|
+
return nextState;
|
|
724
|
+
}, statePath);
|
|
725
|
+
|
|
726
|
+
return committedState;
|
|
727
|
+
}, bindLockPath, { timeoutMs: options.bindLockTimeoutMs ?? 30_000 });
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* Provision or reuse the Tiana Function Relay + Token + .tweb App in the logged-in user's space.
|
|
732
|
+
* Uploads generic relay-go once and writes DSH_REMOTE_POLICY via function parameters (zero recompile on updates).
|
|
733
|
+
*/
|
|
734
|
+
export async function provisionTianaRemote(options = {}) {
|
|
735
|
+
const log = options.log ?? console.log;
|
|
736
|
+
const functionName = options.functionName || DEFAULT_FUNCTION_NAME;
|
|
737
|
+
const webName = options.webName || DEFAULT_WEB_NAME;
|
|
738
|
+
const statePath = options.statePath;
|
|
739
|
+
const cliOpts = options.tianaBin ? { bin: options.tianaBin } : {};
|
|
740
|
+
|
|
741
|
+
const status = await getTianaStatus(cliOpts);
|
|
742
|
+
const bindLockPath = `${resolveStatePath(statePath)}.bind`;
|
|
743
|
+
return await withStateLock(async () => {
|
|
744
|
+
const prevState = await withStateLock(() => loadRemoteState(statePath) || {}, statePath);
|
|
745
|
+
const pending = { ...(prevState.pendingSetup || {}) };
|
|
746
|
+
const identity = defaultHostIdentity();
|
|
747
|
+
const hostId = options.hostId || prevState.host?.hostId || pending.hostId || identity.hostId;
|
|
748
|
+
const hostName = options.hostName || prevState.host?.hostName || identity.hostName;
|
|
749
|
+
|
|
750
|
+
if (!/^[a-z0-9_-]{1,48}$/u.test(hostId)) throw new Error('Invalid host ID');
|
|
751
|
+
const previousOwner = prevState.owner || pending.owner;
|
|
752
|
+
if ((previousOwner?.userId && previousOwner.userId !== status.user.user_id) ||
|
|
753
|
+
(previousOwner?.tenantId && previousOwner.tenantId !== status.user.tenant_id)) {
|
|
754
|
+
throw new Error('Use the Tiana account and space that originally configured this DSH host');
|
|
755
|
+
}
|
|
756
|
+
if ((prevState.host?.hostId || pending.hostId || hostId) !== hostId) {
|
|
757
|
+
throw new Error('This installation is already bound to a different host ID');
|
|
758
|
+
}
|
|
759
|
+
const baseE2eeSource = prevState.e2ee?.secret
|
|
760
|
+
? prevState
|
|
761
|
+
: (pending.e2ee ? { e2ee: pending.e2ee } : prevState);
|
|
762
|
+
const { e2ee } = ensureE2eeConfig(baseE2eeSource, {
|
|
763
|
+
rotate: (!pending.e2ee && prevState.version !== 2) || Boolean(options.rotateE2eeKey),
|
|
764
|
+
});
|
|
765
|
+
const registrationKey = prevState.host?.registrationKey || pending.registrationKey || generateE2eeSecret();
|
|
766
|
+
const owner = { userId: status.user.user_id, tenantId: status.user.tenant_id };
|
|
767
|
+
const checkpoint = async (fields) => {
|
|
768
|
+
Object.assign(pending, fields);
|
|
769
|
+
await withStateLock(() => {
|
|
770
|
+
const current = loadRemoteState(statePath) || {};
|
|
771
|
+
saveRemoteState({ ...current, pendingSetup: { ...pending } }, statePath);
|
|
772
|
+
}, statePath);
|
|
773
|
+
};
|
|
774
|
+
|
|
775
|
+
const { instance: fnInstance } = await ensureRelayFunction({
|
|
776
|
+
functionName, functionId: prevState.function?.id || pending.functionId, log, ...cliOpts,
|
|
777
|
+
});
|
|
778
|
+
if (!fnInstance?.id) throw new Error('Missing configured Function ID');
|
|
779
|
+
await checkpoint({ functionId: fnInstance.id, owner, hostId, registrationKey, e2ee });
|
|
780
|
+
const webApp = await ensureWebApp({ webName, webId: prevState.web?.id || pending.webId, log, ...cliOpts });
|
|
781
|
+
const webId = webApp?.id;
|
|
782
|
+
if (!/^[a-z][a-z0-9]{11}$/u.test(webId || '')) throw new Error('Invalid Web app ID');
|
|
783
|
+
if (!webApp.owner_id || webApp.owner_id !== owner.userId ||
|
|
784
|
+
(webApp.tenant_id && webApp.tenant_id !== owner.tenantId)) {
|
|
785
|
+
throw new Error('The configured Web app does not belong to the DSH owner and space');
|
|
786
|
+
}
|
|
787
|
+
const webUrl = validateWebEndpoint(webApp, webId);
|
|
788
|
+
const webEndpoint = webUrl.href;
|
|
789
|
+
await checkpoint({ webId });
|
|
790
|
+
|
|
791
|
+
const policy = buildRemotePolicy({
|
|
792
|
+
hostId,
|
|
793
|
+
hostName,
|
|
794
|
+
registrationKey,
|
|
795
|
+
ownerUserId: status.user.user_id,
|
|
796
|
+
ownerTenantId: status.user.tenant_id,
|
|
797
|
+
webId,
|
|
798
|
+
origin: webUrl.origin,
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
// Build and validate the browser package in an isolated temporary directory (never pollutes repo!)
|
|
802
|
+
const distTemp = mkdtempSync(join(tmpdir(), 'dsh-remote-web-dist-'));
|
|
803
|
+
try {
|
|
804
|
+
const built = buildWebDist({
|
|
805
|
+
outDir: distTemp,
|
|
806
|
+
config: {
|
|
807
|
+
functionId: fnInstance.id,
|
|
808
|
+
webId,
|
|
809
|
+
defaultHostId: hostId,
|
|
810
|
+
appTitle: `${webName} · ${hostName}`,
|
|
811
|
+
},
|
|
812
|
+
});
|
|
813
|
+
log(`[dsh-remote] Built .tweb bundle (${built.fileCount} files, ${(built.totalBytes / 1024).toFixed(1)} KiB). Publishing to ${webId}...`);
|
|
814
|
+
|
|
815
|
+
const fnShown = await syncAndPublishRelayFunction(fnInstance.id, webId, {
|
|
816
|
+
forcePublish: Boolean(options.forcePublish), log, ...cliOpts,
|
|
817
|
+
});
|
|
818
|
+
const fnUrl = fnShown?.instance?.connection?.url || fnShown?.instance?.url || fnInstance.connection?.url || fnInstance.url;
|
|
819
|
+
if (!fnUrl || new URL(fnUrl).protocol !== 'https:') throw new Error('Function requires an HTTPS endpoint');
|
|
820
|
+
|
|
821
|
+
// Mint token and checkpoint BEFORE mutating cloud policy
|
|
822
|
+
const tokenSeedState = (prevState.function?.id === fnInstance.id && prevState.function?.token &&
|
|
823
|
+
(!pending.tokenInfo?.token || Number(prevState.function.expiresAt) >= Number(pending.tokenInfo.expiresAt)))
|
|
824
|
+
? prevState
|
|
825
|
+
: (pending.tokenInfo ? { function: pending.tokenInfo } : prevState);
|
|
826
|
+
const tokenInfo = await ensureHostToken(tokenSeedState, fnInstance.id, {
|
|
827
|
+
rotateToken: Boolean(options.rotateToken), log, ...cliOpts,
|
|
828
|
+
});
|
|
829
|
+
await checkpoint({ tokenInfo: { ...tokenInfo, id: fnInstance.id } });
|
|
830
|
+
|
|
831
|
+
await updateRemotePolicy(fnInstance.id, policy, { log, ...cliOpts });
|
|
832
|
+
await ensureWebFunctionBinding(webId, fnInstance.id, { log, ...cliOpts });
|
|
833
|
+
|
|
834
|
+
const publishResult = await runTianaJSON([
|
|
835
|
+
'web', 'publish',
|
|
836
|
+
'--dir', distTemp,
|
|
837
|
+
'--json',
|
|
838
|
+
webId,
|
|
839
|
+
], { ...cliOpts, timeoutMs: 240_000 });
|
|
840
|
+
|
|
841
|
+
const nextState = await withStateLock(() => {
|
|
842
|
+
const latestRaw = loadRemoteState(statePath) || prevState;
|
|
843
|
+
const migrated = migrateRemoteState(latestRaw) || {};
|
|
844
|
+
const committedE2ee = (!options.rotateE2eeKey && migrated.e2ee?.secret && migrated.e2ee.secret !== prevState.e2ee?.secret)
|
|
845
|
+
? migrated.e2ee
|
|
846
|
+
: e2ee;
|
|
847
|
+
const keepLatestToken = !options.rotateToken &&
|
|
848
|
+
migrated.function?.id === fnInstance.id &&
|
|
849
|
+
migrated.function?.token &&
|
|
850
|
+
(Number(migrated.function.expiresAt) > Number(tokenInfo.expiresAt) ||
|
|
851
|
+
(Number(migrated.function.expiresAt) === Number(tokenInfo.expiresAt) &&
|
|
852
|
+
migrated.function.token !== prevState.function?.token));
|
|
853
|
+
const committedToken = keepLatestToken
|
|
854
|
+
? { token: migrated.function.token, tokenId: migrated.function.tokenId, expiresAt: migrated.function.expiresAt }
|
|
855
|
+
: tokenInfo;
|
|
856
|
+
const finalState = {
|
|
857
|
+
version: 2,
|
|
858
|
+
configVersion: 2,
|
|
859
|
+
enabled: migrated.enabled !== undefined ? migrated.enabled : true,
|
|
860
|
+
updatedAt: new Date().toISOString(),
|
|
861
|
+
owner: {
|
|
862
|
+
userId: status.user.user_id,
|
|
863
|
+
tenantId: status.user.tenant_id,
|
|
864
|
+
email: status.user.email,
|
|
865
|
+
displayName: status.user.display_name,
|
|
866
|
+
spaceName: status.space?.display_name || '',
|
|
867
|
+
},
|
|
868
|
+
host: {
|
|
869
|
+
hostId,
|
|
870
|
+
hostName,
|
|
871
|
+
registrationKey,
|
|
872
|
+
},
|
|
873
|
+
e2ee: committedE2ee,
|
|
874
|
+
function: {
|
|
875
|
+
id: fnInstance.id,
|
|
876
|
+
name: fnInstance.display_name || fnInstance.name || functionName,
|
|
877
|
+
url: fnUrl,
|
|
878
|
+
token: committedToken.token,
|
|
879
|
+
tokenId: committedToken.tokenId,
|
|
880
|
+
expiresAt: committedToken.expiresAt,
|
|
881
|
+
},
|
|
882
|
+
web: {
|
|
883
|
+
id: webId,
|
|
884
|
+
name: webApp.name || webName,
|
|
885
|
+
endpoint: webEndpoint,
|
|
886
|
+
lastPublish: publishResult,
|
|
887
|
+
},
|
|
888
|
+
network: migrated.network || {
|
|
889
|
+
p2pEnabled: true,
|
|
890
|
+
stunUrls: [...DEFAULT_STUN_URLS],
|
|
891
|
+
},
|
|
892
|
+
security: migrated.security || {
|
|
893
|
+
allowedWebPlugins: [],
|
|
894
|
+
},
|
|
895
|
+
allowedWebPlugins: migrated.security?.allowedWebPlugins || [],
|
|
896
|
+
};
|
|
897
|
+
saveRemoteState(finalState, statePath);
|
|
898
|
+
return finalState;
|
|
899
|
+
}, statePath);
|
|
900
|
+
|
|
901
|
+
return nextState;
|
|
902
|
+
} finally {
|
|
903
|
+
rmSync(distTemp, { recursive: true, force: true });
|
|
904
|
+
}
|
|
905
|
+
}, bindLockPath, { timeoutMs: options.bindLockTimeoutMs ?? 300_000 });
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
export async function republishWebShell(state, { log = console.log, ...cliOpts } = {}) {
|
|
909
|
+
if (!state?.web?.id || !state?.function?.id) {
|
|
910
|
+
throw new Error('Remote web app is not configured.');
|
|
911
|
+
}
|
|
912
|
+
const webId = state.web.id;
|
|
913
|
+
const distTemp = mkdtempSync(join(tmpdir(), 'dsh-remote-web-republish-'));
|
|
914
|
+
try {
|
|
915
|
+
const built = buildWebDist({
|
|
916
|
+
outDir: distTemp,
|
|
917
|
+
config: {
|
|
918
|
+
functionId: state.function.id,
|
|
919
|
+
webId,
|
|
920
|
+
defaultHostId: state.host?.hostId || '',
|
|
921
|
+
appTitle: `${state.web.name || DEFAULT_WEB_NAME} · ${state.host?.hostName || state.host?.hostId || 'DSH'}`,
|
|
922
|
+
},
|
|
923
|
+
});
|
|
924
|
+
log(`[dsh-remote] Rebuilt .tweb bundle (${built.fileCount} files, ${(built.totalBytes / 1024).toFixed(1)} KiB). Publishing...`);
|
|
925
|
+
return await runTianaJSON(['web', 'publish', '--dir', distTemp, '--json', webId], { ...cliOpts, timeoutMs: 240_000 });
|
|
926
|
+
} finally {
|
|
927
|
+
rmSync(distTemp, { recursive: true, force: true });
|
|
928
|
+
}
|
|
929
|
+
}
|