@tianacloud/dsh-remote 0.0.0-stage → 0.2.2

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.
@@ -0,0 +1,1271 @@
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
+ loadRemoteStateSnapshot,
16
+ migrateRemoteState,
17
+ removeRemoteState,
18
+ resolveStatePath,
19
+ saveRemoteState,
20
+ withStateLock,
21
+ } from './state.js';
22
+
23
+ const execFileAsync = promisify(execFile);
24
+ const PROJECT_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
25
+ const RELAY_GO_DIR = join(PROJECT_ROOT, 'relay-go');
26
+
27
+ export const DEFAULT_FUNCTION_NAME = 'dsh-remote-relay';
28
+ export const DEFAULT_WEB_NAME = 'DSH Remote';
29
+ export const DEFAULT_TOKEN_NAME = 'dsh-remote-host';
30
+
31
+ export function tianaBinary(overrideBin) {
32
+ if (typeof overrideBin === 'string' && overrideBin.trim()) return overrideBin.trim();
33
+ return process.env.TIANA_BIN || (process.platform === 'win32' ? 'tiana.cmd' : 'tiana');
34
+ }
35
+
36
+ export async function runTiana(args, options = {}) {
37
+ const bin = tianaBinary(options.bin || options.tianaBin);
38
+ try {
39
+ const { stdout, stderr } = await execFileAsync(bin, args, {
40
+ maxBuffer: 16 * 1024 * 1024,
41
+ timeout: options.timeoutMs ?? 180_000,
42
+ env: options.env ?? process.env,
43
+ shell: process.platform === 'win32',
44
+ });
45
+ return { stdout, stderr };
46
+ } catch (err) {
47
+ const detail = args[0] === 'token' || args[0] === 'status'
48
+ ? 'credential command failed'
49
+ : String(err?.stderr || err?.message || err).trim();
50
+ throw new Error(`tiana ${args.join(' ')} failed: ${detail}`);
51
+ }
52
+ }
53
+
54
+ export async function runTianaJSON(args, options = {}) {
55
+ const { stdout } = await runTiana(args, options);
56
+ const trimmed = stdout.trim();
57
+ let parsed;
58
+ try {
59
+ parsed = JSON.parse(trimmed);
60
+ } catch {
61
+ throw new Error(`tiana ${args.join(' ')} returned invalid JSON`);
62
+ }
63
+ if (parsed?.error) {
64
+ const credentialCommand = args[0] === 'token' || args[0] === 'status';
65
+ const msg = credentialCommand ? 'credential command failed'
66
+ : parsed.error.message || parsed.error.code || 'unknown error';
67
+ throw new Error(`tiana ${args.join(' ')} error: ${msg}`);
68
+ }
69
+ return parsed?.data ?? parsed;
70
+ }
71
+
72
+ export async function getTianaStatus(options = {}) {
73
+ const data = await runTianaJSON(['status', '--json'], options);
74
+ if (!data?.logged_in || !data?.user?.user_id || !data?.user?.tenant_id) {
75
+ throw new Error('Not logged in to Tiana. Run `tiana login` first.');
76
+ }
77
+ return data;
78
+ }
79
+
80
+ export async function listTianaWebApps(options = {}) {
81
+ const data = await runTianaJSON(['web', 'list', '--json'], options);
82
+ return Array.isArray(data?.items) ? data.items : [];
83
+ }
84
+
85
+ export async function getWebFunctionBinding(webId, options = {}) {
86
+ const current = await runTianaJSON(['web', 'functions', 'get', webId, '--json'], options);
87
+ const ids = Array.isArray(current?.function_instance_ids) ? current.function_instance_ids : [];
88
+ return {
89
+ functionInstanceIds: ids,
90
+ projectRevision: current?.project_revision,
91
+ canManage: current?.can_manage,
92
+ raw: current,
93
+ };
94
+ }
95
+
96
+ export async function getFunctionParameters(functionId, options = {}) {
97
+ const data = await runTianaJSON(['function', 'parameters', 'get', functionId, '--json'], options);
98
+ const params = data?.parameters && typeof data.parameters === 'object' ? data.parameters : data;
99
+ if (!params || typeof params !== 'object' || Array.isArray(params)) {
100
+ throw new Error(`Unexpected function parameters response for ${functionId}`);
101
+ }
102
+ return params;
103
+ }
104
+
105
+ export async function setFunctionParameters(functionId, paramsObj, options = {}) {
106
+ const temp = mkdtempSync(join(tmpdir(), 'dsh-remote-params-'));
107
+ try {
108
+ const paramsFile = join(temp, 'parameters.json');
109
+ writeFileSync(paramsFile, `${JSON.stringify(paramsObj, null, 2)}\n`, { mode: 0o600 });
110
+ return await runTianaJSON([
111
+ 'function', 'parameters', 'set',
112
+ functionId,
113
+ '--file', paramsFile,
114
+ '--json',
115
+ ], options);
116
+ } finally {
117
+ rmSync(temp, { recursive: true, force: true });
118
+ }
119
+ }
120
+
121
+ export function buildRemotePolicy({ hostId, hostName, registrationKey, ownerUserId, ownerTenantId, webId, origin }) {
122
+ return {
123
+ version: 1,
124
+ webId,
125
+ origin,
126
+ ownerUserId,
127
+ ownerTenantId,
128
+ hostId,
129
+ hostName: hostName || hostId,
130
+ hostDigest: createHash('sha256').update(registrationKey).digest('hex'),
131
+ updatedAt: new Date().toISOString(),
132
+ };
133
+ }
134
+
135
+ export function parsePolicyFromParameters(params) {
136
+ const entry = params?.DSH_REMOTE_POLICY;
137
+ const raw = typeof entry === 'string' ? entry : entry?.value;
138
+ if (!raw || typeof raw !== 'string') return null;
139
+ try {
140
+ return JSON.parse(raw);
141
+ } catch {
142
+ return null;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Update `DSH_REMOTE_POLICY` while strictly preserving all other function parameters.
148
+ * NEVER swallows `getFunctionParameters` errors (to prevent clobbering existing bindings or user params).
149
+ */
150
+ export async function updateRemotePolicy(functionId, policy, { log = console.log, existingParams, ...options } = {}) {
151
+ const existing = existingParams !== undefined
152
+ ? existingParams
153
+ : await getFunctionParameters(functionId, options);
154
+ const merged = {
155
+ ...existing,
156
+ DSH_REMOTE_POLICY: {
157
+ kind: 'plain',
158
+ value: JSON.stringify(policy),
159
+ },
160
+ };
161
+ log(`[dsh-remote] Updating DSH_REMOTE_POLICY on Function ${functionId} (zero recompile)...`);
162
+ await setFunctionParameters(functionId, merged, options);
163
+ return policy;
164
+ }
165
+
166
+ export function validateRelayFunctionShown(fnShown) {
167
+ const status = String(
168
+ fnShown?.instance?.product_state ??
169
+ fnShown?.instance?.status ??
170
+ fnShown?.function?.status ??
171
+ fnShown?.product_state ??
172
+ fnShown?.status ??
173
+ '',
174
+ ).trim().toUpperCase();
175
+ if (status !== 'ACTIVE') {
176
+ throw new Error(`Relay Function must be ACTIVE (got "${status || 'unknown'}")`);
177
+ }
178
+ if (fnShown?.instance?.enabled === false) {
179
+ throw new Error('Relay Function is disabled');
180
+ }
181
+ if (fnShown?.instance?.deletion_pending === true) {
182
+ throw new Error('Relay Function is pending deletion');
183
+ }
184
+ const fnUrl = fnShown?.instance?.connection?.url || fnShown?.instance?.url || '';
185
+ if (!fnUrl) {
186
+ throw new Error('Relay Function requires an active HTTPS endpoint');
187
+ }
188
+ let parsed;
189
+ try {
190
+ parsed = new URL(fnUrl);
191
+ } catch {
192
+ throw new Error('Relay Function endpoint URL is invalid');
193
+ }
194
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {
195
+ throw new Error('Relay Function requires an active HTTPS endpoint without credentials');
196
+ }
197
+ return fnUrl;
198
+ }
199
+
200
+ export async function verifyRelayHealth(fnUrl, token, options = {}) {
201
+ if (typeof options.probeRelayHealth === 'function') {
202
+ const res = await options.probeRelayHealth(fnUrl, token);
203
+ if (!res || res.ok !== true || typeof res.paired !== 'boolean') {
204
+ throw new Error('Target Function /healthz did not confirm a valid DSH Remote Relay');
205
+ }
206
+ return res;
207
+ }
208
+ const healthUrl = new URL('/healthz', fnUrl);
209
+ if (healthUrl.protocol !== 'https:' || healthUrl.username || healthUrl.password) {
210
+ throw new Error('Relay health probe requires HTTPS URL');
211
+ }
212
+ const headers = { Accept: 'application/json' };
213
+ if (token) headers.Authorization = `Bearer ${token}`;
214
+ const resp = await fetch(healthUrl, {
215
+ headers,
216
+ redirect: 'error',
217
+ signal: AbortSignal.timeout(options.healthTimeoutMs ?? 10_000),
218
+ });
219
+ if (!resp.ok) {
220
+ throw new Error(`Target Function /healthz returned HTTP ${resp.status}; verify this is a DSH Remote Relay`);
221
+ }
222
+ let body;
223
+ try {
224
+ body = await resp.json();
225
+ } catch {
226
+ throw new Error('Target Function /healthz did not return JSON; verify this is a DSH Remote Relay');
227
+ }
228
+ if (body?.ok !== true || typeof body?.paired !== 'boolean') {
229
+ throw new Error('Target Function /healthz payload does not match DSH Remote Relay contract');
230
+ }
231
+ return body;
232
+ }
233
+
234
+ async function ensureRelayFunction({ functionName, functionId, log = console.log, ...cliOpts }) {
235
+ if (functionId) {
236
+ log(`[dsh-remote] Reusing configured Function ${functionId}`);
237
+ const shown = await runTianaJSON(['function', 'show', functionId, '--json'], cliOpts);
238
+ return { instance: shown.instance };
239
+ }
240
+
241
+ log(`[dsh-remote] Creating Function "${functionName}"...`);
242
+ const created = await runTianaJSON([
243
+ 'function', 'create', '--wait',
244
+ '-m', 'DSH Remote WebSocket rendezvous relay',
245
+ '--json',
246
+ functionName,
247
+ ], { ...cliOpts, timeoutMs: 240_000 });
248
+ const createdId = created?.instance_id || created?.instance?.id || created?.id;
249
+ if (!createdId) {
250
+ throw new Error(`Unexpected function create response: ${JSON.stringify(created)}`);
251
+ }
252
+ const shown = await runTianaJSON(['function', 'show', createdId, '--json'], cliOpts);
253
+ return { instance: shown?.instance ?? { id: createdId, display_name: functionName }, details: shown?.function ?? {}, release: shown?.release };
254
+ }
255
+
256
+ async function syncAndPublishRelayFunction(functionId, webId, { forcePublish = false, log = console.log, ...cliOpts } = {}) {
257
+ const goModPath = join(RELAY_GO_DIR, 'go.mod');
258
+ const desiredGoMod = readFileSync(goModPath, 'utf8');
259
+ const template = readFileSync(join(RELAY_GO_DIR, 'main.go'), 'utf8');
260
+ const marker = 'var defaultWebID = ""';
261
+ const desiredMainGo = webId && template.includes(marker)
262
+ ? template.replace(marker, () => `var defaultWebID = ${JSON.stringify(webId)}`)
263
+ : template;
264
+
265
+ const sourceView = await runTianaJSON(['function', 'source', 'list', functionId, '--json'], cliOpts);
266
+ const needsInitial = Boolean(sourceView?.needs_initial_source) || !sourceView?.commit;
267
+
268
+ let sameSource = false;
269
+ if (!needsInitial) {
270
+ try {
271
+ const [curMod, curMain] = await Promise.all([
272
+ runTiana(['function', 'source', 'read', functionId, 'go.mod'], cliOpts),
273
+ runTiana(['function', 'source', 'read', functionId, 'main.go'], cliOpts),
274
+ ]);
275
+ sameSource = curMod.stdout === desiredGoMod && curMain.stdout === desiredMainGo;
276
+ } catch {
277
+ sameSource = false;
278
+ }
279
+ }
280
+
281
+ let commit = sourceView?.commit || '';
282
+ if (!sameSource) {
283
+ log(`[dsh-remote] Uploading Go relay source to ${functionId}...`);
284
+ const baseCommit = needsInitial ? 'empty' : commit;
285
+ const temp = mkdtempSync(join(tmpdir(), 'dsh-remote-relay-'));
286
+ try {
287
+ const mainGoPath = join(temp, 'main.go');
288
+ writeFileSync(mainGoPath, desiredMainGo, { mode: 0o600 });
289
+ const saved = await runTianaJSON([
290
+ 'function', 'source', 'save',
291
+ '--base-commit', baseCommit,
292
+ '--file', `go.mod=${goModPath}`,
293
+ '--file', `main.go=${mainGoPath}`,
294
+ '--json', functionId,
295
+ ], cliOpts);
296
+ if (!saved?.commit) throw new Error('Function source save returned no commit');
297
+ commit = saved.commit;
298
+ } finally {
299
+ rmSync(temp, { recursive: true, force: true });
300
+ }
301
+ } else {
302
+ log(`[dsh-remote] Function source is up to date (${commit.slice(0, 8)}).`);
303
+ }
304
+
305
+ async function isPublished(info) {
306
+ const published = info?.release?.published;
307
+ if (!published?.id) return false;
308
+ const builds = await runTianaJSON(['function', 'builds', '--json', functionId], cliOpts);
309
+ return Boolean(builds?.items?.some((build) => build.id === published.id &&
310
+ build.source_commit === commit && build.build_commit === published.build_commit));
311
+ }
312
+ const shown = await runTianaJSON(['function', 'show', functionId, '--json'], cliOpts);
313
+ if (!forcePublish && sameSource && await isPublished(shown)) {
314
+ log('[dsh-remote] The configured relay source is already published');
315
+ return shown;
316
+ }
317
+
318
+ log(`[dsh-remote] Building & publishing Function ${functionId}...`);
319
+ await runTianaJSON(['function', 'publish', '--commit', commit, '--wait', '--json', functionId],
320
+ { ...cliOpts, timeoutMs: 300_000 });
321
+ const deployed = await runTianaJSON(['function', 'show', functionId, '--json'], cliOpts);
322
+ if (!(await isPublished(deployed))) throw new Error('The relay release does not match the configured source');
323
+ return deployed;
324
+ }
325
+
326
+ export async function ensureHostToken(state, functionId, { rotateToken = false, log = console.log, ...cliOpts } = {}) {
327
+ const now = Math.floor(Date.now() / 1000);
328
+ if (!rotateToken && state?.function?.id === functionId && state?.function?.token &&
329
+ state.function.expiresAt > now + 86400) {
330
+ const { token, tokenId, expiresAt } = state.function;
331
+ return { token, tokenId, expiresAt };
332
+ }
333
+ const expiresAt = now + 30 * 86400;
334
+ const tokenName = `${DEFAULT_TOKEN_NAME}-${Date.now()}`;
335
+ log(`[dsh-remote] Creating instance access token for ${functionId}...`);
336
+ const receipt = await runTianaJSON([
337
+ 'token', 'create',
338
+ '--name', tokenName,
339
+ '--expires-at', String(expiresAt),
340
+ '--json',
341
+ functionId,
342
+ ], cliOpts);
343
+ if (!receipt?.token) {
344
+ throw new Error('Instance Token receipt was missing its credential');
345
+ }
346
+ return { token: receipt.token, tokenId: receipt.token_id || '', expiresAt };
347
+ }
348
+
349
+ async function ensureWebApp({ webName, webId, log = console.log, ...cliOpts }) {
350
+ if (webId) {
351
+ const items = await listTianaWebApps(cliOpts);
352
+ const existing = items.find((item) => item.id === webId);
353
+ if (!existing) throw new Error('The configured Web app is unavailable in the current Tiana space');
354
+ return existing;
355
+ }
356
+ log(`[dsh-remote] Creating Web app "${webName}"...`);
357
+ const created = await runTianaJSON([
358
+ 'web', 'create',
359
+ '--entry', 'dsh-remote-entry.mjs',
360
+ '--description', 'DeepSeek Harness 远程访问入口(由 @tianacloud/dsh-remote 自动编排)',
361
+ '--json',
362
+ webName,
363
+ ], cliOpts);
364
+ const createdApp = created?.project ?? created?.app ?? created;
365
+ if (createdApp?.id && !normalizeIdentityValue(createdApp.owner_id) && !normalizeIdentityValue(createdApp.tenant_id)) {
366
+ const items = await listTianaWebApps(cliOpts);
367
+ const listed = items.find((item) => item.id === createdApp.id);
368
+ if (listed) return listed;
369
+ }
370
+ return createdApp;
371
+ }
372
+
373
+ function normalizeIdentityValue(value) {
374
+ return value == null ? '' : String(value).trim();
375
+ }
376
+
377
+ export function verifyWebAppOwnership(webApp, status, { binding = null, requireBindingProof = false, errorMessage } = {}) {
378
+ const msg = errorMessage || 'Only the verified owner of this DSH Remote Web app can bind a host to it.';
379
+ const expectedUserId = normalizeIdentityValue(status?.user?.user_id);
380
+ const expectedTenantId = normalizeIdentityValue(status?.user?.tenant_id);
381
+ if (!expectedUserId || !expectedTenantId) {
382
+ throw new Error('Tiana login status is missing user_id or tenant_id.');
383
+ }
384
+
385
+ // Explicit management denial ALWAYS rejects fail-closed, even when webApp.owner_id matches.
386
+ if (binding?.canManage === false) {
387
+ throw new Error(msg);
388
+ }
389
+
390
+ const webTenantId = normalizeIdentityValue(webApp?.tenant_id);
391
+ if (webTenantId && webTenantId !== expectedTenantId) {
392
+ throw new Error(msg);
393
+ }
394
+
395
+ const webOwnerId = normalizeIdentityValue(webApp?.owner_id);
396
+ if (webOwnerId) {
397
+ if (webOwnerId !== expectedUserId) {
398
+ throw new Error(msg);
399
+ }
400
+ return { mode: 'owner_id', verified: true };
401
+ }
402
+
403
+ // On Online (tiana CLI v1.0.34), `web list --json` returns `owner_id: ""` with `tenant_id`.
404
+ // Require strict non-empty tenant_id match, space.can_manage (if boolean), and
405
+ // management proof via `web functions get` returning `can_manage: true`.
406
+ if (!webTenantId || webTenantId !== expectedTenantId) {
407
+ throw new Error(msg);
408
+ }
409
+ if (status?.space && typeof status.space.can_manage === 'boolean' && status.space.can_manage !== true) {
410
+ throw new Error(msg);
411
+ }
412
+ if (requireBindingProof) {
413
+ if (binding?.canManage !== true) {
414
+ throw new Error(msg);
415
+ }
416
+ return { mode: 'tenant_can_manage', verified: true };
417
+ }
418
+ return { mode: 'tenant_pending_manage_proof', verified: false };
419
+ }
420
+
421
+ async function revalidateWebAppAuthorization(webId, {
422
+ expectedTenantId = '',
423
+ expectedUserId = '',
424
+ errorMessage,
425
+ cliOpts = {},
426
+ fallbackWebApp = null,
427
+ allowCreatedFallback = false,
428
+ } = {}) {
429
+ const msg = errorMessage || 'Only the verified owner of this DSH Remote Web app can bind a host to it.';
430
+ const latestStatus = await getTianaStatus(cliOpts);
431
+ if (!latestStatus?.user?.user_id || !latestStatus?.user?.tenant_id) {
432
+ throw new Error('Tiana login status is missing user_id or tenant_id.');
433
+ }
434
+ if (expectedTenantId && latestStatus.user.tenant_id !== expectedTenantId) {
435
+ throw new Error(msg);
436
+ }
437
+ if (expectedUserId && latestStatus.user.user_id !== expectedUserId) {
438
+ throw new Error(msg);
439
+ }
440
+
441
+ const latestWebApps = await listTianaWebApps(cliOpts);
442
+ const listedWebApp = latestWebApps.find((item) => item.id === webId);
443
+ if (!listedWebApp) {
444
+ if (!allowCreatedFallback || !fallbackWebApp || latestWebApps.length > 0) {
445
+ throw new Error(`Web app "${webId}" was not found in the current Tiana space.`);
446
+ }
447
+ // Stale owner_id from an earlier `web create` response is NOT current proof when `web list` is empty:
448
+ // require current server-side management proof (`can_manage: true`) from `web functions get` + space check.
449
+ if (latestStatus?.space && typeof latestStatus.space.can_manage === 'boolean' && latestStatus.space.can_manage !== true) {
450
+ throw new Error(msg);
451
+ }
452
+ const latestBinding = await getWebFunctionBinding(webId, cliOpts);
453
+ if (latestBinding?.canManage !== true) {
454
+ throw new Error(msg);
455
+ }
456
+ verifyWebAppOwnership(fallbackWebApp, latestStatus, {
457
+ binding: latestBinding,
458
+ requireBindingProof: true,
459
+ errorMessage: msg,
460
+ });
461
+ if (fallbackWebApp.enabled === false) {
462
+ throw new Error(`Web app "${webId}" is disabled.`);
463
+ }
464
+ if (fallbackWebApp.deletion_pending === true) {
465
+ throw new Error(`Web app "${webId}" is pending deletion.`);
466
+ }
467
+ const latestWebUrl = validateWebEndpoint(fallbackWebApp, webId);
468
+ return {
469
+ status: latestStatus,
470
+ webApp: fallbackWebApp,
471
+ webUrl: latestWebUrl,
472
+ binding: latestBinding,
473
+ requiresManageProof: true,
474
+ };
475
+ }
476
+
477
+ verifyWebAppOwnership(listedWebApp, latestStatus, {
478
+ requireBindingProof: false,
479
+ errorMessage: msg,
480
+ });
481
+ if (listedWebApp.enabled === false) {
482
+ throw new Error(`Web app "${webId}" is disabled.`);
483
+ }
484
+ if (listedWebApp.deletion_pending === true) {
485
+ throw new Error(`Web app "${webId}" is pending deletion.`);
486
+ }
487
+ const latestWebUrl = validateWebEndpoint(listedWebApp, webId);
488
+
489
+ const latestBinding = await getWebFunctionBinding(webId, cliOpts);
490
+ const verified = verifyWebAppOwnership(listedWebApp, latestStatus, {
491
+ binding: latestBinding,
492
+ requireBindingProof: true,
493
+ errorMessage: msg,
494
+ });
495
+ return {
496
+ status: latestStatus,
497
+ webApp: listedWebApp,
498
+ webUrl: latestWebUrl,
499
+ binding: latestBinding,
500
+ requiresManageProof: verified.mode !== 'owner_id',
501
+ };
502
+ }
503
+
504
+ async function ensureWebFunctionBinding(webId, functionId, {
505
+ adoptExisting = false,
506
+ requireManage = false,
507
+ initialBinding = null,
508
+ revalidate = null,
509
+ errorMessage,
510
+ log = console.log,
511
+ ...cliOpts
512
+ } = {}) {
513
+ let current = initialBinding;
514
+ if (!current) {
515
+ if (typeof revalidate === 'function') {
516
+ const fresh = await revalidate();
517
+ current = fresh.binding;
518
+ requireManage = fresh.requiresManageProof;
519
+ } else {
520
+ current = await getWebFunctionBinding(webId, cliOpts);
521
+ }
522
+ }
523
+ if (requireManage && current.canManage !== true) {
524
+ throw new Error(errorMessage || 'Only the verified owner of this DSH Remote Web app can bind a host to it.');
525
+ }
526
+ const bound = current.functionInstanceIds;
527
+ if (bound.length === 1 && bound[0] === functionId) {
528
+ return functionId;
529
+ }
530
+ if (adoptExisting && bound[0]) {
531
+ log(`[dsh-remote] Adopting existing Relay Function ${bound[0]} already bound to Web ${webId}`);
532
+ return bound[0];
533
+ }
534
+ const revision = current.projectRevision;
535
+ if (!revision) {
536
+ throw new Error(`Missing project_revision from web functions get: ${JSON.stringify(current.raw)}`);
537
+ }
538
+ log(`[dsh-remote] Binding Function ${functionId} -> Web ${webId} (rev ${revision})...`);
539
+ try {
540
+ await runTianaJSON([
541
+ 'web', 'functions', 'set',
542
+ '--expected-revision', String(revision),
543
+ '--function-id', functionId,
544
+ '--json',
545
+ webId,
546
+ ], cliOpts);
547
+ return functionId;
548
+ } catch (err) {
549
+ if (adoptExisting) {
550
+ let rechecked;
551
+ let recheckedRequireManage = requireManage;
552
+ if (typeof revalidate === 'function') {
553
+ const fresh = await revalidate();
554
+ rechecked = fresh.binding;
555
+ recheckedRequireManage = fresh.requiresManageProof;
556
+ } else {
557
+ rechecked = await getWebFunctionBinding(webId, cliOpts);
558
+ }
559
+ if (recheckedRequireManage && rechecked.canManage !== true) {
560
+ throw new Error(errorMessage || 'Only the verified owner of this DSH Remote Web app can bind a host to it.');
561
+ }
562
+ if (rechecked.functionInstanceIds[0]) {
563
+ log(`[dsh-remote] Adopting Relay Function ${rechecked.functionInstanceIds[0]} bound concurrently to Web ${webId}`);
564
+ return rechecked.functionInstanceIds[0];
565
+ }
566
+ }
567
+ throw err;
568
+ }
569
+ }
570
+
571
+ function validateWebEndpoint(webApp, webId) {
572
+ const webUrl = new URL(webApp.endpoint || `https://${webId}.tianacloud.site/web/${webId}/`);
573
+ if (webUrl.protocol !== 'https:' || webUrl.username || webUrl.password || webUrl.search ||
574
+ webUrl.hash || webUrl.pathname !== `/web/${webId}/`) {
575
+ throw new Error('Invalid Web app entrypoint');
576
+ }
577
+ return webUrl;
578
+ }
579
+
580
+ export function hasBindingIdentityConflict(existingPolicy, { hostId, registrationKey, hostPublicKey = '' }) {
581
+ if (!existingPolicy || typeof existingPolicy !== 'object') return false;
582
+ if (!existingPolicy.hostId && !existingPolicy.hostDigest && !existingPolicy.hostPublicKey) return false;
583
+
584
+ if (existingPolicy.hostId && existingPolicy.hostId !== hostId) {
585
+ return true;
586
+ }
587
+ const localDigest = registrationKey
588
+ ? createHash('sha256').update(registrationKey).digest('hex')
589
+ : '';
590
+ if (existingPolicy.hostDigest && existingPolicy.hostDigest !== localDigest) {
591
+ return true;
592
+ }
593
+ if (existingPolicy.hostPublicKey && existingPolicy.hostPublicKey !== hostPublicKey) {
594
+ return true;
595
+ }
596
+ return false;
597
+ }
598
+
599
+ /**
600
+ * Zero-recompile binding to an existing Tiana Web app (e.g. installed from Tiana Marketplace).
601
+ * Writes DSH_REMOTE_POLICY via `tiana function parameters set` without rebuilding Go or .tweb.
602
+ *
603
+ * Transactional safety:
604
+ * 1. Validates non-empty user_id/tenant_id and ownership (`webApp.owner_id === status.user.user_id`
605
+ * when non-empty, or non-empty `webApp.tenant_id === status.user.tenant_id` + space/web `can_manage: true`
606
+ * when Online CLI returns `owner_id: ""`).
607
+ * 2. Validates Relay Function is ACTIVE, HTTPS, and passes `/healthz` check.
608
+ * 3. Reads existing function parameters strictly (never swallows errors).
609
+ * 4. Checks rebind conflict across hostId + hostDigest + hostPublicKey.
610
+ * 5. Mints/confirms token and writes local checkpoint BEFORE updating cloud `DSH_REMOTE_POLICY`.
611
+ * 6. Commits final state under `withStateLock` while preserving concurrent local settings edits.
612
+ */
613
+ export async function bindTianaRemoteWeb(options = {}) {
614
+ const log = options.log ?? console.log;
615
+ const webId = String(options.webId || '').trim();
616
+ const statePath = options.statePath;
617
+ const cliOpts = options.tianaBin ? { bin: options.tianaBin } : {};
618
+
619
+ if (!/^[a-z][a-z0-9]{11}$/u.test(webId)) {
620
+ throw new Error(`Invalid Tiana Web app ID: ${webId || '(empty)'}`);
621
+ }
622
+
623
+ let status = await getTianaStatus(cliOpts);
624
+ if (options.spaceId && status.user.tenant_id !== options.spaceId) {
625
+ log(`[dsh-remote] Switching Tiana space to ${options.spaceId}...`);
626
+ await runTianaJSON(['space', 'switch', options.spaceId, '--json'], cliOpts);
627
+ status = await getTianaStatus(cliOpts);
628
+ }
629
+ if (!status?.user?.user_id || !status?.user?.tenant_id) {
630
+ throw new Error('Tiana login status is missing user_id or tenant_id.');
631
+ }
632
+ if (options.spaceId && status.user.tenant_id !== options.spaceId) {
633
+ throw new Error(`Failed to switch Tiana space to "${options.spaceId}".`);
634
+ }
635
+
636
+ const bindOwnerError = 'Only the verified owner of this DSH Remote Web app can bind a host to it.';
637
+ const targetTenantId = options.spaceId || status.user.tenant_id;
638
+ const targetUserId = status.user.user_id;
639
+ const webApps = await listTianaWebApps(cliOpts);
640
+ let webApp = webApps.find((item) => item.id === webId);
641
+ if (!webApp) {
642
+ throw new Error(`Web app "${webId}" was not found in the current Tiana space.`);
643
+ }
644
+ verifyWebAppOwnership(webApp, status, {
645
+ requireBindingProof: false,
646
+ errorMessage: bindOwnerError,
647
+ });
648
+ if (webApp.enabled === false) {
649
+ throw new Error(`Web app "${webId}" is disabled.`);
650
+ }
651
+ if (webApp.deletion_pending === true) {
652
+ throw new Error(`Web app "${webId}" is pending deletion.`);
653
+ }
654
+ let webUrl = validateWebEndpoint(webApp, webId);
655
+
656
+ // Locate bound Relay Function (and verify can_manage proof when owner_id is empty) before any mutation
657
+ const binding = await getWebFunctionBinding(webId, cliOpts);
658
+ verifyWebAppOwnership(webApp, status, {
659
+ binding,
660
+ requireBindingProof: true,
661
+ errorMessage: bindOwnerError,
662
+ });
663
+
664
+ const revalidateBindAuth = () => revalidateWebAppAuthorization(webId, {
665
+ expectedTenantId: targetTenantId,
666
+ expectedUserId: targetUserId,
667
+ errorMessage: bindOwnerError,
668
+ cliOpts,
669
+ });
670
+
671
+ const initialState = await withStateLock(() => {
672
+ const raw = loadRemoteState(statePath);
673
+ return raw ? migrateRemoteState(raw) : {};
674
+ }, statePath);
675
+
676
+ const identity = defaultHostIdentity();
677
+ const initialHostId = options.hostId || initialState.host?.hostId || identity.hostId;
678
+ if (!/^[a-z0-9_-]{1,48}$/u.test(initialHostId)) throw new Error('Invalid host ID');
679
+
680
+ let fnId = binding.functionInstanceIds[0] || '';
681
+ let fnShown = null;
682
+ if (fnId) {
683
+ fnShown = await runTianaJSON(['function', 'show', fnId, '--json'], cliOpts);
684
+ } else {
685
+ log(`[dsh-remote] Web app ${webId} has no bound Relay Function; provisioning generic relay-go...`);
686
+ const created = await ensureRelayFunction({
687
+ functionName: options.functionName || DEFAULT_FUNCTION_NAME,
688
+ log,
689
+ ...cliOpts,
690
+ });
691
+ fnId = created.instance.id;
692
+ fnShown = await syncAndPublishRelayFunction(fnId, webId, { log, ...cliOpts });
693
+ const boundFnId = await ensureWebFunctionBinding(webId, fnId, {
694
+ adoptExisting: true,
695
+ revalidate: revalidateBindAuth,
696
+ errorMessage: bindOwnerError,
697
+ log,
698
+ ...cliOpts,
699
+ });
700
+ if (boundFnId !== fnId) {
701
+ fnId = boundFnId;
702
+ fnShown = await runTianaJSON(['function', 'show', fnId, '--json'], cliOpts);
703
+ }
704
+ }
705
+
706
+ let fnUrl = validateRelayFunctionShown(fnShown);
707
+
708
+ const initialPendingBind = initialState.pendingBind?.functionId === fnId && initialState.pendingBind?.webId === webId
709
+ ? initialState.pendingBind
710
+ : null;
711
+ let preLockToken = initialState.function?.id === fnId ? initialState.function : null;
712
+ const tokenSeedState = (initialState.function?.id === fnId && initialState.function?.token &&
713
+ (!initialPendingBind?.tokenInfo?.token || Number(initialState.function.expiresAt) >= Number(initialPendingBind.tokenInfo.expiresAt)))
714
+ ? initialState
715
+ : (initialPendingBind?.tokenInfo ? { function: initialPendingBind.tokenInfo } : initialState);
716
+ const seedToken = tokenSeedState?.function?.id === fnId ? tokenSeedState.function : null;
717
+
718
+ // Step A: Mint or confirm Function Instance Token BEFORE mutating cloud policy
719
+ let tokenInfo = await ensureHostToken(
720
+ tokenSeedState,
721
+ fnId,
722
+ { rotateToken: Boolean(options.rotateToken), log, ...cliOpts },
723
+ );
724
+ let mintedNewToken = tokenInfo.token !== seedToken?.token;
725
+
726
+ // Step B: Verify target Function /healthz confirms a valid DSH Remote Relay
727
+ await verifyRelayHealth(fnUrl, tokenInfo.token, options);
728
+
729
+ // Serialize the cloud-read + conflict-check + pendingBind checkpoint + policy write + state commit
730
+ // across local processes so concurrent binds can never produce a local/cloud hostDigest mismatch.
731
+ const bindLockPath = `${resolveStatePath(statePath)}.bind`;
732
+ return await withStateLock(async () => {
733
+ const prevState = await withStateLock(() => {
734
+ const raw = loadRemoteState(statePath);
735
+ return raw ? migrateRemoteState(raw) : {};
736
+ }, statePath);
737
+
738
+ // Re-verify fresh status, Web app ownership metadata, and active Relay Function binding under lock
739
+ const freshAuth = await revalidateBindAuth();
740
+ status = freshAuth.status;
741
+ webApp = freshAuth.webApp;
742
+ webUrl = freshAuth.webUrl;
743
+ const activeBinding = freshAuth.binding;
744
+ let activeFnId = activeBinding.functionInstanceIds[0] || '';
745
+ if (!activeFnId) {
746
+ activeFnId = await ensureWebFunctionBinding(webId, fnId, {
747
+ adoptExisting: true,
748
+ initialBinding: activeBinding,
749
+ requireManage: freshAuth.requiresManageProof,
750
+ revalidate: revalidateBindAuth,
751
+ errorMessage: bindOwnerError,
752
+ log,
753
+ ...cliOpts,
754
+ });
755
+ }
756
+ if (activeFnId && activeFnId !== fnId) {
757
+ fnId = activeFnId;
758
+ fnShown = await runTianaJSON(['function', 'show', fnId, '--json'], cliOpts);
759
+ fnUrl = validateRelayFunctionShown(fnShown);
760
+ preLockToken = prevState.function?.id === fnId ? prevState.function : null;
761
+ tokenInfo = await ensureHostToken(prevState, fnId, {
762
+ rotateToken: Boolean(options.rotateToken),
763
+ log,
764
+ ...cliOpts,
765
+ });
766
+ mintedNewToken = tokenInfo.token !== preLockToken?.token;
767
+ await verifyRelayHealth(fnUrl, tokenInfo.token, options);
768
+ }
769
+
770
+ const hostId = options.hostId || prevState.host?.hostId || identity.hostId;
771
+ const hostName = options.hostName || prevState.host?.hostName || identity.hostName;
772
+ if (!/^[a-z0-9_-]{1,48}$/u.test(hostId)) throw new Error('Invalid host ID');
773
+
774
+ // Strictly read fresh existing function parameters (NEVER swallow failure!)
775
+ const existingParams = await getFunctionParameters(fnId, cliOpts);
776
+ const existingPolicy = parsePolicyFromParameters(existingParams);
777
+
778
+ const pendingBind = prevState.pendingBind?.functionId === fnId && prevState.pendingBind?.webId === webId
779
+ ? prevState.pendingBind
780
+ : null;
781
+
782
+ const localPubKey = prevState.host?.publicKey || prevState.hostSigningKeyPair?.publicKey || '';
783
+ const matchesPrevHost = !hasBindingIdentityConflict(existingPolicy, {
784
+ hostId,
785
+ registrationKey: prevState.host?.registrationKey || '',
786
+ hostPublicKey: localPubKey,
787
+ });
788
+ const matchesPendingBind = Boolean(pendingBind) && !hasBindingIdentityConflict(existingPolicy, {
789
+ hostId: pendingBind.hostId || hostId,
790
+ registrationKey: pendingBind.registrationKey || '',
791
+ hostPublicKey: localPubKey,
792
+ });
793
+ const conflict = !matchesPrevHost && !matchesPendingBind;
794
+
795
+ let rotatedRegistration = false;
796
+ if (conflict) {
797
+ if (!options.rebind) {
798
+ if (typeof options.confirmRebind === 'function') {
799
+ const ok = await options.confirmRebind(existingPolicy, { hostId, hostName });
800
+ if (!ok) throw new Error('Rebind cancelled by user.');
801
+ } else {
802
+ throw new Error(
803
+ `Web app ${webId} is already bound to "${existingPolicy.hostName || existingPolicy.hostId}" (${existingPolicy.hostId}). Pass --rebind to switch to this host.`,
804
+ );
805
+ }
806
+ }
807
+ rotatedRegistration = true;
808
+ }
809
+
810
+ const reusePending = Boolean(pendingBind) && (matchesPendingBind || !prevState.host?.registrationKey);
811
+ const registrationKey = rotatedRegistration
812
+ ? generateE2eeSecret()
813
+ : ((reusePending ? pendingBind?.registrationKey : prevState.host?.registrationKey) ||
814
+ pendingBind?.registrationKey ||
815
+ prevState.host?.registrationKey ||
816
+ generateE2eeSecret());
817
+ const baseE2eeSource = prevState.e2ee?.secret
818
+ ? prevState
819
+ : (pendingBind?.e2ee?.secret ? { e2ee: pendingBind.e2ee } : prevState);
820
+ const { e2ee } = ensureE2eeConfig(baseE2eeSource, { rotate: Boolean(options.rotateE2eeKey) });
821
+
822
+ const bindStartToken = prevState.function?.id === fnId ? prevState.function : null;
823
+ let activeTokenInfo = tokenInfo;
824
+ if (!options.rotateToken &&
825
+ prevState.function?.id === fnId &&
826
+ prevState.function?.token &&
827
+ (Number(prevState.function.expiresAt) > Number(tokenInfo.expiresAt) ||
828
+ (Number(prevState.function.expiresAt) === Number(tokenInfo.expiresAt) &&
829
+ (!mintedNewToken || prevState.function.token !== preLockToken?.token)))) {
830
+ activeTokenInfo = {
831
+ token: prevState.function.token,
832
+ tokenId: prevState.function.tokenId,
833
+ expiresAt: prevState.function.expiresAt,
834
+ };
835
+ } else if (!options.rotateToken &&
836
+ pendingBind?.tokenInfo?.token &&
837
+ Number(pendingBind.tokenInfo.expiresAt) > Number(tokenInfo.expiresAt)) {
838
+ activeTokenInfo = {
839
+ token: pendingBind.tokenInfo.token,
840
+ tokenId: pendingBind.tokenInfo.tokenId,
841
+ expiresAt: pendingBind.tokenInfo.expiresAt,
842
+ };
843
+ }
844
+
845
+ // Step C: Save local recovery checkpoint under lock BEFORE mutating cloud DSH_REMOTE_POLICY
846
+ await withStateLock(() => {
847
+ const raw = loadRemoteState(statePath) || {};
848
+ saveRemoteState({
849
+ ...raw,
850
+ pendingBind: {
851
+ webId,
852
+ functionId: fnId,
853
+ hostId,
854
+ hostName,
855
+ registrationKey,
856
+ e2ee,
857
+ tokenInfo: { ...activeTokenInfo, id: fnId },
858
+ createdAt: new Date().toISOString(),
859
+ },
860
+ }, statePath);
861
+ }, statePath);
862
+
863
+ // Step D: Write DSH_REMOTE_POLICY using verified existingParams (preserving unrelated params)
864
+ const policy = buildRemotePolicy({
865
+ hostId,
866
+ hostName,
867
+ registrationKey,
868
+ ownerUserId: status.user.user_id,
869
+ ownerTenantId: status.user.tenant_id,
870
+ webId,
871
+ origin: webUrl.origin,
872
+ });
873
+ await updateRemotePolicy(fnId, policy, { existingParams, log, ...cliOpts });
874
+
875
+ // Step E: Atomically commit final state under lock, merging concurrent settings, key rotation, and token renewals
876
+ const committedState = await withStateLock(() => {
877
+ const latestRaw = loadRemoteState(statePath);
878
+ const latest = latestRaw ? migrateRemoteState(latestRaw) : prevState;
879
+ const committedE2ee = (!options.rotateE2eeKey && latest.e2ee?.secret && latest.e2ee.secret !== prevState.e2ee?.secret)
880
+ ? latest.e2ee
881
+ : e2ee;
882
+ const keepLatestToken = !options.rotateToken &&
883
+ latest.function?.id === fnId &&
884
+ latest.function?.token &&
885
+ (Number(latest.function.expiresAt) > Number(activeTokenInfo.expiresAt) ||
886
+ (Number(latest.function.expiresAt) === Number(activeTokenInfo.expiresAt) &&
887
+ (latest.function.token !== bindStartToken?.token ||
888
+ (!mintedNewToken && latest.function.token !== activeTokenInfo.token))));
889
+ const committedToken = keepLatestToken
890
+ ? { token: latest.function.token, tokenId: latest.function.tokenId, expiresAt: latest.function.expiresAt }
891
+ : activeTokenInfo;
892
+ const nextState = {
893
+ version: 2,
894
+ configVersion: 2,
895
+ enabled: latest.enabled !== undefined ? latest.enabled : true,
896
+ updatedAt: new Date().toISOString(),
897
+ owner: {
898
+ userId: status.user.user_id,
899
+ tenantId: status.user.tenant_id,
900
+ email: status.user.email,
901
+ displayName: status.user.display_name,
902
+ spaceName: status.space?.display_name || '',
903
+ },
904
+ host: {
905
+ hostId,
906
+ hostName,
907
+ registrationKey,
908
+ },
909
+ e2ee: committedE2ee,
910
+ function: {
911
+ id: fnId,
912
+ name: fnShown?.instance?.display_name || fnShown?.instance?.name || DEFAULT_FUNCTION_NAME,
913
+ url: fnUrl,
914
+ token: committedToken.token,
915
+ tokenId: committedToken.tokenId,
916
+ expiresAt: committedToken.expiresAt,
917
+ },
918
+ web: {
919
+ id: webId,
920
+ name: webApp.name || DEFAULT_WEB_NAME,
921
+ endpoint: webUrl.href,
922
+ },
923
+ network: latest.network || {
924
+ p2pEnabled: true,
925
+ stunUrls: [...DEFAULT_STUN_URLS],
926
+ },
927
+ security: latest.security || {
928
+ allowedWebPlugins: [],
929
+ },
930
+ allowedWebPlugins: latest.security?.allowedWebPlugins || latest.allowedWebPlugins || [],
931
+ };
932
+ saveRemoteState(nextState, statePath);
933
+ return nextState;
934
+ }, statePath);
935
+
936
+ return committedState;
937
+ }, bindLockPath, { timeoutMs: options.bindLockTimeoutMs ?? 30_000 });
938
+ }
939
+
940
+ /**
941
+ * Provision or reuse the Tiana Function Relay + Token + .tweb App in the logged-in user's space.
942
+ * Uploads generic relay-go once and writes DSH_REMOTE_POLICY via function parameters (zero recompile on updates).
943
+ */
944
+ export async function provisionTianaRemote(options = {}) {
945
+ const log = options.log ?? console.log;
946
+ const functionName = options.functionName || DEFAULT_FUNCTION_NAME;
947
+ const webName = options.webName || DEFAULT_WEB_NAME;
948
+ const statePath = options.statePath;
949
+ const cliOpts = options.tianaBin ? { bin: options.tianaBin } : {};
950
+
951
+ let status = await getTianaStatus(cliOpts);
952
+ const resolvedStatePath = resolveStatePath(statePath);
953
+ const bindLockPath = `${resolvedStatePath}.bind`;
954
+ const canonicalJson = (value) => {
955
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
956
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
957
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
958
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
959
+ };
960
+ const hasIndependentState = (obj) => {
961
+ if (!obj || typeof obj !== 'object') return false;
962
+ for (const [key, val] of Object.entries(obj)) {
963
+ if (val === undefined) continue;
964
+ if (key === 'pendingSetup') {
965
+ if (val && typeof val === 'object' && Object.keys(val).length > 0) return true;
966
+ continue;
967
+ }
968
+ return true;
969
+ }
970
+ return false;
971
+ };
972
+ return await withStateLock(async () => {
973
+ const { prevState, hadInitialFile, initialSnapshot, initialRawBytes, initialPendingSetup } = await withStateLock(() => {
974
+ const snap = loadRemoteStateSnapshot(resolvedStatePath);
975
+ return {
976
+ prevState: snap?.state ? structuredClone(snap.state) : {},
977
+ hadInitialFile: snap !== null,
978
+ initialSnapshot: snap?.state ? structuredClone(snap.state) : null,
979
+ initialRawBytes: snap?.rawBytes ?? null,
980
+ initialPendingSetup: snap?.state?.pendingSetup !== undefined
981
+ ? structuredClone(snap.state.pendingSetup)
982
+ : undefined,
983
+ };
984
+ }, statePath);
985
+ let lastWrittenPendingSetup = null;
986
+ const restoreInitialState = async () => {
987
+ if (lastWrittenPendingSetup === null) return;
988
+ await withStateLock(() => {
989
+ const current = loadRemoteState(resolvedStatePath);
990
+ if (!current) return;
991
+ if (canonicalJson(current.pendingSetup) === canonicalJson(lastWrittenPendingSetup)) {
992
+ if (initialPendingSetup !== undefined) {
993
+ current.pendingSetup = structuredClone(initialPendingSetup);
994
+ } else {
995
+ delete current.pendingSetup;
996
+ }
997
+ }
998
+ if (!hadInitialFile) {
999
+ if (!hasIndependentState(current)) {
1000
+ removeRemoteState(resolvedStatePath);
1001
+ } else {
1002
+ saveRemoteState(current, resolvedStatePath);
1003
+ }
1004
+ return;
1005
+ }
1006
+ if (canonicalJson(current) === canonicalJson(initialSnapshot)) {
1007
+ saveRemoteState(initialSnapshot, resolvedStatePath, {
1008
+ rawBytes: initialRawBytes,
1009
+ preserveUpdatedAt: true,
1010
+ });
1011
+ } else {
1012
+ saveRemoteState(current, resolvedStatePath);
1013
+ }
1014
+ }, statePath);
1015
+ };
1016
+
1017
+ const pending = { ...(prevState.pendingSetup || {}) };
1018
+ const identity = defaultHostIdentity();
1019
+ const hostId = options.hostId || prevState.host?.hostId || pending.hostId || identity.hostId;
1020
+ const hostName = options.hostName || prevState.host?.hostName || identity.hostName;
1021
+
1022
+ if (!/^[a-z0-9_-]{1,48}$/u.test(hostId)) throw new Error('Invalid host ID');
1023
+ const previousOwner = prevState.owner || pending.owner;
1024
+ if ((previousOwner?.userId && previousOwner.userId !== status.user.user_id) ||
1025
+ (previousOwner?.tenantId && previousOwner.tenantId !== status.user.tenant_id)) {
1026
+ throw new Error('Use the Tiana account and space that originally configured this DSH host');
1027
+ }
1028
+ if ((prevState.host?.hostId || pending.hostId || hostId) !== hostId) {
1029
+ throw new Error('This installation is already bound to a different host ID');
1030
+ }
1031
+ const baseE2eeSource = prevState.e2ee?.secret
1032
+ ? prevState
1033
+ : (pending.e2ee ? { e2ee: pending.e2ee } : prevState);
1034
+ const { e2ee } = ensureE2eeConfig(baseE2eeSource, {
1035
+ rotate: (!pending.e2ee && prevState.version !== 2) || Boolean(options.rotateE2eeKey),
1036
+ });
1037
+ const registrationKey = prevState.host?.registrationKey || pending.registrationKey || generateE2eeSecret();
1038
+ const owner = { userId: status.user.user_id, tenantId: status.user.tenant_id };
1039
+ const checkpoint = async (fields) => {
1040
+ Object.assign(pending, fields);
1041
+ const snapshotPending = structuredClone(pending);
1042
+ await withStateLock(() => {
1043
+ const current = loadRemoteState(resolvedStatePath) || {};
1044
+ saveRemoteState({ ...current, pendingSetup: snapshotPending }, resolvedStatePath);
1045
+ }, statePath);
1046
+ lastWrittenPendingSetup = snapshotPending;
1047
+ };
1048
+
1049
+ const setupOwnerError = 'The configured Web app does not belong to the DSH owner and space';
1050
+ const configuredWebId = prevState.web?.id || pending.webId;
1051
+ const hadExistingWebId = Boolean(configuredWebId);
1052
+ let webApp = await ensureWebApp({ webName, webId: configuredWebId, log, ...cliOpts });
1053
+ const webId = webApp?.id;
1054
+ if (!/^[a-z][a-z0-9]{11}$/u.test(webId || '')) throw new Error('Invalid Web app ID');
1055
+ const ownershipCheck = verifyWebAppOwnership(webApp, status, {
1056
+ requireBindingProof: false,
1057
+ errorMessage: setupOwnerError,
1058
+ });
1059
+ let requiresManageProof = ownershipCheck.mode !== 'owner_id';
1060
+ if (webApp.enabled === false) {
1061
+ throw new Error(`Web app "${webId}" is disabled.`);
1062
+ }
1063
+ if (webApp.deletion_pending === true) {
1064
+ throw new Error(`Web app "${webId}" is pending deletion.`);
1065
+ }
1066
+ let webUrl = validateWebEndpoint(webApp, webId);
1067
+ let webEndpoint = webUrl.href;
1068
+ // Always query web functions binding during preflight (even when owner_id matches)
1069
+ // so an explicit can_manage: false rejects before creating/publishing a Relay Function or minting a token.
1070
+ const initialBinding = await getWebFunctionBinding(webId, cliOpts);
1071
+ verifyWebAppOwnership(webApp, status, {
1072
+ binding: initialBinding,
1073
+ requireBindingProof: true,
1074
+ errorMessage: setupOwnerError,
1075
+ });
1076
+ await checkpoint({ webId, owner, hostId, registrationKey, e2ee });
1077
+
1078
+ const { instance: fnInstance } = await ensureRelayFunction({
1079
+ functionName, functionId: prevState.function?.id || pending.functionId, log, ...cliOpts,
1080
+ });
1081
+ if (!fnInstance?.id) throw new Error('Missing configured Function ID');
1082
+ await checkpoint({ functionId: fnInstance.id });
1083
+
1084
+ // Build and validate the browser package in an isolated temporary directory (never pollutes repo!)
1085
+ const distTemp = mkdtempSync(join(tmpdir(), 'dsh-remote-web-dist-'));
1086
+ try {
1087
+ const built = buildWebDist({
1088
+ outDir: distTemp,
1089
+ config: {
1090
+ functionId: fnInstance.id,
1091
+ webId,
1092
+ defaultHostId: hostId,
1093
+ appTitle: `${webName} · ${hostName}`,
1094
+ },
1095
+ });
1096
+ log(`[dsh-remote] Built .tweb bundle (${built.fileCount} files, ${(built.totalBytes / 1024).toFixed(1)} KiB). Publishing to ${webId}...`);
1097
+
1098
+ // Refresh Web authorization after local build work and BEFORE remote Relay upload/publish or token minting.
1099
+ let preRelayAuth;
1100
+ try {
1101
+ preRelayAuth = await revalidateWebAppAuthorization(webId, {
1102
+ expectedTenantId: owner.tenantId,
1103
+ expectedUserId: owner.userId,
1104
+ errorMessage: setupOwnerError,
1105
+ cliOpts,
1106
+ fallbackWebApp: hadExistingWebId ? null : webApp,
1107
+ allowCreatedFallback: !hadExistingWebId,
1108
+ });
1109
+ } catch (err) {
1110
+ await restoreInitialState();
1111
+ throw err;
1112
+ }
1113
+ status = preRelayAuth.status;
1114
+ webApp = preRelayAuth.webApp;
1115
+ webUrl = preRelayAuth.webUrl;
1116
+ webEndpoint = webUrl.href;
1117
+ requiresManageProof = preRelayAuth.requiresManageProof;
1118
+
1119
+ const fnShown = await syncAndPublishRelayFunction(fnInstance.id, webId, {
1120
+ forcePublish: Boolean(options.forcePublish), log, ...cliOpts,
1121
+ });
1122
+ const fnUrl = fnShown?.instance?.connection?.url || fnShown?.instance?.url || fnInstance.connection?.url || fnInstance.url;
1123
+ if (!fnUrl || new URL(fnUrl).protocol !== 'https:') throw new Error('Function requires an HTTPS endpoint');
1124
+
1125
+ // Mint token and checkpoint BEFORE mutating cloud policy
1126
+ const tokenSeedState = (prevState.function?.id === fnInstance.id && prevState.function?.token &&
1127
+ (!pending.tokenInfo?.token || Number(prevState.function.expiresAt) >= Number(pending.tokenInfo.expiresAt)))
1128
+ ? prevState
1129
+ : (pending.tokenInfo ? { function: pending.tokenInfo } : prevState);
1130
+ const tokenInfo = await ensureHostToken(tokenSeedState, fnInstance.id, {
1131
+ rotateToken: Boolean(options.rotateToken), log, ...cliOpts,
1132
+ });
1133
+ await checkpoint({ tokenInfo: { ...tokenInfo, id: fnInstance.id } });
1134
+
1135
+ // Revalidate fresh status, Web app ownership metadata, and management proof BEFORE writing
1136
+ // DSH_REMOTE_POLICY, binding the Function, publishing the Web app, or committing local state.
1137
+ let freshAuth;
1138
+ try {
1139
+ freshAuth = await revalidateWebAppAuthorization(webId, {
1140
+ expectedTenantId: owner.tenantId,
1141
+ expectedUserId: owner.userId,
1142
+ errorMessage: setupOwnerError,
1143
+ cliOpts,
1144
+ fallbackWebApp: hadExistingWebId ? null : webApp,
1145
+ allowCreatedFallback: !hadExistingWebId,
1146
+ });
1147
+ } catch (err) {
1148
+ await restoreInitialState();
1149
+ throw err;
1150
+ }
1151
+ status = freshAuth.status;
1152
+ webApp = freshAuth.webApp;
1153
+ webUrl = freshAuth.webUrl;
1154
+ webEndpoint = webUrl.href;
1155
+ requiresManageProof = freshAuth.requiresManageProof;
1156
+
1157
+ const policy = buildRemotePolicy({
1158
+ hostId,
1159
+ hostName,
1160
+ registrationKey,
1161
+ ownerUserId: status.user.user_id,
1162
+ ownerTenantId: status.user.tenant_id,
1163
+ webId,
1164
+ origin: webUrl.origin,
1165
+ });
1166
+
1167
+ await updateRemotePolicy(fnInstance.id, policy, { log, ...cliOpts });
1168
+ await ensureWebFunctionBinding(webId, fnInstance.id, {
1169
+ initialBinding: freshAuth.binding,
1170
+ requireManage: requiresManageProof,
1171
+ errorMessage: setupOwnerError,
1172
+ log,
1173
+ ...cliOpts,
1174
+ });
1175
+
1176
+ const publishResult = await runTianaJSON([
1177
+ 'web', 'publish',
1178
+ '--dir', distTemp,
1179
+ '--json',
1180
+ webId,
1181
+ ], { ...cliOpts, timeoutMs: 240_000 });
1182
+
1183
+ const nextState = await withStateLock(() => {
1184
+ const latestRaw = loadRemoteState(statePath) || prevState;
1185
+ const migrated = migrateRemoteState(latestRaw) || {};
1186
+ const committedE2ee = (!options.rotateE2eeKey && migrated.e2ee?.secret && migrated.e2ee.secret !== prevState.e2ee?.secret)
1187
+ ? migrated.e2ee
1188
+ : e2ee;
1189
+ const keepLatestToken = !options.rotateToken &&
1190
+ migrated.function?.id === fnInstance.id &&
1191
+ migrated.function?.token &&
1192
+ (Number(migrated.function.expiresAt) > Number(tokenInfo.expiresAt) ||
1193
+ (Number(migrated.function.expiresAt) === Number(tokenInfo.expiresAt) &&
1194
+ migrated.function.token !== prevState.function?.token));
1195
+ const committedToken = keepLatestToken
1196
+ ? { token: migrated.function.token, tokenId: migrated.function.tokenId, expiresAt: migrated.function.expiresAt }
1197
+ : tokenInfo;
1198
+ const finalState = {
1199
+ version: 2,
1200
+ configVersion: 2,
1201
+ enabled: migrated.enabled !== undefined ? migrated.enabled : true,
1202
+ updatedAt: new Date().toISOString(),
1203
+ owner: {
1204
+ userId: status.user.user_id,
1205
+ tenantId: status.user.tenant_id,
1206
+ email: status.user.email,
1207
+ displayName: status.user.display_name,
1208
+ spaceName: status.space?.display_name || '',
1209
+ },
1210
+ host: {
1211
+ hostId,
1212
+ hostName,
1213
+ registrationKey,
1214
+ },
1215
+ e2ee: committedE2ee,
1216
+ function: {
1217
+ id: fnInstance.id,
1218
+ name: fnInstance.display_name || fnInstance.name || functionName,
1219
+ url: fnUrl,
1220
+ token: committedToken.token,
1221
+ tokenId: committedToken.tokenId,
1222
+ expiresAt: committedToken.expiresAt,
1223
+ },
1224
+ web: {
1225
+ id: webId,
1226
+ name: webApp.name || webName,
1227
+ endpoint: webEndpoint,
1228
+ lastPublish: publishResult,
1229
+ },
1230
+ network: migrated.network || {
1231
+ p2pEnabled: true,
1232
+ stunUrls: [...DEFAULT_STUN_URLS],
1233
+ },
1234
+ security: migrated.security || {
1235
+ allowedWebPlugins: [],
1236
+ },
1237
+ allowedWebPlugins: migrated.security?.allowedWebPlugins || [],
1238
+ };
1239
+ saveRemoteState(finalState, statePath);
1240
+ return finalState;
1241
+ }, statePath);
1242
+
1243
+ return nextState;
1244
+ } finally {
1245
+ rmSync(distTemp, { recursive: true, force: true });
1246
+ }
1247
+ }, bindLockPath, { timeoutMs: options.bindLockTimeoutMs ?? 300_000 });
1248
+ }
1249
+
1250
+ export async function republishWebShell(state, { log = console.log, ...cliOpts } = {}) {
1251
+ if (!state?.web?.id || !state?.function?.id) {
1252
+ throw new Error('Remote web app is not configured.');
1253
+ }
1254
+ const webId = state.web.id;
1255
+ const distTemp = mkdtempSync(join(tmpdir(), 'dsh-remote-web-republish-'));
1256
+ try {
1257
+ const built = buildWebDist({
1258
+ outDir: distTemp,
1259
+ config: {
1260
+ functionId: state.function.id,
1261
+ webId,
1262
+ defaultHostId: state.host?.hostId || '',
1263
+ appTitle: `${state.web.name || DEFAULT_WEB_NAME} · ${state.host?.hostName || state.host?.hostId || 'DSH'}`,
1264
+ },
1265
+ });
1266
+ log(`[dsh-remote] Rebuilt .tweb bundle (${built.fileCount} files, ${(built.totalBytes / 1024).toFixed(1)} KiB). Publishing...`);
1267
+ return await runTianaJSON(['web', 'publish', '--dir', distTemp, '--json', webId], { ...cliOpts, timeoutMs: 240_000 });
1268
+ } finally {
1269
+ rmSync(distTemp, { recursive: true, force: true });
1270
+ }
1271
+ }