@lincoln504/pi-research 1.7.22 → 1.7.23

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.
@@ -2,7 +2,7 @@
2
2
  name: pi-research
3
3
  description: "Multi-agent web research for any coding agent. Use for anything requiring current information from the internet — news, trends, product/service/company facts, statistics, people, places, events, APIs, library behavior, or 'what is X / how does X work' questions. Also use to search a local knowledge store of previously researched findings before doing live research. Powered by the pi-research engine (search, stealth scraping, security databases, Stack Exchange). Not for reading local files, running project commands, or analyzing this repository's own source."
4
4
  license: MIT
5
- metadata: { "author": "Lincoln Deen", "version": "1.7.22", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
5
+ metadata: { "author": "Lincoln Deen", "version": "1.7.23", "package": "@lincoln504/pi-research", "engine": "pi-research-sdk", "openclaw": { "requires": { "bins": ["node"] } } }
6
6
  allowed-tools: Bash(node:*)
7
7
  ---
8
8
 
package/dist/cli.mjs CHANGED
@@ -2013,10 +2013,10 @@ function stripTrailingLlmPunctuation(input) {
2013
2013
  continue;
2014
2014
  }
2015
2015
  if (last === ")" || last === "]" || last === "}") {
2016
- const open5 = last === ")" ? "(" : last === "]" ? "[" : "{";
2016
+ const open6 = last === ")" ? "(" : last === "]" ? "[" : "{";
2017
2017
  let balance = 0;
2018
2018
  for (const ch of s.slice(0, -1)) {
2019
- if (ch === open5) balance++;
2019
+ if (ch === open6) balance++;
2020
2020
  else if (ch === last) balance = Math.max(0, balance - 1);
2021
2021
  }
2022
2022
  if (balance === 0) {
@@ -3475,8 +3475,8 @@ function findMatchingBracket(text, start) {
3475
3475
  let depth = 0;
3476
3476
  let inString = false;
3477
3477
  let escaped = false;
3478
- const open5 = text[start];
3479
- const close = open5 === "{" ? "}" : "]";
3478
+ const open6 = text[start];
3479
+ const close = open6 === "{" ? "}" : "]";
3480
3480
  for (let i = start; i < text.length; i++) {
3481
3481
  const ch = text[i];
3482
3482
  if (escaped) {
@@ -3492,7 +3492,7 @@ function findMatchingBracket(text, start) {
3492
3492
  continue;
3493
3493
  }
3494
3494
  if (inString) continue;
3495
- if (ch === open5) depth++;
3495
+ if (ch === open6) depth++;
3496
3496
  else if (ch === close) {
3497
3497
  depth--;
3498
3498
  if (depth === 0) return { index: i, inString: false };
@@ -7463,6 +7463,16 @@ var init_lancedb_loader = __esm({
7463
7463
  }
7464
7464
  });
7465
7465
 
7466
+ // src/knowledge/sql-utils.ts
7467
+ function sqlString(value) {
7468
+ return `'${value.replace(/'/g, "''")}'`;
7469
+ }
7470
+ var init_sql_utils = __esm({
7471
+ "src/knowledge/sql-utils.ts"() {
7472
+ "use strict";
7473
+ }
7474
+ });
7475
+
7466
7476
  // src/knowledge/store-schema.ts
7467
7477
  import {
7468
7478
  Schema,
@@ -7751,8 +7761,8 @@ async function findRelevantUrlsBm25(table, query, limit, scopeFilter) {
7751
7761
  }
7752
7762
  async function findDocumentsByUrl(table, url, scopeFilter) {
7753
7763
  const startTime = Date.now();
7754
- const escapedUrl = url.replace(/'/g, "''");
7755
- let filter = `url = '${escapedUrl}'`;
7764
+ const escapedUrl = sqlString(url);
7765
+ let filter = `url = ${escapedUrl}`;
7756
7766
  if (scopeFilter) {
7757
7767
  filter = `(${filter}) AND (${scopeFilter})`;
7758
7768
  }
@@ -7824,6 +7834,7 @@ var init_store_operations = __esm({
7824
7834
  "src/knowledge/store-operations.ts"() {
7825
7835
  "use strict";
7826
7836
  init_logger();
7837
+ init_sql_utils();
7827
7838
  init_metrics();
7828
7839
  }
7829
7840
  });
@@ -7841,6 +7852,7 @@ var init_store = __esm({
7841
7852
  "src/knowledge/store.ts"() {
7842
7853
  "use strict";
7843
7854
  init_lancedb_loader();
7855
+ init_sql_utils();
7844
7856
  init_circuit_breaker();
7845
7857
  init_logger();
7846
7858
  init_metrics();
@@ -7917,10 +7929,10 @@ var init_store = __esm({
7917
7929
  return this.options.embedder;
7918
7930
  }
7919
7931
  getScopeFilter() {
7920
- const ws = this.getWorkspace().replace(/'/g, "''");
7932
+ const ws = sqlString(this.getWorkspace());
7921
7933
  switch (this.options.knowledgeMode) {
7922
7934
  case "project":
7923
- return `workspace = '${ws}'`;
7935
+ return `workspace = ${ws}`;
7924
7936
  case "global":
7925
7937
  return "is_global = true";
7926
7938
  default:
@@ -8465,8 +8477,8 @@ var init_store = __esm({
8465
8477
  const table = await this.getFreshTable();
8466
8478
  const startTime = Date.now();
8467
8479
  try {
8468
- const escapedUrl = url.replace(/'/g, "''");
8469
- await table.delete(`url = '${escapedUrl}' AND (${scopeFilter})`);
8480
+ const escapedUrl = sqlString(url);
8481
+ await table.delete(`url = ${escapedUrl} AND (${scopeFilter})`);
8470
8482
  const duration = Date.now() - startTime;
8471
8483
  metrics.observe("knowledge_store_delete_duration_ms", duration);
8472
8484
  metrics.increment("knowledge_store_delete_total", 1, { operation: "by_url", status: "success" });
@@ -8512,10 +8524,10 @@ var init_store = __esm({
8512
8524
  const table = await this.getFreshTable();
8513
8525
  const startTime = Date.now();
8514
8526
  try {
8515
- const escapedUrl = url.replace(/'/g, "''");
8516
- const escapedType = ingestionType.replace(/'/g, "''");
8527
+ const escapedUrl = sqlString(url);
8528
+ const escapedType = sqlString(ingestionType);
8517
8529
  const ageClause = Number.isFinite(olderThan) ? ` AND timestamp < ${Math.floor(olderThan)}` : "";
8518
- await table.delete(`url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND (${scopeFilter})${ageClause}`);
8530
+ await table.delete(`url = ${escapedUrl} AND ingestion_type = ${escapedType} AND (${scopeFilter})${ageClause}`);
8519
8531
  const duration = Date.now() - startTime;
8520
8532
  metrics.observe("knowledge_store_delete_duration_ms", duration, { operation: "by_url_and_type" });
8521
8533
  metrics.increment("knowledge_store_delete_total", 1, { operation: "by_url_and_type", status: "success" });
@@ -8555,10 +8567,10 @@ var init_store = __esm({
8555
8567
  while (retryCount <= MAX_RETRIES) {
8556
8568
  const table = await this.getFreshTable();
8557
8569
  try {
8558
- const escapedUrl = url.replace(/'/g, "''");
8559
- const escapedType = ingestionType.replace(/'/g, "''");
8570
+ const escapedUrl = sqlString(url);
8571
+ const escapedType = sqlString(ingestionType);
8560
8572
  await table.update({
8561
- where: `url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
8573
+ where: `url = ${escapedUrl} AND ingestion_type = ${escapedType} AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
8562
8574
  valuesSql: { timestamp: String(Math.floor(newTs)) }
8563
8575
  });
8564
8576
  logger.log(`[store] Refreshed timestamp for unchanged ${ingestionType} chunks of ${url}`);
@@ -8629,8 +8641,8 @@ var init_store = __esm({
8629
8641
  const table = await this.getFreshTable();
8630
8642
  const scopeFilter = this.getScopeFilter();
8631
8643
  const startTime = Date.now();
8632
- const escapedUrl = url.replace(/'/g, "''");
8633
- const whereClause = `url = '${escapedUrl}' AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
8644
+ const escapedUrl = sqlString(url);
8645
+ const whereClause = `url = ${escapedUrl} AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
8634
8646
  let results = await table.query().where(whereClause).limit(16).toArray();
8635
8647
  if (results.length === 16) {
8636
8648
  results = await table.query().where(whereClause).limit(1024).toArray();
@@ -8883,9 +8895,9 @@ var init_store = __esm({
8883
8895
  try {
8884
8896
  const table = await this.getFreshTable();
8885
8897
  const ws = normalizeWorkspacePath(workspace || this.getWorkspace());
8886
- const escaped = ws.replace(/'/g, "''");
8898
+ const escaped = sqlString(ws);
8887
8899
  const [local, global] = await Promise.all([
8888
- table.countRows(`workspace = '${escaped}'`),
8900
+ table.countRows(`workspace = ${escaped}`),
8889
8901
  table.countRows(`is_global = true`)
8890
8902
  ]);
8891
8903
  const allWorkspaces = await table.query().select(["workspace"]).toArray();
@@ -10288,12 +10300,12 @@ function isTransientSynthesisError(message) {
10288
10300
  m.includes("terminated") || m.includes("other side closed") || m.includes("socket hang up") || m.includes("und_err");
10289
10301
  }
10290
10302
  function splitPromptAtUserTurn(template) {
10291
- const open5 = template.indexOf("<!-- USER_TURN");
10292
- if (open5 < 0) return { system: template, user: null };
10293
- const close = template.indexOf("-->", open5);
10303
+ const open6 = template.indexOf("<!-- USER_TURN");
10304
+ if (open6 < 0) return { system: template, user: null };
10305
+ const close = template.indexOf("-->", open6);
10294
10306
  if (close < 0) return { system: template, user: null };
10295
10307
  return {
10296
- system: template.slice(0, open5).trimEnd(),
10308
+ system: template.slice(0, open6).trimEnd(),
10297
10309
  user: template.slice(close + "-->".length).trimStart()
10298
10310
  };
10299
10311
  }
@@ -11618,19 +11630,19 @@ function rewriteCitationMarkers(text, remap, isDangling) {
11618
11630
  }
11619
11631
  function fencedCodeMask(text) {
11620
11632
  const ranges = [];
11621
- let open5 = -1;
11633
+ let open6 = -1;
11622
11634
  let pos = 0;
11623
11635
  for (const line of text.split("\n")) {
11624
11636
  if (/^\s{0,3}(```|~~~)/.test(line)) {
11625
- if (open5 < 0) open5 = pos;
11637
+ if (open6 < 0) open6 = pos;
11626
11638
  else {
11627
- ranges.push([open5, pos + line.length]);
11628
- open5 = -1;
11639
+ ranges.push([open6, pos + line.length]);
11640
+ open6 = -1;
11629
11641
  }
11630
11642
  }
11631
11643
  pos += line.length + 1;
11632
11644
  }
11633
- if (open5 >= 0) ranges.push([open5, text.length]);
11645
+ if (open6 >= 0) ranges.push([open6, text.length]);
11634
11646
  return (offset) => ranges.some(([start, end]) => offset >= start && offset < end);
11635
11647
  }
11636
11648
  function inInlineCodeSpan(text, offset) {
@@ -18981,11 +18993,11 @@ import { createAgentSession, SessionManager, SettingsManager as SettingsManagerC
18981
18993
 
18982
18994
  // src/tools/read-guard.ts
18983
18995
  import { constants as constants2 } from "node:fs";
18984
- import { access as access3, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
18996
+ import { access as access3, open as open5, readFile as readFile7, realpath as realpath2 } from "node:fs/promises";
18985
18997
  import { homedir as homedir6 } from "node:os";
18986
18998
  import { basename as basename5, dirname as dirname13, relative, isAbsolute as isAbsolute3, parse, sep as sep2 } from "node:path";
18987
- var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud"]);
18988
- var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)(\..*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
18999
+ var DENIED_SEGMENTS = /* @__PURE__ */ new Set([".ssh", ".aws", ".gnupg", ".git", ".kube", ".docker", ".azure", ".gcloud", ".terraform"]);
19000
+ var DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.dockerconfigjson|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)([._-].*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars|key)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
18989
19001
  var ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
18990
19002
  function normalizeName(name) {
18991
19003
  return name.toLowerCase().replace(/:.*$/, "").replace(/[. ]+$/, "");
@@ -19036,7 +19048,16 @@ function createGuardedReadOperations(cwd) {
19036
19048
  },
19037
19049
  readFile: async (p) => {
19038
19050
  await assertReadAllowed(cwd, p);
19039
- return readFile7(p);
19051
+ const handle = await open5(p, constants2.O_RDONLY | constants2.O_NOFOLLOW);
19052
+ try {
19053
+ const stat6 = await handle.stat();
19054
+ if (!stat6.isFile()) {
19055
+ throw new ReadDeniedError("path is not a regular file");
19056
+ }
19057
+ return await readFile7(handle);
19058
+ } finally {
19059
+ await handle.close();
19060
+ }
19040
19061
  }
19041
19062
  };
19042
19063
  }
@@ -2123,9 +2123,13 @@ function getSocksProxyEndpoint() {
2123
2123
  return cached;
2124
2124
  }
2125
2125
  const cfg = JSON.parse(readFileSync(file, "utf8"));
2126
- const host = cfg.host ?? "127.0.0.1";
2127
- const port = cfg.port ?? 1080;
2128
- cached = host ? { host, port } : null;
2126
+ const host = cfg.host === void 0 ? "127.0.0.1" : typeof cfg.host === "string" ? cfg.host.trim() : "";
2127
+ const port = cfg.port === void 0 ? 1080 : Number.isInteger(cfg.port) ? cfg.port : -1;
2128
+ if (host === "" || port < 1 || port > 65535) {
2129
+ cached = null;
2130
+ return cached;
2131
+ }
2132
+ cached = { host, port };
2129
2133
  return cached;
2130
2134
  } catch {
2131
2135
  cached = null;
@@ -2147,9 +2151,7 @@ function loadSocksProxyPrefs() {
2147
2151
  function isProxyHopAddress(ip, proxy = getSocksProxyEndpoint()) {
2148
2152
  if (!proxy) return false;
2149
2153
  const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, "");
2150
- if (addr === "" || addr === "0.0.0.0" || addr === "::" || addr === "::0") return true;
2151
- const proxyHost = proxy.host.trim().toLowerCase().replace(/^\[|\]$/g, "");
2152
- return addr === proxyHost;
2154
+ return addr === "" || addr === "0.0.0.0" || addr === "::" || addr === "::0";
2153
2155
  }
2154
2156
 
2155
2157
  // src/infrastructure/browser/thread-worker-messaging.ts
package/docs/CHANGELOG.md CHANGED
@@ -5,6 +5,35 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.7.23] - 2026-10-26
9
+
10
+ ### Security
11
+
12
+ - **The `undici` floor admits three advisories for consumers.** `package.json` declared `undici ^8.11.2` (and the `jsdom` override `^8.10.2`), and the ranges `>=8.0.0 <8.12.2` carry GHSA-xjj6-f33q-929c (unhandled error on excessive content-encodings, CVSS 7.5), GHSA-4qv8-2p9j-2685 (unbounded memory in the EventSource parser) and GHSA-f72v-6w45-q472 (SRI bypass). This repo's own lock was already at 8.12.3, but the tarball ships no lockfile and npm `overrides` do not reach consumers — a consumer's hoisted `undici` only has to Satisfy `^8.11.2`, and the scraper uses `undici`'s `fetch` against hostile servers, so the content-encoding crash is reachable there. The floor is now `^8.12.2` in both places.
13
+ - **`SECURITY.md` claimed `*.key` files are refused; the read guard did not refuse them.** The `DENIED_BASENAME` list had no `key` extension, so `server.key`, `private.key` and `tls.key` were readable by a researcher session — the exfiltration path the guard exists to close. The list now covers `*.key`, the `id_*_sk` key forms (`id_ecdsa_sk`, `id_rsa_sk` — the `id_*` pattern only accepted a dot suffix), `.dockerconfigjson`, and the `.terraform` directory (credential directory, now in `DENIED_SEGMENTS`). Tests: `test/unit/tools/read-guard.test.ts`.
14
+ - **The standalone SOCKS proxy's IPv6 guard had drifted from the TS classifier.** `scripts/lib/private-addresses.mjs` claims to mirror `isPrivateIpv6` in `src/web-research/scraper-utils.ts`, but was missing the IPv4-tunneling ranges: site-local `fec0::/10`, 6to4 `2002::/16`, Teredo `2001:0::/32` and NAT64 `64:ff9b::/96` — literals like `64:ff9b::a9fe:a9fe` (the cloud-metadata address via NAT64) passed the guard. With the proxy the only SSRF backstop for proxied traffic, that was a live hole. The ranges are now ported with parity tests, and the port also fixed a pre-existing gap the TS classifier does not have: the `fc00::/7` check only covered `fc::` and missed `fd::`. Teredo is checked as `2001:0::/32` (second hextet zero), NOT the whole `2001::/32`, so public DNS like `2001:4860:4860::8888` stays allowed.
15
+ - **The browser's rebinding backstop exempted the proxy host itself.** `isProxyHopAddress` treated an origin address equal to the configured proxy host (normally `127.0.0.1`) as "the hop" and skipped the check — but with the proxy on loopback, an origin of `127.0.0.1` is indistinguishable from a genuine loopback origin, which the guard must poison. Measured camoufox behaviour reports the hop as `0.0.0.0`, which the unspecified-address exemption still covers, so dropping the host equality loses no legitimate scrape. `getSocksProxyEndpoint` now also type-checks `host`/`port` from the JSON (a numeric host or an out-of-range port means "no proxy", not a nonsense endpoint). Tests: `test/unit/infrastructure/thread-worker-ssrf-subresource.test.ts`.
16
+ - **The SOCKS proxy leaked memory and file descriptors, and its logs were injectable.** (a) The handshake `data` listener stayed attached after the handshake, so `buf` grew without bound for the lifetime of every long-lived proxied connection — it is now detached at the handshake's end and capped at 4096 bytes (a well-formed SOCKS request is under 300 bytes). (b) `client.pipe(upstream)` / `upstream.pipe(client)` left the upstream socket open on a client RST (fd leak); `stream.pipeline` now destroys both ends when either ends. (c) `targetHost` is raw domain bytes from a SOCKS client and can carry newlines into the cron log (CodeQL `js/log-injection`); it is now `JSON.stringify`-ed. (d) A refused connection to ANY host rotated the DuckDuckGo pin index, shifting pin order for unrelated destinations; rotation now only applies to DDG hosts. Tests: `test/unit/scripts/ddg-socks-proxy-guard.test.ts`, `test/unit/scripts/private-addresses.test.ts`.
17
+ - **Seven open CodeQL alerts, all now fixed.** `js/log-injection` ×2 in `scripts/ddg-socks-proxy.mjs` (the log-injection above), `js/insecure-temporary-file` in `test/unit/infrastructure/thread-worker-ssrf-subresource.test.ts` (the proxy-config temp file now uses `mkdtemp` at 0700 + a 0600 write), and `js/unused-local-variable` ×4 in `scripts/lib/private-addresses.mjs` (the hextet destructure now takes only the hextets it uses).
18
+ - **Hand-rolled SQL quoting, in eight places, is now one helper.** Every DataFusion string literal in the knowledge store was built by a local `.replace(/'/g, "''")` on attacker-influenced input (stored URLs, workspace paths, ingestion types). `src/knowledge/sql-utils.ts` `sqlString()` is now the single escaping rule, used at all nine sites (`store.ts`, `store-operations.ts`), with tests pinning the doubled-quote rule and the absence of any backslash/backtick/newline rule. `test/unit/knowledge/sql-utils.test.ts`.
19
+ - **The guarded `read` had a check-then-use TOCTOU.** `assertReadAllowed` resolves symlinks, then `readFile(p)` runs a moment later: a local attacker with write access to the project can swap `p` for a symlink in between. The read now opens with `O_NOFOLLOW` (a final-component symlink is refused at open with `ELOOP`), stats the fd (only regular files are read), and reads through the fd, so the bytes come from the file the fd points at. The residual gap — an *intermediate* path component swapped for a directory symlink — cannot be closed with Node's public API (no `openat` walk); it requires a local attacker with write access to the project and no read access elsewhere, and is rated Low and documented in `SECURITY.md`. Test: the final-component-symlink backstop in `test/unit/tools/read-guard.test.ts`.
20
+
21
+ ### Fixed
22
+
23
+ - **The `retry-utils` jitter comment was wrong.** It said "±50% jitter"; the code applies `0–50%` positive jitter. The comment now says so.
24
+ - **CI scripts no longer build shell strings — and now resolve npm as the CLI bundled in the Node distribution.** `scripts/ensure-native-deps.cjs` (two sites) and `scripts/use-npm12.cjs` interpolated `spec` / the npm prefix into `execSync` / `execFileSync` shell strings; both now use argv arrays, so a value read from an installed `package.json` or a `RUNNER_TEMP` path with spaces is never parsed by a shell. The argv arrays exposed a Windows-only failure the shell strings had masked: a bare `npm` in a shell-less spawn is unresolvable on Windows (the npm on PATH is a `.cmd` shim, so `ENOENT`; direct `.cmd` spawns are rejected outright with `EINVAL` since the CVE-2024-27980 hardening in Node 18.20.2 / 20.12.2 / 21.7.3, so `npm.cmd` is not a fix; `shell: true` would re-parse the arguments the hardening removed). `scripts/lib/npm-cmd.cjs` resolves the npm CLI bundled inside the Node distribution (`<node-dir>/node_modules/npm/bin/npm-cli.js` — the nodejs.org/CI layout — or `<node-dir>/../lib/node_modules/npm/bin/npm-cli.js` — the nvm/Homebrew layout) and runs it directly with the Node binary: no PATH lookup, no shim, no shell, arguments stay a clean argv array. `scripts/use-npm12.cjs` (the "Use npm 12" step of every CI leg — the step that was dying with `spawnSync npm ENOENT` on both windows-latest legs) and `scripts/ensure-native-deps.cjs` use it. Test: `test/unit/scripts/npm-cmd.test.ts`.
25
+ - **`madge` is a devDependency, not an `npx --yes` fetch.** The `dep-graph` CI job ran `npx --yes madge@8.0.0` with `contents: write` permissions and `persist-credentials: false`; the unlocked transitive tree of an `npx` fetch is the one uncontrolled install in that job. `deps:generate` now runs the pinned devDependency.
26
+
27
+ ### Changed
28
+
29
+ - **`@typescript-eslint` recommended ruleset enabled.** The ESLint config applied `@typescript-eslint/no-unused-vars` only; the full recommended ruleset (23 rules) now runs over `src/`. The three `ban-ts-comment` findings it surfaced were dead `@ts-ignore` suppressions (the suppressed lines are error-free, which is why `@ts-ignore` and not `@ts-expect-error` was used) — removed, leaving the explanatory text as plain comments. `no-explicit-any` is set to **warn**, not off: 333 sites across 70 files, each a boundary type (camoufox/Playwright JSON, LLM responses) needing a deliberate shape decision. It is a tracked warning surfaced by every lint run, not a silenced rule; the full `any → unknown + narrowing` pass is its own project and must not ride on a security release.
30
+ - **`youtubei.js` 18.2.0 → 18.3.0** (lock refresh; the range was already `^18.0.0`), **`webgpu` 0.6.0 → 0.6.2** (the `^0.6.0` range resolved forward on the refresh), and the local `node_modules` was re-synced to the lock (`impit` was at 0.14.6 against 0.14.7 in `package.json` and the lock).
31
+
32
+ ### Documentation
33
+
34
+ - **Four env vars were read by the code but undocumented in `.env.example` and `docs/CONFIGURATION.md`:** `PI_RESEARCH_PROXY_JSON` (SOCKS proxy config file path), `DDG_SOCKS_PORT` and `DDG_PIN_IPS` (the local SOCKS proxy's port and pinned DuckDuckGo front-doors, read by `scripts/ddg-socks-proxy.mjs`), and `PI_CODING_AGENT_DIR` (the pi agent directory the standalone engine/launcher reads host config from).
35
+ - **`docs/THIRD-PARTY-NOTICES.md` corrected in two places.** (a) The notice said "no third-party code is inlined"; the browser worker bundle (`dist/thread-worker.mjs` and its shipped copy) inlines `typebox` (MIT) — that is now documented. (b) The `ua-parser-js` section claimed the `overrides` pin keeps "this MIT-licensed package free of AGPL-licensed code in its dependency tree"; an npm `overrides` field only applies to the package that carries it, so a consumer's install resolves camoufox's `^2.0.2` declaration itself and typically installs the 2.x (AGPL) copy. The notice now states that the pin protects this repo's own tree only, that no AGPL code is bundled into or redistributed by this package, and why the pin is behavior-neutral.
36
+
8
37
  ## [1.7.22] - 2026-10-25
9
38
 
10
39
  ### Fixed
@@ -179,6 +179,10 @@ Diagnostics & platform
179
179
  | `PLAYWRIGHT_INSTALL_DEPS` | _(unset)_ | Linux only. Set `true` during `npm install` to also install system libraries via `npx playwright install-deps` (same as `npm run install:system-deps`). |
180
180
  | `PI_RESEARCH_STRICT_SETUP` | _(unset)_ | Read by the bundled `scripts/setup.cjs` during `npm install`. Set `1`/`true` to make a failed browser download fail the install instead of deferring it to first use. |
181
181
  | `PI_RESEARCH_CONFIG_DIR_NAME` | `.pi` | Override the host config-directory name under your home dir (advanced; e.g. set to share another harness's config root). |
182
+ | `PI_RESEARCH_PROXY_JSON` | `~/.pi/research/proxy.json` | Path of the SOCKS proxy config file the browser workers read (`{"host":"127.0.0.1","port":1080}`), routing every browser request through the local SOCKS proxy. Read fresh per scrape, so toggling needs no restart. See [Troubleshooting](TROUBLESHOOTING.md). |
183
+ | `DDG_SOCKS_PORT` | `1080` | Port the local SOCKS proxy (`scripts/ddg-socks-proxy.mjs`, run under cron) listens on. Read by the proxy script, not the main runtime. |
184
+ | `DDG_PIN_IPS` | `52.250.42.157,40.89.244.232` | Pinned DuckDuckGo front-door IPs for the local SOCKS proxy (comma-separated). The proxy rotates past any address that stalls, so the list self-heals; change it only for a different egress path. |
185
+ | `PI_CODING_AGENT_DIR` | `~/.pi/agent` | Override the pi agent directory the standalone engine/launcher looks in for host config (settings.json, models.json). |
182
186
 
183
187
  Testing only — never enable in production
184
188
 
@@ -5,10 +5,12 @@ license covers this project's own source code only.
5
5
 
6
6
  This package depends on third-party software distributed under its own license
7
7
  terms. Dependencies are resolved and installed by npm at install time (by
8
- reference); they are **not** bundled into this package's published artifacts, with the one exception
9
- below (the esbuild-bundled entry points — `dist/cli.mjs`, `dist/thread-worker.mjs` — are
10
- built with `--packages=external`, and the remaining `dist/` files are copied
11
- first-party sources, so no third-party code is inlined).
8
+ reference); they are **not** bundled into this package's published artifacts, with the
9
+ two exceptions below: `@lancedb/lancedb` is redistributed in the tarball, and the
10
+ esbuild-bundled browser worker `dist/thread-worker.mjs` (and its copy shipped at
11
+ `src/infrastructure/browser/thread-worker.mjs`) inlines exactly one third-party
12
+ package, `typebox` (MIT — see below). `dist/cli.mjs` inlines no third-party code,
13
+ and the remaining `dist/` files are copied first-party sources.
12
14
 
13
15
  ### Bundled third-party code: `@lancedb/lancedb`
14
16
 
@@ -24,6 +26,17 @@ resolve its pinned `@huggingface/transformers` 3.0.2 and `sharp` 0.33.5 (see `do
24
26
  license file in the bundle. The per-platform LanceDB native bindings are NOT bundled; npm installs
25
27
  them separately.
26
28
 
29
+ ### Inlined third-party code: `typebox`
30
+
31
+ The browser worker bundle (`dist/thread-worker.mjs`, and the copy of it shipped at
32
+ `src/infrastructure/browser/thread-worker.mjs`) inlines exactly one third-party
33
+ package: `typebox`, **MIT**, Copyright the TypeBox authors (https://github.com/sinclairtypebox/typebox).
34
+ The worker is a poolifier cluster child: a plain Node process that gets no help from
35
+ pi's extension loader (which aliases the peer `typebox` for in-process code only),
36
+ and `pi install` never installs peers — so `typebox` is bundled into the worker
37
+ rather than resolved at runtime. (`dist/cli.mjs` inlines nothing; only the worker
38
+ bundle does.)
39
+
27
40
  ### Notable dependency licensing
28
41
 
29
42
  camoufox / Camoufox browser
@@ -40,16 +53,19 @@ own license.
40
53
 
41
54
  ua-parser-js
42
55
 
43
- `ua-parser-js` 2.x is licensed under AGPL-3.0-or-later. To keep this MIT-licensed
44
- package free of AGPL-licensed code in its dependency tree, `package.json`
45
- `overrides` pins `ua-parser-js` to the `1.x` line, which is MIT-licensed. The
46
- 1.x and 2.x APIs are compatible for the only surface our direct dependency
47
- (`camoufox`, which declares `^2.0.2`) uses — it calls just
56
+ `ua-parser-js` 2.x is licensed under AGPL-3.0-or-later. `package.json`
57
+ `overrides` pins `ua-parser-js` to the `1.x` line (MIT) **in this package's own
58
+ install tree** — i.e. this repository and its CI. The pin does NOT reach
59
+ consumers: an npm `overrides` field only applies to the package that carries it,
60
+ and the published tarball ships no lockfile, so a consumer's install resolves
61
+ camoufox's declared `ua-parser-js ^2.0.2` itself and typically installs the 2.x
62
+ (AGPL) copy alongside it. That is a property of the consumer's dependency tree,
63
+ not of this package's artifacts: camoufox calls only
48
64
  `new UAParser(ua).getBrowser().name` and `.getOS().name`, both present in 1.x and
49
- verified against the pinned `1.0.41` — and the pin is behavior-neutral for this
50
- package's usage (no custom `navigator.userAgent`/`fingerprint` is passed to Camoufox).
51
- Re-check that surface on every `camoufox` bump: a 2.x-only call would make
52
- this override a runtime break, not just a licensing choice.
65
+ 2.x, so the pin is behavior-neutral here, and no AGPL code is bundled into, or
66
+ redistributed by, this package. Re-check that call surface on every `camoufox`
67
+ bump: a 2.x-only call would make the pin a runtime break, not just a licensing
68
+ choice.
53
69
 
54
70
  youtubei.js / bgutils-js / jsdom (YouTube transcripts)
55
71
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincoln504/pi-research",
3
- "version": "1.7.22",
3
+ "version": "1.7.23",
4
4
  "description": "Web research for your agents with smart and safe tooling + knowledge store",
5
5
  "type": "module",
6
6
  "private": false,
@@ -112,7 +112,7 @@
112
112
  "install:system-deps": "node scripts/setup.cjs --system-deps",
113
113
  "//deps:check": "dependency-cruiser 18.5 refuses Node 25 (supports ^22 || ^24 || >=26) while engines allows >=22.22.2: run this script under Node 22 or 24 (see .nvmrc).",
114
114
  "deps:check": "depcruise --config config/tooling/dependency-cruiser.cjs --output-type err-long src",
115
- "deps:generate": "npx --yes madge@8.0.0 --image docs/deps.svg src/index.ts",
115
+ "deps:generate": "madge --image docs/deps.svg src/index.ts",
116
116
  "verify:changelog": "node scripts/verify-changelog.cjs",
117
117
  "lock:restore-stubs": "node scripts/restore-lock-stubs.cjs",
118
118
  "analyze:dependencies": "ncu",
@@ -139,8 +139,8 @@
139
139
  "pdf-oxide-wasm": "^0.3.77",
140
140
  "playwright-core": "1.62.1",
141
141
  "poolifier": "^6.0.1",
142
- "undici": "^8.11.2",
143
- "youtubei.js": "^18.0.0"
142
+ "undici": "^8.12.2",
143
+ "youtubei.js": "^18.3.0"
144
144
  },
145
145
  "bundleDependencies": [
146
146
  "@lancedb/lancedb",
@@ -149,14 +149,14 @@
149
149
  ],
150
150
  "optionalDependencies": {
151
151
  "@huggingface/transformers": "4.3.1",
152
- "webgpu": "^0.6.0",
153
152
  "@lancedb/lancedb-darwin-arm64": "0.40.0",
154
- "@lancedb/lancedb-linux-x64-gnu": "0.40.0",
155
153
  "@lancedb/lancedb-linux-arm64-gnu": "0.40.0",
156
- "@lancedb/lancedb-linux-x64-musl": "0.40.0",
157
154
  "@lancedb/lancedb-linux-arm64-musl": "0.40.0",
155
+ "@lancedb/lancedb-linux-x64-gnu": "0.40.0",
156
+ "@lancedb/lancedb-linux-x64-musl": "0.40.0",
157
+ "@lancedb/lancedb-win32-arm64-msvc": "0.40.0",
158
158
  "@lancedb/lancedb-win32-x64-msvc": "0.40.0",
159
- "@lancedb/lancedb-win32-arm64-msvc": "0.40.0"
159
+ "webgpu": "^0.6.0"
160
160
  },
161
161
  "peerDependencies": {
162
162
  "@earendil-works/pi-ai": ">=0.99.0 <2",
@@ -172,7 +172,7 @@
172
172
  "vite": "^8.3.1",
173
173
  "adm-zip": "^0.6.1",
174
174
  "jsdom": {
175
- "undici": "^8.10.2"
175
+ "undici": "^8.12.2"
176
176
  },
177
177
  "sharp": "^0.35.0",
178
178
  "@lancedb/lancedb": {
@@ -191,6 +191,7 @@
191
191
  "dependency-cruiser": "^18.5.0",
192
192
  "depngn": "^0.6.0",
193
193
  "eslint": "10.13.0",
194
+ "madge": "^8.0.0",
194
195
  "npm-check-updates": "^23.1.0",
195
196
  "typebox": "1.3.27",
196
197
  "typescript": ">=6.0.3 <6.1.0",
@@ -29,6 +29,7 @@
29
29
 
30
30
  import net from 'node:net';
31
31
  import dns from 'node:dns';
32
+ import { pipeline } from 'node:stream';
32
33
  import { isBlockedDestination, isBlockedProxyTarget } from './lib/private-addresses.mjs';
33
34
 
34
35
  const PORT = Number(process.env.DDG_SOCKS_PORT || 1080);
@@ -77,9 +78,15 @@ const DATA_DEADLINE_MS = 8000;
77
78
  * so the NEXT connection starts at the next front-door. The caller passes the
78
79
  * client socket precisely so it can be cut on that path.
79
80
  */
80
- function connectWithFallback(client, addrs, port, cb) {
81
+ function connectWithFallback(client, host, addrs, port, cb) {
81
82
  let settled = false;
82
83
  let attempts = 0;
84
+ // Only DuckDuckGo front-doors rotate: for any other destination the address
85
+ // list comes from DNS and a "starting index" has no meaning, so a refused
86
+ // connection to an arbitrary host must not shift the pin order.
87
+ const rotate = (usedIdx) => {
88
+ if (isDdgHost(host)) pinIndex = (usedIdx + 1) % addrs.length;
89
+ };
83
90
  const tryNext = () => {
84
91
  if (settled) return;
85
92
  if (attempts >= addrs.length) {
@@ -96,7 +103,7 @@ function connectWithFallback(client, addrs, port, cb) {
96
103
  // Fast-fail both ends and rotate the starting pin for next time.
97
104
  sock.destroy();
98
105
  client.destroy();
99
- pinIndex = (usedIdx + 1) % addrs.length;
106
+ rotate(usedIdx);
100
107
  console.error(`[ddg-socks] ${addr} connected but sent no data within ${DATA_DEADLINE_MS}ms — client cut, rotating pin`);
101
108
  return;
102
109
  }
@@ -126,7 +133,7 @@ function connectWithFallback(client, addrs, port, cb) {
126
133
  if (!settled) {
127
134
  // Connection refusal / reset — this address is dead from this egress
128
135
  // too; rotate past it for the next connection, same as a stall.
129
- pinIndex = (usedIdx + 1) % addrs.length;
136
+ rotate(usedIdx);
130
137
  tryNext();
131
138
  }
132
139
  });
@@ -141,7 +148,13 @@ const server = net.createServer((client) => {
141
148
  let targetHost = '';
142
149
  let targetPort = 0;
143
150
 
144
- client.on('data', (chunk) => {
151
+ const onData = (chunk) => {
152
+ // Cap the handshake buffer: a well-formed SOCKS request is under 300
153
+ // bytes. Anything larger is not a handshake and must not accumulate.
154
+ if (buf.length + chunk.length > 4096) {
155
+ client.destroy();
156
+ return;
157
+ }
145
158
  buf = Buffer.concat([buf, chunk]);
146
159
  try {
147
160
  if (stage === 'greet') {
@@ -193,13 +206,19 @@ const server = net.createServer((client) => {
193
206
  }
194
207
  if (stage === 'connect') {
195
208
  stage = 'done';
209
+ // Handshake complete: the tunnel below owns the stream from here on.
210
+ // Detach this listener, or `buf` would grow without bound for the
211
+ // lifetime of every long-lived proxied connection.
212
+ client.removeListener('data', onData);
196
213
  // SSRF backstop for proxied traffic. The browser cannot check this itself through
197
214
  // a SOCKS5 proxy (Firefox reports 0.0.0.0 as the origin address — see
198
215
  // src/infrastructure/browser/proxy-prefs.ts), so the proxy is the last place that
199
216
  // can refuse to reach internal infrastructure. A hostile page that gets the
200
217
  // browser to request http://169.254.169.254/ or http://127.0.0.1:8443/ lands here.
201
218
  if (isBlockedProxyTarget(targetHost)) {
202
- console.error(`[ddg-socks] refused private/reserved destination ${targetHost}:${targetPort}`);
219
+ // JSON.stringify: targetHost is raw domain bytes from a SOCKS
220
+ // client and may carry newlines (log injection).
221
+ console.error(`[ddg-socks] refused private/reserved destination ${JSON.stringify(targetHost)}:${targetPort}`);
203
222
  client.write(Buffer.from([0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // not allowed by ruleset
204
223
  client.destroy();
205
224
  return;
@@ -210,7 +229,7 @@ const server = net.createServer((client) => {
210
229
  // The DDG pins are public by construction, so they pass this check too — no
211
230
  // hostname-based bypass, because a bypass is what an attacker would aim for.
212
231
  if (isBlockedDestination(addr)) {
213
- console.error(`[ddg-socks] refused ${targetHost} — resolves to private/reserved ${addr}`);
232
+ console.error(`[ddg-socks] refused ${JSON.stringify(targetHost)} — resolves to private/reserved ${addr}`);
214
233
  return false;
215
234
  }
216
235
  return true;
@@ -220,7 +239,7 @@ const server = net.createServer((client) => {
220
239
  client.destroy();
221
240
  return;
222
241
  }
223
- return connectWithFallback(client, allowed, targetPort, (err, upstream) => {
242
+ return connectWithFallback(client, targetHost, allowed, targetPort, (err, upstream) => {
224
243
  if (err) {
225
244
  client.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); // host unreachable
226
245
  client.destroy();
@@ -233,8 +252,11 @@ const server = net.createServer((client) => {
233
252
  // waiting for this reply, as most do) had those bytes buffered in
234
253
  // `buf` — forward them before attaching pipe, or they are lost.
235
254
  if (buf.length) upstream.write(buf);
236
- client.pipe(upstream);
237
- upstream.pipe(client);
255
+ // pipeline() (not pipe) destroys BOTH ends when either one ends:
256
+ // a client RST used to leave the upstream socket open (fd leak).
257
+ pipeline([client, upstream], (err) => {
258
+ if (err) console.error(`[ddg-socks] tunnel closed: ${err.message}`);
259
+ });
238
260
  });
239
261
  }).catch(() => {
240
262
  client.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
@@ -244,7 +266,8 @@ const server = net.createServer((client) => {
244
266
  } catch {
245
267
  client.destroy();
246
268
  }
247
- });
269
+ };
270
+ client.on('data', onData);
248
271
  });
249
272
 
250
273
  server.on('error', (err) => {
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Resolve npm for a shell-less (argv array) spawn, on every platform.
6
+ *
7
+ * Why this exists: a bare `npm` in an argv-array spawn is unresolvable on
8
+ * Windows. The npm on PATH there is a `.cmd` shim, and Node's shell-less spawn
9
+ * resolves only exact file names — `npm` is `ENOENT`. `npm.cmd` is not a fix
10
+ * either: since the CVE-2024-27980 hardening (Node 18.20.2 / 20.12.2 / 21.7.3,
11
+ * i.e. every Node 20/22/24), spawning a `.cmd` file directly is rejected
12
+ * outright with `EINVAL`. `shell: true` would work, but it reintroduces
13
+ * exactly the argument parsing the argv-array hardening removed — the
14
+ * arguments include paths read from disk (a `RUNNER_TEMP` prefix, a spec read
15
+ * from an installed `package.json`) that must never be parsed by a shell.
16
+ *
17
+ * So: run the npm CLI that ships INSIDE the Node distribution, directly with
18
+ * the Node binary. The absolute path needs no PATH lookup, no shim resolution
19
+ * and no shell, and the arguments stay a clean argv array.
20
+ *
21
+ * Known layouts of the bundled npm CLI (checked in order):
22
+ * <node-dir>/node_modules/npm/bin/npm-cli.js
23
+ * nodejs.org zip/MSI installs and the actions/node-versions builds CI
24
+ * downloads (the CI "Use npm 12" step runs under exactly this layout)
25
+ * <node-dir>/../lib/node_modules/npm/bin/npm-cli.js
26
+ * nvm and Homebrew installs
27
+ *
28
+ * Usage:
29
+ * const { command, args } = npmInvocation();
30
+ * execFileSync(command, [...args, 'install', '-g', 'npm@12', '--prefix', prefix],
31
+ * { stdio: 'inherit' });
32
+ *
33
+ * `execPath` is injectable so tests can pin a layout without a Windows host.
34
+ */
35
+
36
+ const fs = require('node:fs');
37
+ const path = require('node:path');
38
+
39
+ /**
40
+ * Candidate locations of the bundled npm CLI for a node binary at `execPath`,
41
+ * platform-correct one first. Pure path math (no fs), so tests can pin the
42
+ * layout per platform.
43
+ */
44
+ function npmCliCandidates(execPath, platform = process.platform) {
45
+ const p = platform === 'win32' ? path.win32 : path;
46
+ const nodeDir = p.dirname(execPath);
47
+ return [
48
+ p.join(nodeDir, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
49
+ p.join(nodeDir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
50
+ ];
51
+ }
52
+
53
+ /**
54
+ * @param {string} [execPath] the Node binary (default: process.execPath).
55
+ * @returns {{ command: string, args: string[] }} the argv prefix that runs
56
+ * npm without a shell. Primary: the bundled npm CLI run by the Node binary.
57
+ * Fallback (no bundled CLI found — a non-standard Node build): the bare `npm`
58
+ * name, which is correct on POSIX.
59
+ */
60
+ function npmInvocation(execPath = process.execPath) {
61
+ const cli = npmCliCandidates(execPath).find((f) => fs.existsSync(f));
62
+ if (cli) return { command: execPath, args: [cli] };
63
+ return { command: 'npm', args: [] };
64
+ }
65
+
66
+ module.exports = { npmCliCandidates, npmInvocation };
@@ -75,7 +75,7 @@ function ipv6Hextets(address) {
75
75
  function isBlockedIpv6(address) {
76
76
  const hextets = ipv6Hextets(address);
77
77
  if (!hextets) return true; // unparseable → refuse
78
- const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets;
78
+ const [h0, h1, , , , h5, h6, h7] = hextets;
79
79
 
80
80
  // :: and ::1
81
81
  if (hextets.every((h) => h === 0)) return true;
@@ -85,10 +85,24 @@ function isBlockedIpv6(address) {
85
85
  const v4 = `${h6 >> 8}.${h6 & 0xff}.${h7 >> 8}.${h7 & 0xff}`;
86
86
  return isBlockedIpv4(v4);
87
87
  }
88
- // fc00::/7 unique-local, fe80::/10 link-local, ff00::/8 multicast.
89
- if ((h0 & 0xfe00) === 0xfc00) return true;
90
- if ((h0 & 0xffc0) === 0xfe80) return true;
91
- if ((h0 & 0xff00) === 0xff00) return true;
88
+ // fc00::/7 unique-local, fe80::/10 link-local, ff00::/8 multicast, and the
89
+ // deprecated site-local fec0::/10 (RFC 3879) — private/reserved space with
90
+ // no legitimate scrape target. Range checks mirror the TS classifier's
91
+ // string-prefix checks exactly (fc/fd, fe8–feb plus fec–fef, ff).
92
+ // fec0::/10 is a subset of fe80::/10, so the /10 range covers it.
93
+ if (h0 >= 0xfc00 && h0 <= 0xfdff) return true;
94
+ if (h0 >= 0xfe80 && h0 <= 0xfeff) return true;
95
+ if (h0 >= 0xff00) return true;
96
+ // 6to4 (2002::/16), Teredo (2001::/32) and NAT64 (64:ff9b::/96) tunnel an
97
+ // IPv4 address inside the IPv6 literal, so a public-looking literal can
98
+ // carry a private/loopback IPv4 (2002:7f00:1:: → 127.0.0.x,
99
+ // 64:ff9b::a9fe:a9fe → 169.254.169.254). Block the whole ranges, mirroring
100
+ // the TS classifier (isPrivateIpv6 in src/web-research/scraper-utils.ts).
101
+ if (h0 === 0x2002) return true;
102
+ // Teredo is 2001:0::/32, NOT the whole 2001::/32: 2001:4860:4860::8888
103
+ // (public DNS) must stay allowed, so the second hextet must be zero.
104
+ if (h0 === 0x2001 && h1 === 0) return true;
105
+ if (h0 === 0x0064 && h1 === 0xff9b) return true;
92
106
  return false;
93
107
  }
94
108
 
@@ -51,10 +51,17 @@ export function getSocksProxyEndpoint(): SocksProxyEndpoint | null {
51
51
  cached = null;
52
52
  return cached;
53
53
  }
54
- const cfg = JSON.parse(readFileSync(file, 'utf8')) as { host?: string; port?: number };
55
- const host = cfg.host ?? '127.0.0.1';
56
- const port = cfg.port ?? 1080;
57
- cached = host ? { host, port } : null;
54
+ const cfg = JSON.parse(readFileSync(file, 'utf8')) as { host?: unknown; port?: unknown };
55
+ // Type-check the values: a hand-edited file with a numeric host or an
56
+ // out-of-range port must mean "no proxy", not a browser launched with a
57
+ // nonsense endpoint.
58
+ const host = cfg.host === undefined ? '127.0.0.1' : typeof cfg.host === 'string' ? cfg.host.trim() : '';
59
+ const port = cfg.port === undefined ? 1080 : Number.isInteger(cfg.port) ? (cfg.port as number) : -1;
60
+ if (host === '' || port < 1 || port > 65535) {
61
+ cached = null;
62
+ return cached;
63
+ }
64
+ cached = { host, port };
58
65
  return cached;
59
66
  } catch {
60
67
  cached = null;
@@ -103,11 +110,15 @@ export function resetSocksProxyCache(): void {
103
110
  * The check is deliberately gated on a configured proxy: with no proxy, Firefox
104
111
  * reports the true remote address, and an unspecified address there is anomalous
105
112
  * enough to keep blocking.
113
+ *
114
+ * Only the unspecified addresses are exempt, never the proxy host itself:
115
+ * with the proxy on 127.0.0.1 (the normal configuration), an origin address of
116
+ * 127.0.0.1 is indistinguishable from a genuine loopback origin, and the
117
+ * conservative call is to poison the scrape. Measured with camoufox 0.5.8 the
118
+ * hop reports 0.0.0.0, which is covered above.
106
119
  */
107
120
  export function isProxyHopAddress(ip: string, proxy: SocksProxyEndpoint | null = getSocksProxyEndpoint()): boolean {
108
121
  if (!proxy) return false;
109
122
  const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, '');
110
- if (addr === '' || addr === '0.0.0.0' || addr === '::' || addr === '::0') return true;
111
- const proxyHost = proxy.host.trim().toLowerCase().replace(/^\[|\]$/g, '');
112
- return addr === proxyHost;
123
+ return addr === '' || addr === '0.0.0.0' || addr === '::' || addr === '::0';
113
124
  }
@@ -267,7 +267,7 @@ export async function setupMocking(context: any): Promise<void> {
267
267
  async function extractSearchResults(page: any): Promise<any[]> {
268
268
  return await page.evaluate(() => {
269
269
  const found: any[] = [];
270
- // @ts-ignore - document is available in browser context
270
+ // document is available in browser context (callback runs in the page)
271
271
  // eslint-disable-next-line no-undef
272
272
  const links = Array.from(document.querySelectorAll('a.result-link, a.result__a'));
273
273
  links.forEach((link: any) => {
@@ -985,7 +985,7 @@ export async function executeScrapeTask(
985
985
  try {
986
986
  await page.waitForFunction(
987
987
  () => {
988
- // @ts-ignore - document is available in browser context
988
+ // document is available in browser context (callback runs in the page)
989
989
  // eslint-disable-next-line no-undef
990
990
  const body = document.body.innerHTML;
991
991
  return !body.includes('_cf_chl_') &&
@@ -2123,9 +2123,13 @@ function getSocksProxyEndpoint() {
2123
2123
  return cached;
2124
2124
  }
2125
2125
  const cfg = JSON.parse(readFileSync(file, "utf8"));
2126
- const host = cfg.host ?? "127.0.0.1";
2127
- const port = cfg.port ?? 1080;
2128
- cached = host ? { host, port } : null;
2126
+ const host = cfg.host === void 0 ? "127.0.0.1" : typeof cfg.host === "string" ? cfg.host.trim() : "";
2127
+ const port = cfg.port === void 0 ? 1080 : Number.isInteger(cfg.port) ? cfg.port : -1;
2128
+ if (host === "" || port < 1 || port > 65535) {
2129
+ cached = null;
2130
+ return cached;
2131
+ }
2132
+ cached = { host, port };
2129
2133
  return cached;
2130
2134
  } catch {
2131
2135
  cached = null;
@@ -2147,9 +2151,7 @@ function loadSocksProxyPrefs() {
2147
2151
  function isProxyHopAddress(ip, proxy = getSocksProxyEndpoint()) {
2148
2152
  if (!proxy) return false;
2149
2153
  const addr = ip.trim().toLowerCase().replace(/^\[|\]$/g, "");
2150
- if (addr === "" || addr === "0.0.0.0" || addr === "::" || addr === "::0") return true;
2151
- const proxyHost = proxy.host.trim().toLowerCase().replace(/^\[|\]$/g, "");
2152
- return addr === proxyHost;
2154
+ return addr === "" || addr === "0.0.0.0" || addr === "::" || addr === "::0";
2153
2155
  }
2154
2156
 
2155
2157
  // src/infrastructure/browser/thread-worker-messaging.ts
@@ -269,7 +269,7 @@ export async function initializeDawnWebGPU(): Promise<boolean> {
269
269
  // reason; the adapter probe below is the other native entry point and was
270
270
  // missing it, which is why a plain `knowledge` run still printed them.
271
271
  const adapter = await logger.runCapturingStderr(async () => {
272
- // @ts-ignore — optional dependency
272
+ // webgpu is an optional dependency (types resolve because it is installed for dev)
273
273
  const { create, globals } = await import('webgpu');
274
274
  Object.assign(globalThis, globals);
275
275
  // Use Object.defineProperty — Node.js defines navigator as a configurable getter
@@ -0,0 +1,15 @@
1
+ /**
2
+ * SQL string literal for the knowledge store's DataFusion queries.
3
+ *
4
+ * The store builds LanceDB/DataFusion SQL by string interpolation, and the
5
+ * interpolated values are attacker-influenced (stored URLs, workspace paths,
6
+ * ingestion types). Every interpolated string MUST go through here so the
7
+ * escaping rule is written once and cannot drift across the call sites.
8
+ *
9
+ * DataFusion's string-literal grammar escapes a single quote by doubling it
10
+ * (standard SQL `''`); that is the only escape the engine applies on read-back,
11
+ * which is why doubling is the complete rule for this dialect.
12
+ */
13
+ export function sqlString(value: string): string {
14
+ return `'${value.replace(/'/g, "''")}'`;
15
+ }
@@ -10,6 +10,7 @@
10
10
  // ./lancedb-loader.ts for why that matters.
11
11
  import type * as lancedb from '@lancedb/lancedb';
12
12
  import { logger } from '../logger.ts';
13
+ import { sqlString } from './sql-utils.ts';
13
14
  import { metrics } from '../utils/metrics.ts';
14
15
  import { StoreDocument } from '../core/interfaces/knowledge-interfaces.ts';
15
16
 
@@ -376,9 +377,9 @@ export async function findDocumentsByUrl(
376
377
  const startTime = Date.now();
377
378
 
378
379
  // Escape single quotes in URL to prevent SQL injection
379
- const escapedUrl = url.replace(/'/g, "''");
380
+ const escapedUrl = sqlString(url);
380
381
 
381
- let filter = `url = '${escapedUrl}'`;
382
+ let filter = `url = ${escapedUrl}`;
382
383
  if (scopeFilter) {
383
384
  filter = `(${filter}) AND (${scopeFilter})`;
384
385
  }
@@ -9,6 +9,7 @@
9
9
  // hoisted into the CLI bundle and loaded at startup. See ./lancedb-loader.ts.
10
10
  import type * as lancedb from '@lancedb/lancedb';
11
11
  import { getLancedb } from './lancedb-loader.ts';
12
+ import { sqlString } from './sql-utils.ts';
12
13
  import { CircuitBreaker } from '../utils/circuit-breaker.ts';
13
14
  import { logger } from '../logger.ts';
14
15
  import {
@@ -158,11 +159,11 @@ export class KnowledgeStore implements IKnowledgeStore {
158
159
  }
159
160
 
160
161
  private getScopeFilter(): string {
161
- const ws = this.getWorkspace().replace(/'/g, "''");
162
+ const ws = sqlString(this.getWorkspace());
162
163
 
163
164
  switch (this.options.knowledgeMode) {
164
165
  case 'project':
165
- return `workspace = '${ws}'`;
166
+ return `workspace = ${ws}`;
166
167
  case 'global':
167
168
  return 'is_global = true';
168
169
  default: // 'none'
@@ -992,8 +993,8 @@ export class KnowledgeStore implements IKnowledgeStore {
992
993
  const table = await this.getFreshTable();
993
994
  const startTime = Date.now();
994
995
  try {
995
- const escapedUrl = url.replace(/'/g, "''");
996
- await table.delete(`url = '${escapedUrl}' AND (${scopeFilter})`);
996
+ const escapedUrl = sqlString(url);
997
+ await table.delete(`url = ${escapedUrl} AND (${scopeFilter})`);
997
998
  const duration = Date.now() - startTime;
998
999
  metrics.observe('knowledge_store_delete_duration_ms', duration);
999
1000
  metrics.increment('knowledge_store_delete_total', 1, { operation: 'by_url', status: 'success' });
@@ -1048,13 +1049,13 @@ export class KnowledgeStore implements IKnowledgeStore {
1048
1049
  const table = await this.getFreshTable();
1049
1050
  const startTime = Date.now();
1050
1051
  try {
1051
- const escapedUrl = url.replace(/'/g, "''");
1052
- const escapedType = ingestionType.replace(/'/g, "''");
1052
+ const escapedUrl = sqlString(url);
1053
+ const escapedType = sqlString(ingestionType);
1053
1054
  // Integer-coerced so the predicate can never carry anything but digits.
1054
1055
  const ageClause = Number.isFinite(olderThan as number)
1055
1056
  ? ` AND timestamp < ${Math.floor(olderThan as number)}`
1056
1057
  : '';
1057
- await table.delete(`url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND (${scopeFilter})${ageClause}`);
1058
+ await table.delete(`url = ${escapedUrl} AND ingestion_type = ${escapedType} AND (${scopeFilter})${ageClause}`);
1058
1059
  const duration = Date.now() - startTime;
1059
1060
  metrics.observe('knowledge_store_delete_duration_ms', duration, { operation: 'by_url_and_type' });
1060
1061
  metrics.increment('knowledge_store_delete_total', 1, { operation: 'by_url_and_type', status: 'success' });
@@ -1096,13 +1097,13 @@ export class KnowledgeStore implements IKnowledgeStore {
1096
1097
  while (retryCount <= MAX_RETRIES) {
1097
1098
  const table = await this.getFreshTable();
1098
1099
  try {
1099
- const escapedUrl = url.replace(/'/g, "''");
1100
- const escapedType = ingestionType.replace(/'/g, "''");
1100
+ const escapedUrl = sqlString(url);
1101
+ const escapedType = sqlString(ingestionType);
1101
1102
  // valuesSql with integer-coerced literals: timestamp is an Int64 column,
1102
1103
  // and both inputs are integer-coerced so the SQL can never carry
1103
1104
  // anything but digits.
1104
1105
  await table.update({
1105
- where: `url = '${escapedUrl}' AND ingestion_type = '${escapedType}' AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
1106
+ where: `url = ${escapedUrl} AND ingestion_type = ${escapedType} AND timestamp = ${Math.floor(generationTs)} AND (${scopeFilter})`,
1106
1107
  valuesSql: { timestamp: String(Math.floor(newTs)) },
1107
1108
  });
1108
1109
  logger.log(`[store] Refreshed timestamp for unchanged ${ingestionType} chunks of ${url}`);
@@ -1202,13 +1203,13 @@ export class KnowledgeStore implements IKnowledgeStore {
1202
1203
  const scopeFilter = this.getScopeFilter();
1203
1204
 
1204
1205
  const startTime = Date.now();
1205
- const escapedUrl = url.replace(/'/g, "''");
1206
+ const escapedUrl = sqlString(url);
1206
1207
 
1207
1208
  // limit > 1 deliberately: after a failed prune two generations of this URL can
1208
1209
  // coexist, and LanceDB's fragment-scan order typically returns the OLDEST row
1209
1210
  // first — limit(1) would serve the superseded content (and feed its older
1210
1211
  // timestamp to the serve-age gate) until the next successful ingest.
1211
- const whereClause = `url = '${escapedUrl}' AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
1212
+ const whereClause = `url = ${escapedUrl} AND ingestion_type = 'synthesis-description' AND (${scopeFilter})`;
1212
1213
  let results = await table
1213
1214
  .query()
1214
1215
  .where(whereClause)
@@ -1622,10 +1623,10 @@ export class KnowledgeStore implements IKnowledgeStore {
1622
1623
  try {
1623
1624
  const table = await this.getFreshTable();
1624
1625
  const ws = normalizeWorkspacePath(workspace || this.getWorkspace());
1625
- const escaped = ws.replace(/'/g, "''");
1626
+ const escaped = sqlString(ws);
1626
1627
 
1627
1628
  const [local, global] = await Promise.all([
1628
- table.countRows(`workspace = '${escaped}'`),
1629
+ table.countRows(`workspace = ${escaped}`),
1629
1630
  table.countRows(`is_global = true`)
1630
1631
  ]);
1631
1632
 
@@ -9,16 +9,16 @@
9
9
  */
10
10
 
11
11
  import { constants } from 'node:fs';
12
- import { access, readFile, realpath } from 'node:fs/promises';
12
+ import { access, open, readFile, realpath } from 'node:fs/promises';
13
13
  import { homedir } from 'node:os';
14
14
  import { basename, dirname, relative, isAbsolute, parse, sep } from 'node:path';
15
15
  import type { ReadOperations } from '@earendil-works/pi-coding-agent';
16
16
 
17
17
  /** Path segments that are never readable, wherever they sit under the project. */
18
- const DENIED_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg', '.git', '.kube', '.docker', '.azure', '.gcloud']);
18
+ const DENIED_SEGMENTS = new Set(['.ssh', '.aws', '.gnupg', '.git', '.kube', '.docker', '.azure', '.gcloud', '.terraform']);
19
19
 
20
20
  /** Basenames (lower-cased) and patterns that carry credentials. */
21
- const DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)(\..*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
21
+ const DENIED_BASENAME = /^(\.env(\..*)?|\.envrc|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.pgpass|\.my\.cnf|\.htpasswd|\.dockercfg|\.dockerconfigjson|\.vault-token|\.bash_history|\.zsh_history|kubeconfig|terraform\.tfstate(\..*)?|(credentials|secrets?)(\.(json|ya?ml|toml|env|ini|txt|xml))?|id_(rsa|dsa|ecdsa|ed25519)([._-].*)?|.*\.(pem|p12|pfx|jks|keystore|kdbx|asc|gpg|tfvars|key)|.*[-_.](secret|secrets|credentials)\.(json|ya?ml|toml|env)|service-account.*\.json)$/;
22
22
 
23
23
  /** Env templates are meant to be shared and hold no secrets. */
24
24
  const ALLOWED_ENV_TEMPLATE = /^\.env\.(example|sample|template|dist)$/;
@@ -89,7 +89,26 @@ export function createGuardedReadOperations(cwd: string): ReadOperations {
89
89
  readFile: async (p) => {
90
90
  // Re-checked at read time: the access() check and the read are separate calls.
91
91
  await assertReadAllowed(cwd, p);
92
- return readFile(p);
92
+ // The policy check above resolves symlinks, then this open() runs a moment
93
+ // later: a local attacker with write access to the project can swap `p`
94
+ // for a symlink in between (TOCTOU). O_NOFOLLOW makes the open itself
95
+ // refuse a final-component symlink (ELOOP), and the stat on the fd
96
+ // rejects anything that is not a regular file. Reading through the fd
97
+ // (not the path) means the bytes come from the file the fd points at,
98
+ // not whatever the path resolves to at read time. The residual gap is an
99
+ // intermediate path component swapped for a directory symlink, which
100
+ // Node's public API cannot close (no openat-walk); it is documented in
101
+ // SECURITY.md.
102
+ const handle = await open(p, constants.O_RDONLY | constants.O_NOFOLLOW);
103
+ try {
104
+ const stat = await handle.stat();
105
+ if (!stat.isFile()) {
106
+ throw new ReadDeniedError('path is not a regular file');
107
+ }
108
+ return await readFile(handle);
109
+ } finally {
110
+ await handle.close();
111
+ }
93
112
  },
94
113
  };
95
114
  }
@@ -337,7 +337,7 @@ export async function retryWithBackoff<T>(
337
337
 
338
338
  // Calculate delay with exponential backoff and jitter
339
339
  const baseDelay = opts.initialDelay * Math.pow(2, attempt);
340
- const jitter = Math.random() * 0.5 * baseDelay; // ±50% jitter
340
+ const jitter = Math.random() * 0.5 * baseDelay; // 0–50% positive jitter
341
341
  // A caller that knows better (a provider-stated or rate-limit wait) wins over the
342
342
  // step — including over maxDelay, which bounds only the ordinary step.
343
343
  const override = opts.delayFor?.(attempt + 2, lastError);