@dsh-mobile/mobile-remote 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/FAQ.md +2 -2
  2. package/LICENSE +0 -0
  3. package/README.md +13 -8
  4. package/docs/PRIVACY-POLICY.en.md +26 -18
  5. package/docs/PRIVACY-POLICY.md +26 -18
  6. package/docs/SUPPORT.md +1 -1
  7. package/docs/TERMS-OF-SERVICE.en.md +5 -3
  8. package/docs/TERMS-OF-SERVICE.md +5 -3
  9. package/docs/USER-GUIDE.zh-CN.md +7 -6
  10. package/lib/account-usage-query.js +60 -60
  11. package/lib/account-usage.js +10 -10
  12. package/lib/api-helpers.js +114 -110
  13. package/lib/assistant-prefs.js +119 -76
  14. package/lib/auto-config.js +65 -65
  15. package/lib/backup.js +159 -123
  16. package/lib/break-reminder.js +45 -45
  17. package/lib/client.js +336 -138
  18. package/lib/config.js +234 -218
  19. package/lib/git-read-bundled-provider.js +27 -7
  20. package/lib/git-read-service.js +5 -5
  21. package/lib/host-compat.js +84 -84
  22. package/lib/http-util.js +17 -17
  23. package/lib/index.js +1670 -1511
  24. package/lib/memory/context.js +45 -40
  25. package/lib/memory/decay.js +93 -93
  26. package/lib/memory/extract.js +77 -77
  27. package/lib/memory/routes.js +33 -33
  28. package/lib/memory/store.js +239 -192
  29. package/lib/notify-copy.js +93 -93
  30. package/lib/permission-guide.js +86 -86
  31. package/lib/persona-cards.js +73 -61
  32. package/lib/phone-action-args.js +175 -0
  33. package/lib/phone-actions.js +227 -0
  34. package/lib/phone-announce.js +58 -0
  35. package/lib/proactive-material.js +42 -42
  36. package/lib/proactive.js +122 -119
  37. package/lib/protected-paths.js +205 -45
  38. package/lib/protocol.js +62 -23
  39. package/lib/push.js +29 -29
  40. package/lib/rate-limit.js +16 -16
  41. package/lib/relay/connector.js +334 -81
  42. package/lib/relay/crypto.js +15 -15
  43. package/lib/relay/devices.js +64 -32
  44. package/lib/relay/fingerprint.js +34 -34
  45. package/lib/relay/identity.js +26 -26
  46. package/lib/relay/mux.js +60 -46
  47. package/lib/relay/noise.js +40 -40
  48. package/lib/relay/on-demand.js +36 -31
  49. package/lib/relay/p2p.js +239 -0
  50. package/lib/relay/pairing.js +54 -15
  51. package/lib/relay/phone.js +63 -39
  52. package/lib/relay/serve.js +21 -21
  53. package/lib/relay/signal.js +69 -0
  54. package/lib/relay/ws-server.js +245 -0
  55. package/lib/reminders.js +15 -15
  56. package/lib/rpc-adapter.js +43 -43
  57. package/lib/session-list.js +31 -31
  58. package/lib/session-rotation.js +95 -95
  59. package/lib/session-title-cache.js +35 -35
  60. package/lib/session-title-refresh.js +51 -51
  61. package/lib/timeline.js +140 -140
  62. package/lib/turn-outline.js +104 -104
  63. package/package.json +11 -18
