@dsh-mobile/mobile-remote 3.3.1 → 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 (58) hide show
  1. package/README.md +9 -5
  2. package/docs/PRIVACY-POLICY.en.md +10 -3
  3. package/docs/PRIVACY-POLICY.md +10 -3
  4. package/docs/USER-GUIDE.zh-CN.md +1 -0
  5. package/lib/account-usage-query.js +60 -60
  6. package/lib/account-usage.js +10 -10
  7. package/lib/api-helpers.js +109 -109
  8. package/lib/assistant-prefs.js +82 -59
  9. package/lib/auto-config.js +65 -65
  10. package/lib/backup.js +117 -117
  11. package/lib/break-reminder.js +45 -45
  12. package/lib/client.js +93 -93
  13. package/lib/config.js +232 -218
  14. package/lib/git-read-bundled-provider.js +12 -12
  15. package/lib/git-read-service.js +5 -5
  16. package/lib/host-compat.js +84 -84
  17. package/lib/http-util.js +17 -17
  18. package/lib/index.js +1534 -1534
  19. package/lib/memory/context.js +44 -44
  20. package/lib/memory/decay.js +93 -93
  21. package/lib/memory/extract.js +77 -77
  22. package/lib/memory/routes.js +33 -33
  23. package/lib/memory/store.js +196 -196
  24. package/lib/notify-copy.js +93 -93
  25. package/lib/permission-guide.js +86 -86
  26. package/lib/persona-cards.js +73 -65
  27. package/lib/phone-action-args.js +175 -0
  28. package/lib/phone-actions.js +227 -0
  29. package/lib/phone-announce.js +58 -0
  30. package/lib/proactive-material.js +42 -42
  31. package/lib/proactive.js +121 -121
  32. package/lib/protected-paths.js +79 -79
  33. package/lib/protocol.js +61 -26
  34. package/lib/push.js +29 -29
  35. package/lib/rate-limit.js +16 -16
  36. package/lib/relay/connector.js +246 -102
  37. package/lib/relay/crypto.js +15 -15
  38. package/lib/relay/devices.js +36 -36
  39. package/lib/relay/fingerprint.js +34 -34
  40. package/lib/relay/identity.js +26 -26
  41. package/lib/relay/mux.js +60 -46
  42. package/lib/relay/noise.js +40 -40
  43. package/lib/relay/on-demand.js +33 -33
  44. package/lib/relay/p2p.js +239 -0
  45. package/lib/relay/pairing.js +24 -24
  46. package/lib/relay/phone.js +62 -40
  47. package/lib/relay/serve.js +21 -21
  48. package/lib/relay/signal.js +69 -0
  49. package/lib/relay/ws-server.js +32 -32
  50. package/lib/reminders.js +15 -15
  51. package/lib/rpc-adapter.js +43 -43
  52. package/lib/session-list.js +31 -31
  53. package/lib/session-rotation.js +95 -95
  54. package/lib/session-title-cache.js +35 -35
  55. package/lib/session-title-refresh.js +51 -51
  56. package/lib/timeline.js +140 -140
  57. package/lib/turn-outline.js +104 -104
  58. package/package.json +6 -13
@@ -1,29 +1,29 @@
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), in any case
19
- * spelling and through links (A-03: `/DEV/fd/N` is `/dev/fd/N` on a case-insensitive disk).
20
- * - A path whose real path can't be worked out (a symlink chain longer than PATH_MAX, a loop) is
21
- * treated as protected: fail closed (A-05).
22
- * - A file with more than one name (`nlink > 1`) is compared with every file in the DSH home, not
23
- * just the keys (A-04), and `isStillAt(target, st)` checks after opening that the name still
24
- * leads to the opened file outside the protected folders, which closes the check-then-open race
25
- * through a swapped symlink (A-08).
26
- */
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
27
  import { lstatSync, readdirSync, realpathSync, statSync, unlinkSync } from "node:fs";
28
28
  import { homedir } from "node:os";
29
29
  import { basename, dirname, join, resolve, sep } from "node:path";
@@ -33,12 +33,12 @@ const caseInsensitive = process.platform === "darwin" || process.platform === "w
33
33
  const norm = (p) => (caseInsensitive ? p.normalize("NFC").toLowerCase() : p.normalize("NFC"));
34
34
  const idOf = (st) => `${st.dev}:${st.ino}`;
35
35
 
36
- /**
37
- * Resolve symlinks; for a missing path, resolve the nearest existing parent and re-append.
38
- * Only "does not exist" (ENOENT, ENOTDIR) moves on to the parent. Any other error (ENAMETOOLONG
39
- * from an over-long symlink chain, ELOOP, EACCES) throws a `path-unresolvable` error: guessing the
40
- * real path from the spelling is exactly how the A-05 chain reached the DSH home.
41
- */
36
+
37
+
38
+
39
+
40
+
41
+
42
42
  export function realPathOf(path) {
43
43
  let current = resolve(path);
44
44
  const rest = [];
@@ -57,20 +57,20 @@ export function realPathOf(path) {
57
57
  }
58
58
  }
