@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.
package/LICENSE ADDED
@@ -0,0 +1,204 @@
1
+ Copyright (c) 2026 Tiana Cloud
2
+
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # DSH Remote
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 从 Tiana 托管网页安全访问本机 DeepSeek Harness(DSH)。通过 Tiana Function Relay 完成端到端加密认证(ECDH P-256 + HKDF-SHA256 + AES-256-GCM),支持 WebRTC P2P 直连与 Relay 加密中继无感切换,并提供原生子资源流式桥接、大媒体 `206 Partial Content` 窗口流控、主线程 `EventSource`(SSE)保活、DSH 侧栏配置面板与云端一键引导绑定。
4
+
5
+ ## 一键绑定与安装(推荐)
6
+
7
+ 前置要求:`Node.js >= 24.9.0`(与 `@deepseek-ai/dsh` 对齐)。
8
+
9
+ 在 Tiana 应用市场安装 **DSH Remote** 应用并打开后,页面向导会提供针对当前系统的绑定命令:
10
+
11
+ ```sh
12
+ npx --yes @tianacloud/dsh-remote@latest connect --app <appId>
13
+ ```
14
+
15
+ `connect` 会自动完成:
16
+ 1. 校验本机 `Node.js >= 24.9.0`(低于版本友好提示 `fnm`/`nvm`/`winget` 升级命令并安全退出);
17
+ 2. 检测已有 `dsh`(未装时自动安装 `@deepseek-ai/dsh@latest`,无全局写权限回退 `~/.local`,绝不调用 `sudo`),幂等启用 `@tianacloud/dsh-tiana` 与 `@tianacloud/dsh-remote`(完整保留既有项目、对话与其他插件);
18
+ 3. 核验 `tiana` 登录态与应用所有者权限,通过 `DSH_REMOTE_POLICY` 参数免重编译完成云端策略绑定(耗时 `< 3s`);
19
+ 4. 启动或热通知本机 DSH,经系统剪贴板管道复制 `dshk1_...` 配对密钥(**绝不将密钥拼入 URL hash 或 query**),打开干净的远程访问地址,网页向导收到 `host_online` 广播后毫秒级自动切入解锁页。
20
+
21
+ 本机先行首次创建云端资源仍支持 `dsh-remote setup`。
22
+
23
+ ## 侧栏管理面板与安全边界
24
+
25
+ - **本地 DSH 侧栏(Tiana Remote)**:可视化查看在线状态与延迟、热开关远程访问、打开/复制/扫码访问远程 URL、默认掩码查看/复制/二次确认轮换 E2EE 配对密钥(轮换立即以 `4001 key_rotated` 断开所有远端会话)、管理活跃会话与单会话踢出、热更新 P2P/STUN/前端放行插件白名单,以及一键修复重推静态壳层。
26
+ - **远端隧道受限视图**:在托管网页中打开同一侧栏时自动切换为安全受限模式,展示当前通道(`P2P`/`Relay`)与 RTT,提供「刷新前端模块缓存」与「锁定并清除此设备密钥」,**不展示任何配对密钥或宿主管理操作**。
27
+ - **双重管理路由隔离**:`HostBridge` 对经远端隧道发往 `/api/tiana-remote/admin` 及子路径的请求直接拦截返回 `403 Forbidden`,并在所有转发请求强制注入 `X-DSH-Remote-Tunnel: 1`;本机 `src/remote-api.js` 额外实施回环地址 + 非隧道头 + 本机 DSH `owner` 会话三重守卫。
28
+ - **配对密钥存储策略**:解锁页默认勾选「在此受信任浏览器记住密钥」(勾选时保存在当前浏览器 `localStorage`,下次打开免输直连;取消勾选时密钥仅驻留当前标签页 JS 内存,绝不写入 `localStorage` 或 `sessionStorage`,刷新或关闭标签页即销毁;点击锁定通过跨标签页广播立即清空内存与本地存储)。
29
+
30
+ ## 远端浏览器子资源、流式媒体与 SSE 桥接
31
+
32
+ - **无密钥流式 Service Worker(`dsh-remote-sw.js`)**:零密钥、零 `CacheStorage` 持久化,支持原生 `<img>`(含客户端 `3xx` 跟随)、`<video>`/`<audio>` `Range`/`206 Partial Content`、流式 `<a download>` 与沙箱 `<iframe>`;所有合成响应强制附加 `X-Content-Type-Options: nosniff`、`Cache-Control: no-store`,并对 `image/svg+xml`、`text/html`、`application/xhtml+xml` 强制施加不含 `allow-same-origin` 的 `Content-Security-Policy: sandbox` 防 XSS。
33
+ - **官方文件上传闭合**:入口挂载 `globalThis.__DSH_FILE_UPLOAD__ = { fetch: globalThis.fetch }`,使 `@deepseek-ai/dsh-client-file-upload` 直接走主线程加密隧道上传并保留 `AbortSignal` 即时取消。
34
+ - **窗口流控与并发隔离**:单会话最大并发流 `MAX_STREAMS = 64`,SW 子资源只读请求独立并发队列(上限 `16`);双端通过内层加密帧 `MSG_HTTP_RES_WINDOW (0x17)` 执行 `4 MiB` 接收窗口信用流控,大体积媒体暂停或拖动进度条内存占用有界且与旧版对端双向兼容。
35
+ - **主线程 `EventSource`(SSE)与滑动活性保活**:主线程提供标准 W3C `EventSource` 桥接(具名事件、`Last-Event-ID` 重连、`retry:`、`close()` 即时 `MSG_HTTP_ABORT`);`HostBridge` 采用流活动滑动 `5 分钟` 超时、对 `text/event-stream` 上游强制设置 `Accept-Encoding: identity`,并在上游静默每 `25s` 自动注入 `: keepalive\n` 心跳。
36
+ - **无 SW 受限容器极简防御(方案 A)**:SW 注册限时 `1500 ms` 绝不阻塞启动;无 SW 环境下主线程上传、`fetch`(含 `3xx` 跟随)、`EventSource` 与 `/api/remote.mux` WebSocket 100% 可用,仅在工作台顶部展示可手动关闭的系统浏览器打开提示条。
37
+
38
+ ## 本地验证
39
+
40
+ ```sh
41
+ (cd relay-go && go test -race ./... && go vet ./...)
42
+ npm test
43
+ npm run build:web
44
+ npm run test:pack
45
+ ```
package/cli.js ADDED
@@ -0,0 +1,347 @@
1
+ #!/usr/bin/env node
2
+ import { resolve } from 'node:path';
3
+ import { buildWebDist } from './scripts/build-web-dist.mjs';
4
+ import { checkNodeVersion, runConnect } from './src/connect.js';
5
+ import { HostBridge } from './src/host-bridge.js';
6
+ import {
7
+ defaultStatePath,
8
+ ensureE2eeConfig,
9
+ formatPairingKey,
10
+ loadRemoteState,
11
+ migrateRemoteState,
12
+ saveRemoteState,
13
+ withStateLock,
14
+ } from './src/state.js';
15
+ import { getTianaStatus, provisionTianaRemote } from './src/tiana-cli.js';
16
+
17
+ function parseArgs(argv) {
18
+ const positionals = [];
19
+ const flags = {};
20
+ for (let i = 0; i < argv.length; i += 1) {
21
+ const arg = argv[i];
22
+ if (!arg.startsWith('--')) {
23
+ positionals.push(arg);
24
+ continue;
25
+ }
26
+ const eqIdx = arg.indexOf('=');
27
+ if (eqIdx > 2) {
28
+ flags[arg.slice(2, eqIdx)] = arg.slice(eqIdx + 1);
29
+ continue;
30
+ }
31
+ const key = arg.slice(2);
32
+ const next = argv[i + 1];
33
+ if (next !== undefined && !next.startsWith('--')) {
34
+ flags[key] = next;
35
+ i += 1;
36
+ } else {
37
+ flags[key] = true;
38
+ }
39
+ }
40
+ return { command: positionals[0] || 'help', rest: positionals.slice(1), flags };
41
+ }
42
+
43
+ function printHelp() {
44
+ console.log(`dsh-remote — Expose DeepSeek Harness via Tiana (zero platform changes, E2EE)
45
+
46
+ Usage:
47
+ dsh-remote connect --web <webIdOrUrl> [options]
48
+ Bind this machine to an installed Tiana DSH Remote app (zero recompile)
49
+ --web <webIdOrUrl> Tiana Web App ID or URL (alias: --app)
50
+ --space <tenantId> Target Tiana space ID
51
+ --profile <name> DSH profile name (default: web)
52
+ --port <port> Local DSH port (default: 3080)
53
+ --host-name <name> Override display name
54
+ --rebind Rebind without prompt if app is bound to another machine
55
+ --no-start Do not auto-start local DSH
56
+ --no-open Do not auto-open browser
57
+ --no-clipboard Do not copy pairing key to clipboard
58
+ --print-key Print full pairing key to stdout
59
+ --json Print redacted JSON summary to stdout
60
+
61
+ dsh-remote setup [options] Provision/reuse Relay Function, Token, and .tweb app
62
+ --host-id <id> Specify the host ID for a new installation
63
+ --host-name <name> Override display name
64
+ --function-name <name> Relay Function name (default: dsh-remote-relay)
65
+ --web-name <name> Web App name (default: DSH Remote)
66
+ --force-publish Force rebuild & publish Relay Function
67
+ --rotate-token Mint a fresh Function access token
68
+ --rotate-e2ee-key Rotate the local E2EE pairing key
69
+
70
+ dsh-remote key [--rotate] [--json]
71
+ Show or rotate the local E2EE pairing key
72
+ dsh-remote status [--json] Show Tiana login & provisioned remote state (redacted)
73
+ dsh-remote start --port <port> Attach standalone HostBridge to a local DSH port
74
+ Set DSH_LAUNCH_TOKEN in the environment to authenticate to local DSH.
75
+
76
+ dsh-remote build-web [outDir] Build the static .tweb bundle locally
77
+ `);
78
+ }
79
+
80
+ async function cmdConnect(flags) {
81
+ const nodeCheck = checkNodeVersion();
82
+ if (!nodeCheck.ok) {
83
+ console.error(nodeCheck.message);
84
+ process.exitCode = 2;
85
+ return;
86
+ }
87
+ await runConnect({
88
+ app: typeof flags.app === 'string' ? flags.app : undefined,
89
+ web: typeof flags.web === 'string' ? flags.web : undefined,
90
+ space: typeof flags.space === 'string' ? flags.space : undefined,
91
+ profile: typeof flags.profile === 'string' ? flags.profile : undefined,
92
+ port: typeof flags.port === 'string' ? flags.port : undefined,
93
+ hostName: typeof flags['host-name'] === 'string' ? flags['host-name'] : undefined,
94
+ rebind: Boolean(flags.rebind),
95
+ noStart: Boolean(flags['no-start']),
96
+ noOpen: Boolean(flags['no-open']),
97
+ noClipboard: Boolean(flags['no-clipboard']),
98
+ printKey: Boolean(flags['print-key']),
99
+ json: Boolean(flags.json),
100
+ });
101
+ }
102
+
103
+ async function cmdSetup(flags) {
104
+ const state = await provisionTianaRemote({
105
+ hostId: typeof flags['host-id'] === 'string' ? flags['host-id'] : undefined,
106
+ hostName: typeof flags['host-name'] === 'string' ? flags['host-name'] : undefined,
107
+ functionName: typeof flags['function-name'] === 'string' ? flags['function-name'] : undefined,
108
+ webName: typeof flags['web-name'] === 'string' ? flags['web-name'] : undefined,
109
+ forcePublish: Boolean(flags['force-publish']),
110
+ rotateToken: Boolean(flags['rotate-token']),
111
+ rotateE2eeKey: Boolean(flags['rotate-e2ee-key']),
112
+ });
113
+ console.log('');
114
+ console.log('============================================================');
115
+ console.log('DSH Remote provisioning complete!');
116
+ console.log(` Owner : ${state.owner?.email || state.owner?.userId}`);
117
+ console.log(` Space : ${state.owner?.spaceName || state.owner?.tenantId}`);
118
+ console.log(` Host ID : ${state.host?.hostId} (${state.host?.hostName})`);
119
+ console.log(` Relay Fn : ${state.function?.id} -> ${state.function?.url}`);
120
+ console.log(` Web App : ${state.web?.id}`);
121
+ console.log(` E2EE : ${state.e2ee?.algorithm} (key ${state.e2ee?.fingerprint})`);
122
+ console.log(` Remote URL : ${state.web?.endpoint}`);
123
+ console.log(` State file : ${defaultStatePath()}`);
124
+ console.log('============================================================');
125
+ console.log('Next: start `dsh web` (with @tianacloud/dsh-remote installed) and open the Remote URL.');
126
+ }
127
+
128
+ async function cmdStatus(flags) {
129
+ let tianaStatus = null;
130
+ try {
131
+ tianaStatus = await getTianaStatus();
132
+ } catch (err) {
133
+ tianaStatus = { logged_in: false, error: err.message };
134
+ }
135
+ const rawState = loadRemoteState();
136
+ const state = rawState ? migrateRemoteState(rawState) : null;
137
+ let relayHealth = null;
138
+ if (state?.function?.url && state?.function?.token) {
139
+ try {
140
+ const health = new URL('/health', state.function.url);
141
+ if (health.protocol !== 'https:' || health.username || health.password) throw new Error('HTTPS required');
142
+ const resp = await fetch(health, {
143
+ headers: { Authorization: `Bearer ${state.function.token}` },
144
+ redirect: 'error',
145
+ signal: AbortSignal.timeout(10_000),
146
+ });
147
+ if (resp.ok) {
148
+ const body = await resp.json();
149
+ relayHealth = { ok: body?.ok === true, paired: body?.paired };
150
+ } else {
151
+ relayHealth = { ok: false, status: resp.status };
152
+ }
153
+ } catch (err) {
154
+ relayHealth = { ok: false, error: err.message };
155
+ }
156
+ }
157
+
158
+ const redactedState = state ? {
159
+ version: state.version,
160
+ configVersion: state.configVersion,
161
+ enabled: state.enabled,
162
+ owner: state.owner && { userId: state.owner.userId, tenantId: state.owner.tenantId },
163
+ host: state.host && { hostId: state.host.hostId, hostName: state.host.hostName },
164
+ e2ee: state.e2ee?.secret ? {
165
+ enabled: true, algorithm: state.e2ee.algorithm,
166
+ fingerprint: state.e2ee.fingerprint, createdAt: state.e2ee.createdAt,
167
+ } : { enabled: false },
168
+ function: state.function && {
169
+ id: state.function.id, url: state.function.url, name: state.function.name,
170
+ tokenConfigured: Boolean(state.function.token),
171
+ tokenId: state.function.tokenId, expiresAt: state.function.expiresAt,
172
+ },
173
+ web: state.web && { id: state.web.id, endpoint: state.web.endpoint, name: state.web.name },
174
+ network: state.network,
175
+ security: state.security,
176
+ } : null;
177
+
178
+ const summary = {
179
+ tiana: tianaStatus?.logged_in
180
+ ? {
181
+ loggedIn: true,
182
+ email: tianaStatus.user?.email,
183
+ userId: tianaStatus.user?.user_id,
184
+ tenantId: tianaStatus.user?.tenant_id,
185
+ space: tianaStatus.space?.display_name,
186
+ }
187
+ : tianaStatus,
188
+ statePath: defaultStatePath(),
189
+ state: redactedState,
190
+ relayHealth,
191
+ };
192
+
193
+ if (flags.json) {
194
+ console.log(JSON.stringify(summary, null, 2));
195
+ return;
196
+ }
197
+
198
+ console.log('Tiana Login :', summary.tiana?.loggedIn ? `${summary.tiana.email} (${summary.tiana.space})` : 'NOT LOGGED IN');
199
+ if (!redactedState) {
200
+ console.log('Remote State: Not provisioned yet. Run `dsh-remote connect --app <appId>` or `dsh-remote setup`.');
201
+ return;
202
+ }
203
+ console.log('Host :', `${redactedState.host?.hostId} (${redactedState.host?.hostName})`);
204
+ console.log('Relay Fn :', `${redactedState.function?.id} -> ${redactedState.function?.url}`);
205
+ console.log('E2EE :', redactedState.e2ee?.enabled
206
+ ? `${redactedState.e2ee.algorithm} (key ${redactedState.e2ee.fingerprint})`
207
+ : 'not initialized (will auto-generate on next setup/start)');
208
+ console.log('Web Endpoint:', redactedState.web?.endpoint || 'unavailable');
209
+ console.log('Relay Health:', relayHealth ? JSON.stringify(relayHealth) : 'unavailable');
210
+ console.log('Tip : Run `dsh-remote key` to view the pairing key in a private terminal.');
211
+ }
212
+
213
+ async function cmdKey(flags) {
214
+ const rotate = Boolean(flags.rotate);
215
+ const result = await withStateLock(() => {
216
+ const rawState = loadRemoteState();
217
+ if (!rawState) {
218
+ throw new Error('Remote state not found. Run `dsh-remote connect` or `dsh-remote setup` first.');
219
+ }
220
+ const state = migrateRemoteState(rawState);
221
+ const { changed, e2ee } = ensureE2eeConfig(state, { rotate });
222
+ const hostId = state.host?.hostId || 'dsh-host';
223
+ if (changed) {
224
+ state.e2ee = e2ee;
225
+ if (state.web) {
226
+ delete state.web.shareUrl;
227
+ }
228
+ state.updatedAt = new Date().toISOString();
229
+ saveRemoteState(state);
230
+ }
231
+ return { hostId, e2ee, endpoint: state.web?.endpoint };
232
+ });
233
+
234
+ const { hostId, e2ee, endpoint } = result;
235
+ const pairingKey = formatPairingKey(e2ee.secret);
236
+ const printKey = Boolean(flags['print-key']);
237
+ const out = {
238
+ hostId,
239
+ algorithm: e2ee.algorithm,
240
+ fingerprint: e2ee.fingerprint,
241
+ endpoint,
242
+ rotated: rotate,
243
+ ...(printKey ? { pairingKey, secret: e2ee.secret } : {}),
244
+ };
245
+ if (flags.json) {
246
+ console.log(JSON.stringify(out, null, 2));
247
+ return;
248
+ }
249
+ if (rotate) {
250
+ console.log('[dsh-remote] Rotated local E2EE key (running `dsh web` will hot-reload and disconnect active clients).');
251
+ }
252
+ console.log(`Algorithm : ${e2ee.algorithm}`);
253
+ console.log(`Fingerprint: ${e2ee.fingerprint}`);
254
+ console.log(`Pairing Key: ${pairingKey}`);
255
+ if (endpoint) console.log(`Remote URL : ${endpoint}`);
256
+ }
257
+
258
+ async function cmdStart(flags) {
259
+ const rawState = loadRemoteState();
260
+ if (!rawState?.function?.url || !rawState?.function?.token) {
261
+ throw new Error('Remote state not found. Run `dsh-remote connect` or `dsh-remote setup` first.');
262
+ }
263
+ const state = migrateRemoteState(rawState);
264
+ const port = Number(flags.port || process.env.DSH_PORT || 0);
265
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
266
+ throw new Error('Provide --port <port> pointing to the local dsh web port.');
267
+ }
268
+ if (rawState.version !== 2) throw new Error('Run setup or connect with the updated plugin first.');
269
+ if (flags.token || flags['host-id']) throw new Error('Use DSH_LAUNCH_TOKEN and the host ID configured by setup.');
270
+ const { hostId, registrationKey } = state.host;
271
+ const launchToken = process.env.DSH_LAUNCH_TOKEN || '';
272
+ const localOrigin = `http://127.0.0.1:${port}`;
273
+ const bridge = new HostBridge({
274
+ relayUrl: state.function.url,
275
+ relayToken: state.function.token,
276
+ e2eeSecret: state.e2ee.secret,
277
+ hostId,
278
+ registrationKey,
279
+ hostName: state.host?.hostName || 'dsh-host',
280
+ localOrigin,
281
+ getLaunchToken: launchToken ? () => launchToken : null,
282
+ ownerUserId: state.owner?.userId || '',
283
+ ownerTenantId: state.owner?.tenantId,
284
+ webId: state.web?.id,
285
+ p2p: process.env.DSH_REMOTE_P2P ?? state.network?.p2pEnabled,
286
+ stun: process.env.DSH_REMOTE_STUN ?? state.network?.stunUrls,
287
+ frontendOptions: {
288
+ allowlist: process.env.DSH_REMOTE_WEB_PLUGINS ?? state.security?.allowedWebPlugins,
289
+ },
290
+ });
291
+
292
+ const stop = () => {
293
+ bridge.stop();
294
+ process.exit(0);
295
+ };
296
+ process.on('SIGINT', stop);
297
+ process.on('SIGTERM', stop);
298
+
299
+ await bridge.start();
300
+ console.log(`[dsh-remote] E2EE active (${state.e2ee.algorithm}, key ${state.e2ee.fingerprint})`);
301
+ console.log(`[dsh-remote] Bridging ${localOrigin} -> ${state.web.endpoint}`);
302
+ }
303
+
304
+ function cmdBuildWeb(rest) {
305
+ const outDir = resolve(rest[0] || '.dist-tweb/preview');
306
+ const res = buildWebDist({ outDir });
307
+ console.log(`[dsh-remote] Built web dist at ${res.outDir}: ${res.fileCount} files, ${(res.totalBytes / 1024).toFixed(1)} KiB`);
308
+ }
309
+
310
+ async function main() {
311
+ const { command, rest, flags } = parseArgs(process.argv.slice(2));
312
+ if (flags.help || flags.h || command === 'help') {
313
+ printHelp();
314
+ return;
315
+ }
316
+ switch (command) {
317
+ case 'connect':
318
+ await cmdConnect(flags);
319
+ break;
320
+ case 'setup':
321
+ await cmdSetup(flags);
322
+ break;
323
+ case 'key':
324
+ await cmdKey(flags);
325
+ break;
326
+ case 'status':
327
+ await cmdStatus(flags);
328
+ break;
329
+ case 'start':
330
+ await cmdStart(flags);
331
+ break;
332
+ case 'share':
333
+ throw new Error('Shared viewer access is disabled. Only the configured DSH owner can connect.');
334
+ case 'build-web':
335
+ cmdBuildWeb(rest);
336
+ break;
337
+ default:
338
+ console.error(`Unknown command: ${command}`);
339
+ printHelp();
340
+ process.exitCode = 1;
341
+ }
342
+ }
343
+
344
+ main().catch((err) => {
345
+ console.error(`[dsh-remote] Error: ${err instanceof Error ? err.message : String(err)}`);
346
+ process.exitCode = Number.isInteger(err?.exitCode) ? err.exitCode : 1;
347
+ });