@@ -1,39 +1,54 @@
1
- /**
2
- * Folders the phone's file routes must never read, list or write (T-62, finding E11).
3
- *
4
- * `/files`, `/directories` and the git preview let a paired phone look at the PC; that is the
5
- * feature. But the DSH home (default `~/.dsh`, or `$DSH_HOME`) holds DSH's own keys
6
- * (`.credentials.yaml`, `.env`) and this plugin's state (`mobile-remote/`: the access token, the
7
- * relay private key, the memory database and archive, reminders, persona cards, prefs).
8
- *
9
- * T-62 fix: names are not identities. One folder has many spellings (`/System/Volumes/Data/Users/…`
10
- * on macOS, an NFD-decomposed "José", a Windows 8.3 short name, a symlink, `..`), so the check is
11
- * done on file identity, `(dev, ino)`:
12
- * - `isProtectedPath(path)`: the real path of the target, or of its nearest existing parent,
13
- * and every folder above it, compared by `(dev, ino)` with the protected folders. A string
14
- * prefix check runs first as a fast path.
15
- * - `isProtectedFile(stat)`: after opening, the opened file's `(dev, ino)` compared with every
16
- * file inside the protected folders. That catches hard links and `/dev/fd/N`, and checks what
17
- * was actually opened, so there is no check-then-open race.
18
- * - `/dev` and `/proc` are refused outright (they name open files and processes).
19
- */
20
- import { lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+ import { lstatSync, readdirSync, realpathSync, statSync, unlinkSync } from "node:fs";
21
28
  import { homedir } from "node:os";
22
- import { dirname, join, resolve, sep } from "node:path";
29
+ import { basename, dirname, join, resolve, sep } from "node:path";
23
30
  import { mobileRemoteStateDir } from "./auto-config.js";
24
31
 
25
32
  const caseInsensitive = process.platform === "darwin" || process.platform === "win32";
26
33
  const norm = (p) => (caseInsensitive ? p.normalize("NFC").toLowerCase() : p.normalize("NFC"));
27
34
  const idOf = (st) => `${st.dev}:${st.ino}`;
28
35
 
29
- /** Resolve symlinks; for a missing path, resolve the nearest existing parent and re-append. */
36
+
37
+
38
+
39
+
40
+
41
+
30
42
  export function realPathOf(path) {
31
43
  let current = resolve(path);
32
44
  const rest = [];
33
45
  for (;;) {
34
46
  try {
35
47
  return join(realpathSync(current), ...rest.reverse());
36
- } catch {
48
+ } catch (err) {
49
+ if (err?.code !== "ENOENT" && err?.code !== "ENOTDIR") {
50
+ throw Object.assign(new Error("path-unresolvable"), { code: "path-unresolvable", cause: err?.code });
51
+ }
37
52
  const parent = dirname(current);
38
53
  if (parent === current) return resolve(path);
39
54
  rest.push(current.slice(parent.length).replace(/^[\\/]+/, ""));
@@ -42,40 +57,78 @@ export function realPathOf(path) {
42
57
  }
43
58
  }
44
59
 
45
- /** The protected folders: the DSH home and this plugin's state directory (inside it by default). */
60
+
46
61
  export function protectedRoots(env = process.env, home = homedir()) {
47
62
  const dshHome = typeof env.DSH_HOME === "string" && env.DSH_HOME.trim() !== "" ? env.DSH_HOME : join(home, ".dsh");
48
63
  return [dshHome, mobileRemoteStateDir(env, home)].map((root) => realPathOf(root));
49
64
  }
50
65
 
51
- /** `(dev, ino)` of the protected folders that exist. */
66
+
52
67
  function rootIds(roots) {
53
68
  const ids = new Set();
54
69
  for (const root of roots) {
55
70
  try {
56
71
  ids.add(idOf(statSync(root)));
57
72
  } catch {
58
- /* not created yet: nothing to protect there */
73
+
59
74
  }
60
75
  }
61
76
  return ids;
62
77
  }
63
78
 
64
- /** True for `/dev` and `/proc` and anything under them (open files, other processes). */
79
+ const DEVICE_ROOTS = ["/dev", "/proc"];
80
+ const underDevice = (p) => {
81
+ const f = norm(p);
82
+ return DEVICE_ROOTS.some((d) => f === d || f.startsWith(`${d}/`));
83
+ };
84
+
85
+
86
+
87
+
88
+
65
89
  export function isDeviceOrProcPath(path) {
66
90
  if (process.platform === "win32") return false;
67
- const p = resolve(path);
68
- return ["/dev", "/proc"].some((d) => p === d || p.startsWith(`${d}/`));
91
+ if (underDevice(resolve(path))) return true;
92
+ let real;
93
+ try {
94
+ real = realPathOf(path);
95
+ } catch {
96
+ return true;
97
+ }
98
+ if (underDevice(real)) return true;
99
+ const ids = new Set();
100
+ for (const d of DEVICE_ROOTS) {
101
+ try {
102
+ ids.add(idOf(statSync(d)));
103
+ } catch {
104
+
105
+ }
106
+ }
107
+ for (let current = real; ; ) {
108
+ try {
109
+ if (ids.has(idOf(statSync(current)))) return true;
110
+ } catch {
111
+
112
+ }
113
+ const parent = dirname(current);
114
+ if (parent === current) return false;
115
+ current = parent;
116
+ }
69
117
  }
70
118
 
71
- /** True when `target` is a protected folder or anywhere inside one, whatever it is called. */
119
+
72
120
  export function isProtectedPath(target, roots = protectedRoots()) {
73
121
  if (isDeviceOrProcPath(target)) return true;
74
- const real = realPathOf(target);
75
- // Fast path: the usual spelling.
122
+ let real;
123
+ try {
124
+ real = realPathOf(target);
125
+ } catch {
126
+ return true;
127
+ }
128
+
76
129
  const r = norm(real);
77
130
  if (roots.some((root) => r === norm(root) || r.startsWith(norm(root).endsWith(sep) ? norm(root) : `${norm(root)}${sep}`))) return true;
78
- // Identity: the nearest existing folder on the way, and every folder above it.
131
+
79
132
  const ids = rootIds(roots);
80
133
  if (ids.size === 0) return false;
81
134
  let current = real;
@@ -83,7 +136,7 @@ export function isProtectedPath(target, roots = protectedRoots()) {
83
136
  try {
84
137
  if (ids.has(idOf(statSync(current)))) return true;
85
138
  } catch {
86
- /* not there (yet): look at its parent */
139
+
87
140
  }
88
141
  const parent = dirname(current);
89
142
  if (parent === current) return false;
@@ -91,13 +144,13 @@ export function isProtectedPath(target, roots = protectedRoots()) {
91
144
  }
92
145
  }
93
146
 
94
- /**
95
- * `(dev, ino)` of the protected files: everything in the plugin's state folder (a handful of
96
- * files, walked a few levels deep) and the top level of the DSH home, where DSH keeps its keys
97
- * (`.credentials.yaml`, `.env`). Session logs deeper in the DSH home are not keys and are not
98
- * walked, so this stays cheap enough to run per request. Unlisted subfolders of the DSH home
99
- * are still refused by path (`isProtectedPath`).
100
- */
147
+
148
+
149
+
150
+
151
+
152
+
153
+
101
154
  export function protectedFileIds(roots = protectedRoots()) {
102
155
  const [dshHome, stateDir] = roots;
103
156
  const ids = rootIds(roots);
@@ -115,7 +168,7 @@ export function protectedFileIds(roots = protectedRoots()) {
115
168
  ids.add(idOf(st));
116
169
  if (st.isDirectory() && depth > 0) walk(path, depth - 1);
117
170
  } catch {
118
- /* vanished */
171
+
119
172
  }
120
173
  }
121
174
  };
@@ -124,7 +177,114 @@ export function protectedFileIds(roots = protectedRoots()) {
124
177
  return ids;
125
178
  }
126
179
 
127
- /** True when an opened file (its fstat) is one of the protected files. */
128
- export function isProtectedFile(st, ids = protectedFileIds()) {
129
- return Boolean(st) && ids.has(idOf(st));
180
+
181
+ const SKIP_DIRS = new Set(["node_modules", ".pnpm-store", ".git"]);
182
+
183
+ export const FULL_WALK_LIMIT = 100_000;
184
+
185
+
186
+
187
+
188
+
189
+
190
+ export function allProtectedIds(roots = protectedRoots(), limit = FULL_WALK_LIMIT) {
191
+ const ids = rootIds(roots);
192
+ let seen = 0;
193
+ const stack = roots.filter(Boolean).map((r) => [r, 0]);
194
+ while (stack.length) {
195
+ const [dir, depth] = stack.pop();
196
+ let entries;
197
+ try {
198
+ entries = readdirSync(dir, { withFileTypes: true });
199
+ } catch {
200
+ continue;
201
+ }
202
+ for (const entry of entries) {
203
+ if (++seen > limit) return null;
204
+ const path = join(dir, entry.name);
205
+ try {
206
+ const st = lstatSync(path);
207
+ ids.add(idOf(st));
208
+ if (st.isDirectory() && depth < 32 && !SKIP_DIRS.has(entry.name)) stack.push([path, depth + 1]);
209
+ } catch {
210
+
211
+ }
212
+ }
213
+ }
214
+ return ids;
215
+ }
216
+
217
+
218
+
219
+
220
+
221
+ export function isProtectedFile(st, ids) {
222
+ if (!st) return false;
223
+ const id = idOf(st);
224
+ if ((ids ?? protectedFileIds()).has(id)) return true;
225
+ if (ids === undefined && st.nlink > 1 && !st.isDirectory()) {
226
+ const all = allProtectedIds();
227
+ return all === null || all.has(id);
228
+ }
229
+ return false;
230
+ }
231
+
232
+
233
+
234
+
235
+
236
+
237
+ export function isStillAt(target, st, roots = protectedRoots()) {
238
+ try {
239
+ const real = realPathOf(target);
240
+ if (isProtectedPath(real, roots)) return false;
241
+ return idOf(statSync(real)) === idOf(st);
242
+ } catch {
243
+ return false;
244
+ }
245
+ }
246
+
247
+
248
+
249
+
250
+
251
+
252
+ export function removeCreatedEntry(target, st, roots = protectedRoots()) {
253
+ if (!st) return false;
254
+ const name = basename(target);
255
+ const id = idOf(st);
256
+ const dirs = [dirname(resolve(target))];
257
+ try {
258
+ dirs.push(dirname(realPathOf(target)));
259
+ } catch {
260
+
261
+ }
262
+ const stack = roots.filter(Boolean).map((r) => [r, 0]);
263
+ let seen = 0;
264
+ while (stack.length && seen < FULL_WALK_LIMIT) {
265
+ const [dir, depth] = stack.pop();
266
+ dirs.push(dir);
267
+ let entries;
268
+ try {
269
+ entries = readdirSync(dir, { withFileTypes: true });
270
+ } catch {
271
+ continue;
272
+ }
273
+ for (const entry of entries) {
274
+ seen++;
275
+ if (entry.isDirectory() && depth < 32 && !SKIP_DIRS.has(entry.name)) stack.push([join(dir, entry.name), depth + 1]);
276
+ }
277
+ }
278
+ for (const dir of dirs) {
279
+ const candidate = join(dir, name);
280
+ try {
281
+ if (idOf(lstatSync(candidate)) === id) {
282
+ unlinkSync(candidate);
283
+ return true;
284
+ }
285
+ } catch {
286
+
287
+ }
288
+ }
289
+ return false;
130
290
  }
package/lib/protocol.js CHANGED
@@ -1,35 +1,74 @@
1
- /**
2
- * App ↔ plugin protocol and feature negotiation (plan §5.12, T-61).
3
- *
4
- * Every computer may run a different plugin version, so the plugin says what it speaks
5
- * and offers, in `/bootstrap` and in the SSE `hello` frame:
6
- *
7
- * - `protocol: { min, max }`: the protocol versions it speaks. Version 1 is the API as it
8
- * stood when negotiation was added (every older plugin speaks exactly that, without
9
- * saying so). Raise `max` when the plugin learns a new version; raise `min` only when it
10
- * drops an old one.
11
- * - `features`: optional features this build has. The app gates each one per computer
12
- * and shows "update the plugin on {PC}" instead of calling an endpoint that 404s.
13
- * - `minAppVersion`: the oldest app that works with this plugin.
14
- *
15
- * Feature names are shared with the app (`dsh-mobile-app/lib/plugin_protocol.dart`).
16
- * Not built yet, and so not listed (the app reserves them): `p2p`, `multi-pc`,
17
- * `phone-tools`, `toolbox-install`. Add a name here in the same change that ships it.
18
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
19
21
 
20
22
  export const PROTOCOL = Object.freeze({ min: 1, max: 1 });
21
23
 
22
24
  export const FEATURES = Object.freeze([
23
- // Persona cards: GET/POST/DELETE /api/persona (T-31).
25
+
24
26
  "persona-cards",
27
+
28
+
29
+
30
+ "lan-noise",
31
+
32
+
33
+
34
+ "p2p-signal",
35
+
36
+
37
+
38
+ "standby",
39
+ ]);
40
+
41
+
42
+
43
+
44
+
45
+ const dynamicFeatures = new Map();
46
+
47
+ export const DYNAMIC_FEATURES = Object.freeze([
48
+
49
+ "p2p",
25
50
  ]);
51
+ export function registerFeature(name) {
52
+ if (!DYNAMIC_FEATURES.includes(name)) throw new Error(`not a dynamic feature: ${name}`);
53
+ dynamicFeatures.set(name, (dynamicFeatures.get(name) ?? 0) + 1);
54
+ let done = false;
55
+ return () => {
56
+ if (done) return;
57
+ done = true;
58
+ const n = (dynamicFeatures.get(name) ?? 1) - 1;
59
+ if (n <= 0) dynamicFeatures.delete(name);
60
+ else dynamicFeatures.set(name, n);
61
+ };
62
+ }
63
+
64
+ export const PHONE_ACTIONS_FEATURE = "phone-actions";
65
+
26
66
 
27
- /** Apps older than this can't work with this plugin (none so far). */
28
67
  export const MIN_APP_VERSION = "3.0.0";
29
68
 
30
- /** The fields `/bootstrap` and the `hello` frame carry. */
31
- export const protocolInfo = () => ({
69
+
70
+ export const protocolInfo = (extraFeatures = []) => ({
32
71
  protocol: { min: PROTOCOL.min, max: PROTOCOL.max },
33
- features: [...FEATURES],
72
+ features: [...FEATURES, ...dynamicFeatures.keys(), ...extraFeatures],
34
73
  minAppVersion: MIN_APP_VERSION,
35
74
  });
package/lib/push.js CHANGED
@@ -1,22 +1,22 @@
1
- /**
2
- * 第三方推送通道的请求构造。
3
- * 从 lib/index.js 原样拆出(行为不变)。
4
- */
5
-
6
- /**
7
- * ntfy 发布请求(v3.1.4,issue #14 Bug3)。
8
- *
9
- * ntfy 的 JSON 发布契约:`POST /`(或自托管服务器的 base path 根)**且 body 内带 `topic`**;
10
- * 把 JSON 发到主题地址(`POST /<topic>`)时服务端按**纯文本**处理整段 JSON ——
11
- * 实测返回体中无 `title` 字段、`message` 为 `{"title":…,"message":…}` 原文,
12
- * 于是手机通知没有标题、正文是一坨 JSON(用户 12 小时 ntfy 历史里按标题搜不到任何提醒)。
13
- *
14
- * 兼容自托管带 base path 的部署:`https://host/ntfy/topic` → POST `https://host/ntfy/`。
15
- *
16
- * @param {string} url - 配置里的通道地址(形如 `https://ntfy.sh/<topic>`)
17
- * @param {object} payload - 消息字段(title / message / priority …)
18
- * @returns {{url: string, body: string}} 发布地址与 JSON body(已含 topic)
19
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
20
  export function ntfyPublish(url, payload = {}) {
21
21
  const parsed = new URL(url);
22
22
  const segments = parsed.pathname.split("/").filter((segment) => segment !== "");
@@ -28,33 +28,33 @@ export function ntfyPublish(url, payload = {}) {
28
28
  };
29
29
  }
30
30
 
31
- /** 按通道格式(serverchan / ntfy / bark / wecom / generic)构造并发送一次推送;失败抛错,由调用方记录。 */
31
+
32
32
  export async function pushToChannel(logger, target, kind, kindLabel, title, detail, sessionId) {
33
33
  const desp = detail || "详情请在 DSH Remote App 中查看";
34
34
  let url = target.url;
35
35
  const headers = { "user-agent": "dsh-mobile-remote" };
36
36
  let init;
37
37
  if (target.format === "serverchan") {
38
- // Server酱³:POST form,title/desp
38
+
39
39
  const params = new URLSearchParams({ title: `${kindLabel} · ${title}`, desp });
40
40
  init = { method: "POST", headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, body: params.toString() };
41
41
  } else if (target.format === "ntfy") {
42
- // ntfy JSON 格式:标题走 body(x-title 头只接受 Latin-1,中文/emoji 会抛错)
43
- // v3.1.4(issue #14 Bug3):必须 POST 根地址且 body 带 topic——发到主题地址时
44
- // ntfy 把整段 JSON 当纯文本消息,标题丢失(详见 ntfyPublish 注释与实测结论)。
42
+
43
+
44
+
45
45
  const publish = ntfyPublish(url, { title: `${kindLabel} · ${title}`, message: desp });
46
46
  url = publish.url;
47
47
  init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: publish.body };
48
48
  } else if (target.format === "bark") {
49
49
  init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify({ title: `${kindLabel} · ${title}`, body: desp }) };
50
50
  } else if (target.format === "wecom") {
51
- // 企业微信群机器人 Webhook(国内稳定、免登录态;约 20 条/分钟限额)
51
+
52
52
  init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify({ msgtype: "text", text: { content: `${kindLabel} · ${title}\n${desp}` } }) };
53
53
  } else {
54
54
  init = { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: JSON.stringify({ kind, title, detail: desp, sessionId, time: Date.now() }) };
55
55
  }
56
- // v3.1.2:超时 10s→15s,并针对间歇性网络失败(DNS 抖动等)重试一次——
57
- // 只重试 fetch 传输失败(timeout/DNS/ECONNRESET),HTTP 4xx/5xx(配额/参数错)不重试
56
+
57
+
58
58
  const pushOnce = async () => {
59
59
  try {
60
60
  return await fetch(url, { ...init, signal: AbortSignal.timeout(15_000) });
@@ -65,8 +65,8 @@ export async function pushToChannel(logger, target, kind, kindLabel, title, deta
65
65
  };
66
66
  const response = await pushOnce();
67
67
  if (!response.ok) {
68
- // v3.0.0:失败带上响应体(截断)——Server酱/Turbo 400 常带原因说明(额度/参数/转发),
69
- // 裸 "HTTP 400" 无法定位;空 body 则可能为网络中间层拦截
68
+
69
+
70
70
  const text = (await response.text().catch(() => "")).trim().slice(0, 300);
71
71
  throw new Error(`HTTP ${response.status}${text ? `: ${text}` : "(空响应体)"}`);
72
72
  }
package/lib/rate-limit.js CHANGED
@@ -1,20 +1,20 @@
1
- /**
2
- * 登录限流(v2.6.0):按来源 IP 固定窗口计数,防弱口令爆破。从 lib/index.js 原样拆出(行为不变)。
3
- */
4
-
5
- /**
6
- * @param {{ maxFailures?: number, windowMs?: number, blockMs?: number }} [overrides] 即 `config.rateLimit`
7
- * @returns {{ cfg: object, blocked: (ip: string) => boolean, fail: (ip: string) => void, reset: (ip: string) => boolean }}
8
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
9
  export function createLoginRateLimiter(overrides) {
10
- // 正常用户一次成功即重置计数;frp 等中继场景所有外部请求同源(中继 IP),
11
- // 阈值 10 次/60s 对单用户足够宽裕(见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §2)。
10
+
11
+
12
12
  const rateLimitCfg = { maxFailures: 10, windowMs: 60_000, blockMs: 60_000, ...(overrides ?? {}) };
13
- const rateBuckets = new Map(); // ip -> { count, windowStart, blockedUntil? }
14
- // 封锁用显式的 blockedUntil 计时:到阈值那一刻起算 blockMs,与 windowMs 无关。
15
- // 旧实现用 `now - windowStart < blockMs` 判定——blockMs < windowMs 时封锁提前结束,
16
- // 而失败计数仍 ≥ 阈值,窗口剩余时间内每次猜口令都被放行(blockMs 形同虚设);
17
- // blockMs > windowMs 时又被 windowStart 截短。封锁到期即整桶清零,下一个周期重新给 maxFailures 次额度。
13
+ const rateBuckets = new Map();
14
+
15
+
16
+
17
+
18
18
  const rateBlocked = (ip) => {
19
19
  const b = rateBuckets.get(ip);
20
20
  if (b === undefined || b.blockedUntil === undefined) return false;
@@ -31,7 +31,7 @@ export function createLoginRateLimiter(overrides) {
31
31
  }
32
32
  b.count++;
33
33
  if (b.count >= rateLimitCfg.maxFailures) b.blockedUntil = now + rateLimitCfg.blockMs;
34
- // 防内存膨胀:超过 512 个来源时清掉最旧的一半
34
+
35
35
  if (rateBuckets.size > 512) {
36
36
  const oldest = [...rateBuckets.entries()]
37
37
  .sort((x, y) => x[1].windowStart - y[1].windowStart)