59
59
 
60
- /** The protected folders: the DSH home and this plugin's state directory (inside it by default). */
60
+
61
61
  export function protectedRoots(env = process.env, home = homedir()) {
62
62
  const dshHome = typeof env.DSH_HOME === "string" && env.DSH_HOME.trim() !== "" ? env.DSH_HOME : join(home, ".dsh");
63
63
  return [dshHome, mobileRemoteStateDir(env, home)].map((root) => realPathOf(root));
64
64
  }
65
65
 
66
- /** `(dev, ino)` of the protected folders that exist. */
66
+
67
67
  function rootIds(roots) {
68
68
  const ids = new Set();
69
69
  for (const root of roots) {
70
70
  try {
71
71
  ids.add(idOf(statSync(root)));
72
72
  } catch {
73
- /* not created yet: nothing to protect there */
73
+
74
74
  }
75
75
  }
76
76
  return ids;
@@ -81,11 +81,11 @@ const underDevice = (p) => {
81
81
  const f = norm(p);
82
82
  return DEVICE_ROOTS.some((d) => f === d || f.startsWith(`${d}/`));
83
83
  };
84
- /**
85
- * True for `/dev` and `/proc` and anything under them (open files, other processes), however it is
86
- * spelled: case-folded where the disk is case-insensitive (A-03), after resolving links, and by the
87
- * identity of the folders on the way. Unresolvable paths count as device paths (fail closed).
88
- */
84
+
85
+
86
+
87
+
88
+
89
89
  export function isDeviceOrProcPath(path) {
90
90
  if (process.platform === "win32") return false;
91
91
  if (underDevice(resolve(path))) return true;
@@ -101,14 +101,14 @@ export function isDeviceOrProcPath(path) {
101
101
  try {
102
102
  ids.add(idOf(statSync(d)));
103
103
  } catch {
104
- /* no /proc on macOS */
104
+
105
105
  }
106
106
  }
107
107
  for (let current = real; ; ) {
108
108
  try {
109
109
  if (ids.has(idOf(statSync(current)))) return true;
110
110
  } catch {
111
- /* not there (yet) */
111
+
112
112
  }
113
113
  const parent = dirname(current);
114
114
  if (parent === current) return false;
@@ -116,19 +116,19 @@ export function isDeviceOrProcPath(path) {
116
116
  }
117
117
  }
118
118
 
119
- /** True when `target` is a protected folder or anywhere inside one, whatever it is called. */
119
+
120
120
  export function isProtectedPath(target, roots = protectedRoots()) {
121
121
  if (isDeviceOrProcPath(target)) return true;
122
122
  let real;
123
123
  try {
124
124
  real = realPathOf(target);
125
125
  } catch {
126
- return true; // A-05: can't tell where it leads, so it is not served
126
+ return true;
127
127
  }
128
- // Fast path: the usual spelling.
128
+
129
129
  const r = norm(real);
130
130
  if (roots.some((root) => r === norm(root) || r.startsWith(norm(root).endsWith(sep) ? norm(root) : `${norm(root)}${sep}`))) return true;
131
- // Identity: the nearest existing folder on the way, and every folder above it.
131
+
132
132
  const ids = rootIds(roots);
133
133
  if (ids.size === 0) return false;
134
134
  let current = real;
@@ -136,7 +136,7 @@ export function isProtectedPath(target, roots = protectedRoots()) {
136
136
  try {
137
137
  if (ids.has(idOf(statSync(current)))) return true;
138
138
  } catch {
139
- /* not there (yet): look at its parent */
139
+
140
140
  }
141
141
  const parent = dirname(current);
142
142
  if (parent === current) return false;
@@ -144,13 +144,13 @@ export function isProtectedPath(target, roots = protectedRoots()) {
144
144
  }
145
145
  }
146
146
 
147
- /**
148
- * `(dev, ino)` of the protected files: everything in the plugin's state folder (a handful of
149
- * files, walked a few levels deep) and the top level of the DSH home, where DSH keeps its keys
150
- * (`.credentials.yaml`, `.env`). Session logs deeper in the DSH home are not keys and are not
151
- * walked, so this stays cheap enough to run per request. Unlisted subfolders of the DSH home
152
- * are still refused by path (`isProtectedPath`).
153
- */
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
154
  export function protectedFileIds(roots = protectedRoots()) {
155
155
  const [dshHome, stateDir] = roots;
156
156
  const ids = rootIds(roots);
@@ -168,7 +168,7 @@ export function protectedFileIds(roots = protectedRoots()) {
168
168
  ids.add(idOf(st));
169
169
  if (st.isDirectory() && depth > 0) walk(path, depth - 1);
170
170
  } catch {
171
- /* vanished */
171
+
172
172
  }
173
173
  }
174
174
  };
@@ -177,16 +177,16 @@ export function protectedFileIds(roots = protectedRoots()) {
177
177
  return ids;
178
178
  }
179
179
 
180
- /** Folders never walked by the full walk: package installs (pnpm hard-links them by the thousand), no keys. */
180
+
181
181
  const SKIP_DIRS = new Set(["node_modules", ".pnpm-store", ".git"]);
182
- /** Upper bound of the full walk; past it, a hard-linked file is refused rather than guessed about. */
182
+
183
183
  export const FULL_WALK_LIMIT = 100_000;
184
184
 
185
- /**
186
- * `(dev, ino)` of every file and folder in the DSH home and the state folder (A-04: a hard link to
187
- * `profiles/<name>/cordis.patch.yml`, a session log or a deep state file reached nothing before).
188
- * Bounded: returns `null` when the walk hits `limit`, and the caller then fails closed.
189
- */
185
+
186
+
187
+
188
+
189
+
190
190
  export function allProtectedIds(roots = protectedRoots(), limit = FULL_WALK_LIMIT) {
191
191
  const ids = rootIds(roots);
192
192
  let seen = 0;
@@ -207,17 +207,17 @@ export function allProtectedIds(roots = protectedRoots(), limit = FULL_WALK_LIMI
207
207
  ids.add(idOf(st));
208
208
  if (st.isDirectory() && depth < 32 && !SKIP_DIRS.has(entry.name)) stack.push([path, depth + 1]);
209
209
  } catch {
210
- /* vanished */
210
+
211
211
  }
212
212
  }
213
213
  }
214
214
  return ids;
215
215
  }
