@240xu/dsh-websearch 2.8.7 → 2.8.9

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/lib/health.js CHANGED
@@ -7,28 +7,18 @@
7
7
  // provider's own telemetry truncation) and run through a defensive redaction
8
8
  // pass for token-like fragments.
9
9
 
10
- import { rejectionFor } from "./trust.js";
10
+ import { rejectionFor, rejectionBody } from "./trust.js";
11
11
 
12
- const MAX_ERROR_CHARS = 120;
12
+ import { sanitizeError as redactError } from "./util/redact.js";
13
13
 
14
- /** Token-like fragments that must never appear in a health payload. */
15
- const SECRET_PATTERNS = [
16
- /sk-[A-Za-z0-9_-]{8,}/g,
17
- /Bearer\s+[A-Za-z0-9._-]{8,}/gi,
18
- /(api[_-]?key|token|secret|password)\s*[=:]\s*\S{6,}/gi,
19
- ];
14
+ const MAX_ERROR_CHARS = 120;
20
15
 
21
16
  /**
22
17
  * Truncate + redact an error string for safe display.
23
18
  * Returns "" for falsy input; length bounded to 40-120 chars.
24
19
  */
25
20
  export function sanitizeError(err) {
26
- if (err === null || err === undefined) return "";
27
- let s = String(err instanceof Error ? err.message : err);
28
- for (const re of SECRET_PATTERNS) s = s.replace(re, "[redacted]");
29
- s = s.replace(/\s+/g, " ").trim();
30
- if (s.length > MAX_ERROR_CHARS) s = s.slice(0, MAX_ERROR_CHARS);
31
- return s;
21
+ return redactError(err, MAX_ERROR_CHARS);
32
22
  }
33
23
 
34
24
  /**
@@ -60,6 +50,14 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
60
50
  id,
61
51
  enabled,
62
52
  keyless,
53
+ optionalKey: beOpts.optionalKey === true,
54
+ metered: beOpts.metered === true,
55
+ // Observability: expose the breaker classification so callers can tell
56
+ // a quota cooldown from an ordinary outage or a missing key without
57
+ // parsing lastError. Additive fields; existing keys keep their meaning.
58
+ rateLimited: t?.rateLimited === true,
59
+ keylessRejected: t?.keylessRejected === true,
60
+ cooledUntilMs: Number.isFinite(t?.cooledUntil) && t.cooledUntil > 0 ? t.cooledUntil : null,
63
61
  // reachable: true/false from the latest search telemetry; null = never probed.
64
62
  reachable: t ? t.ok === true : null,
65
63
  lastOk: t && typeof t.lastOkAt === "number" ? t.lastOkAt : null,
@@ -72,6 +70,10 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
72
70
  ok: true,
73
71
  enabled: enabledList.length,
74
72
  keyless: enabledList.filter((b) => b.keyless).length,
73
+ // The deployment cap and the user's numResults combine as
74
+ // min(hostCap, userMax) in provider.search(); expose the user value here
75
+ // so an observer can explain why a search returned fewer results.
76
+ requestedMaxResults: Number.isFinite(opts.numResults) ? opts.numResults : null,
75
77
  backends: list,
76
78
  updatedAt: Date.now(),
77
79
  };
@@ -82,8 +84,8 @@ export function buildHealthReport({ resolveOptions, backends, getBackendHealth }
82
84
  * GET only; never probes backends; response is JSON with no credentials.
83
85
  */
