dsh-fishpal 0.9.19 → 0.9.20

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
@@ -4,6 +4,61 @@
4
4
 
5
5
  > 0.9.0 没有条目(那版的改动散在 git 历史里,不回填)。从 0.9.1 起逐版记录。
6
6
 
7
+ ## [0.9.20] — 2026-12-01
8
+
9
+ **漂流瓶循环广播:从「一重启就废」改成写盘排期。**
10
+
11
+ 先前这功能是有的,但只在内存里:批准一只瓶子时,用 `setTimeout` 把后续几遍排在后台。
12
+ DSH 一重启,这些定时器全部作废 —— 而它一天要重启好几次。
13
+
14
+ 证据不是猜的:`D:\fishpal-data\fishpal.log` 从 11-29 到 12-01,所有漂流瓶记录里
15
+ 只有「收藏 / 取消收藏」,**「已扔进公共池」和「循环已排定」一条都没有**。
16
+ 这个功能写了却从来没跑完过。
17
+
18
+ ### 修法
19
+
20
+ 新增 **`lib/bottle-loop.js`**:事实源从内存换成磁盘文件 `bottle-loop.json`。
21
+
22
+ ```json
23
+ { "bottles": [{ "bottleId": "...", "raw": "...", "rounds": [ts1, ts2, ...], "expireAt": 0 }] }
24
+ ```
25
+
26
+ - 报文只存一份(几跳共用),`rounds` 只存时间戳 —— 一只瓶子 6 遍不按遍数翻倍。
27
+ - 发出去一跳就划掉一跳(`consume`),划空整条从文件里消失。
28
+ - 瓶子自己过了 `expire_at` 就不再发,顺手 `purgeExpired` 清掉。
29
+ - 文件坏了当空处理,不抛。
30
+
31
+ `lib/index.js` 两处:
32
+
33
+ - 批准那只瓶子的分支:原来那圈 `setTimeout` 换成 `bottleLoop.plan()` 写盘。
34
+ - 新增一个每分钟扫的 `ctx.effect`(**启动时立即扫一次**,不等 60 秒):
35
+ 把到点的发出去、发完划掉。重启期间错过的会标「现在补发」。
36
+
37
+ 这跟日报的「启动补漏」、回信重发的「15 秒扫文件」是同一个模式:**靠文件判断,不靠内存。**
38
+
39
+ ### 顺带确认的两件事
40
+
41
+ 这两处本来就能扛重启,**没改代码**:
42
+
43
+ - **回信重发**:`setInterval` 每 15 秒扫一次,但「到没到点」是 `bottleAck.listDue()`
44
+ 从文件读的,重启后自己接上。
45
+ - **日报**:靠 `promptedDay()` 读文件判断提醒过没,外加一条开机补昨天漏的。
46
+
47
+ ### 测试
48
+
49
+ 新增 **`tests/e2e-bottle-loop.mjs`**(12 项,已进 `tests/run.mjs` 的 SUITES)。
50
+
51
+ 其中最要紧的一条是「plan 写盘 + 新进程 due 读得到」—— 那个「新进程」是真的
52
+ `spawnSync` 起一个没有任何内存状态的 node 去读文件,不是同进程内存盘再读。
53
+ 「重启不丢」这句话只有这么测才作数。
54
+
55
+ 其余覆盖:没到点不返回、错过几跳标 `overdue`、`consume` 只划一跳、
56
+ 全划掉后瓶子消失、过期瓶子不发、坏 JSON 不炸、同一只重复 plan 只留一条。
57
+
58
+ 全量:**704 通过,0 失败。**
59
+
60
+ ---
61
+
7
62
  ## [0.9.19] — 2026-12-01
8
63
 
9
64
  > **关于 0.9.18**:这个号发不出去。`npm publish` 第一次执行时提交进了 registry 的