216
216
 
217
- /**
218
- * True when an opened file (its fstat) is one of the protected files. A file with more than one
219
- * name may have its other name anywhere in the DSH home, so it is compared with the full walk.
220
- */
217
+
218
+
219
+
220
+
221
221
  export function isProtectedFile(st, ids) {
222
222
  if (!st) return false;
223
223
  const id = idOf(st);
@@ -229,11 +229,11 @@ export function isProtectedFile(st, ids) {
229
229
  return false;
230
230
  }
231
231
 
232
- /**
233
- * After opening `target`: does that name still lead, through its real path, to the very file that
234
- * was opened (`st` = fstat of the descriptor), outside the protected folders? A symlink swapped
235
- * between the path check and the open (A-08) makes the answer no, whichever way it points by now.
236
- */
232
+
233
+
234
+
235
+
236
+
237
237
  export function isStillAt(target, st, roots = protectedRoots()) {
238
238
  try {
239
239
  const real = realPathOf(target);
@@ -244,11 +244,11 @@ export function isStillAt(target, st, roots = protectedRoots()) {
244
244
  }
245
245
  }
246
246
 
247
- /**
248
- * A refused upload that created its file (O_EXCL) removes it again (A-08, A-45): the entry named
249
- * like `target` whose identity is `st`, wherever a swapped folder put it (the target's folder now,
250
- * or any folder in the DSH home). Only that exact inode is removed; nothing else is touched.
251
- */
247
+
248
+
249
+
250
+
251
+
252
252
  export function removeCreatedEntry(target, st, roots = protectedRoots()) {
253
253
  if (!st) return false;
254
254
  const name = basename(target);
@@ -257,7 +257,7 @@ export function removeCreatedEntry(target, st, roots = protectedRoots()) {
257
257
  try {
258
258
  dirs.push(dirname(realPathOf(target)));
259
259
  } catch {
260
- /* unresolvable: the walk below still looks in the DSH home */
260
+
261
261
  }
262
262
  const stack = roots.filter(Boolean).map((r) => [r, 0]);
263
263
  let seen = 0;
@@ -283,7 +283,7 @@ export function removeCreatedEntry(target, st, roots = protectedRoots()) {
283
283
  return true;
284
284
  }
285
285
  } catch {
286
- /* not here */
286
+
287
287
  }
288
288
  }
289
289
  return false;
package/lib/protocol.js CHANGED
@@ -1,39 +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",
25
- // Encrypted LAN path: Noise on the LAN bridge port at /v1/lan (T-25). Whether it is on right
26
- // now (bridge listening, relay identity present) and at which addresses is in
27
- // `capabilities.lanNoise`; this name says the build has it.
27
+
28
+
29
+
28
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",
29
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
+
30
66
 
31
- /** Apps older than this can't work with this plugin (none so far). */
32
67
  export const MIN_APP_VERSION = "3.0.0";
33
68
 
34
- /** The fields `/bootstrap` and the `hello` frame carry. */
35
- export const protocolInfo = () => ({
69
+
70
+ export const protocolInfo = (extraFeatures = []) => ({
36
71
  protocol: { min: PROTOCOL.min, max: PROTOCOL.max },
37
- features: [...FEATURES],
72
+ features: [...FEATURES, ...dynamicFeatures.keys(), ...extraFeatures],
38
73
  minAppVersion: MIN_APP_VERSION,
39
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)