84
86
  export function registerHealthRoute(ws, deps) {
85
- if (!ws || typeof ws.register !== "function") return;
86
- ws.register({
87
+ if (!ws || typeof ws.register !== "function") return [];
88
+ const disposer = ws.register({
87
89
  kind: "exact",
88
90
  path: "/api/unified-search/health",
89
91
  handler: (req, res) => {
@@ -93,7 +95,7 @@ export function registerHealthRoute(ws, deps) {
93
95
  };
94
96
  const rejection = rejectionFor(req, typeof deps.getConnection === "function" ? deps.getConnection() : undefined);
95
97
  if (rejection !== undefined) {
96
- send(rejection, { ok: false, error: rejection === 503 ? "admission unavailable" : "untrusted request" });
98
+ send(rejection, rejectionBody(rejection));
97
99
  return;
98
100
  }
99
101
  if (req.method !== "GET" && req.method !== "HEAD") {
@@ -107,4 +109,5 @@ export function registerHealthRoute(ws, deps) {
107
109
  }
108
110
  },
109
111
  });
112
+ return typeof disposer === "function" ? [disposer] : [];
110
113
  }
package/lib/history.js CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import path from "node:path";
11
- import { rejectionFor } from "./trust.js";
11
+ import { rejectionFor, rejectionBody } from "./trust.js";
12
12
 
13
13
  /** Ring-buffer cap (spec: 50). */
14
14
  export const HISTORY_MAX_ENTRIES = 50;
@@ -82,40 +82,21 @@ export function createHistoryStore({ dir, maxEntries = HISTORY_MAX_ENTRIES }) {
82
82
  return readAll().slice(0, cap).map(toPublicEntry);
83
83
  },
84
84
 
85
- /** Empty the history (removes the file; best-effort). */
85
+ /** Empty the history. Serialised with record() so a pending append cannot
86
+ * resurrect an entry after the clear. */
86
87
  clear() {
87
- try {
88
- if (existsSync(file())) unlinkSync(file());
89
- } catch {
90
- // nothing to do
91
- }
88
+ writeChain = writeChain.then(() => {
89
+ try {
90
+ if (existsSync(file())) unlinkSync(file());
91
+ } catch {
92
+ // nothing to do
93
+ }
94
+ });
95
+ return writeChain;
92
96
  },
93
97
  };
94
98
  }
95
99
 
96
- /**
97
- * Minimal trust fence for plugin-registered routes (the host /api RPC fence
98
- * does not cover webServer.register paths): require a loopback Host (blocks
99
- * DNS rebinding) and a same-site browser context (sec-fetch-site same-origin
100
- * / none, or an Origin whose host matches the request Host — blocks
101
- * cross-site CSRF including text/plain preflight-less POSTs).
102
- * Returns null when trusted, otherwise a short rejection reason.
103
- */
104
- export function isTrustedApiRequest(req) {
105
- const host = String(req?.headers?.host ?? "");
106
- const hostOk = /^(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])(:\d+)?$/.test(host);
107
- if (!hostOk) return "untrusted host";
108
- const site = req?.headers?.["sec-fetch-site"];
109
- if (site === "same-origin" || site === "none") return null;
110
- const origin = req?.headers?.origin;
111
- if (!origin) return site !== undefined ? "cross-site request" : null;
112
- try {
113
- return new URL(origin).host === host ? null : "cross-origin request";
114
- } catch {
115
- return "invalid origin";
116
- }
117
- }
118
-
119
100
  /**
120
101
  * Project the module-level backend health map into a small observability
121
102
  * payload (v2.8.0 P2): per-backend last real success/failure, latency and
@@ -132,6 +113,9 @@ export function toBackendObservability(healthMap, nowMs = Date.now()) {
132
113
  at: Number.isFinite(e?.at) ? e.at : null,
133
114
  failCount: Number.isFinite(e?.failCount) ? e.failCount : 0,
134
115
  cooled: Number.isFinite(e?.cooledUntil) && e.cooledUntil > nowMs,
116
+ cooledUntilMs: Number.isFinite(e?.cooledUntil) && e.cooledUntil > 0 ? e.cooledUntil : null,
117
+ rateLimited: e?.rateLimited === true,
118
+ keylessRejected: e?.keylessRejected === true,
135
119
  });
136
120
  }
137
121
  }
@@ -148,7 +132,7 @@ export function toBackendObservability(healthMap, nowMs = Date.now()) {
148
132
  * decision the kernel applies to its own /api routes).
149
133
  */
150
134
  export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConnection }) {
151
- if (!ws || typeof ws.register !== "function") return;
135
+ if (!ws || typeof ws.register !== "function") return [];
152
136
  const send = (res, code, body) => {
153
137
  res.writeHead(code, { "content-type": "application/json" });
154
138
  res.end(JSON.stringify(body));
@@ -156,12 +140,12 @@ export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConne
156
140
  const guarded = (handler) => (req, res) => {
157
141
  const rejection = rejectionFor(req, typeof getConnection === "function" ? getConnection() : undefined);
158
142
  if (rejection !== undefined) {
159
- send(res, rejection, { ok: false, error: rejection === 503 ? "admission unavailable" : "untrusted request" });
143
+ send(res, rejection, rejectionBody(rejection));
160
144
  return;
161
145
  }
162
146
  handler(req, res);
163
147
  };
164
- ws.register({
148
+ const disposerA = ws.register({
165
149
  kind: "exact",
166
150
  path: "/api/websearch/history",
167
151
  handler: guarded((req, res) => {
@@ -177,7 +161,7 @@ export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConne
177
161
  });
178
162
  }),
179
163
  });
180
- ws.register({
164
+ const disposerB = ws.register({
181
165
  kind: "exact",
182
166
  path: "/api/websearch/history/clear",
183
167
  handler: guarded((req, res) => {
@@ -186,8 +170,14 @@ export function registerHistoryRoutes(ws, { getStore, getBackendHealth, getConne
186
170
  return;
187
171
  }
188
172
  const store = getStore();
189
- store?.clear();
190
- send(res, 200, { ok: true, cleared: true });
173
+ // clear() is serialised behind the write chain, so the 200 must wait for
174
+ // it: otherwise the client's next GET can still see the old entries.
175
+ const cleared = store?.clear();
176
+ Promise.resolve(cleared).then(
177
+ () => send(res, 200, { ok: true, cleared: true }),
178
+ () => send(res, 500, { ok: false, error: "clear failed" }),
179
+ );
191
180
  }),
192
181
  });
182
+ return [disposerA, disposerB].filter((d) => typeof d === "function");
193
183
  }