dsh-convenient-window 0.0.0-stage → 0.2.0

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,75 @@
1
+ # PolyForm Noncommercial License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
12
+
13
+ ## Distribution License
14
+
15
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
16
+
17
+ ## Notices
18
+
19
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
20
+
21
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
22
+
23
+ Required Notice: Copyright (c) 2026 ximizhou. Commercial use requires a separate written license from the copyright holder.
24
+
25
+ ## Changes and New Works License
26
+
27
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
28
+
29
+ ## Patent License
30
+
31
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
32
+
33
+ ## Noncommercial Purposes
34
+
35
+ Any noncommercial purpose is a permitted purpose.
36
+
37
+ ## Personal Uses
38
+
39
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
40
+
41
+ ## Noncommercial Organizations
42
+
43
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
44
+
45
+ ## Fair Use
46
+
47
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
48
+
49
+ ## No Other Rights
50
+
51
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
52
+
53
+ ## Patent Defense
54
+
55
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
56
+
57
+ ## Violations
58
+
59
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
60
+
61
+ ## No Liability
62
+
63
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
64
+
65
+ ## Definitions
66
+
67
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
68
+
69
+ **You** refers to the individual or entity agreeing to these terms.
70
+
71
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
72
+
73
+ **Your licenses** are all the licenses granted to you for the software under these terms.
74
+
75
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
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.
1
+ # dsh-convenient-window · 便捷窗口
2
+
3
+ 在 DeepSeek Harness 侧栏集中管理 Windows 窗口:把暂时不用的窗口藏到屏幕边缘,鼠标移近即可唤回;为屏幕边角设置快捷动作,用鼠标手势执行常用操作,并保存和恢复窗口布局。还支持窗口置顶、拖拽缩放、区域截图、截图贴图与文字识别。
4
+
5
+ ## 功能预览
6
+
7
+ ### 贴边隐藏:需要时展开,不用时收起
8
+
9
+ ![在 DSH 侧栏设置窗口贴边隐藏](https://raw.githubusercontent.com/ximizhou/convenient_window_free/main/docs/images/dsh-panel.png)
10
+
11
+ ### 触发角:把屏幕边角变成快捷操作入口
12
+
13
+ ![触发角与屏幕边缘动作设置](https://raw.githubusercontent.com/ximizhou/convenient_window_free/main/docs/images/hot-zones.png)
14
+
15
+ ### 鼠标手势:画出轨迹,执行常用操作
16
+
17
+ ![鼠标手势与动作设置](https://raw.githubusercontent.com/ximizhou/convenient_window_free/main/docs/images/mouse-gestures.png)
18
+
19
+ 首图为 DSH 实际页签;后两图复用桌面版共享设置页的浅色截图,具体排版以当前插件为准。
20
+
21
+ ## 版本与使用环境
22
+
23
+ 设置页直接复用独立桌面版,Windows 助手已装在插件包里,无需再下载一次。
24
+
25
+ | 插件 | 内置窗口引擎 | 已验收环境 |
26
+ | --- | --- | --- |
27
+ | **0.2.0** | **0.6.12** | Windows 11 x64、DSH **0.2.2-rc.5** |
28
+
29
+ [查看发布与下载](https://github.com/ximizhou/convenient_window_free/releases/tag/dsh-v0.2.0) · [项目首页](../../README.zh-CN.md) · [反馈问题](https://github.com/ximizhou/convenient_window_free/issues/new/choose)
30
+
31
+ ## 安装
32
+
33
+ ### 从 npm 安装(本版在 npm 上线后)
34
+
35
+ 1. 先打开一次 DSH,让它创建 `desktop` 配置,然后从系统托盘**退出 DSH**。
36
+ 2. 打开 PowerShell,粘贴下面的命令并回车。安装时保持联网。
37
+
38
+ ```powershell
39
+ dsh plugin --profile desktop add dsh-convenient-window@0.2.0 --ignore-scripts --registry=https://registry.npmjs.org/
40
+ ```
41
+
42
+ 3. 安装成功后重新打开 DSH,点击左侧 **dsh-convenient-window**。
43
+ 4. 按需开启右上角的功能总开关,再打开需要的功能。首次安装默认关闭总开关。
44
+
45
+ 上面的命令固定本版,只有 npm 已提供 `0.2.0` 后才可用。GitHub 预发布、npm 发布和市场索引是独立状态;如果 npm 尚未提供本版,先按下方 GitHub 下载包方式安装。不要把 `latest` 或 `beta` 默认当成本版,也不要仅凭包号判断已经转正式,具体状态以对应发布页为准。
46
+
47
+ <details>
48
+ <summary><strong>PowerShell 提示找不到 dsh,怎么办?</strong></summary>
49
+
50
+ 找到 DSH 的安装目录,再打开其中的 `resources\runtime\cli\bin` 文件夹,找到 `dsh.cmd`。在 PowerShell 中用其完整路径替换命令开头的 `dsh`。下面的路径是占位示例,需要换成你自己的安装位置:
51
+
52
+ ```powershell
53
+ & "你的 DSH 安装目录\resources\runtime\cli\bin\dsh.cmd" plugin --profile desktop add dsh-convenient-window@0.2.0 --ignore-scripts --registry=https://registry.npmjs.org/
54
+ ```
55
+
56
+ </details>
57
+
58
+ ### 也可以安装 GitHub 下载包
59
+
60
+ 从[本版 Release](https://github.com/ximizhou/convenient_window_free/releases/tag/dsh-v0.2.0)下载 `dsh-convenient-window-0.2.0.tgz`。退出 DSH,在下载目录打开 PowerShell:
61
+
62
+ ```powershell
63
+ $pkg = (Resolve-Path -LiteralPath '.\dsh-convenient-window-0.2.0.tgz').Path
64
+ dsh plugin --profile desktop add "file:$pkg" --ignore-scripts
65
+ ```
66
+
67
+ 保留这个文件,便于重装或回退。npm 发布必须使用这份同一验收包;已上线时可核对两边哈希。日常安装不加 `--offline`,因为 DSH 可能还需核对当前配置中其他插件的依赖。
68
+
69
+ ## 升级、旧名称迁移和卸载
70
+
71
+ **已经是新名称:** 安装前退出 DSH,再执行目标版本的安装命令;使用同一个 profile 保留设置。先阅读目标版本的兼容与迁移说明。
72
+
73
+ **装过旧名 `dsh-plugin-convenient-window`:**
74
+
75
+ 1. 如果开过旧插件的登录自启,先在旧页签运行中心关闭它。
76
+ 2. 从托盘退出 DSH,再移除旧包:
77
+
78
+ ```powershell
79
+ dsh plugin --profile desktop remove dsh-plugin-convenient-window
80
+ ```
81
+
82
+ 3. 确认移除成功,再按上面的 npm 或 GitHub 方式安装新名称。
83
+ 4. 重开后检查设置,并按需重新开启登录自启。最早的 `0.1.0-beta.1` 迁移时,总开关默认关闭。
84
+
85
+ 旧名和新名共用当前 profile 的 `convenient-window/` 数据目录;配置、窗口布局与界面偏好在更名验收中保留。配置导出可作为额外备份,但不等于完整备份窗口布局和所有宿主偏好。
86
+
87
+ **卸载:** 先在插件里关闭登录自启(如果开启),从托盘退出 DSH,然后运行:
88
+
89
+ ```powershell
90
+ dsh plugin --profile desktop remove dsh-convenient-window
91
+ ```
92
+
93
+ 卸载保留 profile 中的设置。回退到保存的旧版包时,先移除当前包,再安装旧包;旧版本未必能读取将来的配置格式,不把回退当成无条件兼容。
94
+
95
+ ## 常见问题
96
+
97
+ - **安装成功但没有页签:** 确认安装到正在使用的 `desktop` profile,并从托盘完全退出后重开 DSH。
98
+ - **助手被占用:** 桌面版、uTools 和 DSH 共用单实例窗口引擎。先在原宿主正常关闭助手,再启用这里的总开关。
99
+ - **DSH 升级后不兼容:** 本版只声明已验收的 `0.2.2-rc.5`。记录两边版本并反馈,不要通过删除兼容限制强行启用。
100
+ - **部分功能入口没显示:** 在右上角齿轮里的功能入口设置中调整。底部空间有限,并非功能被删除。
101
+ - **切页后还能工作吗:** 开启后,切换页签和最小化不停止助手;退出 DSH 会停止本插件拥有的进程。
102
+ - **能和桌面版互相同步吗:** 两边配置独立保存,不自动同步。
103
+ - **没有找到市场条目:** npm 发布、目录审核和市场可搜索是不同状态。未查到时可先用本页固定版本命令,不要安装名称相近的包。
104
+
105
+
106
+ ## 功能范围
107
+
108
+ | 桌面功能 | DSH 本版 |
109
+ | --- | --- |
110
+ | 显示器预览、屏幕选择、可拖动分栏、深浅主题、中英切换、功能入口编排 | 直接编译桌面版的 Svelte 组件和样式;不重画 |
111
+ | 触发角及各边热区、按键与修饰键、贴边收纳、拖拽缩放、置顶图钉 | 使用同一配置模型和 Windows 助手。默认以普通权限运行,电源页可切换助手权限 |
112
+ | 鼠标手势、截图贴图、OCR、音量/亮度、任务栏外观 | 同一设置页和运行引擎;OCR 取决于系统语言包,任务栏效果取决于系统与其他美化工具。音量和亮度使用桌面版的全局提示窗,切走页签后仍可显示 |
113
+ | 窗口布局记录/恢复、布局快捷键与排除名单 | 走实际助手;页签关闭时,插件宿主仍处理已登记的布局快捷键 |
114
+ | 导入/导出、诊断、布局和界面偏好 | JSON 通过本机文件选择/保存;诊断来自本插件助手,设置与布局按 DSH profile 保存 |
115
+ | Windows 启动项管理 | 同一套列表、筛选、查看命令、启停和添加程序。添加时使用 Windows 文件选择器,修改前显示相应程序的确认框 |
116
+ | 登录自启与管理员模式 | 电源页管理 `Convenient Window (DSH)` 登录项。可以为本次会话或登录时的助手请求 Windows 授权,DSH 本身保持普通权限 |
117
+ | 自定义「运行命令」 | 新命令保存前列出内容供确认。触发已配置的动作时由桌面版的普通权限代理执行 |
118
+
119
+ 插件的设置窗口、最小化和托盘入口由 DSH 提供。日常操作都在左侧 `dsh-convenient-window` 页签内完成。安装和升级时从托盘退出整个 DSH。
120
+
121
+ 底部放不下的入口在右上齿轮的功能入口设置里。贴边体验请用未最大化的普通窗口;多屏 DPI、手势手感、截图/OCR 和任务栏实际效果需在目标机器分别体验,自动化的“设置已应用”不能代替真人验收。
122
+
123
+ ## 维护者
124
+
125
+ ```text
126
+ DSH 侧栏 → 独立文档内的桌面 App.svelte + styles.css(同一份源文件)
127
+ ├─ DSH HostBridge:设置、偏好、文件、诊断
128
+ └─ 桌面 HelperClient → 本机适配层 → 同一个正式 Rust 助手
129
+ └─ DSH 原生宿主复用桌面监管、权限、命令、启动项与全局提示窗
130
+ ```
131
+
132
+ - `src/client.js` 只注册 DSH 插槽;隔离文档避免桌面样式、事件和主题污染 DSH。`src/panel.ts` 接宿主功能;`src/globals.js` 仅对本次构建注入传输和偏好适配,不替换 DSH 的全局对象。构建检查桌面组件确实进入成品,拒绝打入 Tauri 渲染 API。
133
+ - `host/panel-controller.js` 复用构建自桌面源码的模型,对写入核对 session/revision,确认回执才显示已应用;不向页面发助手 token,不开放计算任意命令或访问任意文件的接口。旧设置仅用于首次迁移。两个版本使用同一个 Rust helper 源码;本包同步已发布的 0.6.12 引擎,桌面版与 uTools 无需随此版重发。
134
+ - 产品/助手 **0.6.12**,DSH 适配包 **0.2.0**;只声明已验证的 Windows DSH **0.2.2-rc.5**。仅 DSH 变化,先改宿主适配并升级适配包号。不要改已发布的产品版本或 stable 资产。
135
+ - 在 `apps/dsh-plugin` 运行 `npm ci`、`npm test`。按 `runtime-assets.json` 准备正式资产后执行 `npm run stage:helper -- <解压目录>`。使用 native 工具链执行 `npm run build:native -- <与桌面 Cargo.lock 对应的 THIRD-PARTY-NOTICES.txt>`,再执行 `npm run test:native`;测试不抢占其他助手。`npm pack` 生成单包。`npm run test:desktop -- "<DSH.exe>" "<新版.tgz>" ["<已验收的旧版.tgz>"]` 在隔离配置验最终包(可验证升级);同时保留日常有其他插件时不加 `--offline` 的安装回归。测试不替用户修改登录设置、操作真实窗口布局或自动发布。
136
+
137
+ ## 发布与市场收录
138
+
139
+ 为已验收的插件提交创建 `dsh-v<插件版本>` Tag,并将实装验收通过的 `.tgz` 附在 GitHub Pre-release 中。桌面和 DSH 插件共用[产品 Releases 入口](https://github.com/ximizhou/convenient_window_free/releases)。
140
+
141
+ 将同一个 `.tgz` 发布到所选 npm 渠道。候选需要测试分发时用 `beta`;转正式后由发布者将已验收的同一包发布到 `latest`。先预览包名、版本和文件清单,再由发布者在自己的终端执行发布;不要在转正式时重打包。下面为候选频道示例,正式发布时改用 `--tag latest`。将路径换成本次验收文件。
142
+
143
+ ```powershell
144
+ $pkg = (Resolve-Path -LiteralPath '<本轮验收的 .tgz>').Path
145
+ npm.cmd publish "$pkg" --dry-run --access public --tag beta --registry=https://registry.npmjs.org/
146
+ npm.cmd publish "$pkg" --access public --tag beta --registry=https://registry.npmjs.org/
147
+ ```
148
+
149
+ 发布者按 npm 提示完成登录和双重验证。发布后查询所选标签的实际指向,匿名下载 npm 和 GitHub 两边的包,核对大小及 SHA-256,再在全新的 DSH `desktop` 配置按发布页命令试装。`npm publish --dry-run` 只预览,不代表已经发布。见 [npm 发布说明](https://docs.npmjs.com/cli/v11/commands/npm-publish/)。
150
+
151
+ 要进入社区 `dshmarket` 搜索列表,先确认下方条目的 `main/apps/dsh-plugin` 链接可访问,给公开仓库添加 `dsh-plugin` topic,再向 `awesome-dsh-plugin` 提交子目录条目。填写带具体标签的 GitHub Release 附件地址,审核合并后在市场搜索并试装。[市场投稿说明](https://github.com/dsh-market/dsh-market/blob/main/README.zh.md) · [子目录与条目格式](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin/blob/main/contributing.md)。
152
+
153
+ 使用 DSH 自带「插件 → 发现」的用户可以在「索引源」中添加社区目录 `https://cdn.jsdelivr.net/npm/dsh-plugin-catalog/index.json`。目录收录并更新后,可以搜索英文包名或中文描述中的「便捷窗口」。[DSH 发现页与索引说明](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.2-rc.5/packages/boot/plugin-market/README.zh.md)。
154
+
155
+ 本项目对应的投稿文件为 `data/plugins/ximizhou__convenient_window_free--apps-dsh-plugin.yml`。发布附件后可使用以下内容。
156
+
157
+ ```yaml
158
+ url: https://github.com/ximizhou/convenient_window_free/tree/main/apps/dsh-plugin
159
+ name: ximizhou/convenient_window_free#dsh-convenient-window
160
+ category: tools
161
+ description:
162
+ en: Manage Windows windows from the DeepSeek Harness sidebar with edge hiding and hover-to-reveal, hot corners and screen-edge actions, mouse gestures, saved window layouts, window pinning, dragging and resizing, region screenshots, pinned images and OCR.
163
+ zh: 在 DeepSeek Harness 侧栏集中管理 Windows 窗口:将窗口贴边收起、鼠标移近唤回,为屏幕边角设置快捷动作,用鼠标手势执行常用操作,保存并恢复窗口布局;还支持窗口置顶、拖拽缩放、区域截图、截图贴图与文字识别。
164
+ icon: https://raw.githubusercontent.com/ximizhou/convenient_window_free/main/docs/images/app-icon.png
165
+ tarball: https://github.com/ximizhou/convenient_window_free/releases/download/dsh-v0.2.0/dsh-convenient-window-0.2.0.tgz
166
+ ```
167
+
168
+ 另一个 [2BingLing/dsh-market](https://github.com/2BingLing/dsh-market/blob/master/CONTRIBUTING.md) 支持 topic 扫描及插件申请 Issue。填写源码子目录、插件类型 `cordis-plugin`、已验收宿主版本、固定安装包和带版本的安装命令;收录后检查它生成的命令是否错误地指向仓库根目录或无版本 npm 包。
169
+
170
+ 上面的目录条目固定到本版附件。后续发版须更新条目并复核市场实际安装目标;审核通过、索引更新、搜索可见和安装成功分别确认。npm 页面中的 README 来自发布包,仓库文档更新不会回写已发布 npm 包;只改介绍时不重打同版本包。GitHub Release 正文以 [版本说明](../../docs/release-notes/dsh-0.2.0.md) 为准。
171
+
172
+ 市场截图通过本目录的 `screenshots.json` 声明,按顺序展示 DSH 页签、触发角和鼠标手势。复用仓库已有浅色图的 GitHub HTTPS 地址,不复制图片,不用越出插件目录的相对路径。声明合入默认分支后等待目录采集;简介改动则更新上面的社区 YAML 条目并提交 PR。展示资料更新无需发布新的插件包。
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: convenient-window
3
+ name: dsh-convenient-window
package/host/assets.js ADDED
@@ -0,0 +1,33 @@
1
+ import { readFile, lstat, readdir } from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const root = fileURLToPath(new URL('../', import.meta.url));
7
+ export const assets = JSON.parse(
8
+ await readFile(join(root, 'runtime-assets.json'), 'utf8'),
9
+ );
10
+ export const metadata = JSON.parse(
11
+ await readFile(join(root, 'package.json'), 'utf8'),
12
+ );
13
+ // The release manifest is a pinned build input, not a remotely refreshable download policy.
14
+ export async function verifyPayload(dir = join(root, 'payload'), exact = true) {
15
+ const names = assets.files.map((f) => f.name).sort();
16
+ if (
17
+ exact &&
18
+ JSON.stringify((await readdir(dir)).sort()) !== JSON.stringify(names)
19
+ )
20
+ throw Error('payload-invalid');
21
+ for (const f of assets.files) {
22
+ const file = join(dir, f.name),
23
+ stat = await lstat(file);
24
+ if (
25
+ !stat.isFile() ||
26
+ stat.size !== f.bytes ||
27
+ createHash('sha256')
28
+ .update(await readFile(file))
29
+ .digest('hex') !== f.sha256
30
+ )
31
+ throw Error('payload-invalid');
32
+ }
33
+ }
package/host/helper.js ADDED
@@ -0,0 +1,214 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { join, dirname } from 'node:path';
5
+ import { NativeService } from './native-service.js';
6
+
7
+ import { promisify } from 'node:util';
8
+ import { assets, verifyPayload } from './assets.js';
9
+ import { atomicJSON, initial, runtimeConfig } from './settings.js';
10
+
11
+ const exec = promisify(execFile);
12
+ const system = join(process.env.SystemRoot || 'C:\\Windows', 'System32');
13
+ const PORT = 56873; // Fixed by the shared engine; never probe its protocol to discover its owner.
14
+ const commandOptions = {
15
+ windowsHide: true,
16
+ timeout: 9500,
17
+ maxBuffer: 8 * 1024 * 1024,
18
+ encoding: 'utf8',
19
+ };
20
+
21
+ // Use numeric endpoints and PID, not localized status text or a WMI provider.
22
+ export function listenerPids(table, port = PORT) {
23
+ const result = new Set();
24
+ for (const line of table.split(/\r?\n/)) {
25
+ const [protocol, local, remote, , pid] = line.trim().split(/\s+/);
26
+ if (
27
+ protocol !== 'TCP' ||
28
+ !local.endsWith(`:${port}`) ||
29
+ !['0.0.0.0:0', '[::]:0'].includes(remote)
30
+ )
31
+ continue;
32
+ if (!/^\d+$/.test(pid)) throw Error('owner-unavailable');
33
+ result.add(Number(pid));
34
+ }
35
+ return result;
36
+ }
37
+ async function checkListener(expectedPid) {
38
+ let table;
39
+ try {
40
+ ({ stdout: table } = await exec(
41
+ join(system, 'netstat.exe'),
42
+ ['-ano'],
43
+ commandOptions,
44
+ ));
45
+ } catch {
46
+ throw Error('owner-unavailable');
47
+ }
48
+ const pids = listenerPids(table);
49
+ if (!pids.size) return false;
50
+ if (pids.size !== 1 || !pids.has(expectedPid)) throw Error('helper-in-use');
51
+ return true;
52
+ }
53
+ export function matchesReady(d, pid, elevated = false) {
54
+ return (
55
+ !!d &&
56
+ d.processId === pid &&
57
+ d.version === assets.version &&
58
+ d.protocolVersion === 7 &&
59
+ d.schemaVersion === 9 &&
60
+ d.desktopManaged === true &&
61
+ d.elevated === elevated
62
+ );
63
+ }
64
+ export class Helper {
65
+ constructor(dir) {
66
+ this.dir = dir;
67
+ this.native = new NativeService(dirname(dir));
68
+ this.native.onExit = () => {
69
+ if (this.child) this.fault = 'native-disconnected';
70
+ this.invalidate();
71
+ };
72
+ this.child = this.ws = this.pending = this.fault = null;
73
+ this.ready = false;
74
+ }
75
+ get running() {
76
+ return !!(this.ready && this.ws?.readyState === 1 && this.child);
77
+ }
78
+ invalidate() {
79
+ this.ready = false;
80
+ this.child = null;
81
+ const ws = this.ws;
82
+ this.ws = null;
83
+ ws?.close();
84
+ this.pending?.fail('helper-disconnected');
85
+ this.onEnd?.();
86
+ }
87
+ async start() {
88
+ if (this.running) return { alreadyRunning: true, elevated: this.elevated };
89
+ if (process.platform !== 'win32' || process.arch !== 'x64')
90
+ throw Error('unsupported-platform');
91
+ await verifyPayload().catch(() => {
92
+ throw Error('payload-invalid');
93
+ });
94
+ await checkListener(null);
95
+ const inert = await runtimeConfig(initial());
96
+ inert.enabled = false;
97
+ await atomicJSON(this.dir, 'config.json', inert);
98
+ return this.launch('start', null);
99
+ }
100
+ async elevation(enabled) {
101
+ if (!this.running) throw Error('helper-disconnected');
102
+ this.invalidate();
103
+ return this.launch('elevation', { enabled });
104
+ }
105
+ async launch(op, data) {
106
+ const session = await this.native.open();
107
+ let info;
108
+ try {
109
+ info = await this.native.send(session, op, data);
110
+ if (!Number.isInteger(info.pid) || !(await checkListener(info.pid)))
111
+ throw Error('owner-unavailable');
112
+ const token = (
113
+ await readFile(join(this.dir, 'auth-token'), 'utf8')
114
+ ).trim();
115
+ if (!/^[a-f0-9]{64}$/i.test(token)) throw Error('helper-start-failed');
116
+ this.child = { pid: info.pid };
117
+ this.elevated = !!info.elevated;
118
+ this.fault = null;
119
+ const ws = new WebSocket(`ws://127.0.0.1:${PORT}`, token);
120
+ this.ws = ws;
121
+ await new Promise((ok, no) => {
122
+ const fail = () => {
123
+ clearTimeout(timer);
124
+ no(Error('helper-disconnected'));
125
+ };
126
+ const timer = setTimeout(() => no(Error('helper-timeout')), 7000);
127
+ ws.addEventListener('error', fail);
128
+ ws.addEventListener('close', () => {
129
+ if (this.ws === ws) {
130
+ this.fault = 'helper-disconnected';
131
+ this.invalidate();
132
+ void this.native.send(session, 'stop').catch(() => {});
133
+ }
134
+ fail();
135
+ });
136
+ ws.addEventListener('message', (event) => {
137
+ if (this.ws !== ws) return;
138
+ let m;
139
+ try {
140
+ m = JSON.parse(event.data);
141
+ } catch {
142
+ return;
143
+ }
144
+ if (!this.ready && m.type === 'helper.ready') {
145
+ if (!matchesReady(m.data, info.pid, info.elevated)) {
146
+ clearTimeout(timer);
147
+ no(Error('incompatible-helper'));
148
+ return;
149
+ }
150
+ clearTimeout(timer);
151
+ this.ready = true;
152
+ this.onFrame?.(m);
153
+ ok();
154
+ return;
155
+ }
156
+ if (!this.ready) return;
157
+ this.onFrame?.(m);
158
+ const p = this.pending;
159
+ if (!p || m.data?.requestId !== p.id) return;
160
+ if (m.type === 'config.applied' && m.data.revision === p.rev) p.ok();
161
+ else if (m.type === 'runtime.error') p.fail('apply-failed');
162
+ });
163
+ });
164
+ return info;
165
+ } catch (e) {
166
+ this.invalidate();
167
+ await this.native.send(session, 'stop').catch(() => {});
168
+ throw e;
169
+ }
170
+ }
171
+ async apply(config, rev, labels) {
172
+ if (!this.running) throw Error('helper-disconnected');
173
+ if (this.pending) throw Error('apply-busy');
174
+ const id = randomUUID();
175
+ return new Promise((resolve, reject) => {
176
+ const finish = (code) => {
177
+ if (this.pending?.id !== id) return;
178
+ clearTimeout(timer);
179
+ this.pending = null;
180
+ code ? reject(Error(code)) : resolve();
181
+ };
182
+ const timer = setTimeout(() => finish('helper-timeout'), 5500);
183
+ this.pending = { id, rev, ok: () => finish(), fail: finish };
184
+ try {
185
+ this.ws.send(
186
+ JSON.stringify({
187
+ id,
188
+ type: 'config.update',
189
+ time: Date.now(),
190
+ data: {
191
+ protocolVersion: 7,
192
+ revision: rev,
193
+ config,
194
+ gestureLabels: labels,
195
+ },
196
+ }),
197
+ );
198
+ } catch {
199
+ finish('helper-disconnected');
200
+ }
201
+ });
202
+ }
203
+ async stop() {
204
+ this.invalidate();
205
+ if (this.native.session)
206
+ await this.native.send(this.native.session, 'stop');
207
+ this.elevated = false;
208
+ this.fault = null;
209
+ }
210
+ async dispose() {
211
+ this.invalidate();
212
+ await this.native.close();
213
+ }
214
+ }
package/host/index.js ADDED
@@ -0,0 +1,142 @@
1
+ import { isAbsolute, join } from 'node:path';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { PanelController } from './panel-controller.js';
4
+ import { metadata, root } from './assets.js';
5
+ export const name = metadata.name;
6
+ export const inject = ['webServer', 'connection', 'profileContext'];
7
+ export const ROUTE = '/convenient-window/control';
8
+ const loopIP = (a) => ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(a);
9
+ export function permitted(req, connection) {
10
+ if (!loopIP(req.socket.remoteAddress) || !loopIP(req.socket.localAddress))
11
+ return false;
12
+ if (
13
+ !/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(
14
+ req.headers.host || '',
15
+ )
16
+ )
17
+ return false;
18
+ if (
19
+ Object.keys(req.headers).some(
20
+ (h) => h === 'forwarded' || h.startsWith('x-forwarded-'),
21
+ )
22
+ )
23
+ return false;
24
+ if (
25
+ req.headers['sec-fetch-site'] &&
26
+ req.headers['sec-fetch-site'] !== 'same-origin'
27
+ )
28
+ return false;
29
+ return connection.requestRejection(req) === undefined;
30
+ }
31
+ export function dataDir(profile) {
32
+ if (!profile || typeof profile.dir !== 'string' || !isAbsolute(profile.dir))
33
+ throw Error('Missing local DSH profile');
34
+ return join(profile.dir, 'convenient-window'); // Never guess the default profile or another host's paths.
35
+ }
36
+ export function handler(ctl, connection) {
37
+ return async (req, res) => {
38
+ const abort = new AbortController();
39
+ res.once('close', () => abort.abort());
40
+ const send = (s, v) => {
41
+ if (res.destroyed) return;
42
+ res.writeHead(s, {
43
+ 'content-type': 'application/json; charset=utf-8',
44
+ 'cache-control': 'no-store',
45
+ 'x-content-type-options': 'nosniff',
46
+ });
47
+ res.end(JSON.stringify(v));
48
+ };
49
+ try {
50
+ if (!permitted(req, connection))
51
+ return send(403, { error: 'local-only' });
52
+ if (req.method === 'GET') return send(200, await ctl.request(null));
53
+ if (req.method !== 'POST') return send(405, { error: 'invalid-command' });
54
+ if (
55
+ req.headers['x-convenient-window'] !== 'panel' ||
56
+ req.headers['content-type']?.split(';')[0] !== 'application/json'
57
+ )
58
+ return send(415, { error: 'invalid-command' });
59
+ const chunks = [];
60
+ let len = 0;
61
+ for await (const chunk of req) {
62
+ len += chunk.length;
63
+ if (len > 1024 * 1024) return send(413, { error: 'invalid-settings' });
64
+ chunks.push(chunk);
65
+ }
66
+ let body;
67
+ try {
68
+ body = JSON.parse(Buffer.concat(chunks).toString());
69
+ } catch {
70
+ return send(400, { error: 'invalid-command' });
71
+ }
72
+ if (!body || typeof body !== 'object' || Array.isArray(body))
73
+ return send(400, { error: 'invalid-command' });
74
+ return send(200, await ctl.request(body, abort.signal));
75
+ } catch (e) {
76
+ const known =
77
+ /^(stale|local-only|invalid-(?:command|settings)|cancelled|entry-changed|pick-again|invalid-state|missing-(?:dsh|profile)|native-(?:busy|disconnected|failed)|admin[A-Z]\w+|settings-unreadable|helper-(?:in-use|disconnected|start-failed|timeout)|stream-expired|stream-busy|owner-unavailable|ordinary-host-required|incompatible-helper|payload-invalid|unsupported-platform|apply-failed|stop-failed|power-off|startup-unavailable|unloaded)$/;
78
+ const code = known.test(e.message) ? e.message : 'host-failed';
79
+ return send(
80
+ code === 'stale' || code === 'helper-in-use'
81
+ ? 409
82
+ : code.startsWith('invalid-')
83
+ ? 400
84
+ : 503,
85
+ { error: code },
86
+ );
87
+ }
88
+ };
89
+ }
90
+ const files = {
91
+ 'panel.html': 'text/html; charset=utf-8',
92
+ 'panel.css': 'text/css; charset=utf-8',
93
+ 'panel.js': 'text/javascript; charset=utf-8',
94
+ 'app-icon.png': 'image/png',
95
+ };
96
+ export function apply(ctx) {
97
+ const ctl = new PanelController(dataDir(ctx.profileContext));
98
+ ctx.effect(() => {
99
+ void ctl
100
+ .activate(process.env.CW_DSH_LOGIN_DIR, process.env.CW_DSH_LOGIN_ADMIN)
101
+ .catch((error) => {
102
+ ctl.helper.fault = error.message;
103
+ });
104
+ return () => ctl.dispose();
105
+ });
106
+ ctx.effect(() =>
107
+ ctx.webServer.register({
108
+ kind: 'exact',
109
+ path: ROUTE,
110
+ handler: handler(ctl, ctx.connection),
111
+ }),
112
+ );
113
+ for (const [file, mime] of Object.entries(files))
114
+ ctx.effect(() =>
115
+ ctx.webServer.register({
116
+ kind: 'exact',
117
+ path: '/convenient-window/' + file,
118
+ handler: async (req, res) => {
119
+ if (!permitted(req, ctx.connection) || req.method !== 'GET') {
120
+ res.writeHead(403);
121
+ res.end();
122
+ return;
123
+ }
124
+ try {
125
+ const bytes = await readFile(join(root, 'lib', file));
126
+ res.writeHead(200, {
127
+ 'content-type': mime,
128
+ 'cache-control': 'no-store',
129
+ 'x-content-type-options': 'nosniff',
130
+ 'referrer-policy': 'no-referrer',
131
+ 'content-security-policy':
132
+ "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; form-action 'none'; base-uri 'none'",
133
+ });
134
+ res.end(bytes);
135
+ } catch {
136
+ res.writeHead(503);
137
+ res.end();
138
+ }
139
+ },
140
+ }),
141
+ );
142
+ }