@tianacloud/dsh-remote 0.2.1 → 0.2.3

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/cli.js CHANGED
@@ -44,9 +44,9 @@ function printHelp() {
44
44
  console.log(`dsh-remote — Expose DeepSeek Harness via Tiana (zero platform changes, E2EE)
45
45
 
46
46
  Usage:
47
- dsh-remote connect --app <appIdOrUrl> [options]
47
+ dsh-remote connect --web <webIdOrUrl> [options]
48
48
  Bind this machine to an installed Tiana DSH Remote app (zero recompile)
49
- --app <appIdOrUrl> Tiana Web App ID or URL (alias: --web)
49
+ --web <webIdOrUrl> Tiana Web App ID or URL (alias: --app)
50
50
  --space <tenantId> Target Tiana space ID
51
51
  --profile <name> DSH profile name (default: web)
52
52
  --port <port> Local DSH port (default: 3080)
package/host-main.js CHANGED
@@ -223,7 +223,7 @@ export function createHostController(options = {}) {
223
223
  if (!Array.isArray(graph?.entries)) return [];
224
224
  return graph.entries
225
225
  .map((e) => e.id)
226
- .filter((id) => typeof id === 'string' && !id.startsWith('@deepseek-ai/dsh-client-') && id !== '@tianacloud/dsh-remote');
226
+ .filter((id) => typeof id === 'string' && !id.startsWith('@deepseek-ai/dsh-') && id !== '@tianacloud/dsh-remote');
227
227
  } catch {
228
228
  return [];
229
229
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tianacloud/dsh-remote",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "description": "使用 Tiana 能力为 DeepSeek Harness 提供零公网 IP 远程访问、侧栏管理面板、无密钥流式子资源桥接与云端一键引导插件。",
6
6
  "license": "Apache-2.0",
package/src/connect.js CHANGED
@@ -394,6 +394,10 @@ export async function isLocalDshResponsive(origin, { fetchFn = fetch, timeoutMs
394
394
  }
395
395
  }
396
396
 
397
+ export function buildDshStartArgs({ profile = 'web', port = 3080 } = {}) {
398
+ return ['--profile', String(profile || 'web'), '--port', String(port), '--no-open'];
399
+ }
400
+
397
401
  export async function waitForLocalDshReady(port, timeoutMs = 15_000, { childState = null, fetchFn = fetch } = {}) {
398
402
  const deadline = Date.now() + timeoutMs;
399
403
  const origin = `http://127.0.0.1:${port}`;
@@ -425,9 +429,9 @@ export async function runConnect(options = {}, deps = {}) {
425
429
  throw err;
426
430
  }
427
431
 
428
- const webId = parseAppArg(options.app || options.web);
432
+ const webId = parseAppArg(options.web || options.app);
429
433
  if (!webId) {
430
- throw new Error('Provide --app <appIdOrUrl> (or --web <webId>) for the Tiana DSH Remote app.');
434
+ throw new Error('Provide --web <webIdOrUrl> (or --app <appIdOrUrl>) for the Tiana DSH Remote app.');
431
435
  }
432
436
 
433
437
  const profile = options.profile || 'web';
@@ -508,9 +512,11 @@ export async function runConnect(options = {}, deps = {}) {
508
512
  if (deps.startDsh) {
509
513
  dshStarted = await deps.startDsh(dshInfo.bin, { profile, port });
510
514
  } else {
511
- log(`[dsh-remote] Starting local DSH (${dshInfo.bin} web --port ${port} --no-open)...`);
515
+ const spawnFn = deps.spawnFn ?? spawn;
516
+ const startArgs = buildDshStartArgs({ profile, port });
517
+ log(`[dsh-remote] Starting local DSH (${dshInfo.bin} ${startArgs.join(' ')})...`);
512
518
  const childState = { error: null, exited: false, exitCode: null };
513
- const child = spawn(dshInfo.bin, ['web', '--profile', profile, '--port', String(port), '--no-open'], {
519
+ const child = spawnFn(dshInfo.bin, startArgs, {
514
520
  stdio: 'ignore',
515
521
  detached: true,
516
522
  windowsHide: true,
@@ -137,14 +137,14 @@ function cleanBundle(file) {
137
137
  return Buffer.from(readFile(file).toString('utf8').replace(/\r?\n\/\/# source(?:Mapping)?URL=[^\r\n]*/gu, ''));
138
138
  }
139
139
 
140
- const BUILTIN_CLIENT_PREFIX = '@deepseek-ai/dsh-client-';
140
+ const BUILTIN_CLIENT_PREFIX = '@deepseek-ai/dsh-';
141
141
  const SELF_CLIENT_MODULE = '@tianacloud/dsh-remote';
142
142
 
143
143
  /**
144
144
  * Select which active DSH client modules are exposed over the remote tunnel.
145
145
  * - `allowlist: ['*']` (or `'*'`): allow all active modules.
146
146
  * - `allowlist: []` (default) or omitted: allow ONLY builtin DSH core modules
147
- * (`@deepseek-ai/dsh-client-*`) plus `@tianacloud/dsh-remote` itself; third-party plugins are blocked.
147
+ * (`@deepseek-ai/dsh-*`) plus `@tianacloud/dsh-remote` itself; third-party plugins are blocked.
148
148
  * - Explicit IDs: allow builtin core + `@tianacloud/dsh-remote` + exact allowlisted active plugins.
149
149
  */
150
150
  export function selectAllowedWebPlugins(modules, allowlist) {
package/src/state.js CHANGED
@@ -45,7 +45,7 @@ function verifyPrivate(stat, type) {
45
45
  }
46
46
  }
47
47
 
48
- export function loadRemoteState(filePath = defaultStatePath()) {
48
+ export function loadRemoteStateSnapshot(filePath = defaultStatePath()) {
49
49
  let fd;
50
50
  try {
51
51
  verifyPrivate(lstatSync(dirname(filePath)), 'directory');
@@ -58,27 +58,38 @@ export function loadRemoteState(filePath = defaultStatePath()) {
58
58
  const info = fstatSync(fd);
59
59
  verifyPrivate(info, 'file');
60
60
  if (info.size > 256 * 1024) throw new Error('DSH remote state file is too large');
61
+ const rawBytes = readFileSync(fd);
61
62
  let parsed;
62
- try { parsed = JSON.parse(readFileSync(fd, 'utf8')); }
63
+ try { parsed = JSON.parse(rawBytes.toString('utf8')); }
63
64
  catch { throw new Error('Invalid DSH remote state file'); }
64
65
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
65
66
  throw new Error('Invalid DSH remote state file');
66
67
  }
67
- return parsed;
68
+ return { state: parsed, rawBytes };
68
69
  } finally {
69
70
  closeSync(fd);
70
71
  }
71
72
  }
72
73
 
73
- export function saveRemoteState(state, filePath = defaultStatePath()) {
74
+ export function loadRemoteState(filePath = defaultStatePath()) {
75
+ return loadRemoteStateSnapshot(filePath)?.state ?? null;
76
+ }
77
+
78
+ export function saveRemoteState(state, filePath = defaultStatePath(), options = {}) {
74
79
  const dir = dirname(filePath);
75
80
  mkdirSync(dir, { recursive: true, mode: 0o700 });
76
81
  verifyPrivate(lstatSync(dir), 'directory');
82
+ const next = options?.preserveUpdatedAt === true && typeof state?.updatedAt === 'string' && state.updatedAt
83
+ ? { ...state, updatedAt: state.updatedAt }
84
+ : state;
85
+ const payload = options?.rawBytes !== undefined
86
+ ? options.rawBytes
87
+ : `${JSON.stringify(next, null, 2)}\n`;
77
88
  const tmp = `${filePath}.tmp.${randomBytes(16).toString('hex')}`;
78
89
  const fd = openSync(tmp, 'wx', 0o600);
79
90
  try {
80
91
  try {
81
- writeFileSync(fd, `${JSON.stringify(state, null, 2)}\n`);
92
+ writeFileSync(fd, payload);
82
93
  } finally {
83
94
  closeSync(fd);
84
95
  }
@@ -89,6 +100,25 @@ export function saveRemoteState(state, filePath = defaultStatePath()) {
89
100
  }
90
101
  }
91
102
 
103
+ export function removeRemoteState(filePath = defaultStatePath()) {
104
+ let info;
105
+ try {
106
+ verifyPrivate(lstatSync(dirname(filePath)), 'directory');
107
+ info = lstatSync(filePath);
108
+ } catch (err) {
109
+ if (err?.code === 'ENOENT') return false;
110
+ throw err;
111
+ }
112
+ verifyPrivate(info, 'file');
113
+ try {
114
+ unlinkSync(filePath);
115
+ return true;
116
+ } catch (err) {
117
+ if (err?.code === 'ENOENT') return false;
118
+ throw err;
119
+ }
120
+ }
121
+
92
122
  /**
93
123
  * Lossless v1 -> v2 migration / normalization.
94
124
  * Preserves existing hostId, hostSigningKeyPair, e2ee/e2eeKeySeed, tiana/owner/function/web fields,
package/src/tiana-cli.js CHANGED
@@ -12,7 +12,9 @@ import {
12
12
  ensureE2eeConfig,
13
13
  generateE2eeSecret,
14
14
  loadRemoteState,
15
+ loadRemoteStateSnapshot,
15
16
  migrateRemoteState,
17
+ removeRemoteState,
16
18
  resolveStatePath,
17
19
  saveRemoteState,
18
20
  withStateLock,
@@ -86,6 +88,7 @@ export async function getWebFunctionBinding(webId, options = {}) {
86
88
  return {
87
89
  functionInstanceIds: ids,
88
90
  projectRevision: current?.project_revision,
91
+ canManage: current?.can_manage,
89
92
  raw: current,
90
93
  };
91
94
  }
@@ -358,12 +361,169 @@ async function ensureWebApp({ webName, webId, log = console.log, ...cliOpts }) {
358
361
  '--json',
359
362
  webName,
360
363
  ], cliOpts);
361
- return created?.project ?? created?.app ?? created;
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 };
362
419
  }
363
420
 
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 : [];
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;
367
527
  if (bound.length === 1 && bound[0] === functionId) {
368
528
  return functionId;
369
529
  }
@@ -371,9 +531,9 @@ async function ensureWebFunctionBinding(webId, functionId, { adoptExisting = fal
371
531
  log(`[dsh-remote] Adopting existing Relay Function ${bound[0]} already bound to Web ${webId}`);
372
532
  return bound[0];
373
533
  }
374
- const revision = current?.project_revision;
534
+ const revision = current.projectRevision;
375
535
  if (!revision) {
376
- throw new Error(`Missing project_revision from web functions get: ${JSON.stringify(current)}`);
536
+ throw new Error(`Missing project_revision from web functions get: ${JSON.stringify(current.raw)}`);
377
537
  }
378
538
  log(`[dsh-remote] Binding Function ${functionId} -> Web ${webId} (rev ${revision})...`);
379
539
  try {
@@ -387,7 +547,18 @@ async function ensureWebFunctionBinding(webId, functionId, { adoptExisting = fal
387
547
  return functionId;
388
548
  } catch (err) {
389
549
  if (adoptExisting) {
390
- const rechecked = await getWebFunctionBinding(webId, cliOpts);
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
+ }
391
562
  if (rechecked.functionInstanceIds[0]) {
392
563
  log(`[dsh-remote] Adopting Relay Function ${rechecked.functionInstanceIds[0]} bound concurrently to Web ${webId}`);
393
564
  return rechecked.functionInstanceIds[0];
@@ -430,7 +601,9 @@ export function hasBindingIdentityConflict(existingPolicy, { hostId, registratio
430
601
  * Writes DSH_REMOTE_POLICY via `tiana function parameters set` without rebuilding Go or .tweb.
431
602
  *
432
603
  * Transactional safety:
433
- * 1. Validates non-empty user_id/tenant_id and strict `webApp.owner_id === status.user.user_id`.
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: ""`).
434
607
  * 2. Validates Relay Function is ACTIVE, HTTPS, and passes `/healthz` check.
435
608
  * 3. Reads existing function parameters strictly (never swallows errors).
436
609
  * 4. Checks rebind conflict across hostId + hostDigest + hostPublicKey.
@@ -456,23 +629,44 @@ export async function bindTianaRemoteWeb(options = {}) {
456
629
  if (!status?.user?.user_id || !status?.user?.tenant_id) {
457
630
  throw new Error('Tiana login status is missing user_id or tenant_id.');
458
631
  }
632
+ if (options.spaceId && status.user.tenant_id !== options.spaceId) {
633
+ throw new Error(`Failed to switch Tiana space to "${options.spaceId}".`);
634
+ }
459
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;
460
639
  const webApps = await listTianaWebApps(cliOpts);
461
- const webApp = webApps.find((item) => item.id === webId);
640
+ let webApp = webApps.find((item) => item.id === webId);
462
641
  if (!webApp) {
463
642
  throw new Error(`Web app "${webId}" was not found in the current Tiana space.`);
464
643
  }
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
- }
644
+ verifyWebAppOwnership(webApp, status, {
645
+ requireBindingProof: false,
646
+ errorMessage: bindOwnerError,
647
+ });
469
648
  if (webApp.enabled === false) {
470
649
  throw new Error(`Web app "${webId}" is disabled.`);
471
650
  }
472
651
  if (webApp.deletion_pending === true) {
473
652
  throw new Error(`Web app "${webId}" is pending deletion.`);
474
653
  }
475
- const webUrl = validateWebEndpoint(webApp, webId);
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
+ });
476
670
 
477
671
  const initialState = await withStateLock(() => {
478
672
  const raw = loadRemoteState(statePath);
@@ -483,8 +677,6 @@ export async function bindTianaRemoteWeb(options = {}) {
483
677
  const initialHostId = options.hostId || initialState.host?.hostId || identity.hostId;
484
678
  if (!/^[a-z0-9_-]{1,48}$/u.test(initialHostId)) throw new Error('Invalid host ID');
485
679
 
486
- // Locate bound Relay Function or provision one if empty
487
- const binding = await getWebFunctionBinding(webId, cliOpts);
488
680
  let fnId = binding.functionInstanceIds[0] || '';
489
681
  let fnShown = null;
490
682
  if (fnId) {
@@ -498,7 +690,13 @@ export async function bindTianaRemoteWeb(options = {}) {
498
690
  });
499
691
  fnId = created.instance.id;
500
692
  fnShown = await syncAndPublishRelayFunction(fnId, webId, { log, ...cliOpts });
501
- const boundFnId = await ensureWebFunctionBinding(webId, fnId, { adoptExisting: true, log, ...cliOpts });
693
+ const boundFnId = await ensureWebFunctionBinding(webId, fnId, {
694
+ adoptExisting: true,
695
+ revalidate: revalidateBindAuth,
696
+ errorMessage: bindOwnerError,
697
+ log,
698
+ ...cliOpts,
699
+ });
502
700
  if (boundFnId !== fnId) {
503
701
  fnId = boundFnId;
504
702
  fnShown = await runTianaJSON(['function', 'show', fnId, '--json'], cliOpts);
@@ -537,11 +735,23 @@ export async function bindTianaRemoteWeb(options = {}) {
537
735
  return raw ? migrateRemoteState(raw) : {};
538
736
  }, statePath);
539
737
 
540
- // Re-verify the Web app's active Relay Function binding under lock
541
- const activeBinding = await getWebFunctionBinding(webId, cliOpts);
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;
542
744
  let activeFnId = activeBinding.functionInstanceIds[0] || '';
543
745
  if (!activeFnId) {
544
- activeFnId = await ensureWebFunctionBinding(webId, fnId, { adoptExisting: true, log, ...cliOpts });
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
+ });
545
755
  }
546
756
  if (activeFnId && activeFnId !== fnId) {
547
757
  fnId = activeFnId;
@@ -738,10 +948,72 @@ export async function provisionTianaRemote(options = {}) {
738
948
  const statePath = options.statePath;
739
949
  const cliOpts = options.tianaBin ? { bin: options.tianaBin } : {};
740
950
 
741
- const status = await getTianaStatus(cliOpts);
742
- const bindLockPath = `${resolveStatePath(statePath)}.bind`;
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
+ };
743
972
  return await withStateLock(async () => {
744
- const prevState = await withStateLock(() => loadRemoteState(statePath) || {}, statePath);
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
+
745
1017
  const pending = { ...(prevState.pendingSetup || {}) };
746
1018
  const identity = defaultHostIdentity();
747
1019
  const hostId = options.hostId || prevState.host?.hostId || pending.hostId || identity.hostId;
@@ -766,37 +1038,48 @@ export async function provisionTianaRemote(options = {}) {
766
1038
  const owner = { userId: status.user.user_id, tenantId: status.user.tenant_id };
767
1039
  const checkpoint = async (fields) => {
768
1040
  Object.assign(pending, fields);
1041
+ const snapshotPending = structuredClone(pending);
769
1042
  await withStateLock(() => {
770
- const current = loadRemoteState(statePath) || {};
771
- saveRemoteState({ ...current, pendingSetup: { ...pending } }, statePath);
1043
+ const current = loadRemoteState(resolvedStatePath) || {};
1044
+ saveRemoteState({ ...current, pendingSetup: snapshotPending }, resolvedStatePath);
772
1045
  }, statePath);
1046
+ lastWrittenPendingSetup = snapshotPending;
773
1047
  };
774
1048
 
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 });
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 });
781
1053
  const webId = webApp?.id;
782
1054
  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');
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.`);
786
1065
  }
787
- const webUrl = validateWebEndpoint(webApp, webId);
788
- const webEndpoint = webUrl.href;
789
- await checkpoint({ webId });
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 });
790
1077
 
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,
1078
+ const { instance: fnInstance } = await ensureRelayFunction({
1079
+ functionName, functionId: prevState.function?.id || pending.functionId, log, ...cliOpts,
799
1080
  });
1081
+ if (!fnInstance?.id) throw new Error('Missing configured Function ID');
1082
+ await checkpoint({ functionId: fnInstance.id });
800
1083
 
801
1084
  // Build and validate the browser package in an isolated temporary directory (never pollutes repo!)
802
1085
  const distTemp = mkdtempSync(join(tmpdir(), 'dsh-remote-web-dist-'));
@@ -812,6 +1095,27 @@ export async function provisionTianaRemote(options = {}) {
812
1095
  });
813
1096
  log(`[dsh-remote] Built .tweb bundle (${built.fileCount} files, ${(built.totalBytes / 1024).toFixed(1)} KiB). Publishing to ${webId}...`);
814
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
+
815
1119
  const fnShown = await syncAndPublishRelayFunction(fnInstance.id, webId, {
816
1120
  forcePublish: Boolean(options.forcePublish), log, ...cliOpts,
817
1121
  });
@@ -828,8 +1132,46 @@ export async function provisionTianaRemote(options = {}) {
828
1132
  });
829
1133
  await checkpoint({ tokenInfo: { ...tokenInfo, id: fnInstance.id } });
830
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
+
831
1167
  await updateRemotePolicy(fnInstance.id, policy, { log, ...cliOpts });
832
- await ensureWebFunctionBinding(webId, fnInstance.id, { log, ...cliOpts });
1168
+ await ensureWebFunctionBinding(webId, fnInstance.id, {
1169
+ initialBinding: freshAuth.binding,
1170
+ requireManage: requiresManageProof,
1171
+ errorMessage: setupOwnerError,
1172
+ log,
1173
+ ...cliOpts,
1174
+ });
833
1175
 
834
1176
  const publishResult = await runTianaJSON([
835
1177
  'web', 'publish',
@@ -1874,6 +1874,7 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1874
1874
  const dlUrl = new URL(next, location.href);
1875
1875
  dlUrl.searchParams.set('__dsh_dl', (anchor.getAttribute('download') || '').trim() || '1');
1876
1876
  const f = document.createElement('iframe');
1877
+ f.referrerPolicy = 'same-origin';
1877
1878
  f.style.display = 'none';
1878
1879
  f.setAttribute('aria-hidden', 'true');
1879
1880
  f.src = dlUrl.href;
@@ -1883,6 +1884,13 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1883
1884
 
1884
1885
  if (!iframeNavHooksInstalled && typeof HTMLIFrameElement !== 'undefined') {
1885
1886
  iframeNavHooksInstalled = true;
1887
+ const ensureSameOriginReferrer = (el, nextUrl) => {
1888
+ if (nextUrl && nextUrl.includes('__dsh_nav=')) {
1889
+ // Override document-level `Referrer-Policy: no-referrer` strictly for same-origin SW-tunneled iframes
1890
+ // without ever leaking referrers cross-origin.
1891
+ try { el.referrerPolicy = 'same-origin'; } catch { /* ignore */ }
1892
+ }
1893
+ };
1886
1894
  const desc = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src');
1887
1895
  if (desc?.set && desc.configurable) {
1888
1896
  Object.defineProperty(HTMLIFrameElement.prototype, 'src', {
@@ -1891,6 +1899,7 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1891
1899
  get: desc.get,
1892
1900
  set(val) {
1893
1901
  const next = activeSwNavRewriter ? activeSwNavRewriter(String(val)) : String(val);
1902
+ ensureSameOriginReferrer(this, next);
1894
1903
  return desc.set.call(this, next);
1895
1904
  },
1896
1905
  });
@@ -1899,6 +1908,7 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1899
1908
  HTMLIFrameElement.prototype.setAttribute = function setAttribute(name, value) {
1900
1909
  if (String(name).toLowerCase() === 'src') {
1901
1910
  const next = activeSwNavRewriter ? activeSwNavRewriter(String(value)) : String(value);
1911
+ ensureSameOriginReferrer(this, next);
1902
1912
  return origSetAttr.call(this, name, next);
1903
1913
  }
1904
1914
  return origSetAttr.call(this, name, value);
@@ -349,6 +349,33 @@ function resolvePortByNavToken(navToken) {
349
349
 
350
350
  async function resolvePortForEvent(event, url) {
351
351
  const directClientId = event.clientId || '';
352
+ const dest = event.request.destination || '';
353
+ const referrer = event.request.referrer || '';
354
+ if (dest === 'iframe' || dest === 'frame') {
355
+ if (referrer) {
356
+ if (!isTrustedAppUrl(referrer)) {
357
+ return null;
358
+ }
359
+ } else {
360
+ const secFetchSite = String(event.request.headers.get('sec-fetch-site') || '').trim().toLowerCase();
361
+ if (secFetchSite !== 'same-origin') {
362
+ return null;
363
+ }
364
+ if (!directClientId) {
365
+ return null;
366
+ }
367
+ let parentClient = null;
368
+ try {
369
+ parentClient = await self.clients.get(directClientId);
370
+ } catch {
371
+ parentClient = null;
372
+ }
373
+ if (!isTrustedWindowClient(parentClient)) {
374
+ return null;
375
+ }
376
+ }
377
+ }
378
+
352
379
  if (directClientId) {
353
380
  const existingDirect = portsByClientId.get(directClientId);
354
381
  if (existingDirect) return existingDirect;
@@ -366,11 +393,6 @@ async function resolvePortForEvent(event, url) {
366
393
 
367
394
  const navToken = extractNavToken(event.request, url);
368
395
  if (navToken) {
369
- const dest = event.request.destination || '';
370
- const referrer = event.request.referrer || '';
371
- if ((dest === 'iframe' || dest === 'frame') && !isTrustedAppUrl(referrer)) {
372
- return null;
373
- }
374
396
  if (referrer && (referrer.startsWith('http://') || referrer.startsWith('https://')) && !isTrustedAppUrl(referrer)) {
375
397
  return null;
376
398
  }