dsh-balance-sentinel 0.1.0 → 0.1.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/CHANGELOG.md +16 -0
- package/README.en.md +8 -6
- package/README.md +8 -6
- package/client.js +97 -39
- package/lib/localapi.js +64 -6
- package/lib/notify.js +21 -7
- package/lib/state.js +70 -2
- package/locale/en.json +1 -1
- package/locale/zh.json +3 -3
- package/package.json +2 -2
- package/scripts/selftest-client.mjs +166 -5
- package/scripts/selftest.mjs +199 -4
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,21 @@
|
|
|
3
3
|
All notable changes to this project are documented here. Format follows
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/); versions follow [SemVer](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## [0.1.2] - 2026-11-17
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- **保存失败不再卡死**:服务端返回错误后,「仅保存」「保存并测试」「保存阈值」「关闭推送」的按钮曾停在「保存中…」并保持禁用。现在所有保存路径都用 `finally` 清理忙碌态,「保存并测试」从保存切到测试期间也不再闪回可用状态。
|
|
11
|
+
- **重新进入面板时阈值输入框为空**:草稿的「是否被编辑」判断写在 `setState` 的函数式更新里,而 React 要等下一次渲染才执行它——此时闭包变量已被下一行代码改写成新值,条件恒为假,两个输入框就停在空字符串并显示「需为正数」的红字。改为用 `useRef` 同步判断,并让未编辑的草稿直接回落到服务端阈值渲染,任何加载延迟都不会再出现空输入框。
|
|
12
|
+
- **测试结果不再张冠李戴**:A 地址测试还没返回时,另一页面保存了 B 地址,A 的成功会被记到 B 头上。现在用 `channel|url|secret` 的哈希把裁决钉在具体配置上,返回时若发现配置已变更就丢弃结果,并在面板提示「测试期间推送配置已变更,本次结果未计入当前通道」。该指纹只留在服务端,`/status` 不返回。
|
|
13
|
+
- **失败的测试不会被旧成功掩盖**:此前测试成功、本次失败且状态文件写入失败时,面板仍显示绿色的「最近测试成功」。现在无论写盘是否成功都会立即更新内存中的裁决,写盘失败再额外标注「结果未写入状态文件,重启后会丢失」;随后监控周期的读取合并与写回(`mergeStateFromDisk` 与 `saveState`)都不会把这条未持久化的较新裁决换回旧记录 —— 这一轮补存成功则转为已持久化,仍失败则继续标注;配置一旦变化则连同裁决一起失效。
|
|
14
|
+
- **「已配置」不再暗示发送成功**:面板区分「已配置,待测试」「最近测试成功」「最近测试失败(含原因与时间)」,改通道或凭据会立即清除旧结果,避免用一条从未验证过的 webhook 冒充已接通。
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- 通知署名保持原样文字(`安装:github:liancheng2020/dsh-balance-sentinel`),只把其中的仓库标识做成可点击链接:markdown 通道直接可点,飞书卡片脚注改用 `lark_md`,纯文本通道(Bark/Telegram/通用)只保留标识、不附网址(正文里的裸 URL 不受影响);`notify.signature: false` 仍可整体关闭,`signatureText` 可换文案。
|
|
19
|
+
- 文案更准确:README 与面板的「免 Key」改为「支持宿主账号免填 Key」,「不漏发」改为「失败可追踪、可重试」(推送仍按原去重规则不重发)。
|
|
20
|
+
|
|
6
21
|
## [0.1.0] - 2026-11-17
|
|
7
22
|
|
|
8
23
|
首个发布版。仓库历史自 `22bb4d1` 起至本版发布提交,对应本版本的全部内容;后续改动在下一版
|
|
@@ -39,4 +54,5 @@ All notable changes to this project are documented here. Format follows
|
|
|
39
54
|
- README 面板截图前置、补「先看三行」要点;适用范围与免 Key 边界并入安装节,不再单列小节。
|
|
40
55
|
- GitHub About 描述收紧为一句:低余额推送 + 本机运行边界。
|
|
41
56
|
|
|
57
|
+
[0.1.2]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.2
|
|
42
58
|
[0.1.0]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.0
|
package/README.en.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
[](LICENSE)
|
|
10
10
|
[](https://github.com/liancheng2020/dsh-balance-sentinel#readme)
|
|
11
11
|
|
|
12
|
-
**DeepSeek balance
|
|
12
|
+
A DeepSeek Harness plugin: **DeepSeek balance monitoring** + **two-tier low-balance alerts pushed to Feishu / DingTalk and more** + **key-free on hosts with the built-in account service, zero runtime dependencies**
|
|
13
13
|
|
|
14
14
|
> **Three lines first**
|
|
15
15
|
> - **Monitored while DSH runs**, stops when it exits; no remote web panel
|
|
@@ -32,27 +32,29 @@ dsh plugin --profile web add github:liancheng2020/dsh-balance-sentinel
|
|
|
32
32
|
# or npm (published to npm alongside each Release)
|
|
33
33
|
dsh plugin --profile web add dsh-balance-sentinel
|
|
34
34
|
# or the pinned Release tarball
|
|
35
|
-
dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.
|
|
35
|
+
dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.2/dsh-balance-sentinel-0.1.2.tgz
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
Any one of the three is enough; if the npm/Release line is not live yet, use the first. Desktop app: Settings → Plugins → add `dsh-balance-sentinel` or `github:liancheng2020/dsh-balance-sentinel`. Restart DSH once.
|
|
39
39
|
|
|
40
|
-
**Where it runs**: local DSH desktop or local web host only — monitoring lives in the DSH process and **stops when DSH exits** (reopening resumes from the local state file); **no remote web panel** (the bridge binds `127.0.0.1:17430` and only accepts pages from this machine). **
|
|
40
|
+
**Where it runs**: local DSH desktop or local web host only — monitoring lives in the DSH process and **stops when DSH exits** (reopening resumes from the local state file); **no remote web panel** (the bridge binds `127.0.0.1:17430` and only accepts pages from this machine). **Key-free host accounts are supported**: the host must expose the account service with a signed-in account (key-free ≠ account-free); otherwise use `DEEPSEEK_API_KEY` or `balance.apiKey` — with neither, the panel states the exact reason.
|
|
41
41
|
|
|
42
|
-
> Current version `0.1.
|
|
42
|
+
> Current version `0.1.2` (see [CHANGELOG](CHANGELOG.md)).
|
|
43
43
|
|
|
44
44
|
## First use (two steps)
|
|
45
45
|
|
|
46
46
|
1. Open the **Balance Sentinel** panel: your real balance immediately, or a clear reason (signed out / no account service / network…).
|
|
47
47
|
2. Pick a channel, paste the webhook (auto-detected) → **Save and send test**. The Feishu/DingTalk form includes "How to get a bot webhook": official doc + three-step path + the security settings that channel supports. **Until a channel is saved it watches without pushing**.
|
|
48
48
|
|
|
49
|
+
Saving only gets you to "configured, not tested"; the badge turns into "last test succeeded" once a test push actually lands, and into "last test failed" (with the reason and time) when it does not. Editing the channel or credentials clears the old result, so a stale "verified" can never pass for a working endpoint.
|
|
50
|
+
|
|
49
51
|
If the balance is already below a threshold when you connect, one current-state notice is sent (once).
|
|
50
52
|
|
|
51
53
|
## How it works
|
|
52
54
|
|
|
53
55
|
- **Two levels**: below 20 pushes "warn", below 5 pushes "critical" (account currency, panel-editable); a top-up or a threshold tweak back above warn pushes one "recovered"/"resolved" notice, effective immediately on save.
|
|
54
56
|
- **No spam**: same level never repeats; a real top-up pushes "recovered" (10-min anti-flap cooldown); a threshold tweak that resolves a delivered alert pushes "resolved" immediately; undelivered alerts cancel silently; quiet hours defer and merge into a single push afterwards.
|
|
55
|
-
- **
|
|
57
|
+
- **Failures are traceable and retryable**: pending alerts persist; business failures back off 10 min and hold after 3 (manual retry in the panel); timeouts and dead response bodies are "delivery unconfirmed" — held immediately, never auto re-sent; a failed state save writes a fallback receipt, so restarts and multiple instances still do not re-send it (unconfirmed restores as held, never as sent). If neither the state nor the receipt can be written, the duplicate risk is logged explicitly.
|
|
56
58
|
- **No wedge, no duplicate across instances**: host queries have a 15s deadline and the scheduler survives any exception; desktop + web sharing `DSH_HOME` push each transition exactly once (whole-cycle lock + disk merge).
|
|
57
59
|
- **Channels**: WeCom / DingTalk / Feishu (card) / Bark / ServerChan / Telegram / generic webhook; auto-chunking; HTTP-200 business failures count as failures.
|
|
58
60
|
- Balance is the **official account number**; v1 ships no cost estimates.
|
|
@@ -72,7 +74,7 @@ If the balance is already below a threshold when you connect, one current-state
|
|
|
72
74
|
quiet: { start: "", end: "" } # e.g. "23:00"–"08:00"
|
|
73
75
|
apiKey: "" # fallback for older hosts only
|
|
74
76
|
notify:
|
|
75
|
-
signature: true # "via
|
|
77
|
+
signature: true # "via …" footer line whose install spec is tappable, opt-out
|
|
76
78
|
signatureText: ""
|
|
77
79
|
localApi:
|
|
78
80
|
enabled: true # panel bridge on 127.0.0.1:17430
|
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
[](LICENSE)
|
|
10
10
|
[](https://github.com/liancheng2020/dsh-balance-sentinel#readme)
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
DSH 插件:**DeepSeek 余额监控** + **低余额两级告警推送到飞书/钉钉等 IM** + **支持宿主账号免填 Key、零运行时依赖**
|
|
13
13
|
|
|
14
14
|
> **先看三行**
|
|
15
15
|
> - **DSH 运行期间监控**,关闭即停;不支持远程 Web 面板
|
|
@@ -32,27 +32,29 @@ dsh plugin --profile web add github:liancheng2020/dsh-balance-sentinel
|
|
|
32
32
|
# 或 npm(随 Release 一同发布到 npm)
|
|
33
33
|
dsh plugin --profile web add dsh-balance-sentinel
|
|
34
34
|
# 或 Release 固定版本 tarball
|
|
35
|
-
dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.
|
|
35
|
+
dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.2/dsh-balance-sentinel-0.1.2.tgz
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
三条任选一条即可;若 npm/Release 那条还没上线,用第一条。桌面端:设置 → 插件 → 添加插件,填 `dsh-balance-sentinel` 或 `github:liancheng2020/dsh-balance-sentinel`。装完重启一次 DSH。
|
|
39
39
|
|
|
40
|
-
**适用环境**:仅本机 DSH Desktop/本机 Web,监控跑在 DSH 进程里、**退出即停**(重开从本机状态继续);**不支持远程 Web 面板**(桥接只绑 `127.0.0.1:17430
|
|
40
|
+
**适用环境**:仅本机 DSH Desktop/本机 Web,监控跑在 DSH 进程里、**退出即停**(重开从本机状态继续);**不支持远程 Web 面板**(桥接只绑 `127.0.0.1:17430`,只接受本机页面)。**支持宿主账号免填 Key**:宿主内置账号服务且已登录(免填 ≠ 无需账户),否则用 `DEEPSEEK_API_KEY` 或 `balance.apiKey`,都没有时面板给出明确原因。
|
|
41
41
|
|
|
42
|
-
> 当前版本 `0.1.
|
|
42
|
+
> 当前版本 `0.1.2`(见 [CHANGELOG](CHANGELOG.md))。
|
|
43
43
|
|
|
44
44
|
## 首次使用(两步接通)
|
|
45
45
|
|
|
46
46
|
1. 打开 **余额哨兵** 面板:立刻看到真实余额,或明确原因(未登录 / 无账号服务 / 网络…)。
|
|
47
47
|
2. 「推送配置」选通道 → 粘 webhook(自动识别)→ **保存并发送测试**。飞书/钉钉框内有「如何获取机器人 Webhook」:官方链接 + 三步路径 + 该通道适用的安全设置。**没配通道前只监控不推送**。
|
|
48
48
|
|
|
49
|
+
保存成功只说明通道「已配置,待测试」,测试推送真的送达才会变成「最近测试成功」;失败则显示「最近测试失败」并附原因与时间。改通道或凭据后旧结果立即清除,不会有残留的「已验证」冒充接通。
|
|
50
|
+
|
|
49
51
|
接通时余额已低于阈值,会补发一条当前状态(仅一次)。
|
|
50
52
|
|
|
51
53
|
## 它怎么工作
|
|
52
54
|
|
|
53
55
|
- **两级阈值**:默认低于 ¥20 推「预警」、低于 ¥5 推「告急」(账户币种,面板可改);充值或调阈值回到预警之上推一条「恢复/解除」,保存即生效。
|
|
54
56
|
- **不刷屏**:同级停留不重推;充值回升推「恢复」(10 分钟冷却防抖),调阈值解除已送达告警立即推「解除」;告警未送达时静默取消;免打扰时段顺延、出窗合并成一条。
|
|
55
|
-
-
|
|
57
|
+
- **失败可追踪、可重试**:待发送告警持久化;业务失败 10 分钟退避、3 次后挂起可手动重试;超时等「送达不确定」立即挂起、不自动重发;状态保存失败时落盘备用回执,重启/多实例恢复后仍不重发(不确定的恢复为挂起,不标记成功)。状态与回执都无法落盘时会明确告警「去重无法保证」。
|
|
56
58
|
- **不卡死、多实例不重推**:宿主查询 15s 兜底,任何异常后调度继续;desktop + web 共享 `DSH_HOME` 时整周期锁 + 磁盘合并,同一跃迁只推一次。
|
|
57
59
|
- **通道**:企微 / 钉钉 / 飞书(消息卡片)/ Bark / Server酱 / Telegram / 通用 Webhook;超长自动分条;HTTP 200 但业务失败同样判失败。
|
|
58
60
|
- 余额来自**官方账户同源**,v1 不做成本估算。
|
|
@@ -72,7 +74,7 @@ dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentin
|
|
|
72
74
|
quiet: { start: "", end: "" } # 免打扰,如 "23:00"–"08:00"
|
|
73
75
|
apiKey: "" # 仅老宿主回落用;优先宿主账号/环境变量
|
|
74
76
|
notify:
|
|
75
|
-
signature: true #
|
|
77
|
+
signature: true # 推送尾部署名(安装标识可点击),可关
|
|
76
78
|
signatureText: ""
|
|
77
79
|
localApi:
|
|
78
80
|
enabled: true # 面板桥接 127.0.0.1:17430,可关
|
package/client.js
CHANGED
|
@@ -53,9 +53,9 @@ window.__ModuleLoader__.load({
|
|
|
53
53
|
'hero.topup': '去充值', 'hero.checkedAt': '核对于 {t}', 'hero.source': '官方账户同源 · 免估算',
|
|
54
54
|
'level.normal': '余额正常', 'level.warn': '余额预警', 'level.critical': '余额告急',
|
|
55
55
|
'reason.title': '余额暂不可用', 'reason.retry': '重试',
|
|
56
|
-
'reason.no-source': '宿主没有账号服务,也未提供 API Key
|
|
56
|
+
'reason.no-source': '宿主没有账号服务,也未提供 API Key。带官方「设置→账号与余额」的宿主支持免填 Key;否则在配置 balance.apiKey 或环境变量 DEEPSEEK_API_KEY 提供 Key。',
|
|
57
57
|
'reason.signed-out': '宿主未登录 DeepSeek 账户:请在官方「设置→账号与余额」登录后重试。',
|
|
58
|
-
'reason.unauthorized': 'API Key 无效或过期:请更新 Key
|
|
58
|
+
'reason.unauthorized': 'API Key 无效或过期:请更新 Key,或改用宿主账号登录(免填 Key)。',
|
|
59
59
|
'reason.account-failed': '宿主账号服务查询失败,稍后自动重试。',
|
|
60
60
|
'reason.account-error': '宿主账号服务调用异常,稍后自动重试。',
|
|
61
61
|
'reason.network': '网络不可达:确认本机能访问 api.deepseek.com(或被代理/防火墙拦截)。',
|
|
@@ -66,12 +66,18 @@ window.__ModuleLoader__.load({
|
|
|
66
66
|
'alert.pending': '有一条「{k}」通知待发送。', 'alert.hold': '告警发送受阻:{e}', 'alert.retry': '重试发送',
|
|
67
67
|
'alert.retried': '已触发重试,立即补发。',
|
|
68
68
|
'monitor.off': '后台监控已关闭(balance.enabled=false),面板仅展示。',
|
|
69
|
-
'support.scope': '仅支持本机 DSH Desktop/本机 Web:DSH 运行时监控,退出后停止;不支持远程 Web
|
|
69
|
+
'support.scope': '仅支持本机 DSH Desktop/本机 Web:DSH 运行时监控,退出后停止;不支持远程 Web 面板连接。支持宿主账号免填 Key:需宿主提供账号服务且已登录。',
|
|
70
70
|
'quiet.on': '免打扰 {s}–{e},期间告警顺延、出窗合并推送。',
|
|
71
71
|
'th.title': '告警阈值', 'th.warn': '预警阈值', 'th.critical': '告急阈值', 'th.save': '保存阈值',
|
|
72
72
|
'th.saved': '阈值已保存,立即生效。', 'th.bad': '需为正数,且预警阈值大于告急阈值。',
|
|
73
73
|
'th.hint': '低于预警值推「预警」,低于告急值推「告急」;充值或调阈值回到预警值之上推一条「恢复/解除」。告警未送达时静默取消,不补发。',
|
|
74
74
|
'sec.push': '推送配置', 'push.channel': '推送通道:{c}', 'push.on': '已配置', 'push.off': '未配置',
|
|
75
|
+
'push.untested': '已配置,待测试', 'push.verified': '最近测试成功', 'push.failed': '最近测试失败',
|
|
76
|
+
'push.untestedHint': '通道已保存,但还没有测试过发送:点「发送测试推送」确认能收到,别等真告警时才发现地址不通。',
|
|
77
|
+
'push.verifiedAt': '最近测试成功:{t}',
|
|
78
|
+
'push.failedAt': '最近测试失败:{t}{e}',
|
|
79
|
+
'push.testStale': '测试期间推送配置已变更,本次结果未计入当前通道。',
|
|
80
|
+
'push.notPersisted': '结果未写入状态文件,重启后会丢失。',
|
|
75
81
|
'chan.none': '未配置', 'chan.wecom': '企业微信', 'chan.dingtalk': '钉钉', 'chan.feishu': '飞书',
|
|
76
82
|
'chan.bark': 'Bark', 'chan.serverchan': 'Server酱', 'chan.telegram': 'Telegram', 'chan.generic': '通用 Webhook',
|
|
77
83
|
'push.hint': '低余额/恢复通知将推送到这里,保存即生效,无需重启。',
|
|
@@ -98,9 +104,9 @@ window.__ModuleLoader__.load({
|
|
|
98
104
|
'hero.topup': 'Top up', 'hero.checkedAt': 'checked at {t}', 'hero.source': 'Official account source · no estimates',
|
|
99
105
|
'level.normal': 'Balance OK', 'level.warn': 'Low balance', 'level.critical': 'Critical balance',
|
|
100
106
|
'reason.title': 'Balance unavailable', 'reason.retry': 'Retry',
|
|
101
|
-
'reason.no-source': 'No host account service and no API key. Hosts with the official "Account & Balance" page
|
|
107
|
+
'reason.no-source': 'No host account service and no API key. Hosts with the official "Account & Balance" page support key-free accounts; otherwise set balance.apiKey in config or the DEEPSEEK_API_KEY env var.',
|
|
102
108
|
'reason.signed-out': 'The host is not signed in to a DeepSeek account: sign in via the official "Account & Balance" page, then retry.',
|
|
103
|
-
'reason.unauthorized': 'API key invalid or expired: update the key, or sign in with the host account (no key).',
|
|
109
|
+
'reason.unauthorized': 'API key invalid or expired: update the key, or sign in with the host account (no key needed).',
|
|
104
110
|
'reason.account-failed': 'Host account service query failed; retrying automatically.',
|
|
105
111
|
'reason.account-error': 'Host account service call errored; retrying automatically.',
|
|
106
112
|
'reason.network': 'Network unreachable: make sure this machine can reach api.deepseek.com (proxy/firewall?).',
|
|
@@ -111,12 +117,18 @@ window.__ModuleLoader__.load({
|
|
|
111
117
|
'alert.pending': 'A "{k}" notice is waiting to be sent.', 'alert.hold': 'Alert delivery blocked: {e}', 'alert.retry': 'Retry send',
|
|
112
118
|
'alert.retried': 'Retry triggered; sending immediately.',
|
|
113
119
|
'monitor.off': 'Background monitoring is off (balance.enabled=false); the panel is display-only.',
|
|
114
|
-
'support.scope': 'Local DSH Desktop or local web host only: monitoring runs while DSH is running and stops when it exits; remote web panels are not supported.
|
|
120
|
+
'support.scope': 'Local DSH Desktop or local web host only: monitoring runs while DSH is running and stops when it exits; remote web panels are not supported. Key-free host accounts are supported: the host needs the account service and a signed-in account.',
|
|
115
121
|
'quiet.on': 'Quiet hours {s}–{e}: alerts defer and merge into one push afterwards.',
|
|
116
122
|
'th.title': 'Alert thresholds', 'th.warn': 'Warn below', 'th.critical': 'Critical below', 'th.save': 'Save thresholds',
|
|
117
123
|
'th.saved': 'Thresholds saved; effective immediately.', 'th.bad': 'Positive numbers required, warn above critical.',
|
|
118
124
|
'th.hint': 'Below warn pushes "low", below critical pushes "critical"; a top-up or a threshold tweak back above warn pushes one "recovered"/"resolved" notice. Undelivered alerts cancel silently.',
|
|
119
125
|
'sec.push': 'Push settings', 'push.channel': 'Push channel: {c}', 'push.on': 'Configured', 'push.off': 'Not set',
|
|
126
|
+
'push.untested': 'Configured, not tested', 'push.verified': 'Last test succeeded', 'push.failed': 'Last test failed',
|
|
127
|
+
'push.untestedHint': 'The webhook is saved but has never been tested: hit "Send test push" now, so a dead endpoint cannot stay hidden until a real alert needs it.',
|
|
128
|
+
'push.verifiedAt': 'Last test succeeded: {t}',
|
|
129
|
+
'push.failedAt': 'Last test failed: {t}{e}',
|
|
130
|
+
'push.testStale': 'The push config changed while the test was running; this result was discarded.',
|
|
131
|
+
'push.notPersisted': 'Result not written to the state file; it will be lost on restart.',
|
|
120
132
|
'chan.none': 'Not set', 'chan.wecom': 'WeCom', 'chan.dingtalk': 'DingTalk', 'chan.feishu': 'Feishu',
|
|
121
133
|
'chan.bark': 'Bark', 'chan.serverchan': 'ServerChan', 'chan.telegram': 'Telegram', 'chan.generic': 'Generic webhook',
|
|
122
134
|
'push.hint': 'Low-balance / recovery notices push here. Saving applies immediately, no restart.',
|
|
@@ -245,8 +257,13 @@ window.__ModuleLoader__.load({
|
|
|
245
257
|
const [busy, setBusy] = useState('')
|
|
246
258
|
const [result, setResultState] = useState(null)
|
|
247
259
|
const [offConfirm, setOffConfirm] = useState(false)
|
|
248
|
-
|
|
249
|
-
|
|
260
|
+
// null = "still showing the host's value". The inputs render the threshold
|
|
261
|
+
// in that case instead of an empty string, so a slow /status, a remount, or
|
|
262
|
+
// any path where the seed never ran can no longer leave a blank field with
|
|
263
|
+
// a red "must be positive" warning under it.
|
|
264
|
+
const [warnDraft, setWarnDraft] = useState(null)
|
|
265
|
+
const [critDraft, setCritDraft] = useState(null)
|
|
266
|
+
const thTouched = useRef(false) // user typed in a threshold field
|
|
250
267
|
const [toast, setToast] = useState(null)
|
|
251
268
|
|
|
252
269
|
useEffect(() => {
|
|
@@ -300,8 +317,6 @@ window.__ModuleLoader__.load({
|
|
|
300
317
|
let timer = null
|
|
301
318
|
let attempt = 0
|
|
302
319
|
let seeded = false
|
|
303
|
-
let lastWarn = null
|
|
304
|
-
let lastCrit = null
|
|
305
320
|
const load = async () => {
|
|
306
321
|
try {
|
|
307
322
|
const res = await fetch(LOCAL_API + '/status', { headers: { Accept: 'application/json' } })
|
|
@@ -314,14 +329,16 @@ window.__ModuleLoader__.load({
|
|
|
314
329
|
// must not re-open it under a user who just closed it.
|
|
315
330
|
if (!seeded && !j.configured) setEditing(true)
|
|
316
331
|
seeded = true
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
//
|
|
320
|
-
//
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
332
|
+
// Refresh the draft only while the user has not typed in the field.
|
|
333
|
+
// This must be a synchronous ref read, not a functional setState that
|
|
334
|
+
// compares against a closure variable: React runs that updater later,
|
|
335
|
+
// so a variable written on the next line was already the new value and
|
|
336
|
+
// the comparison wrongly concluded "the user is editing" — which left
|
|
337
|
+
// both inputs empty on first load.
|
|
338
|
+
if (!thTouched.current) {
|
|
339
|
+
setWarnDraft(String(j.thresholds?.warn ?? 20))
|
|
340
|
+
setCritDraft(String(j.thresholds?.critical ?? 5))
|
|
341
|
+
}
|
|
325
342
|
} catch (e) {
|
|
326
343
|
if (cancelled) return
|
|
327
344
|
if (attempt < 2) { attempt++; timer = setTimeout(load, attempt * 500); return }
|
|
@@ -374,15 +391,26 @@ window.__ModuleLoader__.load({
|
|
|
374
391
|
}
|
|
375
392
|
const refreshSoon = (ms = 400) => setTimeout(() => setNonce((n) => n + 1), ms)
|
|
376
393
|
|
|
394
|
+
// Shared by the standalone test button and the save+test flow. It owns no
|
|
395
|
+
// busy state on purpose: the caller keeps one busy window, so a failed save
|
|
396
|
+
// or a failed test can never leave a button stuck on "Saving…".
|
|
397
|
+
const sendTest = async () => {
|
|
398
|
+
const j = await post('/test-push')
|
|
399
|
+
// The config was repointed while this request was in flight, so the
|
|
400
|
+
// verdict belongs to a webhook that is no longer in use: say so instead
|
|
401
|
+
// of letting the user read it as the state of the current channel.
|
|
402
|
+
if (j.stale) { showResult({ ok: false, message: t('push.testStale') }); return j }
|
|
403
|
+
const warn = j.persisted === false ? t('push.notPersisted') : ''
|
|
404
|
+
showResult(j.ok
|
|
405
|
+
? { ok: true, message: t('push.testOk', { c: j.channel || '', n: j.chunks || 1 }), hint: warn }
|
|
406
|
+
: { ok: false, message: j.message || j.error || '', hint: [j.hint, warn].filter(Boolean).join(' ') })
|
|
407
|
+
return j
|
|
408
|
+
}
|
|
409
|
+
|
|
377
410
|
const testPush = async () => {
|
|
378
411
|
setBusy('test'); showResult(null)
|
|
379
|
-
try {
|
|
380
|
-
|
|
381
|
-
showResult(j.ok
|
|
382
|
-
? { ok: true, message: t('push.testOk', { c: j.channel || '', n: j.chunks || 1 }) }
|
|
383
|
-
: { ok: false, message: j.message || j.error || '', hint: j.hint || '' })
|
|
384
|
-
} catch (e) { showResult({ ok: false, message: String(e?.message || e) }) }
|
|
385
|
-
setBusy('')
|
|
412
|
+
try { await sendTest() } catch (e) { showResult({ ok: false, message: String(e?.message || e) }) }
|
|
413
|
+
finally { setBusy('') }
|
|
386
414
|
}
|
|
387
415
|
|
|
388
416
|
const saveWebhook = async (thenTest) => {
|
|
@@ -390,14 +418,25 @@ window.__ModuleLoader__.load({
|
|
|
390
418
|
try {
|
|
391
419
|
const j = await post('/webhook', form)
|
|
392
420
|
if (!j.ok) { showResult({ ok: false, message: j.message || '' }); return }
|
|
393
|
-
|
|
421
|
+
// The server decides what happens to the old test result: an unchanged
|
|
422
|
+
// webhook keeps it, any edit drops it. Trust the response instead of
|
|
423
|
+
// blanking locally and flashing "untested" on a no-op re-save.
|
|
424
|
+
setHost((prev) => ({ ...(prev || {}), channel: j.channel, configured: j.configured, urlHost: j.urlHost, secretSet: j.secretSet, verify: j.verify ?? null }))
|
|
394
425
|
setEditing(false)
|
|
395
426
|
setForm({ channel: j.channel, url: '', secret: '' })
|
|
396
|
-
if (thenTest) {
|
|
397
|
-
|
|
427
|
+
if (!thenTest) {
|
|
428
|
+
showResult({ ok: true, message: t('push.saved') })
|
|
429
|
+
refreshSoon()
|
|
430
|
+
return
|
|
431
|
+
}
|
|
432
|
+
// Save succeeded and the user asked for a test: stay inside the same
|
|
433
|
+
// busy window (relabel to "sending") — never flash an enabled button
|
|
434
|
+
// between saving and testing.
|
|
435
|
+
setBusy('test')
|
|
436
|
+
await sendTest()
|
|
398
437
|
refreshSoon()
|
|
399
438
|
} catch (e) { showResult({ ok: false, message: String(e?.message || e) }) }
|
|
400
|
-
setBusy('')
|
|
439
|
+
finally { setBusy('') }
|
|
401
440
|
}
|
|
402
441
|
|
|
403
442
|
const disablePush = async () => {
|
|
@@ -406,19 +445,21 @@ window.__ModuleLoader__.load({
|
|
|
406
445
|
try {
|
|
407
446
|
const j = await post('/webhook', { channel: 'none' })
|
|
408
447
|
if (!j.ok) { showResult({ ok: false, message: j.message || '' }); return }
|
|
409
|
-
setHost((prev) => ({ ...(prev || {}), channel: 'none', configured: false, urlHost: '', secretSet: false }))
|
|
448
|
+
setHost((prev) => ({ ...(prev || {}), channel: 'none', configured: false, urlHost: '', secretSet: false, verify: null }))
|
|
410
449
|
setEditing(false)
|
|
411
450
|
showResult({ ok: true, message: t('push.disabled') })
|
|
412
451
|
} catch (e) { showResult({ ok: false, message: String(e?.message || e) }) }
|
|
413
|
-
setBusy('')
|
|
452
|
+
finally { setBusy('') }
|
|
414
453
|
}
|
|
415
454
|
|
|
416
455
|
const savePrefs = async () => {
|
|
417
456
|
setBusy('prefs'); showResult(null)
|
|
418
457
|
try {
|
|
419
|
-
const j = await post('/prefs', { warn: Number(
|
|
458
|
+
const j = await post('/prefs', { warn: Number(warnShown), critical: Number(critShown) })
|
|
420
459
|
if (!j.ok) { showResult({ ok: false, message: j.message || t('th.bad'), scope: 'th' }); return }
|
|
421
460
|
setHost((prev) => (prev ? { ...prev, thresholds: j.thresholds } : prev))
|
|
461
|
+
// Saved values are now the host's values: let polls follow them again.
|
|
462
|
+
thTouched.current = false
|
|
422
463
|
// Threshold saves confirm via the floating toast, so the card does not
|
|
423
464
|
// grow a line (and push the sections below) just to take it away again.
|
|
424
465
|
// Failures stay inline next to the inputs they refer to.
|
|
@@ -426,7 +467,7 @@ window.__ModuleLoader__.load({
|
|
|
426
467
|
setToast({ ok: true, title: t('th.saved'), n: Date.now() })
|
|
427
468
|
refreshSoon(900)
|
|
428
469
|
} catch (e) { showResult({ ok: false, message: String(e?.message || e), scope: 'th' }) }
|
|
429
|
-
setBusy('')
|
|
470
|
+
finally { setBusy('') }
|
|
430
471
|
}
|
|
431
472
|
|
|
432
473
|
const retryAlert = async () => {
|
|
@@ -436,7 +477,7 @@ window.__ModuleLoader__.load({
|
|
|
436
477
|
showResult(j.ok ? { ok: true, message: t('alert.retried') } : { ok: false, message: j.message || '' })
|
|
437
478
|
refreshSoon()
|
|
438
479
|
} catch (e) { showResult({ ok: false, message: String(e?.message || e) }) }
|
|
439
|
-
setBusy('')
|
|
480
|
+
finally { setBusy('') }
|
|
440
481
|
}
|
|
441
482
|
|
|
442
483
|
const openForm = () => {
|
|
@@ -451,7 +492,10 @@ window.__ModuleLoader__.load({
|
|
|
451
492
|
const level = host?.alert?.level || 'normal'
|
|
452
493
|
const pending = host?.pending
|
|
453
494
|
const th = host?.thresholds || { warn: 20, critical: 5 }
|
|
454
|
-
|
|
495
|
+
// An untouched draft shows the host value; only user typing replaces it.
|
|
496
|
+
const warnShown = warnDraft === null ? String(th.warn) : warnDraft
|
|
497
|
+
const critShown = critDraft === null ? String(th.critical) : critDraft
|
|
498
|
+
const warnN = Number(warnShown), critN = Number(critShown)
|
|
455
499
|
const thValid = Number.isFinite(warnN) && Number.isFinite(critN) && warnN > 0 && critN > 0 && warnN > critN
|
|
456
500
|
const thDirty = warnN !== th.warn || critN !== th.critical
|
|
457
501
|
|
|
@@ -526,11 +570,25 @@ window.__ModuleLoader__.load({
|
|
|
526
570
|
onClick: () => saveWebhook(true),
|
|
527
571
|
}, busy === 'test' ? t('push.testing') : busy === 'save' ? t('push.saving') : t('push.saveTest'))))
|
|
528
572
|
|
|
573
|
+
// "Configured" is not "connected": a stored webhook proves nothing until a
|
|
574
|
+
// test push comes back. Four states, and only a tested-good one is green —
|
|
575
|
+
// an old success is dropped server-side the moment the webhook changes.
|
|
576
|
+
const verifyInfo = host?.verify || null
|
|
577
|
+
const connState = !host?.configured ? 'off' : !verifyInfo ? 'untested' : verifyInfo.ok ? 'verified' : 'failed'
|
|
578
|
+
const connColor = connState === 'verified' ? T.success : connState === 'failed' ? T.error : connState === 'off' ? T.warn : T.sub
|
|
579
|
+
const connLine = connState === 'verified' ? t('push.verifiedAt', { t: fmtTime(verifyInfo.at) })
|
|
580
|
+
+ (verifyInfo.persisted === false ? ' · ' + t('push.notPersisted') : '')
|
|
581
|
+
: connState === 'failed'
|
|
582
|
+
? t('push.failedAt', { t: fmtTime(verifyInfo.at), e: verifyInfo.error ? (LANG === 'en' ? ': ' : ':') + verifyInfo.error : '' })
|
|
583
|
+
+ (verifyInfo.persisted === false ? ' · ' + t('push.notPersisted') : '')
|
|
584
|
+
: connState === 'untested' ? t('push.untestedHint') : ''
|
|
585
|
+
|
|
529
586
|
const pushSummary = () => h('div', { style: css.card },
|
|
530
587
|
h('div', { style: css.row },
|
|
531
|
-
h('span', { style: css.cardTitle }, h('span', { style: { width: 8, height: 8, borderRadius: '50%', background:
|
|
532
|
-
h('span', { style: css.badgeSoft(
|
|
588
|
+
h('span', { style: css.cardTitle }, h('span', { style: { width: 8, height: 8, borderRadius: '50%', background: connColor, flex: 'none' } }), t('push.channel', { c: t('chan.' + host.channel) })),
|
|
589
|
+
h('span', { style: css.badgeSoft(connColor) }, t('push.' + connState))),
|
|
533
590
|
host.urlHost ? h('div', { style: css.metaDim }, t('push.current', { h: host.urlHost })) : null,
|
|
591
|
+
connLine ? h('div', { style: { ...css.metaDim, color: connState === 'failed' ? T.error : undefined } }, connLine) : null,
|
|
534
592
|
h('div', { style: css.metaDim }, host.configured ? t('push.hint') : t('push.empty')),
|
|
535
593
|
h('div', { style: { display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' } },
|
|
536
594
|
h('button', {
|
|
@@ -571,10 +629,10 @@ window.__ModuleLoader__.load({
|
|
|
571
629
|
h('div', { style: { display: 'flex', gap: 10, flexWrap: 'wrap' } },
|
|
572
630
|
h('div', { style: { ...css.field, flex: 1, minWidth: 110 } },
|
|
573
631
|
h('label', { style: css.fieldLabel, htmlFor: 'sentinel-warn' }, t('th.warn')),
|
|
574
|
-
h('input', { id: 'sentinel-warn', style: css.input, value:
|
|
632
|
+
h('input', { id: 'sentinel-warn', style: css.input, value: warnShown, inputMode: 'decimal', onChange: (e) => { thTouched.current = true; setWarnDraft(e.target.value) } })),
|
|
575
633
|
h('div', { style: { ...css.field, flex: 1, minWidth: 110 } },
|
|
576
634
|
h('label', { style: css.fieldLabel, htmlFor: 'sentinel-crit' }, t('th.critical')),
|
|
577
|
-
h('input', { id: 'sentinel-crit', style: css.input, value:
|
|
635
|
+
h('input', { id: 'sentinel-crit', style: css.input, value: critShown, inputMode: 'decimal', onChange: (e) => { thTouched.current = true; setCritDraft(e.target.value) } }))),
|
|
578
636
|
h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
|
|
579
637
|
h('button', { type: 'button', disabled: !!busy || !thValid || !thDirty, style: thValid && thDirty ? css.btnPrimary : { ...css.btnPrimary, opacity: 0.5, cursor: 'not-allowed' }, onClick: savePrefs }, t('th.save')),
|
|
580
638
|
!thValid ? h('span', { style: { fontSize: 11.5 }, className: 'sentinel-th-bad' }, t('th.bad')) : null),
|
package/lib/localapi.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import http from 'node:http'
|
|
9
9
|
import { withSignature, isWebhookConfigured as configured } from './notify.js'
|
|
10
10
|
import { effectiveThresholds } from './balance.js'
|
|
11
|
-
import { mergeStateFromDisk, stateLockHeld } from './state.js'
|
|
11
|
+
import { mergeStateFromDisk, stateLockHeld, webhookFingerprint } from './state.js'
|
|
12
12
|
|
|
13
13
|
export const LOCAL_API_PORT = 17430
|
|
14
14
|
|
|
@@ -16,6 +16,12 @@ const CHANNELS = new Set(['none', 'wecom', 'dingtalk', 'feishu', 'bark', 'server
|
|
|
16
16
|
const MAX_URL = 2048
|
|
17
17
|
const MAX_BODY = 8192
|
|
18
18
|
|
|
19
|
+
// What the panel is allowed to see of a verdict: no fingerprint, since it is
|
|
20
|
+
// derived from the url/secret and /status must never help reconstruct those.
|
|
21
|
+
const publicVerify = (v) => (v
|
|
22
|
+
? { at: v.at, ok: v.ok, channel: v.channel, error: v.error, persisted: v.persisted !== false }
|
|
23
|
+
: null)
|
|
24
|
+
|
|
19
25
|
// Show only the host so the panel can confirm the endpoint without exposing it.
|
|
20
26
|
function hostOf(wh) {
|
|
21
27
|
if (!wh?.url) return ''
|
|
@@ -149,6 +155,9 @@ export function startLocalApi({ port = LOCAL_API_PORT, state, notifier, config,
|
|
|
149
155
|
quiet: config.balance?.quiet || { start: '', end: '' },
|
|
150
156
|
enabled: config.balance?.enabled !== false,
|
|
151
157
|
signature: config.notify?.signature !== false,
|
|
158
|
+
// Most recent "send test" outcome. `configured` only says a webhook is
|
|
159
|
+
// stored; this is the only field that can say the channel ever worked.
|
|
160
|
+
verify: publicVerify(state.verify),
|
|
152
161
|
sourceDiag: diag ? diag() : null,
|
|
153
162
|
})
|
|
154
163
|
}
|
|
@@ -167,25 +176,36 @@ export function startLocalApi({ port = LOCAL_API_PORT, state, notifier, config,
|
|
|
167
176
|
const tx = { ...state }
|
|
168
177
|
mergeStateFromDisk(tx)
|
|
169
178
|
const wasConfigured = configured(tx.webhook)
|
|
179
|
+
// Any change to channel / url / secret invalidates the previous test: an
|
|
180
|
+
// old "verified" badge must never survive a repointed webhook.
|
|
181
|
+
const prev = tx.webhook || {}
|
|
182
|
+
const changed = prev.channel !== value.channel
|
|
183
|
+
|| String(prev.url || '') !== String(value.url || '')
|
|
184
|
+
|| String(prev.secret || '') !== String(value.secret || '')
|
|
170
185
|
tx.webhook = value
|
|
171
|
-
|
|
186
|
+
const own = ['webhook']
|
|
187
|
+
if (changed) { tx.verify = null; own.push('verify') }
|
|
172
188
|
// First connect while already in an alert state: supplement ONE current
|
|
173
189
|
// state notice — never while a monitor cycle holds the lock, so an
|
|
174
190
|
// in-flight pending cannot be overwritten through the shared object.
|
|
175
191
|
if (!wasConfigured && configured(value) && tx.alert?.level !== 'normal' && !tx.pending && !stateLockHeld()) {
|
|
176
192
|
tx.pending = { kind: 'current', attempts: 0, hold: false, ambiguous: false, nextAt: Date.now(), lastError: null }
|
|
177
|
-
own
|
|
193
|
+
own.push('pending')
|
|
178
194
|
}
|
|
179
195
|
if (save && save(tx, own) === false) {
|
|
180
196
|
return json(res, 503, fail('busy', '状态文件被占用,请稍后重试'))
|
|
181
197
|
}
|
|
182
198
|
state.webhook = tx.webhook
|
|
199
|
+
if (own.includes('verify')) state.verify = null
|
|
183
200
|
if (own.includes('pending')) state.pending = tx.pending
|
|
184
201
|
logger?.info?.(`推送通道已更新:${value.channel}`) // never log url/secret
|
|
185
202
|
poke?.()
|
|
186
203
|
return json(res, 200, {
|
|
187
204
|
ok: true, channel: value.channel, configured: configured(value),
|
|
188
205
|
urlHost: hostOf(value), secretSet: !!value.secret,
|
|
206
|
+
// Echo the surviving test result: re-saving an unchanged webhook keeps
|
|
207
|
+
// it, any edit drops it, and the panel must not have to guess which.
|
|
208
|
+
verify: tx.verify ?? null,
|
|
189
209
|
})
|
|
190
210
|
}
|
|
191
211
|
|
|
@@ -237,12 +257,50 @@ export function startLocalApi({ port = LOCAL_API_PORT, state, notifier, config,
|
|
|
237
257
|
const now = Date.now()
|
|
238
258
|
if (now - lastTest < 3000) return json(res, 429, fail('too-frequent', '操作太频繁,请 3 秒后再试'))
|
|
239
259
|
lastTest = now
|
|
240
|
-
|
|
260
|
+
// Pin the exact configuration being tested. A send can take up to the
|
|
261
|
+
// notifier timeout, and another page may save a different webhook in the
|
|
262
|
+
// meantime: without this pin, A's success gets stamped on B's badge.
|
|
263
|
+
const target = state.webhook
|
|
264
|
+
const targetFp = webhookFingerprint(target)
|
|
265
|
+
const channel = target.channel
|
|
266
|
+
const r = await notifier.send(target, '余额哨兵 · 测试推送',
|
|
241
267
|
withSignature('这是一条测试消息:webhook 通道工作正常。', config.notify))
|
|
268
|
+
const hint = r.ok ? '' : hintFor(channel, r.code, r.error, r.status || 0)
|
|
269
|
+
|
|
270
|
+
// The saved config is the source of truth. If it moved while the request
|
|
271
|
+
// was in flight, this verdict describes an endpoint nobody uses any more:
|
|
272
|
+
// discard it instead of certifying the new one.
|
|
273
|
+
const tx = { ...state }
|
|
274
|
+
mergeStateFromDisk(tx)
|
|
275
|
+
if (webhookFingerprint(tx.webhook) !== targetFp) {
|
|
276
|
+
logger?.info?.('测试推送返回时推送配置已变更,本次结果已丢弃')
|
|
277
|
+
return json(res, 200, {
|
|
278
|
+
ok: r.ok, error: r.ok ? null : (r.error || ''), chunks: r.chunks || 0,
|
|
279
|
+
status: r.status || 0, code: r.code ?? null, channel,
|
|
280
|
+
hint, stale: true, verify: publicVerify(state.verify),
|
|
281
|
+
})
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// A stored webhook proves nothing about delivery, so the verdict is the
|
|
285
|
+
// only thing that can turn the badge green. Memory is updated even when
|
|
286
|
+
// the file write fails: leaving yesterday's green "succeeded" up for a
|
|
287
|
+
// test that just failed is worse than a result that may not survive a
|
|
288
|
+
// restart, as long as the panel says it was not persisted.
|
|
289
|
+
const verify = { at: Date.now(), ok: !!r.ok, channel, error: r.ok ? null : (r.error || ''), fp: targetFp }
|
|
290
|
+
let persisted = true
|
|
291
|
+
tx.verify = verify
|
|
292
|
+
try {
|
|
293
|
+
if (save && save(tx, ['verify']) === false) persisted = false
|
|
294
|
+
} catch (err) {
|
|
295
|
+
persisted = false
|
|
296
|
+
logger?.warn?.(`测试推送结果写入失败:${String(err?.message || err)}`)
|
|
297
|
+
}
|
|
298
|
+
state.verify = { ...verify, persisted }
|
|
299
|
+
if (!persisted) logger?.warn?.('测试推送结果未能写入状态文件(文件被占用),本次仅在内存中生效')
|
|
242
300
|
return json(res, 200, {
|
|
243
301
|
ok: r.ok, error: r.ok ? null : (r.error || ''), chunks: r.chunks || 0,
|
|
244
|
-
status: r.status || 0, code: r.code ?? null, channel
|
|
245
|
-
hint
|
|
302
|
+
status: r.status || 0, code: r.code ?? null, channel,
|
|
303
|
+
hint, persisted, verify: publicVerify(state.verify),
|
|
246
304
|
})
|
|
247
305
|
}
|
|
248
306
|
|
package/lib/notify.js
CHANGED
|
@@ -5,10 +5,18 @@
|
|
|
5
5
|
|
|
6
6
|
import { createHmac } from 'node:crypto'
|
|
7
7
|
|
|
8
|
-
// One-line attribution appended to every push card
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
|
|
8
|
+
// One-line attribution appended to every push card: pushes land in shared IM
|
|
9
|
+
// groups, so each card doubles as a lightweight install entry; on by default,
|
|
10
|
+
// removable via notify.signature: false (and replaceable via signatureText).
|
|
11
|
+
// The visible label stays the `github:owner/repo` spec people already recognise
|
|
12
|
+
// (the "安装:" prefix plus an identifiable source reads better than a vague
|
|
13
|
+
// "安装说明"), and only that spec is wrapped in a markdown link so it is also
|
|
14
|
+
// tappable — the two goals are not a trade-off. Channels that render no
|
|
15
|
+
// markdown flatten it through toPlainText() into "label + url", which these
|
|
16
|
+
// clients still linkify.
|
|
17
|
+
export const REPO_URL = 'https://github.com/liancheng2020/dsh-balance-sentinel'
|
|
18
|
+
export const INSTALL_SPEC = 'github:liancheng2020/dsh-balance-sentinel'
|
|
19
|
+
export const DEFAULT_SIGNATURE = `via DeepSeek 余额哨兵 · 安装:[${INSTALL_SPEC}](${REPO_URL}#readme)`
|
|
12
20
|
|
|
13
21
|
// Single source of truth for "can we actually push?" — the bridge and the
|
|
14
22
|
// digest scheduler must agree, or the panel says "on" while nothing is sent.
|
|
@@ -34,14 +42,18 @@ function dingtalkSign(secret, timestamp) {
|
|
|
34
42
|
|
|
35
43
|
// Some channels render no markdown at all (Feishu text, Telegram without
|
|
36
44
|
// parse_mode, Bark). Sending raw markdown there shows "### 标题" and
|
|
37
|
-
// "[
|
|
45
|
+
// "[label](url)" as source in the group chat, so flatten it first.
|
|
46
|
+
// A markdown link keeps its label and drops the target: the only markdown link
|
|
47
|
+
// the plugin emits is the signature, whose label already IS the install spec
|
|
48
|
+
// (`github:owner/repo`), and printing the URL next to it just doubled the line.
|
|
49
|
+
// Every other URL in an alert body is written bare, so it survives untouched.
|
|
38
50
|
export function toPlainText(md) {
|
|
39
51
|
return String(md ?? '')
|
|
40
52
|
.replace(/^#{1,6}\s+/gm, '')
|
|
41
53
|
.replace(/\*\*([^*]+)\*\*/g, '$1')
|
|
42
54
|
.replace(/__([^_]+)__/g, '$1')
|
|
43
55
|
.replace(/`([^`]+)`/g, '$1')
|
|
44
|
-
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1
|
|
56
|
+
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1')
|
|
45
57
|
}
|
|
46
58
|
|
|
47
59
|
// Feishu card colour carries the meaning: scanning a busy group chat, red
|
|
@@ -69,7 +81,9 @@ export function toFeishuCard(title, text) {
|
|
|
69
81
|
.trim()
|
|
70
82
|
const elements = []
|
|
71
83
|
if (body) elements.push({ tag: 'div', text: { tag: 'lark_md', content: body } })
|
|
72
|
-
|
|
84
|
+
// lark_md (not plain_text) so the install link in the signature stays tappable
|
|
85
|
+
// in the footer; plain_text would print the markdown source verbatim.
|
|
86
|
+
if (sigAt >= 0) elements.push({ tag: 'note', elements: [{ tag: 'lark_md', content: lines[sigAt].trim() }] })
|
|
73
87
|
return {
|
|
74
88
|
config: { wide_screen_mode: true },
|
|
75
89
|
header: {
|
package/lib/state.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { mkdirSync, readFileSync, writeFileSync, renameSync, chmodSync, unlinkSync } from 'node:fs'
|
|
7
7
|
import { join } from 'node:path'
|
|
8
8
|
import { homedir } from 'node:os'
|
|
9
|
-
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
10
10
|
|
|
11
11
|
export function resolveHome() {
|
|
12
12
|
const env = process.env.DSH_HOME
|
|
@@ -32,6 +32,10 @@ function defaultState() {
|
|
|
32
32
|
prefs: { warn: null, critical: null }, // panel overrides; null = config decides
|
|
33
33
|
balance: { value: null, currency: null, at: null, ok: false, reason: null },
|
|
34
34
|
lastResult: { at: null, ok: false, error: null },
|
|
35
|
+
// Last panel "send test" outcome. Configuring a webhook proves nothing about
|
|
36
|
+
// delivery, so the panel needs this to say "configured, untested" instead of
|
|
37
|
+
// implying the channel works. Cleared whenever the channel/url/secret changes.
|
|
38
|
+
verify: null, // { at, ok, channel, error }
|
|
35
39
|
actor: randomUUID(),
|
|
36
40
|
}
|
|
37
41
|
}
|
|
@@ -46,6 +50,20 @@ function normalize(parsed) {
|
|
|
46
50
|
const pending = p && typeof p === 'object' && KINDS.has(p.kind)
|
|
47
51
|
? { kind: p.kind, attempts: Number(p.attempts) || 0, hold: !!p.hold, ambiguous: !!p.ambiguous, nextAt: Number(p.nextAt) || 0, lastError: p.lastError || null }
|
|
48
52
|
: null
|
|
53
|
+
const rawVerify = parsed.verify
|
|
54
|
+
// `fp` pins the verdict to the webhook it ran against; `persisted` is only
|
|
55
|
+
// false for a verdict that lives in memory and will be lost on restart. A
|
|
56
|
+
// record read back from disk was obviously persisted, so it defaults to true.
|
|
57
|
+
const verify = rawVerify && typeof rawVerify === 'object' && typeof rawVerify.ok === 'boolean'
|
|
58
|
+
? {
|
|
59
|
+
at: Number(rawVerify.at) || null,
|
|
60
|
+
ok: rawVerify.ok,
|
|
61
|
+
channel: String(rawVerify.channel || ''),
|
|
62
|
+
error: rawVerify.error ? String(rawVerify.error) : null,
|
|
63
|
+
fp: rawVerify.fp ? String(rawVerify.fp) : null,
|
|
64
|
+
persisted: rawVerify.persisted !== false,
|
|
65
|
+
}
|
|
66
|
+
: null
|
|
49
67
|
return {
|
|
50
68
|
...d,
|
|
51
69
|
...parsed,
|
|
@@ -55,6 +73,7 @@ function normalize(parsed) {
|
|
|
55
73
|
prefs: { warn: numOrNull(parsed.prefs?.warn), critical: numOrNull(parsed.prefs?.critical) },
|
|
56
74
|
balance: { ...d.balance, ...(parsed.balance || {}) },
|
|
57
75
|
lastResult: { ...d.lastResult, ...(parsed.lastResult || {}) },
|
|
76
|
+
verify,
|
|
58
77
|
}
|
|
59
78
|
}
|
|
60
79
|
|
|
@@ -217,6 +236,37 @@ export function touchStateLock() {
|
|
|
217
236
|
return true
|
|
218
237
|
}
|
|
219
238
|
|
|
239
|
+
// Identity of a webhook config that can travel through state and /status
|
|
240
|
+
// without exposing the url/secret. A test verdict only describes the endpoint it
|
|
241
|
+
// ran against, so this pins one to the other. Lives here because both the bridge
|
|
242
|
+
// (writing verdicts) and the merge below (validating them) need the same value.
|
|
243
|
+
export function webhookFingerprint(wh) {
|
|
244
|
+
return createHash('sha256')
|
|
245
|
+
.update(`${wh?.channel || 'none'}|${wh?.url || ''}|${wh?.secret || ''}`)
|
|
246
|
+
.digest('hex')
|
|
247
|
+
.slice(0, 16)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Which verdict survives when memory and disk disagree. A verdict that never
|
|
251
|
+
// reached the file is newer than the one the file still holds, so it keeps
|
|
252
|
+
// winning while it is at least as recent; an already-persisted one is the file's
|
|
253
|
+
// to decide (another instance may have tested in the meantime).
|
|
254
|
+
function pickVerify(mine, theirs) {
|
|
255
|
+
const keepMine = !!mine && mine.persisted === false
|
|
256
|
+
&& Number(mine.at || 0) >= Number(theirs?.at || 0)
|
|
257
|
+
return keepMine ? mine : (theirs ?? null)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// A verdict only describes the webhook it was produced from: once the
|
|
261
|
+
// channel/url/secret changes, it is meaningless and must be dropped. Both merge
|
|
262
|
+
// paths (read-from-disk and write-to-disk) go through here so neither can keep a
|
|
263
|
+
// verdict alive across a config change.
|
|
264
|
+
function reconcileVerify(mine, theirs, webhook) {
|
|
265
|
+
const picked = pickVerify(mine, theirs)
|
|
266
|
+
if (picked?.fp && picked.fp !== webhookFingerprint(webhook)) return null
|
|
267
|
+
return picked
|
|
268
|
+
}
|
|
269
|
+
|
|
220
270
|
// Re-read the shared state while holding the lock. The in-memory copy may be
|
|
221
271
|
// minutes old (and the panel may have saved a new webhook from the other
|
|
222
272
|
// instance meanwhile), so writing it back untouched would both lose that edit
|
|
@@ -240,6 +290,11 @@ export function mergeStateFromDisk(state) {
|
|
|
240
290
|
if (disk.lastResult && typeof disk.lastResult === 'object') {
|
|
241
291
|
if (!state.lastResult?.at || String(disk.lastResult.at || '') >= String(state.lastResult.at || '')) state.lastResult = disk.lastResult
|
|
242
292
|
}
|
|
293
|
+
// A verdict that could not be written lives only in memory; the file still
|
|
294
|
+
// holds the one before it. Taking the file unconditionally would resurrect an
|
|
295
|
+
// old green "succeeded" over a newer failed test the user just watched fail.
|
|
296
|
+
if (disk.verify !== undefined) state.verify = reconcileVerify(state.verify, disk.verify, state.webhook)
|
|
297
|
+
else if (state.verify?.fp && state.verify.fp !== webhookFingerprint(state.webhook)) state.verify = null
|
|
243
298
|
return true
|
|
244
299
|
}
|
|
245
300
|
|
|
@@ -253,7 +308,7 @@ function readDiskState() {
|
|
|
253
308
|
// Sections a caller can own. The monitor owns the runtime ones; the panel owns
|
|
254
309
|
// the webhook and the threshold prefs.
|
|
255
310
|
const OWN_RUNTIME = ['alert', 'pending', 'balance', 'lastResult']
|
|
256
|
-
const SECTIONS = [...OWN_RUNTIME, 'webhook', 'prefs']
|
|
311
|
+
const SECTIONS = [...OWN_RUNTIME, 'webhook', 'prefs', 'verify']
|
|
257
312
|
|
|
258
313
|
// Compose the document to write. A section the caller does not own is taken from
|
|
259
314
|
// the file verbatim — never merged with the caller's memory. Merging looks safer
|
|
@@ -266,6 +321,10 @@ function mergeForWrite(disk, state, own) {
|
|
|
266
321
|
for (const section of SECTIONS) {
|
|
267
322
|
if (!own.has(section) && disk[section] !== undefined) out[section] = disk[section]
|
|
268
323
|
}
|
|
324
|
+
// Same rule as the read path: an unwritten newer verdict must not be replaced
|
|
325
|
+
// by the older one still in the file when the caller re-writes some other
|
|
326
|
+
// section (a monitor cycle), or the panel's red "failed" reverts to green.
|
|
327
|
+
if (!own.has('verify')) out.verify = reconcileVerify(state.verify, disk.verify ?? null, out.webhook)
|
|
269
328
|
out.actor = disk.actor || state.actor
|
|
270
329
|
out.version = disk.version ?? state.version
|
|
271
330
|
return out
|
|
@@ -289,6 +348,15 @@ export function saveState(state, logger, opts = {}) {
|
|
|
289
348
|
return false
|
|
290
349
|
}
|
|
291
350
|
const next = mergeForWrite(readDiskState(), state, new Set(opts.own || OWN_RUNTIME))
|
|
351
|
+
// `persisted` describes the in-memory copy, not the document: anything that
|
|
352
|
+
// reaches the file has by definition been persisted, so the flag is dropped
|
|
353
|
+
// here. A write that throws never gets this far, so memory keeps saying
|
|
354
|
+
// "not persisted" exactly when that is still true.
|
|
355
|
+
if (next.verify && 'persisted' in next.verify) {
|
|
356
|
+
const written = { ...next.verify }
|
|
357
|
+
delete written.persisted
|
|
358
|
+
next.verify = written
|
|
359
|
+
}
|
|
292
360
|
const file = join(dir, 'state.json')
|
|
293
361
|
const tmp = join(dir, `.state-${randomUUID()}.tmp`)
|
|
294
362
|
writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf8')
|
package/locale/en.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "Balance Sentinel",
|
|
4
|
-
"description": "DeepSeek low-balance alerts pushed to Feishu/DingTalk IM. Local DSH Desktop or local web host only, monitored while DSH runs;
|
|
4
|
+
"description": "DeepSeek low-balance alerts pushed to Feishu/DingTalk IM. Local DSH Desktop or local web host only, monitored while DSH runs; key-free host accounts are supported when the account service is available and signed in."
|
|
5
5
|
},
|
|
6
6
|
"sub": "DeepSeek balance watch · proactive low-balance alerts",
|
|
7
7
|
"refresh": "Refresh",
|
package/locale/zh.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "余额哨兵",
|
|
4
|
-
"description": "DeepSeek 低余额主动推送到飞书/钉钉等 IM;仅支持本机 DSH Desktop/本机 Web,DSH
|
|
4
|
+
"description": "DeepSeek 低余额主动推送到飞书/钉钉等 IM;仅支持本机 DSH Desktop/本机 Web,DSH 运行期间监控;支持宿主账号免填 API Key(需已登录)。"
|
|
5
5
|
},
|
|
6
6
|
"sub": "DeepSeek 余额监控 · 低余额主动提醒",
|
|
7
7
|
"refresh": "刷新",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"level.critical": "余额告急",
|
|
14
14
|
"reason.title": "余额暂不可用",
|
|
15
15
|
"reason.retry": "重试",
|
|
16
|
-
"reason.unauthorized": "API Key 无效或过期:请更新 Key
|
|
16
|
+
"reason.unauthorized": "API Key 无效或过期:请更新 Key,或改用宿主账号登录(免填 Key)。",
|
|
17
17
|
"reason.network": "网络不可达:确认本机能访问 api.deepseek.com(或被代理/防火墙拦截)。",
|
|
18
18
|
"reason.http": "余额接口 HTTP {c},稍后自动重试。",
|
|
19
19
|
"banner": "监控中,通知未接通:配置通道后,低余额会自动推到你的 IM。",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"alert.retry": "重试发送",
|
|
29
29
|
"alert.retried": "已触发重试,立即补发。",
|
|
30
30
|
"monitor.off": "后台监控已关闭(balance.enabled=false),面板仅展示。",
|
|
31
|
-
"support.scope": "仅支持本机 DSH Desktop/本机 Web:DSH 运行时监控,退出后停止;不支持远程 Web
|
|
31
|
+
"support.scope": "仅支持本机 DSH Desktop/本机 Web:DSH 运行时监控,退出后停止;不支持远程 Web 面板连接。支持宿主账号免填 Key:需宿主提供账号服务且已登录。",
|
|
32
32
|
"quiet.on": "免打扰 {s}–{e},期间告警顺延、出窗合并推送。",
|
|
33
33
|
"th.title": "告警阈值",
|
|
34
34
|
"th.warn": "预警阈值",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-balance-sentinel",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "DeepSeek 低余额主动推送到飞书/钉钉等 IM;仅限本机 DSH Desktop/本机 Web,DSH
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "DeepSeek 低余额主动推送到飞书/钉钉等 IM;仅限本机 DSH Desktop/本机 Web,DSH 运行期间监控;支持宿主账号免填 API Key(需已登录)。",
|
|
5
5
|
"author": "liancheng2020",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"engines": {
|
|
@@ -19,7 +19,15 @@ function createMiniReact() {
|
|
|
19
19
|
const useState = (init) => {
|
|
20
20
|
const store = ctx.store, i = ctx.idx++
|
|
21
21
|
if (store.hooks.length <= i) store.hooks[i] = typeof init === 'function' ? init() : init
|
|
22
|
-
|
|
22
|
+
// React runs a functional update during the NEXT render, not at call time.
|
|
23
|
+
// Applying it eagerly here would hide a real class of bug: an updater that
|
|
24
|
+
// compares against a closure variable which the caller reassigns on the very
|
|
25
|
+
// next line. That is what left the threshold inputs empty in the real panel
|
|
26
|
+
// while every test stayed green.
|
|
27
|
+
const set = (v) => {
|
|
28
|
+
if (typeof v === 'function') { store.queue.push([i, v]); return }
|
|
29
|
+
store.hooks[i] = v
|
|
30
|
+
}
|
|
23
31
|
return [store.hooks[i], set]
|
|
24
32
|
}
|
|
25
33
|
// Dependency-aware: a real component re-runs an effect when deps change, and
|
|
@@ -41,14 +49,27 @@ function createMiniReact() {
|
|
|
41
49
|
return store.refs[i]
|
|
42
50
|
}
|
|
43
51
|
const useMemo = (fn) => fn()
|
|
52
|
+
// Pending functional updates are applied at the top of a render pass, the way
|
|
53
|
+
// React does it, so a test cannot accidentally depend on eager application.
|
|
54
|
+
const flushPending = () => {
|
|
55
|
+
for (const s of stores.values()) {
|
|
56
|
+
while (s.queue.length) { const [i, fn] = s.queue.shift(); s.hooks[i] = fn(s.hooks[i]) }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
let depth = 0
|
|
44
60
|
function render(el, path = '0') {
|
|
61
|
+
if (depth === 0) flushPending()
|
|
62
|
+
depth++
|
|
63
|
+
try { return renderNode(el, path) } finally { depth-- }
|
|
64
|
+
}
|
|
65
|
+
function renderNode(el, path) {
|
|
45
66
|
if (el == null || typeof el === 'boolean') return null
|
|
46
67
|
if (typeof el === 'string' || typeof el === 'number') return { text: String(el) }
|
|
47
68
|
if (Array.isArray(el)) return { array: el.map((c, i) => render(c, path + '/' + i)).filter(Boolean) }
|
|
48
69
|
const { type, props, children } = el
|
|
49
70
|
if (typeof type === 'function') {
|
|
50
71
|
const key = path + ':' + (type.name || 'anon')
|
|
51
|
-
if (!stores.has(key)) stores.set(key, { hooks: [], effects: [], refs: [], ran: false })
|
|
72
|
+
if (!stores.has(key)) stores.set(key, { hooks: [], effects: [], refs: [], ran: false, queue: [] })
|
|
52
73
|
const store = stores.get(key); const prev = ctx
|
|
53
74
|
ctx = { hooks: store.hooks, idx: 0, store }
|
|
54
75
|
const out = type({ ...props, children })
|
|
@@ -99,6 +120,9 @@ const HOST = {
|
|
|
99
120
|
let statusFails = 0
|
|
100
121
|
let statusCalls = 0
|
|
101
122
|
let webhookFails = 0
|
|
123
|
+
let testPushFails = 0
|
|
124
|
+
let testPushStale = 0
|
|
125
|
+
let testPushUnpersisted = 0
|
|
102
126
|
const posts = []
|
|
103
127
|
const fetchMock = async (url, init) => {
|
|
104
128
|
const u = String(url)
|
|
@@ -117,7 +141,22 @@ const fetchMock = async (url, init) => {
|
|
|
117
141
|
}
|
|
118
142
|
return { ok: true, status: 200, json: async () => ({ ok: true, channel: body.channel, configured: !off, urlHost: off ? '' : 'qyapi.weixin.qq.com', secretSet: false }) }
|
|
119
143
|
}
|
|
120
|
-
if (u.startsWith('http://127.0.0.1:17430/test-push')) {
|
|
144
|
+
if (u.startsWith('http://127.0.0.1:17430/test-push')) {
|
|
145
|
+
posts.push(['test-push'])
|
|
146
|
+
if (testPushStale > 0) {
|
|
147
|
+
testPushStale--
|
|
148
|
+
return { ok: true, status: 200, json: async () => ({ ok: true, stale: true, chunks: 1, channel: 'wecom' }) }
|
|
149
|
+
}
|
|
150
|
+
if (testPushUnpersisted > 0) {
|
|
151
|
+
testPushUnpersisted--
|
|
152
|
+
return { ok: true, status: 200, json: async () => ({ ok: false, error: 'errcode 93000 invalid webhook', code: 93000, persisted: false }) }
|
|
153
|
+
}
|
|
154
|
+
if (testPushFails > 0) {
|
|
155
|
+
testPushFails--
|
|
156
|
+
return { ok: true, status: 200, json: async () => ({ ok: false, error: 'errcode 93000 invalid webhook', code: 93000, hint: 'Webhook 地址无效' }) }
|
|
157
|
+
}
|
|
158
|
+
return { ok: true, status: 200, json: async () => ({ ok: true, chunks: 1, channel: 'wecom' }) }
|
|
159
|
+
}
|
|
121
160
|
if (u.startsWith('http://127.0.0.1:17430/prefs')) {
|
|
122
161
|
const body = JSON.parse(init?.body || '{}')
|
|
123
162
|
posts.push(['prefs', body])
|
|
@@ -181,8 +220,16 @@ await atest('P1 hero shows official balance + level badge', async () => {
|
|
|
181
220
|
const { render, dispose } = boot()
|
|
182
221
|
render()
|
|
183
222
|
await sleep(30)
|
|
184
|
-
const
|
|
223
|
+
const node = render()
|
|
224
|
+
const txt = textOf(node)
|
|
185
225
|
if (!txt.includes('¥12.50') || !txt.includes('余额预警')) throw new Error(txt.slice(0, 200))
|
|
226
|
+
// Re-entering the panel used to leave both threshold inputs blank with a red
|
|
227
|
+
// "must be positive" warning: the first /status must seed the drafts.
|
|
228
|
+
const warnIn = findById(node, 'sentinel-warn')
|
|
229
|
+
const critIn = findById(node, 'sentinel-crit')
|
|
230
|
+
if (warnIn.props.value !== '20' || critIn.props.value !== '5') {
|
|
231
|
+
throw new Error('threshold drafts not seeded: ' + JSON.stringify([warnIn.props.value, critIn.props.value]))
|
|
232
|
+
}
|
|
186
233
|
dispose()
|
|
187
234
|
})
|
|
188
235
|
await atest('P2 unavailable: clear reason + retry', async () => {
|
|
@@ -330,7 +377,7 @@ await atest('P12 support boundary shown in zh/en; bridge-down names remote panel
|
|
|
330
377
|
await sleep(30)
|
|
331
378
|
let txt = textOf(b.render())
|
|
332
379
|
if (!txt.includes('仅支持本机 DSH Desktop') || !txt.includes('不支持远程 Web 面板')) throw new Error(txt.slice(0, 300))
|
|
333
|
-
if (!txt.includes('
|
|
380
|
+
if (!txt.includes('支持宿主账号免填 Key:需宿主提供账号服务且已登录')) throw new Error('no-key boundary missing')
|
|
334
381
|
b.dispose()
|
|
335
382
|
|
|
336
383
|
resetHost()
|
|
@@ -340,6 +387,7 @@ await atest('P12 support boundary shown in zh/en; bridge-down names remote panel
|
|
|
340
387
|
txt = textOf(b.render())
|
|
341
388
|
if (!txt.includes('Local DSH Desktop or local web host only')) throw new Error(txt.slice(0, 300))
|
|
342
389
|
if (!txt.includes('remote web panels are not supported')) throw new Error('en support boundary incomplete')
|
|
390
|
+
if (!txt.includes('Key-free host accounts are supported')) throw new Error('en key-free boundary must stay conditional')
|
|
343
391
|
b.dispose()
|
|
344
392
|
|
|
345
393
|
resetHost(); statusFails = 99
|
|
@@ -351,6 +399,119 @@ await atest('P12 support boundary shown in zh/en; bridge-down names remote panel
|
|
|
351
399
|
b.dispose()
|
|
352
400
|
})
|
|
353
401
|
|
|
402
|
+
// Regression: a server-side rejection used to return before clearing `busy`, so
|
|
403
|
+
// the save button stayed on "保存中…" and disabled forever.
|
|
404
|
+
await atest('P14 save failure clears busy; edit then retry succeeds', async () => {
|
|
405
|
+
resetHost(); HOST.configured = false; HOST.channel = 'none'
|
|
406
|
+
webhookFails = 1
|
|
407
|
+
const { render, dispose } = boot()
|
|
408
|
+
render()
|
|
409
|
+
await sleep(30)
|
|
410
|
+
let node = render()
|
|
411
|
+
findById(node, 'sentinel-url').props.onChange({ target: { value: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=k' } })
|
|
412
|
+
node = render()
|
|
413
|
+
await findButton(node, '仅保存').props.onClick()
|
|
414
|
+
await sleep(80)
|
|
415
|
+
node = render()
|
|
416
|
+
if (!textOf(node).includes('URL 格式不对')) throw new Error('server rejection must be shown')
|
|
417
|
+
const retryBtn = findButton(node, '仅保存')
|
|
418
|
+
if (!retryBtn) throw new Error('button stuck on 保存中 after a failed save')
|
|
419
|
+
if (retryBtn.props.disabled) throw new Error('button must be re-enabled after a failed save')
|
|
420
|
+
findById(node, 'sentinel-url').props.onChange({ target: { value: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ok' } })
|
|
421
|
+
node = render()
|
|
422
|
+
await findButton(node, '仅保存').props.onClick()
|
|
423
|
+
await sleep(80)
|
|
424
|
+
node = render()
|
|
425
|
+
const txt = textOf(node)
|
|
426
|
+
if (!txt.includes('已保存,立即生效')) throw new Error('retry after fixing the input must succeed')
|
|
427
|
+
if (!txt.includes('已配置,待测试')) throw new Error('saved-but-untested must not read as connected')
|
|
428
|
+
webhookFails = 0
|
|
429
|
+
dispose()
|
|
430
|
+
})
|
|
431
|
+
await atest('P15 configured vs connected: untested / verified / failed', async () => {
|
|
432
|
+
resetHost(); HOST.verify = null
|
|
433
|
+
let b = boot(); b.render(); await sleep(30)
|
|
434
|
+
let txt = textOf(b.render())
|
|
435
|
+
if (!txt.includes('已配置,待测试')) throw new Error('untested state missing: ' + txt.slice(0, 200))
|
|
436
|
+
if (txt.includes('最近测试成功')) throw new Error('must not claim delivery before a test')
|
|
437
|
+
b.dispose()
|
|
438
|
+
|
|
439
|
+
resetHost(); HOST.verify = { at: Date.now(), ok: true, channel: 'wecom', error: null }
|
|
440
|
+
b = boot(); b.render(); await sleep(30)
|
|
441
|
+
txt = textOf(b.render())
|
|
442
|
+
if (!txt.includes('最近测试成功')) throw new Error('verified state missing')
|
|
443
|
+
b.dispose()
|
|
444
|
+
|
|
445
|
+
resetHost(); HOST.verify = { at: Date.now(), ok: false, channel: 'wecom', error: 'errcode 93000 invalid webhook' }
|
|
446
|
+
b = boot(); b.render(); await sleep(30)
|
|
447
|
+
txt = textOf(b.render())
|
|
448
|
+
if (!txt.includes('最近测试失败') || !txt.includes('93000')) throw new Error('failed state must carry the reason: ' + txt.slice(0, 240))
|
|
449
|
+
b.dispose()
|
|
450
|
+
})
|
|
451
|
+
// Regression: re-entering the panel once showed two empty threshold inputs plus
|
|
452
|
+
// a red "must be positive" line, because the drafts were seeded only by a /status
|
|
453
|
+
// that may land late (or not at all). An untouched draft must fall back to the
|
|
454
|
+
// host value instead of rendering ''.
|
|
455
|
+
await atest('P17 thresholds never render blank; fallback when host omits them', async () => {
|
|
456
|
+
resetHost(); delete HOST.thresholds
|
|
457
|
+
const { render, dispose } = boot()
|
|
458
|
+
render()
|
|
459
|
+
await sleep(30)
|
|
460
|
+
const node = render()
|
|
461
|
+
const w = findById(node, 'sentinel-warn').props.value
|
|
462
|
+
const c = findById(node, 'sentinel-crit').props.value
|
|
463
|
+
if (w !== '20' || c !== '5') throw new Error('blank/incorrect fallback: ' + JSON.stringify([w, c]))
|
|
464
|
+
if (textOf(node).includes('需为正数')) throw new Error('validation error shown for untouched defaults')
|
|
465
|
+
dispose()
|
|
466
|
+
})
|
|
467
|
+
await atest('P16 save&test failure still re-enables the button', async () => {
|
|
468
|
+
resetHost(); HOST.configured = false; HOST.channel = 'none'
|
|
469
|
+
testPushFails = 1
|
|
470
|
+
const { render, dispose } = boot()
|
|
471
|
+
render()
|
|
472
|
+
await sleep(30)
|
|
473
|
+
let node = render()
|
|
474
|
+
findById(node, 'sentinel-url').props.onChange({ target: { value: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=k' } })
|
|
475
|
+
node = render()
|
|
476
|
+
await findButton(node, '保存并发送测试').props.onClick()
|
|
477
|
+
await sleep(120)
|
|
478
|
+
node = render()
|
|
479
|
+
const txt = textOf(node)
|
|
480
|
+
if (!txt.includes('93000')) throw new Error('test failure must be surfaced: ' + txt.slice(0, 240))
|
|
481
|
+
if (txt.includes('保存中') || txt.includes('发送中')) throw new Error('button stuck busy after a failed test')
|
|
482
|
+
if (!findButton(node, '发送测试推送')) throw new Error('test button not restored')
|
|
483
|
+
testPushFails = 0
|
|
484
|
+
dispose()
|
|
485
|
+
})
|
|
486
|
+
// A verdict can arrive after another page repointed the webhook; the panel must
|
|
487
|
+
// say it was discarded instead of letting it read as the new channel's result.
|
|
488
|
+
await atest('P19 stale verdict is explained, never shown as success', async () => {
|
|
489
|
+
resetHost()
|
|
490
|
+
testPushStale = 1
|
|
491
|
+
const { render, dispose } = boot()
|
|
492
|
+
render()
|
|
493
|
+
await sleep(30)
|
|
494
|
+
await findButton(render(), '发送测试推送').props.onClick()
|
|
495
|
+
await sleep(80)
|
|
496
|
+
const txt = textOf(render())
|
|
497
|
+
if (!txt.includes('推送配置已变更')) throw new Error('stale verdict must be explained: ' + txt.slice(0, 240))
|
|
498
|
+
if (txt.includes('测试推送成功')) throw new Error('stale verdict must not read as success')
|
|
499
|
+
dispose()
|
|
500
|
+
})
|
|
501
|
+
await atest('P20 unpersisted verdict is shown and labelled', async () => {
|
|
502
|
+
resetHost()
|
|
503
|
+
testPushUnpersisted = 1
|
|
504
|
+
const { render, dispose } = boot()
|
|
505
|
+
render()
|
|
506
|
+
await sleep(30)
|
|
507
|
+
await findButton(render(), '发送测试推送').props.onClick()
|
|
508
|
+
await sleep(80)
|
|
509
|
+
const txt = textOf(render())
|
|
510
|
+
if (!txt.includes('93000')) throw new Error('failure must still be shown: ' + txt.slice(0, 240))
|
|
511
|
+
if (!txt.includes('重启后会丢失')) throw new Error('unpersisted result must say so')
|
|
512
|
+
dispose()
|
|
513
|
+
})
|
|
514
|
+
|
|
354
515
|
await atest('P13 zh/en catalogs have identical keys', async () => {
|
|
355
516
|
const iZh = clientCode.indexOf(' zh: {')
|
|
356
517
|
const iEn = clientCode.indexOf(' en: {')
|
package/scripts/selftest.mjs
CHANGED
|
@@ -12,8 +12,8 @@ import { join } from 'node:path'
|
|
|
12
12
|
process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'sentinel-selftest-'))
|
|
13
13
|
|
|
14
14
|
const { normalizeWallets, pickPrimary, levelOf, effectiveThresholds, applyBalance, deliverPending, formatAlert, createBalanceSource, startMonitor, RECOVERY_COOLDOWN_MS } = await import('../lib/balance.js')
|
|
15
|
-
const { mergeStateFromDisk, acquireStateLock, saveState, loadState } = await import('../lib/state.js')
|
|
16
|
-
const { createNotifier, chunkContent, withSignature, DEFAULT_SIGNATURE, toFeishuCard } = await import('../lib/notify.js')
|
|
15
|
+
const { mergeStateFromDisk, acquireStateLock, saveState, loadState, webhookFingerprint } = await import('../lib/state.js')
|
|
16
|
+
const { createNotifier, chunkContent, withSignature, DEFAULT_SIGNATURE, REPO_URL, INSTALL_SPEC, toFeishuCard, toPlainText } = await import('../lib/notify.js')
|
|
17
17
|
const { startLocalApi } = await import('../lib/localapi.js')
|
|
18
18
|
const { isQuietNow } = await import('../lib/time.js')
|
|
19
19
|
|
|
@@ -208,10 +208,27 @@ test('F3 resolved notice explains threshold cause', () => {
|
|
|
208
208
|
assert.ok(top.title.includes('已恢复'))
|
|
209
209
|
assert.ok(!top.text.includes('解除原因'))
|
|
210
210
|
})
|
|
211
|
-
test('F2 signature
|
|
212
|
-
|
|
211
|
+
test('F2 signature keeps the install spec readable and tappable, opt-out', () => {
|
|
212
|
+
// The label stays the recognisable `github:owner/repo` spec (with its 安装:
|
|
213
|
+
// prefix); only that spec is the link. Replacing the text with a generic
|
|
214
|
+
// "安装说明" lost the distinction the previous footer had.
|
|
215
|
+
assert.ok(DEFAULT_SIGNATURE.includes(`安装:[${INSTALL_SPEC}](${REPO_URL}#readme)`), 'signature must label the link with the install spec')
|
|
216
|
+
assert.ok(!DEFAULT_SIGNATURE.includes('[安装说明]'))
|
|
213
217
|
assert.ok(withSignature('x', {}).endsWith(DEFAULT_SIGNATURE))
|
|
214
218
|
assert.ok(!withSignature('x', { signature: false }).includes('via'))
|
|
219
|
+
// Feishu renders the footer from a note element: plain_text would print the
|
|
220
|
+
// markdown source, so it must be lark_md to keep the link tappable.
|
|
221
|
+
const note = toFeishuCard('t', withSignature('body', {})).elements.find((e) => e.tag === 'note')
|
|
222
|
+
assert.equal(note.elements[0].tag, 'lark_md')
|
|
223
|
+
assert.ok(note.elements[0].content.includes('#readme'))
|
|
224
|
+
// Channels without markdown must show the label only: no "](" leftovers and no
|
|
225
|
+
// duplicated URL, while bare URLs elsewhere in the body stay intact.
|
|
226
|
+
const plain = toPlainText(withSignature('body', {}))
|
|
227
|
+
assert.ok(!plain.includes(']('), 'plain channels must not show markdown source')
|
|
228
|
+
assert.ok(plain.includes(`安装:${INSTALL_SPEC}`), 'plain footer keeps the install spec')
|
|
229
|
+
assert.ok(!plain.includes(REPO_URL), 'plain channels must not append the link target')
|
|
230
|
+
assert.ok(toPlainText('充值:https://platform.deepseek.com/').includes('https://platform.deepseek.com/'),
|
|
231
|
+
'bare URLs in the body must survive flattening')
|
|
215
232
|
})
|
|
216
233
|
|
|
217
234
|
// ---- S: source chain ----
|
|
@@ -398,6 +415,87 @@ await atest('B6 test-push reaches webhook', async () => {
|
|
|
398
415
|
await new Promise((r) => hook.close(r))
|
|
399
416
|
})
|
|
400
417
|
|
|
418
|
+
// ---- V: configured != connected (test result is remembered, and invalidated) ----
|
|
419
|
+
await atest('B7 test-push records the result; a new webhook clears it', async () => {
|
|
420
|
+
const s = fresh()
|
|
421
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
422
|
+
const stop = bridge(17437, s, { notifier: { send: async () => ({ ok: true, chunks: 1, status: 200 }) } })
|
|
423
|
+
await wait()
|
|
424
|
+
await (await fetch('http://127.0.0.1:17437/test-push', { method: 'POST' })).json()
|
|
425
|
+
let st = await (await fetch('http://127.0.0.1:17437/status')).json()
|
|
426
|
+
assert.equal(st.verify.ok, true, 'a delivered test must be recorded')
|
|
427
|
+
assert.equal(st.verify.channel, 'wecom')
|
|
428
|
+
// Re-saving the same webhook must keep the result: a no-op edit is not a
|
|
429
|
+
// re-test, and blanking it would flash "untested" for an unchanged endpoint.
|
|
430
|
+
const same = await (await fetch('http://127.0.0.1:17437/webhook', {
|
|
431
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
432
|
+
body: JSON.stringify({ channel: 'wecom', url: 'http://127.0.0.1:1/a' }),
|
|
433
|
+
})).json()
|
|
434
|
+
assert.equal(same.verify?.ok, true, 'unchanged webhook keeps its test result')
|
|
435
|
+
// Repointing the webhook must invalidate the old "verified": otherwise the
|
|
436
|
+
// panel keeps claiming delivery for an endpoint that was never tested.
|
|
437
|
+
const w = await (await fetch('http://127.0.0.1:17437/webhook', {
|
|
438
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
439
|
+
body: JSON.stringify({ channel: 'wecom', url: 'http://127.0.0.1:1/b' }),
|
|
440
|
+
})).json()
|
|
441
|
+
assert.equal(w.ok, true)
|
|
442
|
+
st = await (await fetch('http://127.0.0.1:17437/status')).json()
|
|
443
|
+
assert.equal(st.verify, null, 'editing the webhook must drop the stale test result')
|
|
444
|
+
stop()
|
|
445
|
+
})
|
|
446
|
+
await atest('B8 failed test-push records ok:false with the reason', async () => {
|
|
447
|
+
const s = fresh()
|
|
448
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
449
|
+
const stop = bridge(17438, s, {
|
|
450
|
+
notifier: { send: async () => ({ ok: false, chunks: 1, status: 200, code: 93000, error: 'invalid webhook' }) },
|
|
451
|
+
})
|
|
452
|
+
await wait()
|
|
453
|
+
await (await fetch('http://127.0.0.1:17438/test-push', { method: 'POST' })).json()
|
|
454
|
+
const st = await (await fetch('http://127.0.0.1:17438/status')).json()
|
|
455
|
+
assert.equal(st.verify.ok, false)
|
|
456
|
+
assert.ok(String(st.verify.error).includes('invalid webhook'))
|
|
457
|
+
stop()
|
|
458
|
+
})
|
|
459
|
+
await atest('B9 a verdict is pinned to the tested webhook; a repoint discards it', async () => {
|
|
460
|
+
const s = fresh()
|
|
461
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
462
|
+
let release
|
|
463
|
+
const gate = new Promise((r) => { release = r })
|
|
464
|
+
const stop = bridge(17439, s, { notifier: { send: async () => { await gate; return { ok: true, chunks: 1, status: 200 } } } })
|
|
465
|
+
await wait()
|
|
466
|
+
// Start testing A, then have another page save B while A's send is in flight.
|
|
467
|
+
const pending = fetch('http://127.0.0.1:17439/test-push', { method: 'POST' }).then((r) => r.json())
|
|
468
|
+
await wait()
|
|
469
|
+
const w = await (await fetch('http://127.0.0.1:17439/webhook', {
|
|
470
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
471
|
+
body: JSON.stringify({ channel: 'wecom', url: 'http://127.0.0.1:1/b' }),
|
|
472
|
+
})).json()
|
|
473
|
+
assert.equal(w.ok, true)
|
|
474
|
+
release()
|
|
475
|
+
const j = await pending
|
|
476
|
+
assert.equal(j.stale, true, 'a verdict for a replaced webhook must be flagged stale')
|
|
477
|
+
const st = await (await fetch('http://127.0.0.1:17439/status')).json()
|
|
478
|
+
assert.equal(st.verify, null, "A's success must never certify B")
|
|
479
|
+
stop()
|
|
480
|
+
})
|
|
481
|
+
await atest('B10 failed test beats an older success even when the save fails', async () => {
|
|
482
|
+
const s = fresh()
|
|
483
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
484
|
+
s.verify = { at: 1, ok: true, channel: 'wecom', error: null, fp: 'old', persisted: true }
|
|
485
|
+
const stop = bridge(17440, s, {
|
|
486
|
+
save: () => false, // state file locked / unwritable
|
|
487
|
+
notifier: { send: async () => ({ ok: false, chunks: 1, status: 200, code: 93000, error: 'invalid webhook' }) },
|
|
488
|
+
})
|
|
489
|
+
await wait()
|
|
490
|
+
const j = await (await fetch('http://127.0.0.1:17440/test-push', { method: 'POST' })).json()
|
|
491
|
+
assert.equal(j.ok, false)
|
|
492
|
+
assert.equal(j.persisted, false, 'the response must admit the result was not written')
|
|
493
|
+
const st = await (await fetch('http://127.0.0.1:17440/status')).json()
|
|
494
|
+
assert.equal(st.verify.ok, false, 'the previous green success must not survive a failed test')
|
|
495
|
+
assert.equal(st.verify.persisted, false, 'the panel must know it was not persisted')
|
|
496
|
+
stop()
|
|
497
|
+
})
|
|
498
|
+
|
|
401
499
|
// ---- W: wecom chunking still within platform cap ----
|
|
402
500
|
await atest('W1 wecom 8000B chunks each <=4096B', async () => {
|
|
403
501
|
const received = []
|
|
@@ -679,6 +777,103 @@ await atest('M10 state + fallback receipt both unwritable: risk is surfaced, ded
|
|
|
679
777
|
rmSync(blocker, { recursive: true, force: true })
|
|
680
778
|
})
|
|
681
779
|
|
|
780
|
+
// Real temp state file: the disk still holds an older success while memory holds
|
|
781
|
+
// a failure that could not be written. A monitor cycle merges before deciding,
|
|
782
|
+
// and that merge used to resurrect the old green verdict.
|
|
783
|
+
await atest('M11 an unwritten verdict beats the older success on disk', async () => {
|
|
784
|
+
const s = fresh()
|
|
785
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
786
|
+
s.verify = { at: 1000, ok: true, channel: 'wecom', error: null, fp: webhookFingerprint(s.webhook), persisted: true }
|
|
787
|
+
assert.equal(saveState(s, undefined, { own: ['webhook', 'verify'] }), true)
|
|
788
|
+
|
|
789
|
+
// The panel's failed test could not be written: it exists only in memory.
|
|
790
|
+
s.verify = { at: 2000, ok: false, channel: 'wecom', error: 'invalid webhook', fp: webhookFingerprint(s.webhook), persisted: false }
|
|
791
|
+
mergeStateFromDisk(s) // what any monitor cycle does before deciding
|
|
792
|
+
assert.equal(s.verify.ok, false, 'a newer unwritten failure must survive the merge')
|
|
793
|
+
assert.equal(s.verify.persisted, false, 'and must keep saying it was not persisted')
|
|
794
|
+
mergeStateFromDisk(s)
|
|
795
|
+
assert.equal(s.verify.ok, false, 'and stay stable across cycles')
|
|
796
|
+
assert.equal(loadState().verify.ok, true, 'the file itself still holds the old success')
|
|
797
|
+
})
|
|
798
|
+
await atest('M12 a verdict dies with the config it was tested against', async () => {
|
|
799
|
+
const s = fresh()
|
|
800
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
801
|
+
s.verify = { at: 1000, ok: true, channel: 'wecom', error: null, fp: webhookFingerprint(s.webhook), persisted: true }
|
|
802
|
+
assert.equal(saveState(s, undefined, { own: ['webhook', 'verify'] }), true)
|
|
803
|
+
|
|
804
|
+
// Another page repoints the webhook and clears the verdict on disk.
|
|
805
|
+
const disk = loadState()
|
|
806
|
+
disk.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/b', secret: '' }
|
|
807
|
+
disk.verify = null
|
|
808
|
+
assert.equal(saveState(disk, undefined, { own: ['webhook', 'verify'] }), true)
|
|
809
|
+
|
|
810
|
+
// Memory still holds an unwritten failure produced by the OLD webhook.
|
|
811
|
+
s.verify = { at: 2000, ok: false, channel: 'wecom', error: 'invalid webhook', fp: webhookFingerprint(s.webhook), persisted: false }
|
|
812
|
+
mergeStateFromDisk(s)
|
|
813
|
+
assert.equal(s.webhook.url, 'http://127.0.0.1:1/b', 'config comes from disk')
|
|
814
|
+
assert.equal(s.verify, null, 'the old verdict must not outlive its config')
|
|
815
|
+
})
|
|
816
|
+
|
|
817
|
+
// End-to-end: a real monitor cycle (disk merge at the start, real saveState at
|
|
818
|
+
// the end) must not swap the unwritten failure back for the older success, and
|
|
819
|
+
// once that cycle does write it, the verdict stops claiming "not persisted".
|
|
820
|
+
await atest('M13 a full monitor cycle keeps the newer failed verdict and persists it', async () => {
|
|
821
|
+
const s = fresh()
|
|
822
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
823
|
+
s.verify = { at: 1000, ok: true, channel: 'wecom', error: null, fp: webhookFingerprint(s.webhook), persisted: true }
|
|
824
|
+
assert.equal(saveState(s, undefined, { own: ['webhook', 'verify'] }), true) // disk: older success
|
|
825
|
+
|
|
826
|
+
// Panel: the new test failed AND its save failed — memory only.
|
|
827
|
+
s.verify = { at: 2000, ok: false, channel: 'wecom', error: 'invalid webhook', fp: webhookFingerprint(s.webhook), persisted: false }
|
|
828
|
+
|
|
829
|
+
const ctl = startMonitor({
|
|
830
|
+
fetchBalance: async () => okFr(10),
|
|
831
|
+
state: s,
|
|
832
|
+
notifier: okNotifier,
|
|
833
|
+
config: { balance: { pollSeconds: 3600 } },
|
|
834
|
+
save: (x) => saveState(x),
|
|
835
|
+
})
|
|
836
|
+
ctl.poke()
|
|
837
|
+
await pause(400)
|
|
838
|
+
ctl.stop()
|
|
839
|
+
|
|
840
|
+
assert.equal(s.verify.ok, false, 'the failed verdict must survive a full cycle')
|
|
841
|
+
assert.notEqual(s.verify.persisted, false, 'a verdict the cycle did write is no longer unpersisted')
|
|
842
|
+
assert.equal(loadState().verify.ok, false, 'the file now holds the failure')
|
|
843
|
+
})
|
|
844
|
+
await atest('M14 a cycle does not carry a verdict onto a replaced webhook', async () => {
|
|
845
|
+
const s = fresh()
|
|
846
|
+
s.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
|
|
847
|
+
s.verify = { at: 1000, ok: true, channel: 'wecom', error: null, fp: webhookFingerprint(s.webhook), persisted: true }
|
|
848
|
+
assert.equal(saveState(s, undefined, { own: ['webhook', 'verify'] }), true)
|
|
849
|
+
|
|
850
|
+
// Another page repoints the webhook on disk while memory still holds an
|
|
851
|
+
// unwritten failure produced by the old one.
|
|
852
|
+
const disk = loadState()
|
|
853
|
+
disk.webhook = { channel: 'wecom', url: 'http://127.0.0.1:1/b', secret: '' }
|
|
854
|
+
disk.verify = null
|
|
855
|
+
assert.equal(saveState(disk, undefined, { own: ['webhook', 'verify'] }), true)
|
|
856
|
+
s.verify = {
|
|
857
|
+
at: 2000, ok: false, channel: 'wecom', error: 'invalid webhook',
|
|
858
|
+
fp: webhookFingerprint({ channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }), persisted: false,
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
const ctl = startMonitor({
|
|
862
|
+
fetchBalance: async () => okFr(10),
|
|
863
|
+
state: s,
|
|
864
|
+
notifier: okNotifier,
|
|
865
|
+
config: { balance: { pollSeconds: 3600 } },
|
|
866
|
+
save: (x) => saveState(x),
|
|
867
|
+
})
|
|
868
|
+
ctl.poke()
|
|
869
|
+
await pause(400)
|
|
870
|
+
ctl.stop()
|
|
871
|
+
|
|
872
|
+
assert.equal(s.webhook.url, 'http://127.0.0.1:1/b', 'config comes from disk')
|
|
873
|
+
assert.equal(s.verify, null, 'a verdict for the old webhook must not follow the config')
|
|
874
|
+
assert.equal(loadState().verify, null, 'and it must not be written back either')
|
|
875
|
+
})
|
|
876
|
+
|
|
682
877
|
console.log(`\n${passed} passed, ${failed} failed`)
|
|
683
878
|
process.exitCode = failed ? 1 : 0
|
|
684
879
|
setTimeout(() => process.exit(process.exitCode), 100).unref()
|