dsh-notify-me 1.14.7 → 1.15.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/CHANGELOG.md CHANGED
@@ -2,6 +2,48 @@
2
2
 
3
3
  All notable changes to **dsh-notify-me** are documented here.
4
4
 
5
+ ## [1.15.0] — 2026-10-28
6
+
7
+ 收编 [#25](https://github.com/chromoany/dsh-notify-me/pull/25)(回应 [#24](https://github.com/chromoany/dsh-notify-me/issues/24));两项宿主侧能力默认关,未配置时行为与上一版一致。
8
+
9
+ ### 修复
10
+
11
+ - **指向网关的直连目标自动改走同源中继**(本轮报障的直接原因):页面的「自定义」目标如果填的正是宿主中继的上游网关地址,浏览器永远拿不到可读回执——Basic 认证让请求变成预检,而网关回预检时没有 `Access-Control-Allow-*`;转 opaque `no-cors` 兜底又成了**跨站** POST,Apprise 直接回 `403 Cross-site request rejected`。旧版把这种结局记成 `unverified`,设置页于是显示「上次已送出(不可确认)」、测试按钮报「已送出不可确认 1 · 失败 0」,**而消息根本没投出去**。现在这类目标在发送时折叠到同源中继路由(相对路径 → 同源、无预检、无跨站拒绝;凭据由宿主补上,回执是网关真实状态),状态变成「上次成功」。折叠要同时满足 `type: custom`、URL 的主机名与路径都等于中继上游那条地址、目标没有配签名密钥、且目标不是本页同源,差一项就原样直发:别的网关(Discord / Bark / 别的自建中转)本来就不是这条中继能送到的,而同一个网关上不同的 notify key 靠路径区分,只比主机名会把 A key 的提醒发到 B key,配了签名密钥的目标折叠过去则丢了签名。
12
+ - **「未确认」不再读起来像成功**:`unverified` 的文案改为「上次已发出(未确认送达)」(英文 `last delivery unconfirmable`),并把原因一并写进健康记录(`opaque` → 跨域端点读不到回执,是否送达无法确认;`via-relay` → 经同源中继)。旧版只给失败写原因,所以页面在真正失败时也只说「已送出」,用户没有任何线索可查。测试按钮的计数同步改成「未确认送达」。
13
+
14
+ ### 安全加固
15
+
16
+ - **折叠必须命中同一条网关地址**:主机名与路径都要等于中继上游,且目标没有配签名密钥、目标也不是本页同源(详见上面「修复」第一条)。旧写法只比主机名,等于把一个网关上 A key 的提醒悄悄发到 B key。
17
+ - **中继 `POST` 要求 `x-dsh-notify-me-relay: relay` 意图头**:没有它,任何能猜到路径的页面(含跨站 `no-cors` 表单、不带预检的简单请求)都能把宿主当免费推送器;带自定义头必然触发预检,而这条部署的预检必然失败。探针与 `POST` 仍各自过同一道闸门。
18
+ - **上游回执限量读取**:`upstreamBody` 只取前 500 字符(对外口径不变),但底层读取改成 64 KiB 上限的受控读取——旧写法用 `res.text()` 整段读进内存,一个异常或恶意的网关可以让宿主无限读下去。
19
+ - **读客户端 body 时客户端中途挂断也能落定**:以前只等 `end` / `error`,直接断连的请求会让 Promise 永不结算、句柄挂着不还;现在 `close` 同样落定。
20
+ - **凭据读取失败只记路径与错误码**,不打完整错误对象(里面常带绝对路径与系统调用细节)。
21
+ - **页面桥接的生命周期补齐**:探测定时器与三个监听器都进了 `unsubs`,禁用插件或热重载后租约立刻释放、心跳停掉;旧写法在页面已卸载后仍每 60 秒拿回租约,宿主兜底被静默关掉而设置页显示「已启用」。
22
+ - **能力状态如实回报**:`host-bridge` 回的 `hostFallback.enabled` / `relay.enabled` 现在是「能不能真跑」而不是「配置里写没写」——缺网关、缺绝对路径时为 `false`,`features` 同步。旧写法会让页面握着永远等不到的租约,或者往根本没挂载的中继路由发提醒、把网关的沉默记成一次「拒绝」。
23
+
24
+ ### 新增
25
+
26
+ - **`host-bridge` 公布中继的上游端点**(`relay.upstreamHost` / `relay.upstreamPath`,只发布主机名与路径,不含凭据与路径 token):页面靠它们判断某个直连目标是不是「中继自己的那个网关端点」——只比主机名会在一个网关挂着多个 notify key 时发错。`debug().hostBridge` 同步暴露 `relayUpstreamHost` / `relayUpstreamPath`;设置页会在会被折叠的目标下显示一行说明,免得用户以为那个地址在浏览器里本来就能用。
27
+
28
+ - **页面关闭后的宿主侧兜底**(`lib/host-fallback.js`,默认关):订阅宿主的 `session/event`,页面不在时继续把「审批请求」「回复完成」发往配置的网关——**文案与页面通知逐字一致**(标题 `<前缀> · 审批请求` / `<前缀> · 回复完成`;正文「回复完成」只有会话名、审批是 `会话名:工具名 · 原因`),不含任何用户消息正文,因此不会把注入的 `<system-reminder>` / 记忆上下文 / 时间戳带进通知。审批按 id 去重(每会话缓存上限 500)、`turn/end` 每会话按 `turnEndThrottleMs`(默认 15000 ms)节流(只管 `completed`,`aborted` / `error` / `max-tokens` 这些收尾不节流:它们本来就少,而且往往是最该看到的那一条)、子代理会话默认跳过、`language: 'auto'` 时跟随页面心跳报告的语言;`turn/end` 的 `reason` 按对象 `{kind}` 读取,`completed` 之外的收尾会把 kind 附在正文;`session/disposed` 用独立事件清缓存(它不是会话日志项)。
29
+ - **同源中继**(`lib/relay.js`,默认关):`<relay.path>` 上 `GET` / `HEAD` 是只读探针,`POST` 把页面载荷映射为网关的 `{title, body, type:'info'}`(不透传 `tag`——Apprise 把未匹配的 tag 当 424)、由宿主补上凭据与 `gateway.headers` 转发,回 `200 {ok, upstreamStatus, upstreamBody}`(`upstreamBody` 上限 500 字符);上游非 2xx 回 `502`,凭据文件配了但读不出来回 `503`,上游异常或网关回 3xx 回 `502 {reason:'upstream-error'}`(跳转不跟:跟过去会把 body 和 `Authorization` 重放到别处);`POST` 必须带 `x-dsh-notify-me-relay: relay` 意图头,缺了回 `403 {reason:'missing-intent'}`(跨站表单发不出自定义头,要发就得多一次预检,而预检在网关这里必然失败)。启用需要绝对路径与可达的 `relay.target`,否则不注册路由,只在日志里留一行 warning,状态回包也如实报「未启用」。
30
+ - **页面在线租约**(`lib/page-bridge.js` 的 `createPresence`):页面 `GET` 探测 `/__dsh-notify-me/host-bridge`,只在 `hostFallback.enabled` 为真时心跳(间隔 `leaseMs/3`,夹在 5–20 秒),`pagehide` 发 `{alive:false}` 立刻释放;租约默认 60000 ms,`pageLeaseMs: 0` 关闭协调(页面开着也会重复,仅调试用)。心跳 body 只承载 `{alive, language}`:语言让宿主文案跟着页面走,页面自己的推送开关与可见性判定不进宿主(规则是「没有页面持有租约时宿主接手」,只照做一半会得到谁也算不清的规则)。
31
+ - **共享请求闸门泛化**(`lib/page-bridge.js` 的 `gateRequest`):从抬窗路由迁出并新增「由 `allowedOrigins` 派生的公网 `Host`」一档,供隧道 / 反代下的页面入口使用;不传 `allowedOrigins` 的抬窗路由行为与旧版一致。同源判定按连接的实际协议与端口补齐默认值(`Host` 里不写端口时,`https` 按 443、`http` 按 80 与 `Origin` 比较,反代下的 `Host: example.com` 配 `Origin: https://example.com` 不再被误判 `cross-origin`)。宿主兜底与中继的宿主入口不再各自实现一份闸门。
32
+ - **凭据读取器**(宿主内):0600 JSON 支持 `{user, password}`(HTTP Basic)与 `{authorization}`(原样发送;裸 token 补 `Bearer `);未配置凭据文件时请求不带认证头(多数 webhook 端点本就不需要认证),只有「配了路径但读不出来」才算凭据不可用;缓存只在宿主进程内,网关回 401 / 403 时丢缓存重读文件、只重试一次,所以轮换密码不需要重启宿主;读失败时日志只写「哪个路径读不出来」与错误码,不打错误对象(里面常带完整路径与系统调用细节)。
33
+ - 设置页「高级设置 → 外部推送」新增两行只读状态:「宿主侧兜底」(已启用 · 页面关闭后仍会推送 / 未启用 / 宿主未响应)与「同源中继」(已启用 + 可复制的 `location.origin` + `relay.path`)。`debug()` 新增 `hostBridge: {state, leaseMs, relayEnabled, relayPath, relayUpstreamHost, relayUpstreamPath, lastReason, lastProbeAt, lastBeaconAt}`(`lastReason` 只在上一次探测失败时带值,如 `bad-host` / `cross-origin` / `http-403`)。中英文案同时补齐(`TXT.zh` / `TXT.en` 与 `UI_zh` / `UI_en`)。
34
+
35
+ ### 测试
36
+
37
+ - 新增 `smoke/page-bridge-test.mjs`(状态回包形状、心跳与释放、缺意图头 `403`、跨源 `403`、坏 JSON `400`、超长 `413`、`allowedOrigins` 派生 `Host` 放行、路径冲突、同源判定的端口默认值(`https` / `http` 隐式端口、`Host` 不带端口)、缺失网关时兜底与中继都不报「已启用」)、`smoke/host-fallback-test.mjs`(审批去重、`turn/end` 节流且只节流 `completed`、子代理跳过、租约新鲜时不发、租约过期后发、`alive:false` 后立刻发、语言跟随心跳、401 重读凭据、健康探针)、`smoke/relay-route-test.mjs`(`GET` 探针、`405`、跨源 `403`、缺意图头 `403` 且不碰上游、`413`、`400`、`503`、`200` / `502` 映射、401 只重试一次)。
38
+ - `smoke/smoke-test.cjs` 补页面侧用例:探测回「已启用」时发出心跳且语言正确、404 时不心跳、`pagehide` 发 `alive:false` 并停心跳、`debug().hostBridge` 字段形状(含 `relayUpstreamHost` / `relayUpstreamPath`)。
39
+ - `smoke/smoke-test.cjs` 补中继折叠用例:指向中继上游网关的 `custom` 目标被改写到中继路径、请求带 `x-dsh-notify-me-relay: relay` 意图头、状态为 `sent`、载荷仍带标题与正文且不是 opaque 请求;路径相同但主机不同、主机相同但路径不同(同一网关的另一个 key)、以及配了签名密钥的目标都不被改写;中继关闭时目标直发并落到 `unverified` + `reason:'opaque'`(变异测试确认这些断言会失败)。
40
+ - `npm test` 串上三个新套件(顺序:smoke-test → host-route → page-bridge → host-fallback → relay-route → cordis-host);三个新套件自带假 `ctx`,不依赖本机 DSH、不联网。`package.json` 的 `files` 增加三个新模块。
41
+
42
+ ### 文档
43
+
44
+ - README 中英:顶部特性与运行前提改成准确口径(本地通知仍要页面在;开启宿主兜底后外部推送由宿主接着发);「高级设置」新增「页面关闭后:宿主侧兜底与同源中继」小节(可粘贴的 profile 覆盖示例、逐键默认值、0600 凭据文件、租约去重语义、健康探针、中继的三条 CORS 事实与 `200` / `502` / `503` / `400` / `405` / `413` 口径、`allowedOrigins` 与隧道 / 反代的 `Host` 闸门);中继 `POST` 补意图头与 3xx 不跟随的说明,折叠条件补「主机名 + 路径都要一致、带签名密钥不折叠、同源不折叠」,节流口径补「只管 `completed`」,`host-bridge` 回包补 `upstreamHost` / `upstreamPath`,`debug()` 补 `relayUpstreamHost` / `relayUpstreamPath`;提醒渠道表补两行;已知限制补运行前提与仍然成立的边界(宿主进程需在运行、代理环境要配 `no_proxy`);开发自检补三个 smoke 套件。
45
+ - SECURITY 中英:数据处理范围补宿主兜底与同源中继(同样的会话名 / 审批文本由宿主发往你自己的网关、凭据只在宿主 0600 文件、中继路径等同口令、闸门新增 `allowedOrigins` 派生 `Host` 一档);把「路径只对能过闸门的调用方可见、随机性挡猜路径而闸门挡不速之客」与折叠的同源性判据写进威胁模型,受理范围补中继能力路径被绕过与租约协调缺陷。
46
+
5
47
  ## [1.14.7] — 2026-10-27
6
48
 
7
49
  ### 修复
package/README.en.md CHANGED
@@ -12,6 +12,7 @@
12
12
  [![npm downloads](https://img.shields.io/npm/dm/dsh-notify-me?style=flat-square&label=downloads%2Fmonth&color=1F883D)](https://www.npmjs.com/package/dsh-notify-me)
13
13
  [![npm total downloads](https://img.shields.io/npm/dt/dsh-notify-me?style=flat-square&label=total%20downloads&color=1F883D)](https://www.npmjs.com/package/dsh-notify-me)
14
14
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](LICENSE)
15
+ [![test](https://github.com/chromoany/dsh-notify-me/actions/workflows/test.yml/badge.svg)](https://github.com/chromoany/dsh-notify-me/actions/workflows/test.yml)
15
16
  [![DSH Web and Desktop](https://img.shields.io/badge/DSH-Web%20%7C%20Desktop-blue?style=flat-square)](#installation)
16
17
  [![Package size](https://img.shields.io/npm/unpacked-size/dsh-notify-me?style=flat-square&label=package%20size)](https://www.npmjs.com/package/dsh-notify-me)
17
18
  [![DSH Compatibility](https://img.shields.io/badge/DSH-tested%200.2.1--rc.2-6366f1.svg?style=flat-square)](#compatibility)
@@ -27,8 +28,9 @@ A notification plugin for DSH Web / Desktop, so you can afford to keep full acce
27
28
  - **When a background reply finishes:** come back for the result; clicking the notification returns to that conversation. Pick "background only", "quiet for the open one", or "always".
28
29
  - **When you walk off but the window stays in front:** over 3 minutes without input counts as away, and the alert still fires as usual; the toast that arrived does not clear itself before you come back.
29
30
  - **When you leave your computer:** optionally forward alerts to Discord, Bark, Gotify, Feishu group bots, ServerChan, WxPusher, or your own webhook.
31
+ - **When you close the page entirely:** optional host-side fallback — with no page open the host process keeps pushing "needs you" / "reply finished" to your gateway; or turn on just the same-origin relay so the page can reach an authenticated gateway. Both are off by default and configured in the profile's patch layer (see "After the page closes" under [Advanced](#advanced)).
30
32
 
31
- > The page or desktop app has to stay running (background / minimized is fine); system notifications need notification permission. Approval buttons rely on a Service Worker, so only Web has them — Desktop notifications carry no buttons, and clicking one takes you back to the conversation to decide.
33
+ > The page or desktop app has to stay running (background / minimized is fine); system notifications need notification permission. Approval buttons rely on a Service Worker, so only Web has them — Desktop notifications carry no buttons, and clicking one takes you back to the conversation to decide. With host-side fallback enabled you still get external push once the page is closed — local toasts and the approval buttons still need the page.
32
34
 
33
35
  ## UI Preview
34
36
 
@@ -80,7 +82,7 @@ Web users can also test the approval buttons, which then appear on the notificat
80
82
  window.__dshNotifyMe.test("done") // "reply finished" sample
81
83
  window.__dshNotifyMe.test("attention") // "needs you" sample
82
84
  window.__dshNotifyMe.test("approval") // Approve / Reject when the bridge is available; a plain notification otherwise (which is what Desktop gets)
83
- window.__dshNotifyMe.debug() // bridge ("active" = buttons work), raiseChannel, the last raise attempt in raiseLast, a refused toast's platform message in lastToastReject, and configStored for whether the settings really persisted
85
+ window.__dshNotifyMe.debug() // bridge ("active" = buttons work), raiseChannel, the last raise attempt in raiseLast, a refused toast's platform message in lastToastReject, configStored for whether the settings really persisted, and hostBridge for host coordination
84
86
  ```
85
87
 
86
88
  If no test notification appears, check in this order: whether the notification permission was declined (click once on the page and choose **Allow**; or address-bar lock → Site settings → Notifications → Allow → reload), whether DSH was restarted after installing, and whether the browser's notifications are switched off in the OS settings.
@@ -169,6 +171,98 @@ Off by default. Supports Discord Webhook / Bark / Gotify / Feishu group bots / S
169
171
 
170
172
  </details>
171
173
 
174
+ #### After the page closes: host-side fallback and the same-origin relay
175
+
176
+ Both live in the host process (`lib/host-fallback.js`, `lib/relay.js`, optional modules inside the package) and both are off by default: with no config the host registers the raise-window route and nothing else, so behaviour is identical before and after the upgrade. They are configured in the profile's patch layer, not on the Settings page — they make the host act on the page's behalf, they are not browser preferences; the Settings page only reports the state it probed.
177
+
178
+ <details>
179
+ <summary>Host-side fallback: the host keeps pushing after the page closes</summary>
180
+
181
+ With no page open the browser half does not run, and that is where alerts stop. The host-side fallback subscribes to the host's session event feed (`session/event`) and pushes the same two alerts to your gateway on its own once the page is closed.
182
+
183
+ An override example for the profile (`~/.dsh/profiles/<profile>/cordis.patch.yml`). **`config` is replaced wholesale, not deep-merged**: a patch row naming the same `id` assigns the whole `config`, which is why the example spells out all three blocks — an omitted key falls back to the plugin's own defaults (the same values as the bundled YAML), but a `gateway.target` wiped along with it does not come back on its own.
184
+
185
+ ```yaml
186
+ - id: notify-me
187
+ config:
188
+ allowedOrigins: [] # top level: page-entry allow-list; empty = loopback / bind address only (all three host routes)
189
+ gateway:
190
+ target: '' # e.g. https://cue.example/notify/<key>
191
+ credentialsFile: '' # mode-0600 JSON, see below
192
+ headers: {} # extra request headers, optional
193
+ hostFallback:
194
+ enabled: true
195
+ target: '' # empty = use gateway.target
196
+ credentialsFile: '' # empty = use gateway.credentialsFile
197
+ events: ['turn/end', 'approval/asked']
198
+ includeSubagents: false
199
+ turnEndThrottleMs: 15000
200
+ titlePrefix: 'DSH'
201
+ language: 'auto' # auto | zh | en
202
+ pageLeaseMs: 60000 # 0 = no coordination with the page (duplicates while it is open)
203
+ healthPath: '/__dsh-notify-me/host-fallback'
204
+ relay:
205
+ enabled: false
206
+ path: ''
207
+ target: ''
208
+ credentialsFile: ''
209
+ ```
210
+
211
+ Key by key (defaults in parentheses):
212
+
213
+ - `enabled` (`false`): off means the host subscribes to nothing and registers no health probe;
214
+ - `target` / `credentialsFile` (empty): empty falls back to `gateway.*`; with both empty there is nowhere to push, so the module is not mounted at all and only one warning line lands in the host log — easier to act on than a failed delivery every time;
215
+ - `events` (`['turn/end', 'approval/asked']`): the events to push; listing one gives you only that one;
216
+ - `includeSubagents` (`false`): sessions with `origin === 'subagent'` are skipped by default, for the same reason as on the page side — they are steps inside the parent conversation's turn;
217
+ - `turnEndThrottleMs` (`15000`): one "reply finished" per session inside that window; the window is only spent when an alert actually went out, so one held off by the lease does not consume it. The throttle covers `completed` only — `aborted` / `error` / `max-tokens` ends are never throttled: they are rare to begin with, and they are usually the one alert you want to see;
218
+ - **The copy matches the page's own toast verbatim**: the title is `<prefix> · Reply finished` / `<prefix> · Approval request`, the body is the session name for a finished turn and `session: tool · reason` for an approval — never any of the user message text (a user message often carries injected `<system-reminder>` blocks, memory context and timestamps, which make a notification unreadable); an abnormal end (`aborted` / `error` / `max-tokens`, …) appends a short parenthetical such as ` (error)`;
219
+ - `titlePrefix` (`DSH`): titles read `<prefix> · Approval request` / `<prefix> · Reply finished` (the page's own labels);
220
+ - `language` (`auto`): `auto` follows the language of the page's last heartbeat and only falls back to Chinese with no heartbeat at all; `zh` / `en` force one;
221
+ - `pageLeaseMs` (`60000`): the page's online lease, see "deduplication" below;
222
+ - `healthPath` (`/__dsh-notify-me/host-fallback`): the path of the read-only health probe.
223
+
224
+ **The credentials file** is a mode-0600 JSON file readable by the host user, holding `{"user": "...", "password": "..."}` (sent as HTTP Basic) or `{"authorization": "Bearer ..."}` (sent verbatim; a bare token gets `Bearer ` prepended). It must not go into the patch layer — that layer is world-readable and lands in the profile directory. Leaving the key empty sends the request without an authentication header: plenty of webhook endpoints never ask for one, and treating a missing credentials file as an error would make every alert fail; only a path that is configured and unreadable counts as credentials-unavailable. When the gateway answers 401 / 403 the host drops the cached credential, re-reads the file and retries exactly once, so a rotated password needs no host restart.
225
+
226
+ **Deduplication rides on one page online lease**: on load the page probes `GET /__dsh-notify-me/host-bridge` once (and again every 60 s; no probe while the page is hidden, one catch-up probe when it becomes visible), and it only starts heartbeating when the reply says `hostFallback.enabled === true` — the body carries `{alive, language}` only, the interval is `leaseMs/3` clamped to 5–20 s, and `pagehide` releases immediately with one `{alive:false}` (sent with `keepalive`). A fresh host-side lease means no fallback push (the page is delivering), while an expired lease or an `alive:false` hands over, waiting at most `pageLeaseMs`. The heartbeat carries the language, not the page's push switches: the rule is simply that the host takes over while no page holds the lease, and the page's own visibility and idle heuristics are invisible to the host — honouring half of them would produce a rule nobody can predict. The language it brings is what keeps an English page from getting Chinese host alerts, and it applies whenever `language: 'auto'`. `pageLeaseMs: 0` turns coordination off so the host always pushes — the page then gets everything twice while it is open, so use it for debugging only.
227
+
228
+ **The two route contracts**: the probe the page calls, `GET /__dsh-notify-me/host-bridge`, answers `{ok, version, features, hostFallback:{enabled, leaseMs}, relay:{enabled, path, upstreamHost, upstreamPath}, language, page:{alive, ageMs}}` (`upstreamHost` / `upstreamPath` name the gateway the host forwards to, present only while the relay is enabled; the credential is never published); it is only registered while `hostFallback.enabled` or `relay.enabled` is true, so on a stock install it is a 404 and the page reads that as "off" rather than as a fault. The heartbeat `POST` requires the intent header `x-dsh-notify-me-page: bridge` (missing header → `403`), answers `400` to bad JSON and `413` to a body over 16 KiB, and `200 {ok, leaseUntil}` on success.
229
+
230
+ **The health probe**: `GET <healthPath>` answers `{ok, version, enabled, events, includeSubagents, pageAlive, lastDelivery: {at, ok, status} | null}`, and any other method gets `405`. It shares the same gate as the other host entry points: the peer has to be this machine (loopback, or the exact address the listener itself is bound to), the `Host` has to be a loopback name, that bind address, or a public name derived from `allowedOrigins`, and a request that fails either is answered `403` with `reason` (`bad-remote` / `bad-host` / `cross-origin`). The probe carries no credential and forwards nothing — it is what you curl from a terminal to confirm that this host process is pushing at all and how the last delivery went.
231
+
232
+ **Behind a tunnel or reverse proxy `allowedOrigins` is mandatory**: there the `Host` reaching the host is the public domain rather than a loopback address, and `allowedOrigins` is both the `Origin` allow-list and the source of the public `Host` names that are accepted. Without it the page's heartbeat is refused as `bad-host` (the settings row reads "Host did not answer" and the note underneath points you at the top-level `allowedOrigins`), and the host pushes duplicates for a page that is open — exactly the duplication the lease exists to prevent.
233
+
234
+ </details>
235
+
236
+ <details>
237
+ <summary>Same-origin relay: reaching a gateway that wants authentication</summary>
238
+
239
+ The page pushes to its external targets with its own `fetch`, and a gateway behind Basic auth is a dead end, blocked three separate ways:
240
+
241
+ 1. Credentials in the URL (`https://user:pass@host/…`): `fetch` throws before a byte leaves;
242
+ 2. An `Authorization` header: the request turns into a preflighted one, and a gateway like Apprise answers no `Access-Control-Allow-*` at all, so the preflight fails;
243
+ 3. The `no-cors` fallback: it cannot carry a custom header, which amounts to no authentication at all.
244
+
245
+ The page is left reporting "sent but unverifiable". The same-origin relay moves that leg into the host: the page POSTs to a route on its own origin, the host adds the credentials and calls the gateway, then answers the page with the gateway's real status.
246
+
247
+ Enabling it takes `relay.enabled: true`, an absolute `relay.path`, `relay.target` (empty falls back to `gateway.target`) and `relay.credentialsFile` (empty falls back to `gateway.credentialsFile`). The path is itself the capability — knowing it is enough to make the host send a notification for you, so it is worth as much as a password; keep a random token in it: `/__dsh-notify-me/relay/<32 hex token>`.
248
+
249
+ How to use it: **Settings → Notify me → Advanced → External push** gains two read-only rows, and the "Same-origin relay" one shows `Enabled · address: <origin><relay.path>`; paste that absolute address into the URL of a **custom webhook** target on the same page, and the page never has to know the credentials.
250
+
251
+ You do not have to change the address either: **a "custom webhook" target that names the relay's own upstream gateway is folded onto the relay route when it is sent.** Such an address cannot work from a browser (the three CORS facts above block it, and the `no-cors` fallback is a *cross-site* POST that Apprise answers `403 Cross-site request rejected`), and older builds recorded that as `unverified` — the settings row read "last delivery sent-unverified" and the test button reported "sent-unverified", **while the phone stayed silent**. Folded, the request stays same-origin and the host adds the credential, so the verdict is the gateway's real status. Folding requires all of: the target is of type "custom", its URL's host equals `relay.upstreamHost`, its path equals `relay.upstreamPath`, it carries no signature secret (the signature is computed in the page and the relay cannot carry it), and it is not already same-origin with this page. If either the host or the path differs it is posted exactly as configured — one gateway usually serves several notify keys by path, so comparing the host alone would send key A's alert to key B; the settings page prints a note under any target that will be folded.
252
+
253
+ Behind a tunnel or reverse proxy the relay passes the same `Host` gate as the bridge route: put the page's public origin in the top-level `allowedOrigins`, or both the probe and the `POST` are refused as `bad-host`.
254
+
255
+ What comes back (which is how the page turns "sent but unverifiable" into something checkable):
256
+
257
+ - `GET` / `HEAD` `<relay.path>` → `200 {ok, route, version, enabled}`: a read-only probe that forwards nothing and carries no credential, but it does go through **the same gate as the other host entry points** — the path itself is the capability, so an ungated probe would tell whoever guessed it that the guess was right; use it to confirm that this process mounted the path you configured;
258
+ - `POST` → reads the body (64 KiB cap), requires a JSON object, maps it onto the gateway's `{title, body, type:'info'}` (the payload's `tag` is deliberately not forwarded: Apprise treats a tag as a service filter, and an unmatched one answers 424), and attaches `gateway.headers` plus the credentials; the request must carry the `x-dsh-notify-me-relay: relay` intent header, without it the answer is `403 {reason:'missing-intent'}` — a cross-site form post cannot set a custom header, and setting one costs a preflight the gateway always fails;
259
+ - `200 {ok, upstreamStatus, upstreamBody}` (with `upstreamBody` at most 500 characters) — the forward succeeded; a non-2xx from the gateway answers `502` in the same shape;
260
+ - `400` (bad or empty JSON body), `413` (body over the cap), `405` (wrong method), `403` (refused by the gate, or a missing intent header), `503` (a credentials file is configured but cannot be read), `502 {reason:'upstream-error'}` (the upstream call itself failed, or the gateway answered 3xx — redirects are not followed, because following one would replay the body and the `Authorization` header somewhere else).
261
+
262
+ Credentials stay in the host: the page cannot read them, and they are never echoed into a response or a log line. The `POST` goes through the same gate as the other host entry points, so a forged caller (a cross-site page, a DNS-rebinding page) is refused even if it learns the path.
263
+
264
+ </details>
265
+
172
266
  #### Runtime & diagnostics
173
267
 
174
268
  The last block inside Advanced. The page protocol is detected automatically to tell Web from Desktop (DSH Desktop, `dsh-app://`); override it by hand if detection is wrong — on Windows a toast click goes through the host route for native raising, on macOS / Linux through the `dsh://open` deep link (see [How the Desktop window gets raised](#how-the-desktop-window-gets-raised)), and it carries no quick-decision buttons, while Web uses `window.focus()` plus the Service Worker bridge. When the manual override disagrees with detection the page says so.
@@ -190,8 +284,10 @@ The last block inside Advanced. The page protocol is detected automatically to t
190
284
  | Sound | WebAudio cue by default, with different patterns for "needs you" and "done"; swap in a custom audio file, or hand the sound over to the system notification sound |
191
285
  | Tab title | `🔔 Action needed · …` / `✅ Reply finished · …`, following the alert language; gone once you open that session, and both markers can be up at the same time |
192
286
  | External push (optional, default off) | Forwards the same alert to Discord / Bark / Gotify / Feishu / ServerChan / WxPusher / a custom webhook |
287
+ | Host-side fallback (optional, default off) | After the page closes the host process keeps pushing "needs you" / "reply finished" to your gateway; needs profile config and a mode-0600 credentials file |
288
+ | Same-origin relay (optional, default off) | The page POSTs to a host route on its own origin, the host adds the credentials and forwards to an authenticated gateway, answering with the gateway's real status |
193
289
 
194
- This is a **browser-layer** plugin: the DSH page has to stay open (minimized or backgrounded is fine — that is exactly the "away" state it watches for).
290
+ This is primarily a **browser-layer** plugin: local toasts, sound and the title marker still only work while the page is open (minimized or backgrounded is fine — that is exactly the "away" state it watches for); with host-side fallback enabled, external push keeps going from the host process once the page is closed.
195
291
 
196
292
  ## Compatibility
197
293
 
@@ -264,6 +360,8 @@ window.__dshNotifyMe.testExternal() // explicit outbound test to v
264
360
  > Picked audio files do not live in `dshNotifyMe.config`: each kind gets its own key (`dshNotifyMe.sound.done` / `dshNotifyMe.sound.attention`, holding a `{name, size, data}` data URL), because one file inflates by ~1.37× once turned into a data URL and would slow down every config read. `resetConfig()` clears both keys along with the config.
265
361
  >
266
362
  > To confirm which source is actually in effect, check `soundDone` / `soundAttention` and `customSoundDone` / `customSoundAttention` in `window.__dshNotifyMe.debug()`.
363
+ >
364
+ > `debug().hostBridge` is the read-only snapshot of host coordination: `state` (`idle` the probe has not answered yet; `active` the host has a fallback and this page is holding the lease with its heartbeat; `unavailable` the host is there but offers no fallback, which is what a stock install looks like — an unregistered 404 route counts here too and is not a fault; `error` the host answered nothing usable, or the gate refused this page outright), `leaseMs` (the lease the host granted, in milliseconds), `relayEnabled` and `relayPath` (the relay route, when the host enabled one), `relayUpstreamHost` / `relayUpstreamPath` (the gateway endpoint the fold matches), `lastReason` (why the last probe failed — `bad-host` / `cross-origin` / `http-403` — and `null` when it was not a fault), and `lastProbeAt` / `lastBeaconAt` (the last probe and the last heartbeat, as ISO strings or `null`). A gate refusal reads as `error` rather than as "off", because it is a configuration the user can fix: add this page's origin to the top-level `allowedOrigins` of the `- id: notify-me` entry in the profile.
267
365
 
268
366
  </details>
269
367
 
@@ -323,7 +421,7 @@ The cases where it will not raise are the same ones listed under [Known limitati
323
421
 
324
422
  **Runtime prerequisites**
325
423
 
326
- - The page must be open for alerts to fire (background tab / minimized is fine; closing the tab stops it — inherent to a browser-layer plugin).
424
+ - By default alerts only fire while the page is open (a background tab / minimized is fine; closing the tab stops it — inherent to a browser-layer plugin). With host-side fallback enabled you still get **external push** while the page is closed: it needs `hostFallback.enabled: true`, `gateway.target` (or `hostFallback.target`) and a mode-0600 credentials file in the profile, and the host process itself running.
327
425
  - Notifications come through the browser, so notification permission must be granted; the first sound / toast after each page load needs one click on the page first; without permission only the sound and the title marker are left.
328
426
  - System notification banners are drawn on the primary display only: Windows has no setting and Chromium no API to aim one at another monitor (on a multi-monitor setup the second screen never gets them). The only way across screens is external push to your phone (since 1.12.0 the page no longer draws an approval card).
329
427
  - Config lives in browser `localStorage`: switching browsers / devices or clearing site data returns to the defaults (the Settings page restores them in one click).
@@ -345,6 +443,7 @@ The cases where it will not raise are the same ones listed under [Known limitati
345
443
  **External push**
346
444
 
347
445
  - Bounded by browser CORS: an endpoint that does not allow cross-origin degrades to "sent but unverifiable" (no-cors) and is labelled as such; Discord, Feishu, ServerChan and WxPusher do allow cross-origin, so delivery to them is confirmed. DingTalk allows no CORS header at all and only accepts `application/json`, so a page cannot send to it — hence no DingTalk target type (relay it through your own box and use a custom target). A transient failure (network error, 5xx, 429) is retried on the backoff, and a delivery that still fails lands in the failure log; anything else stops at once, no retry. Forwarding is triggered only after the local alert has decided to fire, so an alert muted by the rules is never sent out either.
446
+ - The same-origin relay closes exactly one of those gaps — a page reaching a gateway that wants authentication: the page POSTs to a same-origin route, the host adds the credentials and answers with the gateway's real status. What still holds: both the relay and the host-side fallback need the host process running (`dsh web` or the Desktop main process) — neither is a standalone daemon, so quitting the host stops both; on a host behind a proxy the gateway host has to be in `no_proxy`, or the delivery leaves through the proxy instead; the fallback only covers external push, so local toasts, sound, the title marker and the approval buttons still need the page; `pageLeaseMs: 0` is a debugging switch that gets an open page everything twice; and the relay path is a password, so keep it out of public records.
348
447
 
349
448
  **Settings icon patch**
350
449
 
@@ -355,11 +454,13 @@ The cases where it will not raise are the same ones listed under [Known limitati
355
454
  ```sh
356
455
  node --check lib/client.js
357
456
  node --check lib/index.js
358
- npm test # smoke-test (state machine) + host-route-test (host half) + cordis-host-test
457
+ npm test # smoke-test (state machine) + host-route-test (host half) + page-bridge-test + host-fallback-test + relay-route-test + cordis-host-test
359
458
  npm pack --dry-run # preview the published tarball
360
459
  ```
361
460
 
362
- `smoke/smoke-test.cjs` is the offline state-machine suite: three host generations + master switch + zh/en cases + the quick-decision bridge (worker half included) + idle detection and toast self-dismiss + toast tag length handling. `smoke/host-route-test.mjs` needs no local DSH and runs the `lib/index.js` route, its probe and the 403/405/501 gate on every platform.
461
+ `smoke/smoke-test.cjs` is the offline state-machine suite: three host generations + master switch + zh/en cases + the quick-decision bridge (worker half included) + idle detection and toast self-dismiss + toast tag length handling + the page's host-bridge probe / heartbeat / release and the shape of `debug().hostBridge`. `smoke/host-route-test.mjs` needs no local DSH and runs the `lib/index.js` route, its probe and the 403/405/501 gate on every platform.
462
+
463
+ The three new suites also ship their own fake `ctx`, need no local DSH and touch no network: `smoke/page-bridge-test.mjs` runs the page-bridge route — status shape, heartbeat and release, missing intent header `403`, cross-origin `403`, bad JSON `400`, oversized `413`, the `allowedOrigins`-derived `Host` (a simulated tunnel) being let through, and path collisions; `smoke/host-fallback-test.mjs` runs the host fallback — approval dedupe, `turn/end` throttling, subagent skip, no push on a fresh lease, a push after the lease expires, an immediate push after `alive:false`, language following the heartbeat, credentials re-read after a 401, and the health probe; `smoke/relay-route-test.mjs` runs the relay — the `GET` probe, `405`, cross-origin `403`, `413`, `400`, `503`, the `200` / `502` mapping and "retry exactly once on a 401".
363
464
 
364
465
  When `lib/focus-window.ps1` changes (Windows only), also run it by hand:
365
466
 
@@ -384,6 +485,7 @@ powershell -NoProfile -File lib/focus-window.ps1 -ProcessId 0 # the last line
384
485
  | <a href="https://github.com/Donald-Yip"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/Donald-Yip.png" width="40" height="40" alt="@Donald-Yip"></a> | [#18](https://github.com/chromoany/dsh-notify-me/issues/18): the report that a Windows notification tag over the 64-character cap made the platform silently reject the approval test toast |
385
486
  | <a href="https://github.com/dunxuan"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/dunxuan.png" width="40" height="40" alt="@dunxuan"></a> | [#20](https://github.com/chromoany/dsh-notify-me/issues/20): the report that alerts for the open session showed a placeholder instead of the session title |
386
487
  | <a href="https://github.com/unnamed42"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/unnamed42.png" width="40" height="40" alt="@unnamed42"></a> | [#21](https://github.com/chromoany/dsh-notify-me/issues/21) / [#22](https://github.com/chromoany/dsh-notify-me/pull/22): the Linux `dsh://open` raise-path report and patch, which brought the deep link back on macOS / Linux in 1.14.4 |
488
+ | <a href="https://github.com/LIEGU0317"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/LIEGU0317.png" width="40" height="40" alt="@LIEGU0317"></a> | [#24](https://github.com/chromoany/dsh-notify-me/issues/24) / [#25](https://github.com/chromoany/dsh-notify-me/pull/25): the host-side fallback push and same-origin relay modules (optional, off by default), with tests and docs |
387
489
 
388
490
  Attribution policy: external PRs are landed as maintainer commits — the original commit is not reused and no Co-authored-by trailer is added, so GitHub's contributors graph lists the maintainer only and contributors are credited above.
389
491
 
package/README.md CHANGED
@@ -12,6 +12,7 @@
12
12
  [![npm downloads](https://img.shields.io/npm/dm/dsh-notify-me?style=flat-square&label=downloads%2Fmonth&color=1F883D)](https://www.npmjs.com/package/dsh-notify-me)
13
13
  [![npm total downloads](https://img.shields.io/npm/dt/dsh-notify-me?style=flat-square&label=total%20downloads&color=1F883D)](https://www.npmjs.com/package/dsh-notify-me)
14
14
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue?style=flat-square)](LICENSE)
15
+ [![test](https://github.com/chromoany/dsh-notify-me/actions/workflows/test.yml/badge.svg)](https://github.com/chromoany/dsh-notify-me/actions/workflows/test.yml)
15
16
  [![DSH Web and Desktop](https://img.shields.io/badge/DSH-Web%20%7C%20Desktop-blue?style=flat-square)](#安装)
16
17
  [![Package size](https://img.shields.io/npm/unpacked-size/dsh-notify-me?style=flat-square&label=package%20size)](https://www.npmjs.com/package/dsh-notify-me)
17
18
  [![DSH Compatibility](https://img.shields.io/badge/DSH-%E5%B7%B2%E9%80%82%E9%85%8D%200.2.1--rc.2-6366f1.svg?style=flat-square)](#兼容性)
@@ -27,8 +28,9 @@ DSH Web / Desktop 的通知插件,让你敢不开完整访问,也不必一
27
28
  - **后台回复完成时**:及时回来查看结果,点击通知可回到对应对话;提醒时机可选「仅后台 / 仅当前对话静默 / 总是提醒」。
28
29
  - **人走开但窗口没走**:窗口留在最前台、人却离开座位,超过 3 分钟没有输入也算离开,该提醒的照常提醒;收到的那条通知不会在你回来之前自己消失。
29
30
  - **离开电脑时**:可选转发到 Discord、Bark、Gotify、飞书群机器人、Server酱、WxPusher 或自己的 Webhook。
31
+ - **连页面都关掉时**:可选让宿主进程兜底——页面不在时宿主继续把「需要你操作」「回复完成」推到你的网关;也可以只开同源中继,让页面够到要认证的网关。两项默认关,配置写在 profile 的 patch 层(见[高级设置](#高级设置)里的「页面关闭后:宿主侧兜底与同源中继」)。
30
32
 
31
- > 页面或桌面应用需保持运行(后台 / 最小化可以);系统通知需要通知权限。审批按钮依赖 Service Worker,只有 Web 端有,桌面端的通知不带按钮,点通知回到对话里裁决。
33
+ > 页面或桌面应用需保持运行(后台 / 最小化可以);系统通知需要通知权限。审批按钮依赖 Service Worker,只有 Web 端有,桌面端的通知不带按钮,点通知回到对话里裁决。开启宿主侧兜底后,页面关闭仍能收到外部推送——本地通知与审批按钮仍要页面在。
32
34
 
33
35
  ## 效果预览
34
36
 
@@ -80,7 +82,7 @@ Web 用户可再测审批按钮,通知上会带「同意 / 拒绝」。桌面
80
82
  window.__dshNotifyMe.test("done") // 「完成」示例
81
83
  window.__dshNotifyMe.test("attention") // 「需要你」示例
82
84
  window.__dshNotifyMe.test("approval") // 桥可用时带「同意 / 拒绝」按钮;否则只发普通通知(桌面端即如此)
83
- window.__dshNotifyMe.debug() // 桥接看 bridge(active = 按钮可用)、抬窗通道 raiseChannel、最近一次尝试 raiseLast、平台拒发原文 lastToastReject、设置是否真存下来 configStored
85
+ window.__dshNotifyMe.debug() // 桥接看 bridge(active = 按钮可用)、抬窗通道 raiseChannel、最近一次尝试 raiseLast、平台拒发原文 lastToastReject、设置是否真存下来 configStored、宿主协调看 hostBridge
84
86
  ```
85
87
 
86
88
  没有测试通知时,先检查:通知权限是否被拒绝(在页面上点一下 → 选「允许」;或地址栏锁 → 站点设置 → 通知 → 允许 → 刷新)、装完没重启 DSH、系统设置里浏览器通知被关。
@@ -169,6 +171,98 @@ dsh-notify-me 把「监督」和「守在屏幕前」解耦:只在真的出现
169
171
 
170
172
  </details>
171
173
 
174
+ #### 页面关闭后:宿主侧兜底与同源中继
175
+
176
+ 这两块能力住在宿主进程里(`lib/host-fallback.js`、`lib/relay.js`,都是包内的可选模块),默认关:没有配置时宿主只注册抬窗那一条路由,升级前后行为一致。它们的配置写在 profile 的 patch 层,不在设置页里——它们让宿主替页面干活,不是浏览器偏好;设置页只如实显示探测到的状态。
177
+
178
+ <details>
179
+ <summary>宿主侧兜底:页面关闭后由宿主接着推</summary>
180
+
181
+ 页面不在时页面半体不运行,提醒就断在这里。宿主侧兜底订阅宿主的会话事件流(`session/event`),在页面关闭后自己把同样两条提醒发到你配置的网关。
182
+
183
+ profile 覆盖示例(`~/.dsh/profiles/<profile>/cordis.patch.yml`)。**`config` 是整块替换、不是深合并**:patch 里写同一个 `id` 就把整个 `config` 赋过去,所以示例把三块都写全——漏写的键会回落到插件内的默认值(与随包 YAML 是同一份),但被一起冲掉的 `gateway.target` 不会自己回来。
184
+
185
+ ```yaml
186
+ - id: notify-me
187
+ config:
188
+ allowedOrigins: [] # 顶层:页面入口白名单,留空 = 只接受回环 / 绑定地址(三条宿主入口共用)
189
+ gateway:
190
+ target: '' # 例:https://cue.example/notify/<key>
191
+ credentialsFile: '' # 0600 JSON,见下
192
+ headers: {} # 额外请求头,可选
193
+ hostFallback:
194
+ enabled: true
195
+ target: '' # 留空 = 用 gateway.target
196
+ credentialsFile: '' # 留空 = 用 gateway.credentialsFile
197
+ events: ['turn/end', 'approval/asked']
198
+ includeSubagents: false
199
+ turnEndThrottleMs: 15000
200
+ titlePrefix: 'DSH'
201
+ language: 'auto' # auto | zh | en
202
+ pageLeaseMs: 60000 # 0 = 不与页面协调(页面开着也会重复)
203
+ healthPath: '/__dsh-notify-me/host-fallback'
204
+ relay:
205
+ enabled: false
206
+ path: ''
207
+ target: ''
208
+ credentialsFile: ''
209
+ ```
210
+
211
+ 逐键说明(括号内是默认值):
212
+
213
+ - `enabled`(`false`):关着时宿主不订阅任何事件,也不注册健康探针;
214
+ - `target` / `credentialsFile`(空):留空回落到 `gateway.*`;两处都空等于没地方可推,模块干脆不挂载,只在宿主日志里留一行 warning——比每次投递都失败好查;
215
+ - `events`(`['turn/end', 'approval/asked']`):要推的事件,只列一种就只有那一种;
216
+ - `includeSubagents`(`false`):`origin === 'subagent'` 的会话默认跳过,理由与页面侧一致——它们是主对话一轮里的步骤;
217
+ - `turnEndThrottleMs`(`15000`):同一会话的「回复完成」在这个窗口内只推一条;窗口只在真发出去时才消耗,被租约挡掉的那次不算。节流只管 `completed`——`aborted` / `error` / `max-tokens` 这些收尾不节流,它们本来就少,而且往往是此刻最该看到的那一条;
218
+ - **文案与页面通知逐字一致**:标题是 `<前缀> · 回复完成` / `<前缀> · 审批请求`,正文「回复完成」只有会话名、「审批请求」是 `会话名:工具名 · 原因`——不含任何用户消息正文(用户消息里常带注入的 `<system-reminder>`、记忆上下文与时间戳,复制进通知就没法读了);非正常收尾(`aborted` / `error` / `max-tokens`…)会在正文尾部附一个短后缀,如 `(error)`;
219
+ - `titlePrefix`(`DSH`):标题是 `<前缀> · 审批请求` / `<前缀> · 回复完成`(与页面通知同一套标签);
220
+ - `language`(`auto`):`auto` 用页面最近一次心跳报的语言,没有心跳才回落到中文;`zh` / `en` 强制;
221
+ - `pageLeaseMs`(`60000`):页面在线租约,见下面「去重」;
222
+ - `healthPath`(`/__dsh-notify-me/host-fallback`):只读健康探针的路径。
223
+
224
+ **凭据文件**:宿主用户可读的 0600 JSON,内容是 `{"user": "...", "password": "..."}`(按 HTTP Basic 发)或 `{"authorization": "Bearer ..."}`(原样发;裸 token 会自动补上 `Bearer `)。它不能写进 patch 层——那一层世界可读、还会进 profile 目录。不填这个键时请求不带认证头:很多 webhook 端点本来就不要认证,把「没配凭据」当成错误会让每个提醒都失败;只有「配了路径却读不出来」才算凭据不可用。网关回 401 / 403 时宿主丢掉缓存的凭据、重读文件、只重试一次,所以轮换密码不需要重启宿主。
225
+
226
+ **去重靠一条页面在线租约**:页面加载后 `GET /__dsh-notify-me/host-bridge` 探测一次(之后每 60 秒复探,页面隐藏时不探、回到可见补探一次),只有回包 `hostFallback.enabled === true` 才开始心跳——body 只有 `{alive, language}`,间隔取 `leaseMs/3`、夹在 5–20 秒;`pagehide` 时发一条 `{alive:false}`(带 `keepalive`)立刻释放。宿主侧租约新鲜就不补推(页面自己在推),租约过期或收到 `alive:false` 才接手,最多等 `pageLeaseMs` 这么久。心跳只带语言,不带页面的推送开关:规则是「没有页面持有租约时宿主接手」,而页面的可见性与闲置判定宿主看不见,只照做一半会得到谁也算不清的规则。语言带过来是为了英文页面不收中文宿主提醒,`language: 'auto'` 时生效。`pageLeaseMs: 0` 关掉协调,宿主永远推——页面开着时会收到两份,只在调试时用。
227
+
228
+ **两个路由的契约**:页面探测的那条 `GET /__dsh-notify-me/host-bridge` 回 `{ok, version, features, hostFallback:{enabled, leaseMs}, relay:{enabled, path, upstreamHost, upstreamPath}, language, page:{alive, ageMs}}`(`upstreamHost` / `upstreamPath` 是宿主替你转发时的网关主机名与路径,只在中继启用时给出,凭据永不下发);它只在 `hostFallback.enabled` 或 `relay.enabled` 为真时注册,默认安装下是 404,页面按「未启用」处理而不是当故障。心跳 `POST` 要求意图头 `x-dsh-notify-me-page: bridge`(缺了回 `403`),坏 JSON 回 `400`,body 超 16 KiB 回 `413`,成功回 `200 {ok, leaseUntil}`。
229
+
230
+ **健康探针**:`GET <healthPath>` 回 `{ok, version, enabled, events, includeSubagents, pageAlive, lastDelivery: {at, ok, status} | null}`,非 GET / HEAD 回 `405`。它和其它宿主入口共用同一道闸门:对端必须是本机(回环或监听器自己绑定的那个地址),`Host` 必须是回环名 / 绑定地址 / `allowedOrigins` 派生的公网域名,不符回 `403` 并带 `reason`(`bad-remote` / `bad-host` / `cross-origin`)。探针不收凭据、不转发,用它在终端确认「这个宿主进程到底有没有在推、上一次投递是什么结果」。
231
+
232
+ **走隧道或反代时必须配 `allowedOrigins`**:那种部署下发往宿主的 `Host` 是公网域名而不是回环地址,而 `allowedOrigins` 既是 `Origin` 白名单,也是可接受的 `Host` 来源。不写它,页面的心跳会被闸门判 `bad-host`(设置页那行显示「宿主未响应」,下方直接提示去顶层 `allowedOrigins` 补本页来源),宿主于是把开着页面的提醒也补推一遍——正是租约要避免的那种重复。
233
+
234
+ </details>
235
+
236
+ <details>
237
+ <summary>同源中继:让页面够到要认证的网关</summary>
238
+
239
+ 页面用自己的 `fetch` 往外部目标推,碰上要 Basic 认证的网关就是死路,三条 CORS 事实各堵一次:
240
+
241
+ 1. 把凭据写进 URL(`https://user:pass@host/…`):`fetch` 直接抛错,请求根本没发出去;
242
+ 2. 加 `Authorization` 头:请求变成预检,而 Apprise 这类网关不回任何 `Access-Control-Allow-*`,预检失败;
243
+ 3. 退到 `no-cors`:带不了自定义头,等于没有认证。
244
+
245
+ 于是页面只能报「已送出不可确认」。同源中继把这一段搬到宿主:页面 POST 到与自己同源的路由,宿主补上凭据再打网关,然后把网关的真实状态回给页面。
246
+
247
+ 启用需要 `relay.enabled: true`、`relay.path`(必须是绝对路径)、`relay.target`(留空回落到 `gateway.target`)和 `relay.credentialsFile`(留空回落到 `gateway.credentialsFile`)。路径本身就是能力——知道它就能让宿主替你发一条通知,价值等同口令,所以建议带一段随机 token:`/__dsh-notify-me/relay/<32 hex token>`。
248
+
249
+ 用法:**设置 → 通知提醒 → 高级设置 → 外部推送** 里多出两行只读状态,「同源中继」一行显示 `已启用 · 地址:<origin><relay.path>`;把那个绝对地址填进同页「自定义 Webhook」目标的地址即可,页面不必知道凭据。
250
+
251
+ 不想改地址也行:**「自定义 Webhook」目标里如果填的是中继上游网关本身的地址,发送时会自动折叠到中继路由**。这类地址在浏览器里注定失败(上面三条 CORS 事实各堵一次,其中 `no-cors` 兜底还会被 Apprise 当成跨站请求直接 `403 Cross-site request rejected`),旧版把它记成 `unverified`——设置页显示「上次已送出(不可确认)」、测试按钮报「已送出不可确认」,**而手机一声不响**。折叠之后请求走同源、凭据由宿主补,回执就是网关的真实状态。折叠要同时满足:目标类型是「自定义」、URL 主机名等于 `relay.upstreamHost`、路径也等于 `relay.upstreamPath`、目标没配签名密钥(签名在页面算,中继带不过去)、且目标不是本页同源。主机名或路径有一项对不上就原样直发(一个网关常按路径分多个 notify key,只比主机名会把 A key 的提醒发到 B key 去),设置页会在会被折叠的目标下写一行说明。
252
+
253
+ 走隧道 / 反代时中继要和桥接路由过同一道 `Host` 闸门:把页面的公网来源写进顶层 `allowedOrigins`,否则探针与 `POST` 都会被判 `bad-host`。
254
+
255
+ 回包口径(页面据此把「已送出不可确认」变成可核对的状态):
256
+
257
+ - `GET` / `HEAD` `<relay.path>` → `200 {ok, route, version, enabled}`:只读探针,不转发、不带凭据,但**和其它宿主入口走同一道闸门**——路径本身就是能力,不设闸门的探针会把「猜对了」告诉猜的人;拿它确认「这个进程挂的是不是我配的那条路径」;
258
+ - `POST` → 读 body(上限 64 KiB)、要求是 JSON 对象,映射成网关的 `{title, body, type:'info'}`(页面载荷里的 `tag` 不透传:Apprise 把 tag 当服务过滤,不匹配会回 424),附上 `gateway.headers` 与凭据;请求必须带 `x-dsh-notify-me-relay: relay` 意图头,缺了回 `403 {reason:'missing-intent'}`——跨站表单发不出自定义头,要发就得多一次预检,而预检在网关这里必然失败;
259
+ - `200 {ok, upstreamStatus, upstreamBody}`(`upstreamBody` 最多 500 字符)=转发成功;上游非 2xx 回 `502`,同为这一形状;
260
+ - `400`(坏 JSON 或空 body)、`413`(body 超限)、`405`(方法不对)、`403`(闸门拒绝或缺少意图头)、`503`(配了凭据文件但读不出来)、`502 {reason:'upstream-error'}`(上游异常或网关回了 3xx——跳转不跟,因为跟过去会把 body 和 `Authorization` 重放到别处)。
261
+
262
+ 凭据只在宿主:页面拿不到它,它也不会回显在响应或日志里。`POST` 走与其它宿主入口同一道闸门,所以跨站页面或 DNS rebinding 的伪造来源即使猜到路径也会被拒。
263
+
264
+ </details>
265
+
172
266
  #### 运行环境与诊断
173
267
 
174
268
  在「高级设置」最后一块。默认自动识别当前是 Web 端还是桌面端(DSH Desktop,`dsh-app://`);识别不准时可手动指定——Windows 桌面点通知走宿主路由做原生抬窗、macOS / Linux 走 `dsh://open` 深链(见[桌面端怎么抬窗的](#桌面端怎么抬窗的))、通知上不带快捷裁决按钮;Web 端走 `window.focus()` 与 Service Worker 桥。手动覆盖与自动识别不一致时,设置页会明示检测结果。
@@ -190,8 +284,10 @@ dsh-notify-me 把「监督」和「守在屏幕前」解耦:只在真的出现
190
284
  | 提示音 | 默认 WebAudio 合成音,「需要你」与「完成」音型不同;可换自定义音频,或交给系统通知音 |
191
285
  | 标签页标题 | `🔔 需要你 · …` / `✅ 回复完成 · …`(随通知语言切换),打开对应会话即消失;两种标记可同时出现 |
192
286
  | 外部推送(可选,默认关) | 把同一条提醒转发到 Discord / Bark / Gotify / 飞书 / Server酱 / WxPusher / 自定义 Webhook |
287
+ | 宿主侧兜底(可选,默认关) | 页面关闭后由宿主进程继续把「需要你操作」「回复完成」推到你的网关;要 profile 配置与 0600 凭据文件 |
288
+ | 同源中继(可选,默认关) | 页面 POST 到宿主同源路由,由宿主补凭据转发给要认证的网关,并回传网关真实状态码 |
193
289
 
194
- 本插件是**浏览器层**实现:DSH 页面需保持打开(最小化/后台即可——那正是它监听的「离开」状态)。
290
+ 本插件以**浏览器层**为主:本地通知、提示音、标题标记仍只在页面开着时工作(最小化 / 后台即可——那正是它监听的「离开」状态);开启宿主侧兜底后,外部推送在页面关闭后由宿主进程接着发。
195
291
 
196
292
  ## 兼容性
197
293
 
@@ -263,6 +359,8 @@ window.__dshNotifyMe.testExternal() // 显式外发测试:向有
263
359
  > 自定义音效文件不在 `dshNotifyMe.config` 里,而是按类别各存一个键(`dshNotifyMe.sound.done` / `dshNotifyMe.sound.attention`,内容是 `{name, size, data}` 的 data URL)——一个文件转成 data URL 会膨胀约 1.37 倍,塞进配置会拖慢每次读取。`resetConfig()` 会连这两个键一起清掉。
264
360
  >
265
361
  > 想确认当前生效的来源,看 `window.__dshNotifyMe.debug()` 的 `soundDone` / `soundAttention` 与 `customSoundDone` / `customSoundAttention`。
362
+ >
363
+ > `debug().hostBridge` 是宿主协调的只读快照:`state`(`idle` 还没探到;`active` 宿主有兜底、本页正用心跳占住租约;`unavailable` 宿主在但没有兜底,默认安装即如此——路由没注册的 404 也算这一档,不是故障;`error` 宿主答不出可用回包,或被闸门直接拒了)、`leaseMs`(宿主授予的租约,毫秒)、`relayEnabled` 与 `relayPath`(宿主启用了中继时给出它的路径)、`relayUpstreamHost` / `relayUpstreamPath`(中继上游网关的主机名与路径,即会被折叠的那个端点)、`lastReason`(上一次探测失败的原因,如 `bad-host` / `cross-origin` / `http-403`,正常时为 `null`)、`lastProbeAt` / `lastBeaconAt`(最近一次探测与心跳的时间,ISO 字符串或 `null`)。闸门拒绝算 `error` 而不是「未启用」,因为那是能自己修的配置:把本页来源补进 profile 里 `- id: notify-me` 顶层的 `allowedOrigins`。
266
364
 
267
365
  </details>
268
366
 
@@ -322,7 +420,7 @@ Windows 的激活顺序是实的:已经在前台就什么都不做(最常见
322
420
 
323
421
  **运行前提**
324
422
 
325
- - 页面必须开着才会提醒(后台标签 / 最小化可以,关标签页即失效——浏览器层方案固有限制)。
423
+ - 默认只在页面开着时提醒(后台标签 / 最小化可以,关标签页即失效——浏览器层方案固有限制)。开启宿主侧兜底后,页面关闭仍能收到**外部推送**:它要 profile 里 `hostFallback.enabled: true`、`gateway.target`(或 `hostFallback.target`)与一个 0600 凭据文件,而且宿主进程自己在跑。
326
424
  - 通知经由浏览器弹出,需允许浏览器通知权限;每次页面加载后第一次出声 / 弹通知前要先在页面上点过一下;未授权时只剩提示音与标题标记。
327
425
  - 系统通知横幅只画在主屏:Windows 没有设置项、Chromium 没有 API 能把它指到别的显示器(多屏时副屏收不到)。要跨屏只能靠外部推送转到手机(1.12.0 起页面里不再画审批卡片)。
328
426
  - 配置存在浏览器 `localStorage`:换浏览器 / 设备或清除站点数据后回到默认值(设置页可一键恢复默认)。
@@ -344,6 +442,7 @@ Windows 的激活顺序是实的:已经在前台就什么都不做(最常见
344
442
  **外部推送**
345
443
 
346
444
  - 受浏览器跨域(CORS)限制:端点不放行时自动降级为「送出但不可确认」(no-cors),如实标为「已送出不可确认」;Discord、飞书、Server酱、WxPusher 放行跨域,可直接确认送达。钉钉不放行任何 CORS 头、又只收 `application/json`,页面发不出去,所以没有做成目标类型(自建中转 + 自定义目标才行)。临时失败(网络中断、5xx、429)按退避重试,重试仍失败进失败记录,其余错误立即停、不重试;转发在本地提醒决定要发之后才触发,所以被静音的提醒也不会外发。
445
+ - 同源中继补上的只是「页面够不到要认证的网关」这一类:页面 POST 到同源路由,宿主补凭据并回传网关的真实状态码。仍然成立的边界有几条——中继与宿主侧兜底都要求宿主进程在运行(`dsh web` 或桌面端主进程),它们不是独立守护进程,宿主退出就都停;宿主跑在代理环境里时网关域名要进 `no_proxy`,否则投递会绕到代理出去;兜底只补外部推送,本地系统通知、提示音、标题标记与审批按钮仍要页面在;`pageLeaseMs: 0` 是调试开关,页面开着也会收到两份;中继路由路径等同于口令,别让它出现在公开记录里。
347
446
 
348
447
  **设置页图标补丁**
349
448
 
@@ -354,11 +453,13 @@ Windows 的激活顺序是实的:已经在前台就什么都不做(最常见
354
453
  ```sh
355
454
  node --check lib/client.js
356
455
  node --check lib/index.js
357
- npm test # smoke-test(状态机)+ host-route-test(宿主半路由)+ cordis-host-test
456
+ npm test # smoke-test(状态机)+ host-route-test(宿主半路由)+ page-bridge-test + host-fallback-test + relay-route-test + cordis-host-test
358
457
  npm pack --dry-run # 预览发布包
359
458
  ```
360
459
 
361
- `smoke/smoke-test.cjs` 是离线状态机测试:三代宿主 + 主开关 + 中英语言用例 + 快捷裁决桥(Service Worker 半侧一并跑)+ 闲置判定与通知自收 + 通知标签长度收口。`smoke/host-route-test.mjs` 不需要本机 DSH,`lib/index.js` 的路由、探针与 403/405/501 闸门在任何平台都会跑。
460
+ `smoke/smoke-test.cjs` 是离线状态机测试:三代宿主 + 主开关 + 中英语言用例 + 快捷裁决桥(Service Worker 半侧一并跑)+ 闲置判定与通知自收 + 通知标签长度收口 + 页面侧 host-bridge 探测/心跳/释放与 `debug().hostBridge` 形状。`smoke/host-route-test.mjs` 不需要本机 DSH,`lib/index.js` 的路由、探针与 403/405/501 闸门在任何平台都会跑。
461
+
462
+ 新增的三个套件同样自带假 `ctx`、不联网、不需要本机 DSH:`smoke/page-bridge-test.mjs` 跑页面桥接路由的状态回包形状、心跳与释放、缺意图头 `403`、跨源 `403`、坏 JSON `400`、超长 `413`,以及 `allowedOrigins` 派生的 `Host`(模拟隧道)放行与路径冲突;`smoke/host-fallback-test.mjs` 跑宿主兜底——审批去重、`turn/end` 节流、子代理跳过、租约新鲜时不发、租约过期后发、`alive:false` 后立刻发、语言跟随心跳、401 后重读凭据、健康探针;`smoke/relay-route-test.mjs` 跑中继——`GET` 探针、`405`、跨源 `403`、`413`、`400`、`503`、`200` / `502` 映射与「401 只重试一次」。
362
463
 
363
464
  改到 `lib/focus-window.ps1` 时(仅 Windows),另需手动跑一次:
364
465
 
@@ -383,6 +484,7 @@ powershell -NoProfile -File lib/focus-window.ps1 -ProcessId 0 # 末行应是 F
383
484
  | <a href="https://github.com/Donald-Yip"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/Donald-Yip.png" width="40" height="40" alt="@Donald-Yip"></a> | [#18](https://github.com/chromoany/dsh-notify-me/issues/18):Windows 通知 tag 超过 64 字符上限、审批测试通知被平台静默拒收的报告 |
384
485
  | <a href="https://github.com/dunxuan"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/dunxuan.png" width="40" height="40" alt="@dunxuan"></a> | [#20](https://github.com/chromoany/dsh-notify-me/issues/20):当前会话的通知正文用占位符、未取会话标题的报告 |
385
486
  | <a href="https://github.com/unnamed42"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/unnamed42.png" width="40" height="40" alt="@unnamed42"></a> | [#21](https://github.com/chromoany/dsh-notify-me/issues/21) / [#22](https://github.com/chromoany/dsh-notify-me/pull/22):Linux 上 `dsh://open` 抬窗失效的报障与补丁,1.14.4 起 macOS / Linux 恢复深链抬窗 |
487
+ | <a href="https://github.com/LIEGU0317"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/LIEGU0317.png" width="40" height="40" alt="@LIEGU0317"></a> | [#24](https://github.com/chromoany/dsh-notify-me/issues/24) / [#25](https://github.com/chromoany/dsh-notify-me/pull/25):页面关闭后由宿主兜底推送、同源中继两个可选模块(默认关),含测试与文档 |
386
488
 
387
489
  署名口径:本仓库收编外部 PR 时以维护者提交落地——不沿用原 commit、不挂 Co-authored-by,GitHub 的 contributors 图只显示维护者,贡献者以上面的致谢署名。
388
490
 
package/cordis.patch.yml CHANGED
@@ -2,6 +2,80 @@
2
2
  # plugin package. The entry is a normal cordis loader entry (id + package
3
3
  # name); the browser half is picked up by dsh-client-modules through the
4
4
  # package's dsh.client declaration, exactly like the shipped ui-* packages.
5
+ #
6
+ # Two optional host-side modules hang off the same entry, both OFF by default:
7
+ #
8
+ # hostFallback pushes "needs you" / "reply finished" from the host's session
9
+ # feed, so alerts arrive with no page open.
10
+ # relay a same-origin route that lets the page reach an authenticated
11
+ # notification gateway the browser cannot talk to.
12
+ #
13
+ # HOW TO OVERRIDE
14
+ # A profile patch row that names the same id REPLACES the entry's `config`
15
+ # wholesale — the loader assigns the field, it does not deep-merge. So a
16
+ # minimal override only has to name what it changes, but it must not expect the
17
+ # values below to survive: the plugin's own defaults (lib/index.js normalizeConfig)
18
+ # fill every key the override leaves out, using the same values written here.
19
+ # Example, in ~/.dsh/profiles/<profile>/cordis.patch.yml:
20
+ #
21
+ # - id: notify-me
22
+ # config:
23
+ # hostFallback:
24
+ # enabled: true
25
+ #
26
+ # That alone is enough: the gateway target below is empty and JS defaults keep
27
+ # everything else off, but `hostFallback.target` still has to name the gateway.
28
+ #
29
+ # CREDENTIALS
30
+ # `credentialsFile` is a JSON file readable by the host user only (chmod 600)
31
+ # holding either {"user": "...", "password": "..."} (sent as HTTP Basic) or
32
+ # {"authorization": "Bearer ..."} (sent verbatim; a bare token gets "Bearer ").
33
+ # It never goes into this file: the patch layer is world-readable and ends up in
34
+ # the profile directory, so a password here would be a plaintext secret on disk.
35
+ # A rotated password needs no restart — a 401/403 re-reads the file once.
36
+ # Leave it empty when the gateway needs no authentication (a plain webhook):
37
+ # deliveries then go out without an Authorization header, and an empty path is
38
+ # never reported as a credential problem.
39
+ #
40
+ # `allowedOrigins` (top level, one key for all three routes) is the
41
+ # deployment's public origin list. It does two things: it is the Origin
42
+ # allow-list, and its host names are the public `Host` values the shared
43
+ # request gate accepts — behind a tunnel or reverse proxy the Host header is
44
+ # the public domain, not the loopback address the listener binds. It lives at
45
+ # the top level and not under relay or hostFallback because every gated route
46
+ # (the page bridge, the relay, the health probe) consults the same list, and a
47
+ # deployment that enables only one of the modules still has to be reachable
48
+ # through that public name.
5
49
  - insert:
6
50
  - id: notify-me
7
51
  name: 'dsh-notify-me'
52
+ config:
53
+ # Public origin(s) of this deployment, e.g. ['https://dsh.example.com'];
54
+ # empty means loopback / bind-address requests only.
55
+ allowedOrigins: []
56
+ # Notification gateway, shared by the relay and the host fallback; each
57
+ # module may override target/credentialsFile below.
58
+ gateway:
59
+ target: '' # e.g. https://cue.example/notify/<key>
60
+ credentialsFile: '' # mode-0600 JSON, see CREDENTIALS above
61
+ headers: {} # extra request headers, optional
62
+ # Patch 1: fallback push while no page is open.
63
+ hostFallback:
64
+ enabled: false
65
+ target: '' # empty = use gateway.target
66
+ credentialsFile: '' # empty = use gateway.credentialsFile
67
+ events: ['turn/end', 'approval/asked']
68
+ includeSubagents: false
69
+ turnEndThrottleMs: 15000
70
+ titlePrefix: 'DSH'
71
+ language: 'auto' # auto | zh | en
72
+ pageLeaseMs: 60000 # 0 = no coordination with the page (duplicates while it is open)
73
+ healthPath: '/__dsh-notify-me/host-fallback'
74
+ # Patch 2: same-origin relay (page -> host -> gateway, host adds the
75
+ # authentication). Keep a random token in the path: the path is the
76
+ # capability, so it is worth as much as a password.
77
+ relay:
78
+ enabled: false
79
+ path: '' # exact route, e.g. /__dsh-notify-me/relay/<32 hex token>
80
+ target: ''
81
+ credentialsFile: ''