@@ -0,0 +1,152 @@
1
+ /**
2
+ * 漂流瓶循环广播的**持久排期**。
3
+ *
4
+ * ★ 为什么要有这个文件(2026-12-01 岸:「我估计重起了也会断」):
5
+ * 原来那版是在 approve 的时候用 `setTimeout` 把后续几遍挂在内存里 ——
6
+ * DSH 一重启,全部作废。实测日志里「循环已排定」一条都没有,说明它从来没跑完过。
7
+ *
8
+ * ★ 现在的事实源是**磁盘**,不是内存:
9
+ * - 排期写进 bottle-loop.json(`{ bottles: [{ bottleId, raw, rounds: [ts, ...] }] }`)
10
+ * - `due()` 每次返回「到点了还没发」的那几条
11
+ * - `consume()` 发出去之后把那一跳从 rounds 里删掉
12
+ * - 跑完了(rounds 空)整条瓶子从文件里消失
13
+ * - 启动时 `due()` 会把「错过的那几跳」一并返回 —— 重启不再丢
14
+ *
15
+ * ★ 报文只存一份(`raw`),几跳共用;rounds 里只存时间戳。
16
+ * 一只瓶子 6 遍,报文约 500 字节,存一份就够,不按遍数翻倍。
17
+ *
18
+ * ★ 过期:超过 expire_at(报文里那个)的排期直接丢掉 —— 瓶子自己已经过期了,
19
+ * 再发出去对面也不会收(verifyBottlePacket 会挡)。
20
+ */
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+
24
+ const FILE = 'bottle-loop.json';
25
+ const MAX_BOTTLES = 200; // 防文件无限长
26
+
27
+ function fileOf(dataDir) {
28
+ return path.join(dataDir, FILE);
29
+ }
30
+
31
+ function readAll(dataDir) {
32
+ try {
33
+ const j = JSON.parse(fs.readFileSync(fileOf(dataDir), 'utf8'));
34
+ if (j && Array.isArray(j.bottles)) return j.bottles;
35
+ } catch {
36
+ /* 没有就是没有 */
37
+ }
38
+ return [];
39
+ }
40
+
41
+ function writeAll(dataDir, bottles) {
42
+ try {
43
+ fs.mkdirSync(dataDir, { recursive: true });
44
+ const list = bottles.slice(0, MAX_BOTTLES);
45
+ const tmp = fileOf(dataDir) + '.tmp';
46
+ fs.writeFileSync(tmp, JSON.stringify({ schemaVersion: 1, bottles: list }, null, 2), {
47
+ encoding: 'utf8',
48
+ mode: 0o600,
49
+ });
50
+ fs.renameSync(tmp, fileOf(dataDir));
51
+ return true;
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * 记一只瓶子的整份排期。
59
+ * @param {string} dataDir
60
+ * @param {{ bottleId: string, raw: string, rounds: number[], expireAt?: number }} entry
61
+ * rounds = 后续每一跳的**绝对时间戳**(毫秒);不含首发(首发当场发,不进排期)
62
+ */
63
+ export function plan(dataDir, { bottleId, raw, rounds, expireAt = 0 } = {}) {
64
+ const id = String(bottleId || '').trim();
65
+ if (!id || !raw) return { ok: false, error: '缺 bottleId 或报文' };
66
+ const ts = (Array.isArray(rounds) ? rounds : []).map(Number).filter((n) => Number.isFinite(n) && n > 0);
67
+ const bottles = readAll(dataDir).filter((b) => b && b.bottleId !== id);
68
+ if (ts.length) bottles.unshift({ bottleId: id, raw, rounds: ts, expireAt: Number(expireAt) || 0 });
69
+ return writeAll(dataDir, bottles)
70
+ ? { ok: true, count: ts.length }
71
+ : { ok: false, error: '排期文件写不进去(磁盘或权限)' };
72
+ }
73
+
74
+ /**
75
+ * 到点了、该发的那些。
76
+ * @param {string} dataDir
77
+ * @param {number} now
78
+ * @returns {{ bottleId: string, raw: string, at: number, overdue: boolean }[]}
79
+ * overdue=true 表示这一跳在重启期间错过了(现在补发)
80
+ */
81
+ export function due(dataDir, now = Date.now()) {
82
+ const out = [];
83
+ for (const b of readAll(dataDir)) {
84
+ if (!b || !b.bottleId || !b.raw) continue;
85
+ const exp = Number(b.expireAt) || 0;
86
+ if (exp && exp < now) continue; // 瓶子本身过期了,不必再发
87
+ for (const at of b.rounds || []) {
88
+ const t = Number(at) || 0;
89
+ if (t && t <= now) out.push({ bottleId: b.bottleId, raw: b.raw, at: t, overdue: now - t > 60_000 });
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /**
96
+ * 某一跳发完了 —— 从排期里划掉。划空了整条瓶子就消失。
97
+ * @returns {{ ok: boolean, left: number }}
98
+ */
99
+ export function consume(dataDir, bottleId, at) {
100
+ const id = String(bottleId || '').trim();
101
+ const t = Number(at) || 0;
102
+ let left = 0;
103
+ const bottles = readAll(dataDir)
104
+ .map((b) => {
105
+ if (!b || b.bottleId !== id) return b;
106
+ const rounds = (b.rounds || []).filter((x) => Number(x) !== t);
107
+ left = rounds.length;
108
+ return rounds.length ? { ...b, rounds } : null;
109
+ })
110
+ .filter(Boolean);
111
+ writeAll(dataDir, bottles);
112
+ return { ok: true, left };
113
+ }
114
+
115
+ /** 丢掉某只瓶子的全部排期(瓶子被删 / 撤回 / 手动取消时用)。 */
116
+ export function cancel(dataDir, bottleId) {
117
+ const id = String(bottleId || '').trim();
118
+ const before = readAll(dataDir);
119
+ const after = before.filter((b) => b && b.bottleId !== id);
120
+ if (after.length === before.length) return { ok: false, error: '没有这只瓶子的排期' };
121
+ writeAll(dataDir, after);
122
+ return { ok: true };
123
+ }
124
+
125
+ /** 清掉过期的整条记录(瓶子 expire_at 已经过了的)—— 每次扫描顺手调一次。 */
126
+ export function purgeExpired(dataDir, now = Date.now()) {
127
+ const before = readAll(dataDir);
128
+ const after = before.filter((b) => {
129
+ if (!b) return false;
130
+ const exp = Number(b.expireAt) || 0;
131
+ if (!exp) return true;
132
+ return exp >= now;
133
+ });
134
+ if (after.length !== before.length) writeAll(dataDir, after);
135
+ return { removed: before.length - after.length, left: after.length };
136
+ }
137
+
138
+ /** 给设置页 / 诊断看的现状。 */
139
+ export function status(dataDir, now = Date.now()) {
140
+ const list = readAll(dataDir);
141
+ const all = [];
142
+ for (const b of list) {
143
+ for (const at of b.rounds || []) all.push(Number(at) || 0);
144
+ }
145
+ all.sort((a, b) => a - b);
146
+ return {
147
+ bottles: list.length,
148
+ rounds: all.length,
149
+ nextAt: all.find((t) => t > now) || 0,
150
+ overdue: all.filter((t) => t <= now).length,
151
+ };
152
+ }
package/lib/index.js CHANGED
@@ -83,6 +83,7 @@ import * as bottleAck from './bottle-ack.js';
83
83
  // ★ 2026-12-01 岸:「收到的瓶子肯定是要有历史记录的。回信也是。」
84
84
  // 一条 = 一个瓶子 + 它的回信(收藏馆合并成一块就看这个文件)。
85
85
  import * as bottleHistory from './bottle-history.js';
86
+ import * as bottleLoop from './bottle-loop.js';
86
87
 
87
88
  /**
88
89
  * 漂流瓶一次发几遍(2026-11-29 岸:「确保很多人收到也可以选择循环几次」)
@@ -1062,20 +1063,30 @@ function applyInner(ctx, config = {}) {
1062
1063
  const nextGap = () => minGap + Math.floor(Math.random() * ONE_HOUR);
1063
1064
  const raw = JSON.stringify(r.packet);
1064
1065
  await transport.publish(P.BOTTLE_POOL_TOPIC, raw);
1066
+ // ★ 2026-12-01 岸:「我估计重起了也会断」—— 他说对了。
1067
+ // 原来这里是 setTimeout 挂在内存里,DSH 一重启后续几遍全作废。
1068
+ // 实测日志里「循环已排定」一条都没有,说明它从没跑完过。
1069
+ // 现在改成**磁盘排期**(lib/bottle-loop.js):排期写进 bottle-loop.json,
1070
+ // 另有一个每分钟扫一次的定时器负责把到点的发出去 —— 那个扫描器
1071
+ // 是靠文件判断的,重启后自己就接上了,跟日报、回信重发同一个模式。
1065
1072
  let elapsed = 0;
1066
1073
  const planned = [];
1074
+ const rounds = [];
1075
+ const baseMs = Date.now();
1067
1076
  for (let i = 1; i < copies; i += 1) {
1068
1077
  elapsed += nextGap();
1069
- const atMs = elapsed;
1070
- planned.push({ round: i + 1, atMs });
1071
- setTimeout(() => {
1072
- if (!transport || !transport.connected) return;
1073
- transport
1074
- .publish(P.BOTTLE_POOL_TOPIC, raw)
1075
- .then(() => log(`漂流瓶循环第 ${i + 1}/${copies} 次发出去了(约 ${Math.round(atMs / 60000)} 分钟后)`))
1076
- .catch((e) => log(`漂流瓶循环发不出去:${e?.message ?? e}`));
1077
- }, atMs);
1078
+ rounds.push(baseMs + elapsed);
1079
+ planned.push({ round: i + 1, atMs: elapsed });
1078
1080
  }
1081
+ const expireMs = Date.parse(r.packet?.expire_at || '') || 0;
1082
+ const loopId = r.packet?.bottle_id || id;
1083
+ const planRes = bottleLoop.plan(dir, {
1084
+ bottleId: loopId,
1085
+ raw,
1086
+ rounds,
1087
+ expireAt: expireMs,
1088
+ });
1089
+ if (!planRes.ok) log(`漂流瓶循环排期没写进去:${planRes.error}`);
1079
1090
  // ★ 2026-11-30:把「排了哪几次」当场记下来 ——
1080
1091
  // 以前只有每跳真发出去时才有日志,投完到第一跳之间是黑的,
1081
1092
  // 主人不知道到底排上了没有。现在投完就能看见整份计划。
@@ -2387,6 +2398,43 @@ function applyInner(ctx, config = {}) {
2387
2398
  return () => clearInterval(retryTimer);
2388
2399
  }, 'fishpal.outbox-retry');
2389
2400
 
2401
+ // ★ 漂流瓶循环广播的扫描器(2026-12-01 岸:「我估计重起了也会断」)。
2402
+ // 排期写在 lib/bottle-loop.js 的 bottle-loop.json 里,这里只负责:
2403
+ // 每分钟看一眼有没有到点的,有就发,发完从排期里划掉。
2404
+ // ★ 启动时**立即扫一次**(跟日报的「启动补漏」同一个理由):
2405
+ // 等 60 秒才扫的话,重启后第一分钟里的排期会多等一轮。
2406
+ // ★ 靠文件判断,不靠内存 —— 重启后自己就接上了,这是这次改动全部的意义。
2407
+ ctx.effect(() => {
2408
+ const scan = async () => {
2409
+ try {
2410
+ const d = dataDir();
2411
+ bottleLoop.purgeExpired(d);
2412
+ const due = bottleLoop.due(d);
2413
+ if (!due.length) return;
2414
+ if (!transport || !transport.connected) return;
2415
+ for (const item of due) {
2416
+ try {
2417
+ await transport.publish(P.BOTTLE_POOL_TOPIC, item.raw);
2418
+ const left = bottleLoop.consume(d, item.bottleId, item.at);
2419
+ log(
2420
+ `漂流瓶循环又发了一遍(bottle ${String(item.bottleId).slice(0, 10)}…,还剩 ${left.left} 跳)` +
2421
+ (item.overdue ? '(重启期间错过,现在补发)' : ''),
2422
+ );
2423
+ } catch (e) {
2424
+ log(`漂流瓶循环发不出去:${e?.message ?? e}`);
2425
+ }
2426
+ }
2427
+ } catch (e) {
2428
+ log(`漂流瓶循环扫描出错:${e?.message ?? e}`);
2429
+ }
2430
+ };
2431
+ // 启动补漏:先把错过的排期发掉
2432
+ void scan();
2433
+ const timer = setInterval(() => void scan(), 60_000);
2434
+ if (typeof timer.unref === 'function') timer.unref();
2435
+ return () => clearInterval(timer);
2436
+ }, 'fishpal.bottle-loop');
2437
+
2390
2438
  // ★ 在线状态:惰性探测(岸 2026-11-30 晚定的方案)。
2391
2439
  // 平时一条都不发 —— 岸原话「不要这么频繁」。每 30 秒看一眼有没有「该探的」,
2392
2440
  // 没有就什么也不做(due() 会直接告诉你 false)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fishpal",
3
- "version": "0.9.19",
3
+ "version": "0.9.20",
4
4
  "description": "给你的 DSH 虚拟鱼找个朋友 — 跨机器端到端加密,互递漂流瓶、还会来串门。不是人类聊天工具。",
5
5
  "author": "xinze404",
6
6
  "license": "MIT",
@@ -0,0 +1,208 @@
1
+ /**
2
+ * 漂流瓶循环排期的离线测试(2026-12-01)。
3
+ *
4
+ * 要证明的事只有一条:**排期在磁盘上,重启后还在。**
5
+ * 所以这里每个「重启」都是真的另起一个进程 —— 新进程没有任何内存状态,
6
+ * 只能靠读文件知道还有几跳该发。那才是「重起了也不会断」的实际含义。
7
+ */
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { spawnSync } from 'node:child_process';
12
+ import { fileURLToPath } from 'node:url';
13
+ import assert from 'node:assert';
14
+
15
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
16
+ const LIB = path.resolve(HERE, '..', 'lib', 'bottle-loop.js');
17
+
18
+ let pass = 0;
19
+ const fail = [];
20
+ function ok(name, fn) {
21
+ try {
22
+ fn();
23
+ pass += 1;
24
+ } catch (e) {
25
+ fail.push({ name, err: e });
26
+ }
27
+ }
28
+ async function okAsync(name, fn) {
29
+ try {
30
+ await fn();
31
+ pass += 1;
32
+ } catch (e) {
33
+ fail.push({ name, err: e });
34
+ }
35
+ }
36
+
37
+ function tmpDir() {
38
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'fploop-'));
39
+ return d;
40
+ }
41
+
42
+ /** 另起一个进程跑一段代码,模拟「DSH 重启」—— 新进程没有任何内存状态。 */
43
+ function runFresh(dir, body) {
44
+ const file = path.join(dir, '_fresh.mjs');
45
+ const libUrl = 'file:///' + LIB.replace(/\\/g, '/');
46
+ const script =
47
+ 'import * as L from ' + JSON.stringify(libUrl) + ';\n' +
48
+ 'const dir = ' + JSON.stringify(dir) + ';\n' +
49
+ body;
50
+ fs.writeFileSync(file, script, 'utf8');
51
+ const r = spawnSync(process.execPath, [file], { encoding: 'utf8', timeout: 30000 });
52
+ if (r.status !== 0) {
53
+ throw new Error('子进程失败:' + (r.stderr || r.stdout || '').slice(0, 500));
54
+ }
55
+ return r.stdout.trim();
56
+ }
57
+
58
+ const mod = await import('file:///' + LIB.replace(/\\/g, '/'));
59
+
60
+ // ── 1. 排期写进去,另一个进程读得到 ─────────────────────────────
61
+ await okAsync('plan 写盘 + 新进程 due 读得到(= 重启不丢)', async () => {
62
+ const dir = tmpDir();
63
+ const now = Date.now();
64
+ const r = mod.plan(dir, {
65
+ bottleId: 'bd_test_1',
66
+ raw: '{"hello":"bottle"}',
67
+ rounds: [now + 3600_000, now + 7200_000],
68
+ expireAt: now + 86400_000,
69
+ });
70
+ assert.equal(r.ok, true);
71
+ assert.equal(r.count, 2);
72
+ assert.ok(fs.existsSync(path.join(dir, 'bottle-loop.json')), '文件应该真在磁盘上');
73
+
74
+ // ★ 关键:新进程(新内存)读 —— 两跳都还在
75
+ const out = runFresh(
76
+ dir,
77
+ `const d = L.due(dir, ${now + 8_000_000});
78
+ console.log(JSON.stringify({ n: d.length, ids: d.map(x => x.bottleId), raw: d[0] && d[0].raw }));`,
79
+ );
80
+ const got = JSON.parse(out);
81
+ assert.equal(got.n, 2, '新进程应该看到 2 跳');
82
+ assert.equal(got.ids[0], 'bd_test_1');
83
+ assert.equal(got.raw, '{"hello":"bottle"}');
84
+ });
85
+
86
+ // ── 2. 没到点的不 due ─────────────────────────────────────────
87
+ ok('没到点的不返回', () => {
88
+ const dir = tmpDir();
89
+ const now = Date.now();
90
+ mod.plan(dir, { bottleId: 'bd_t2', raw: '{}', rounds: [now + 3600_000], expireAt: now + 86400_000 });
91
+ assert.equal(mod.due(dir, now).length, 0, '现在还不该发');
92
+ assert.equal(mod.due(dir, now + 3600_000 + 1).length, 1, '到点就该发');
93
+ });
94
+
95
+ // ── 3. 过了几跳全返回(重启补发)────────────────────────────────
96
+ ok('重启期间错过几跳就补几跳,并且标 overdue', () => {
97
+ const dir = tmpDir();
98
+ const t0 = 1_000_000;
99
+ mod.plan(dir, { bottleId: 'bd_t3', raw: '{}', rounds: [t0 + 1000, t0 + 2000, t0 + 3000], expireAt: 0 });
100
+ const d = mod.due(dir, t0 + 3_600_000);
101
+ assert.equal(d.length, 3, '三跳都过了,应该都返回');
102
+ assert.ok(d.every((x) => x.overdue === true), '超过 60 秒的应标 overdue');
103
+ });
104
+
105
+ // ── 4. consume 只划掉那一跳 ───────────────────────────────────
106
+ ok('consume 划掉一跳,其余保留', () => {
107
+ const dir = tmpDir();
108
+ const now = Date.now();
109
+ const r1 = now + 1000;
110
+ const r2 = now + 2000;
111
+ mod.plan(dir, { bottleId: 'bd_t4', raw: '{}', rounds: [r1, r2], expireAt: 0 });
112
+ const c = mod.consume(dir, 'bd_t4', r1);
113
+ assert.equal(c.left, 1);
114
+ const left = mod.due(dir, now + 9999);
115
+ assert.equal(left.length, 1);
116
+ assert.equal(left[0].at, r2);
117
+ });
118
+
119
+ // ── 5. 全划掉后整只瓶子消失 ────────────────────────────────────
120
+ ok('全部发完后瓶子从文件里消失', () => {
121
+ const dir = tmpDir();
122
+ const now = Date.now();
123
+ const at = now + 1000;
124
+ mod.plan(dir, { bottleId: 'bd_t5', raw: '{}', rounds: [at], expireAt: 0 });
125
+ mod.consume(dir, 'bd_t5', at);
126
+ const j = JSON.parse(fs.readFileSync(path.join(dir, 'bottle-loop.json'), 'utf8'));
127
+ assert.equal(j.bottles.length, 0, '排期空了就该从文件里消失');
128
+ assert.equal(mod.status(dir, now).bottles, 0);
129
+ });
130
+
131
+ // ── 6. 过期的瓶子不发 ─────────────────────────────────────────
132
+ ok('瓶子本身过期就不再发', () => {
133
+ const dir = tmpDir();
134
+ const now = Date.now();
135
+ mod.plan(dir, { bottleId: 'bd_t6', raw: '{}', rounds: [now + 1000], expireAt: now + 500 });
136
+ assert.equal(mod.due(dir, now + 2000).length, 0, '过期瓶子不该再发');
137
+ });
138
+
139
+ // ── 7. purgeExpired 清掉过期记录 ──────────────────────────────
140
+ ok('purgeExpired 清掉过期记录', () => {
141
+ const dir = tmpDir();
142
+ const now = Date.now();
143
+ mod.plan(dir, { bottleId: 'bd_alive', raw: '{}', rounds: [now + 1000], expireAt: now + 86400_000 });
144
+ mod.plan(dir, { bottleId: 'bd_dead', raw: '{}', rounds: [now + 1000], expireAt: now - 1 });
145
+ const p = mod.purgeExpired(dir, now);
146
+ assert.equal(p.removed, 1);
147
+ assert.equal(p.left, 1);
148
+ });
149
+
150
+ // ── 8. cancel 取消整只 ───────────────────────────────────────
151
+ ok('cancel 取消某只瓶子的全部排期', () => {
152
+ const dir = tmpDir();
153
+ const now = Date.now();
154
+ mod.plan(dir, { bottleId: 'bd_t8', raw: '{}', rounds: [now + 1000, now + 2000], expireAt: 0 });
155
+ const c = mod.cancel(dir, 'bd_t8');
156
+ assert.equal(c.ok, true);
157
+ assert.equal(mod.due(dir, now + 9999).length, 0);
158
+ });
159
+
160
+ // ── 9. 重复 plan 同一只只留一条 ───────────────────────────────
161
+ ok('同一只瓶子重复 plan 只留一条', () => {
162
+ const dir = tmpDir();
163
+ const now = Date.now();
164
+ mod.plan(dir, { bottleId: 'bd_t9', raw: 'A', rounds: [now + 1000], expireAt: 0 });
165
+ mod.plan(dir, { bottleId: 'bd_t9', raw: 'B', rounds: [now + 2000], expireAt: 0 });
166
+ const j = JSON.parse(fs.readFileSync(path.join(dir, 'bottle-loop.json'), 'utf8'));
167
+ assert.equal(j.bottles.length, 1);
168
+ assert.equal(j.bottles[0].raw, 'B', '后来的覆盖前面');
169
+ });
170
+
171
+ // ── 10. 文件坏了不炸 ─────────────────────────────────────────
172
+ ok('排期文件是坏 JSON 时当空处理,不抛', () => {
173
+ const dir = tmpDir();
174
+ fs.writeFileSync(path.join(dir, 'bottle-loop.json'), '{不是合法 json', 'utf8');
175
+ assert.equal(mod.due(dir, Date.now()).length, 0);
176
+ assert.equal(mod.status(dir).bottles, 0);
177
+ });
178
+
179
+ // ── 11. 空 rounds 不写文件 ────────────────────────────────────
180
+ ok('copies=1(没有后续跳)时 plan 不留下空记录', () => {
181
+ const dir = tmpDir();
182
+ const r = mod.plan(dir, { bottleId: 'bd_t11', raw: '{}', rounds: [], expireAt: 0 });
183
+ assert.equal(r.ok, true);
184
+ assert.equal(r.count, 0);
185
+ assert.equal(mod.status(dir).bottles, 0);
186
+ });
187
+
188
+ // ── 12. status 的 nextAt / overdue ───────────────────────────
189
+ ok('status 报得出下一跳和过期跳数', () => {
190
+ const dir = tmpDir();
191
+ const now = 2_000_000;
192
+ mod.plan(dir, { bottleId: 'bd_t12', raw: '{}', rounds: [now - 1000, now + 5000], expireAt: 0 });
193
+ const s = mod.status(dir, now);
194
+ assert.equal(s.rounds, 2);
195
+ assert.equal(s.overdue, 1);
196
+ assert.equal(s.nextAt, now + 5000);
197
+ });
198
+
199
+ // ── 输出 ─────────────────────────────────────────────────────
200
+ if (fail.length) {
201
+ for (const f of fail) {
202
+ console.error(`✗ ${f.name}`);
203
+ console.error(' ' + String(f.err && f.err.message ? f.err.message : f.err).split('\n')[0]);
204
+ }
205
+ console.log(`结果:${pass} 通过,${fail.length} 失败`);
206
+ process.exit(1);
207
+ }
208
+ console.log(`结果:${pass} 通过,0 失败`);
@@ -0,0 +1,139 @@
1
+ // 漂流瓶端到端闭环测试:丢出去 → 对面收到 → 对面回信 → 我收到回信
2
+ // 不走真 MQTT(不污染公共池),但走真加密、真验签、真 PoW、真状态机。
3
+ // 用法:node tests/e2e-bottle.mjs
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import * as bottle from '../lib/bottle.js';
8
+ import * as bottleCrypto from '../lib/bottle-crypto.js';
9
+
10
+ let pass = 0;
11
+ let fail = 0;
12
+ const failures = [];
13
+
14
+ function ok(name, cond, extra = '') {
15
+ if (cond) {
16
+ pass++;
17
+ console.log(` ✓ ${name}`);
18
+ } else {
19
+ fail++;
20
+ failures.push(name + (extra ? ` — ${extra}` : ''));
21
+ console.log(` ✗ ${name}${extra ? ' — ' + extra : ''}`);
22
+ }
23
+ }
24
+
25
+ function tmpDir(tag) {
26
+ return fs.mkdtempSync(path.join(os.tmpdir(), `fp-e2e-${tag}-`));
27
+ }
28
+
29
+ function hex(b) {
30
+ return Buffer.isBuffer(b) ? b.toString('hex').slice(0, 12) : String(b ?? '').slice(0, 12);
31
+ }
32
+
33
+ // ── 造两条鱼 ────────────────────────────────────────────────
34
+ const dirA = tmpDir('a');
35
+ const dirB = tmpDir('b');
36
+
37
+ console.log('\n=== 准备两套匿名身份 ===');
38
+ const idA = bottle.ensureAnonIdentity(dirA);
39
+ const idB = bottle.ensureAnonIdentity(dirB);
40
+ ok('A 有匿名身份(签名公钥 + 交换公钥)', !!(idA?.signing?.public && idA?.exchange?.public));
41
+ ok('B 有匿名身份(签名公钥 + 交换公钥)', !!(idB?.signing?.public && idB?.exchange?.public));
42
+ ok('两条鱼身份不同', idA.signing.public !== idB.signing.public, `A=${hex(idA.signing.public)} B=${hex(idB.signing.public)}`);
43
+
44
+ // ── A 写瓶子 ────────────────────────────────────────────────
45
+ console.log('\n=== A 写一只瓶子 ===');
46
+ const BOTTLE_TEXT = '这是一只用来测试投递链路的瓶子,正文要能原样到达对面。';
47
+ const draft = bottle.createDraft(dirA, { text: BOTTLE_TEXT });
48
+ ok('建草稿成功', draft.ok === true, draft.error);
49
+ const bottleId = draft.draft?.id || draft.id;
50
+ ok('拿到 bottleId', !!bottleId, String(bottleId));
51
+
52
+ // ── A 放行 → 生成报文 ───────────────────────────────────────
53
+ console.log('\n=== A 放行(点「放行」才真的能发)===');
54
+ const approved = await bottle.approveDraft(dirA, bottleId);
55
+ ok('放行成功', approved.ok === true, approved.error);
56
+ ok('拿到了报文', !!approved.packet, 'packet 为空');
57
+
58
+ // 模拟 MQTT:报文序列化后跨进程传输
59
+ const rawPacket = JSON.stringify(approved.packet);
60
+ ok('报文能序列化', rawPacket.length > 0, `${rawPacket.length} 字节`);
61
+
62
+ // ── B 收到并验签 ────────────────────────────────────────────
63
+ console.log('\n=== B 收到报文,走验签 / 时间窗 / PoW ===');
64
+ const verified = bottle.verifyBottlePacket(rawPacket, idB.signing.public);
65
+ ok('B 验签通过', verified.ok === true, verified.reason);
66
+ ok('正文完整到达', verified.packet?.text === BOTTLE_TEXT, `收到 ${String(verified.packet?.text ?? '').length} 字`);
67
+ ok('报文带 bottle_id', verified.packet?.bottle_id === bottleId);
68
+ // 报文里带的是「发这只瓶子时用的那把匿名钥匙」的公钥。
69
+ // 判据不是「跟我外面拿的 id 一样」,而是「它能自证」——下面验签已经过了这一步,
70
+ // 再确认它是本机身份文件里认得的形状(SPKI base64)。
71
+ ok('报文里的匿名签名公钥是本机身份格式', /^MCowBQYDK2Vw/.test(String(verified.packet?.anon_sign_pub)));
72
+
73
+ // ── 自己发的不该收 ──────────────────────────────────────────
74
+ // 判据是「拿我自己那把签名公钥去验,它会认出这是我发的」。
75
+ const selfCheck = bottle.verifyBottlePacket(rawPacket, verified.packet.anon_sign_pub);
76
+ ok('A 收到自己发的那只会被挡(这是我自己发的)', selfCheck.ok === false, selfCheck.reason);
77
+
78
+ // ── 篡改检测 ────────────────────────────────────────────────
79
+ console.log('\n=== 篡改检测 ===');
80
+ const tampered = JSON.parse(rawPacket);
81
+ tampered.text = '被中途改过的正文';
82
+ const tamperCheck = bottle.verifyBottlePacket(JSON.stringify(tampered), idB.signing.public);
83
+ ok('改过正文的报文验签失败', tamperCheck.ok === false, tamperCheck.reason);
84
+
85
+ // ── B 回信 ──────────────────────────────────────────────────
86
+ console.log('\n=== B 回一句 ===');
87
+ const REPLY_TEXT = '收到了,这句是回给你的。';
88
+ const replyDraft = bottle.createReplyDraft(dirB, {
89
+ bottleId,
90
+ text: REPLY_TEXT,
91
+ toAnonPub: verified.packet.anon_pub,
92
+ });
93
+ ok('建回信草稿成功', replyDraft.ok === true, replyDraft.error);
94
+
95
+ const replyBuilt = await bottle.buildReplyPacket(dirB, bottleId);
96
+ ok('回信能打成报文', replyBuilt.ok === true, replyBuilt.error);
97
+
98
+ // 模拟 MQTT:回信是加密的,公共水面只看得到密文
99
+ const rawReply = JSON.stringify(replyBuilt.packet);
100
+ ok('回信不含明文', !rawReply.includes(REPLY_TEXT), '回信报文里出现了明文,加密没生效');
101
+ ok('回信报文能序列化', rawReply.length > 0, `${rawReply.length} 字节`);
102
+
103
+ // ── A 解密回信 ──────────────────────────────────────────────
104
+ console.log('\n=== A 收回信并解密 ===');
105
+ const aKeys = bottleCrypto.bottleKeyOf(dirA, bottleId);
106
+ ok('A 本地留着这只瓶子的钥匙', !!aKeys, '找不到 bottleKey');
107
+ ok('钥匙里带交换密钥对(解回信要用它)', !!aKeys?.exchange, 'bottleKey 缺 exchange');
108
+ ok('回信报文带了自己的匿名公钥', !!replyBuilt.packet?.anon_pub, '回信里没有 anon_pub,对面就解不开');
109
+ // 解密这一环本机测不完:A 的钥匙是“发瓶子时”那把,回信由 B 侧密封,
110
+ // 密封用的是 B 对 A 匿名公钥的理解,测试里拿不到同一份引用做对称校验。
111
+ // 真实环境有证据:2026-11-30 收到的两只瓶子都带 reply 正文,说明这条链在线上是通的。
112
+ // 这里只断言“该有的东西都在 + 密文里没有明文”,不假装解开了。
113
+
114
+ // ── 第二只瓶子换钥匙 ────────────────────────────────────────
115
+ console.log('\n=== 每只瓶子一把新钥匙(用一次换一次)===');
116
+ const draft2 = bottle.createDraft(dirA, { text: '第二只瓶子,应该用另一把钥匙。' });
117
+ const approved2 = await bottle.approveDraft(dirA, draft2.draft?.id || draft2.id);
118
+ const key1 = bottleCrypto.bottleKeyOf(dirA, bottleId);
119
+ const key2 = bottleCrypto.bottleKeyOf(dirA, approved2.packet?.bottle_id);
120
+ ok('第二只瓶子拿到了钥匙', !!key2);
121
+ ok('两只瓶子的钥匙不一样', !!key1 && !!key2 && JSON.stringify(key1) !== JSON.stringify(key2));
122
+
123
+ // ── 收尾 ────────────────────────────────────────────────────
124
+ console.log('\n' + '─'.repeat(56));
125
+ console.log(`结果:${pass} 通过,${fail} 失败`);
126
+ if (fail) {
127
+ console.log('\n失败项:');
128
+ failures.forEach((f) => console.log(' · ' + f));
129
+ }
130
+ console.log('─'.repeat(56));
131
+
132
+ try {
133
+ fs.rmSync(dirA, { recursive: true, force: true });
134
+ fs.rmSync(dirB, { recursive: true, force: true });
135
+ } catch {
136
+ /* 清理失败不影响结果 */
137
+ }
138
+
139
+ process.exit(fail ? 1 : 0);
@@ -0,0 +1,62 @@
1
+ // 单连接先订阅后发布:证明公共池真的能收到
2
+ import mqtt from 'mqtt';
3
+ import * as bottle from './lib/bottle.js';
4
+
5
+ const DIR = 'D:/fishpal-data';
6
+ const POOL = 'fishpal/bottle/pool';
7
+
8
+ const client = mqtt.connect('wss://broker.emqx.io:8084/mqtt', {
9
+ clientId: 'fp-round-' + Math.random().toString(16).slice(2, 10),
10
+ connectTimeout: 20000,
11
+ reconnectPeriod: 0,
12
+ });
13
+
14
+ const got = [];
15
+ client.on('message', (topic, payload) => {
16
+ const raw = payload.toString('utf8');
17
+ try {
18
+ const p = JSON.parse(raw);
19
+ got.push({ bottleId: p.bottle_id, textLen: (p.text || '').length, bytes: raw.length });
20
+ console.log(` ← 收到 ${raw.length} 字节 bottle=${p.bottle_id}`);
21
+ } catch {
22
+ console.log(` ← 收到 ${raw.length} 字节(非 JSON)`);
23
+ }
24
+ });
25
+
26
+ await new Promise((res, rej) => {
27
+ const t = setTimeout(() => rej(new Error('连接超时 20s')), 21000);
28
+ client.once('connect', () => { clearTimeout(t); res(); });
29
+ client.once('error', (e) => { clearTimeout(t); rej(e); });
30
+ });
31
+ console.log('✓ 已连上 broker');
32
+
33
+ await new Promise((res, rej) => {
34
+ client.subscribe(POOL, { qos: 1 }, (err) => (err ? rej(err) : res()));
35
+ });
36
+ console.log('✓ 已订阅池子(同一个连接)');
37
+
38
+ const draft = bottle.createDraft(DIR, { text: '投递探针:一个连接自己订自己发,验证公共池能不能收到。' });
39
+ const approved = await bottle.approveDraft(DIR, draft.draft?.id || draft.id);
40
+ if (!approved.ok) { console.error('✗ 造瓶子失败:', approved.error); process.exit(1); }
41
+ const pid = approved.packet.bottle_id;
42
+
43
+ console.log('✓ 瓶子造好:' + pid);
44
+ await new Promise((r) => setTimeout(r, 800));
45
+
46
+ await new Promise((res, rej) => {
47
+ client.publish(POOL, JSON.stringify(approved.packet), { qos: 1 }, (err) => (err ? rej(err) : res()));
48
+ });
49
+ console.log('✓ 已发布,等 10 秒……');
50
+ console.log('');
51
+
52
+ await new Promise((r) => setTimeout(r, 10000));
53
+ client.end(true);
54
+
55
+ console.log('');
56
+ console.log('── 结果 ──');
57
+ console.log(`收到 ${got.length} 条`);
58
+ const hit = got.find((g) => g.bottleId === pid);
59
+ console.log(hit
60
+ ? `✓ 通!自己的瓶子 ${pid} 从公共池转了一圈回到自己手里(${hit.bytes} 字节,正文 ${hit.textLen} 字)`
61
+ : `✗ 没收到 ${pid}`);
62
+ process.exit(hit ? 0 : 1);
package/tests/run.mjs CHANGED
@@ -109,6 +109,11 @@ const SUITES = [
109
109
  '_verify-wordfilter-api.mjs',
110
110
  // 2026-12-01 多好友分辨:投递包裹带备注名(引号必须转义)+ 全局设置那道门真的能开
111
111
  '_verify-peer-name.mjs',
112
+ // e2e: bottle round-trip (offline, no network). Two independent identities:
113
+ // A drafts+approves -> B verifies (sig/PoW/time-window/tamper) -> B replies -> A has the key.
114
+ // Fills the gap "unit tests cover parts, nobody tested the whole delivery chain".
115
+ // The live step (subscribe pool + real publish) is tests/e2e-pool-live.mjs, manual only.
116
+ 'tests/e2e-bottle.mjs', 'tests/e2e-bottle-loop.mjs',
112
117
  ];
113
118
 
114
119
  let totalPass = 0;