neurastream 0.2.27 β†’ 0.2.28

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/README.md CHANGED
@@ -195,6 +195,38 @@ Guard rules around it:
195
195
 
196
196
  "Needs you" pings use the same channels so the owner learns on the phone that a decision is his: when a Main turn ends with an open plan whose `WAITING on owner:` line was not pinged before, neurastream posts `πŸ”” Needs you β€” <plan>: <question>` (with the `neurastream ui` phone-page link when `ui.enabled: true`), and when the guard refuses a Main tool call because it touches a protected guard file, it posts `πŸ”“ Main needs an unlock to continue (<file>)` β€” the unlock ping at most once per 30 minutes, each waiting question once until its line changes or disappears, remembered in `<queue_state>/notify-waiting.json`. Every decision logs one `notify: needs-you posted|skipped (<why>)` guard-log line.
197
197
 
198
+ ## Secrets never reach the chat
199
+
200
+ A value the machine holds is hidden before the model, the chat and the session log see it (`src/core/secret-redact.ts`, plan 20261025_2204, incident I-20261025-197). Detection is by **content**, not by file name β€” the old name list never knew about `~/.npmrc`.
201
+
202
+ - Every tool result of Main and of every subagent goes through the redactor at the omp `tool_result` hook (redact first, then the plan/guard logic works on markers). A hit becomes `[REDACTED:<type>]` and the result gains one line `secret-redact: hid N value(s) (<types>)`. The key name stays: `password = [REDACTED:generic-secret]`.
203
+ - Shapes: npm, GitHub, GitLab, OpenAI/Anthropic/OpenRouter (`sk-…`), the AWS key id and the value after `aws_secret_access_key`, Google, Slack, Discord webhooks, Stripe, JWTs, PEM private keys, URL credentials, `_authToken`/`_password`, and `(password|passwd|secret|token|api_key|access_key|client_secret) = …` with a value of 8 or more characters.
204
+ - Exact values are hidden wherever they appear, whatever the file is called: env vars whose name looks like a credential, `~/.npmrc`, every file in `secrets.known_value_files`, every top-level dotenv file under `paths.work_roots`, and the notify webhook files. File contents are cached per process and re-read when a file's mtime or size changes.
205
+ - `neurastream redact < file` prints the redacted text on stdout and the hit summary on stderr, so another harness hook can pipe a tool result through the same rules. Notify posts (`notify test`, Main's final reply) are scrubbed before they leave.
206
+ - `neurastream doctor` reports `secrets: redactor on, N known value(s), secretgate installed|missing, proxy none|secretgate` β€” a count only, never a value.
207
+
208
+ Config (`docs/config.md`, `templates/config.yml`):
209
+
210
+ ```yaml
211
+ secrets:
212
+ redact: true
213
+ known_value_files: ["~/.npmrc"]
214
+ extra_patterns: [] # your own shapes: [{type: "my-token", regex: "myapp_[A-Za-z0-9]{32}"}]
215
+ proxy: "none" # or "secretgate"
216
+ ```
217
+
218
+ ### secretgate as a second net
219
+
220
+ The redactor keeps a secret out of the chat screen and the local session log; it cannot stop a value that reaches the harness another way. [secretgate](https://github.com/secretgate/secretgate) (Apache-2.0) is a local proxy that cleans what leaves the machine, so the two together cover both ends:
221
+
222
+ ```bash
223
+ pipx install secretgate # the binary must be on PATH
224
+ secretgate ca init # create its CA; the command prints the CA path
225
+ # trust that CA for this machine (firefox/chrome/system store, whichever you use)
226
+ ```
227
+
228
+ Then set `secrets.proxy: secretgate` and restart Main: `neurastream main` starts omp as `secretgate wrap -- omp`. When the binary is missing, omp starts normally and one warning says the second net is off β€” the owner is never blocked by it.
229
+
198
230
  ## Provider rate limits
199
231
 
200
232
  When a Main turn ends on a provider rate limit, neurastream waits it out instead of asking again straight into the limit. The stop guard sees the turn's error text, matches it against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive) and, on a hit, allows the stop without consulting the normal stop rules or touching the idle-stop counters. The chat channels get one post per episode β€” `⏳ Main is rate limited by its provider until HH:MM (local); it resumes on its own.` β€” and exactly one resume timer is armed (replacing any earlier one). When the wait is over, the plugin gives Main a new turn: `main-guard: the provider rate limit is over (waited until HH:MM). Continue the queue where you stopped.`, and the guard log carries the whole story:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.27",
3
+ "version": "0.2.28",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -12,6 +12,7 @@ import { fileURLToPath } from "node:url";
12
12
  import { blockState, renderBlock } from "../../core/agents-md.ts";
13
13
  import { loadConfig } from "../../core/config.ts";
14
14
  import { notifyFindings } from "../../core/notify.ts";
15
+ import { loadKnownSecrets, proxyOnPath } from "../../core/secret-redact.ts";
15
16
  import { readIndex } from "../../core/queue/lib.ts";
16
17
  import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
17
18
 
@@ -217,6 +218,15 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
217
218
  const notify = notifyFindings(cfg);
218
219
  problems.push(...notify.problems);
219
220
  warnings.push(...notify.warnings);
221
+ // Secrets (plan 20261025_2204): the redactor's state and the second net, count only β€” doctor
222
+ // never prints a value. A missing proxy binary is a warning, never a problem: the launch path
223
+ // falls back to a plain harness start.
224
+ const known = loadKnownSecrets(cfg).length;
225
+ const proxy = proxyOnPath();
226
+ ok.push(`secrets: redactor ${cfg.secrets.redact ? "on" : "off"}, ${known} known value(s), secretgate ${proxy ? "installed" : "missing"}, proxy ${cfg.secrets.proxy}`);
227
+ if (cfg.secrets.proxy === "secretgate" && !proxy) {
228
+ warnings.push("secrets.proxy is secretgate but secretgate is not on PATH; the harness starts without the proxy (README: Secrets)");
229
+ }
220
230
  const viewed = npmViewVersion(name, env);
221
231
  let registry: string | null = null;
222
232
  if ("warning" in viewed) warnings.push(viewed.warning);
@@ -26,6 +26,7 @@ import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/
26
26
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
27
27
  import { rateLimitWait } from "../../core/rate-limit.ts";
28
28
  import { notifyProviders, postReply } from "../../core/notify.ts";
29
+ import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
29
30
  import { inboxPath } from "../../core/owner-ui.ts";
30
31
  import { realTailscale } from "../../core/tailscale.ts";
31
32
  import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
@@ -267,6 +268,28 @@ function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string
267
268
  }
268
269
  }
269
270
 
271
+ // Secrets never reach the model, the chat or the session log (plan 20261025_2204): every tool
272
+ // result of every agent β€” Main and subs both fire tool_result β€” is redacted here before the rest of
273
+ // the handler, the model, the chat and the session file see it. The rewritten content goes back
274
+ // with one line naming what was hidden; a clean result keeps its original shape and returns nothing.
275
+ function redactToolResult(content: unknown[], cfg: Config): { content: unknown[]; note: string } {
276
+ if (!cfg.secrets.redact || content.length === 0) return { content, note: "" };
277
+ const known = loadKnownSecrets(cfg);
278
+ const hits = new Map<string, number>();
279
+ let changed = false;
280
+ const out = content.map(part => {
281
+ const p = asRecord(part);
282
+ if (p.type !== "text" || typeof p.text !== "string" || p.text === "") return part;
283
+ const r = redactSecrets(p.text, known, cfg.secrets.extra_patterns);
284
+ if (r.hits.length === 0) return part;
285
+ changed = true;
286
+ for (const hit of r.hits) hits.set(hit.type, (hits.get(hit.type) ?? 0) + hit.count);
287
+ return { ...p, text: r.text };
288
+ });
289
+ if (!changed) return { content, note: "" };
290
+ return { content: out, note: redactSummary([...hits].map(([type, count]) => ({ type, count }))) };
291
+ }
292
+
270
293
  // Session rollover helpers: the harness context read through runtime checks, and the file size and
271
294
  // mtime reads. The decisions are in src/core/rollover.ts.
272
295
  const WAIT_NOTICE_MS = 15 * 60_000;
@@ -750,7 +773,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
750
773
  const c = asCtx(ctx);
751
774
  const id = asString(e.toolCallId);
752
775
  const snap = pending.get(id);
753
- const notes: string[] = [];
776
+ // Redact first: everything below (plan checks, detectors, the returned content, the model,
777
+ // the chat and the session log) then works on text that holds markers, never values.
778
+ const redacted = redactToolResult(Array.isArray(e.content) ? e.content : [], cfg);
779
+ const content = redacted.content;
780
+ const notes: string[] = redacted.note ? [redacted.note] : [];
754
781
  if (snap) {
755
782
  pending.delete(id);
756
783
  for (const [file, before] of snap) {
@@ -779,7 +806,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
779
806
  if (PUSH_MERGE.test(asString(asRecord(e.input).command))) autoClose(cfg);
780
807
  }
781
808
  if ((!c.hasAgent || c.kind === "main") && !e.isError) {
782
- const content = Array.isArray(e.content) ? e.content : [];
783
809
  const text = content.map(p => asString(asRecord(p).text)).join("\n");
784
810
  recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
785
811
  }
@@ -788,12 +814,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
788
814
  }
789
815
  // Real-time detectors after each Main bash result, crashes included (D2 wants the stack).
790
816
  if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash") {
791
- const content = Array.isArray(e.content) ? e.content : [];
792
817
  mainDetectors(cfg, {
793
818
  bash: { command: asString(asRecord(e.input).command), output: content.map(p => asString(asRecord(p).text)).join("\n") },
794
819
  });
795
820
  }
796
- if (notes.length) return { content: [...(Array.isArray(e.content) ? e.content : []), ...notes.map(text => ({ type: "text", text }))] };
821
+ if (notes.length) return { content: [...content, ...notes.map(text => ({ type: "text", text }))] };
797
822
  return undefined;
798
823
  });
799
824
 
@@ -11,6 +11,7 @@ import { mainStartText } from "../../core/main-start.ts";
11
11
  import { applyQueueEnv } from "../../core/queue/env.ts";
12
12
  import * as q from "../../core/queue/lib.ts";
13
13
  import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath } from "../../core/rollover.ts";
14
+ import { PROXY_BIN, proxyOnPath } from "../../core/secret-redact.ts";
14
15
  import { adapterLog } from "./index.ts";
15
16
  import { PACKAGE_ROOT, packageJsonPath, packageVersion } from "./package-root.ts";
16
17
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
@@ -18,6 +19,32 @@ import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
18
19
  /** The harness the launcher runs. Tests pass another path through LaunchOptions. */
19
20
  export const OMP_BIN = "omp";
20
21
 
22
+ export interface ProxyPlan {
23
+ /** The command to spawn. */
24
+ cmd: string;
25
+ /** Arguments that come before the harness's own: `wrap -- <harness>` when proxied. */
26
+ prefix: string[];
27
+ /** One stderr line when the proxy was asked for but cannot run; empty otherwise. */
28
+ warning: string;
29
+ }
30
+
31
+ /**
32
+ * `secretgate wrap -- <harness>` when `secrets.proxy: secretgate`, so everything the harness sends
33
+ * leaves through the proxy's own redaction net. A missing binary never blocks the owner: the
34
+ * harness starts normally and one warning says why the second net is off.
35
+ */
36
+ export function proxyPlan(harness: string, cfg: Config, onPath: boolean = proxyOnPath()): ProxyPlan {
37
+ if (cfg.secrets.proxy !== "secretgate") return { cmd: harness, prefix: [], warning: "" };
38
+ if (!onPath) {
39
+ return {
40
+ cmd: harness,
41
+ prefix: [],
42
+ warning: `neurastream: secrets.proxy is secretgate but ${PROXY_BIN} is not on PATH; starting ${harness} without the proxy`,
43
+ };
44
+ }
45
+ return { cmd: PROXY_BIN, prefix: ["wrap", "--", harness], warning: "" };
46
+ }
47
+
21
48
  /** Flags that take the next argument as their value (omp 18.11.1 --help shows them as `--flag=<value>`). */
22
49
  export const VALUE_FLAGS: Record<string, true> = {
23
50
  "--model": true, "--smol": true, "--slow": true, "--plan": true, "--goal": true, "--prewalk-into": true,
@@ -105,6 +132,8 @@ interface RelaunchRequest {
105
132
  export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchOptions = {}): Promise<number> {
106
133
  applyQueueEnv(cfg);
107
134
  const harness = opts.harness ?? OMP_BIN;
135
+ const proxy = proxyPlan(harness, cfg);
136
+ if (proxy.warning) console.error(proxy.warning);
108
137
  const mainStart = opts.mainStart ?? mainStartText;
109
138
  const carried = carriedArgs(args);
110
139
  const loaded = packageVersion(packageJsonPath());
@@ -141,7 +170,7 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
141
170
  }
142
171
  for (;;) {
143
172
  const started = Date.now();
144
- const code = await runChild(harness, runArgs, { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
173
+ const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
145
174
  const req = readRequest(started, cfg);
146
175
  if (req === null) return code;
147
176
  const installed = packageVersion(packageJsonPath());
@@ -1,6 +1,8 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { pagesDoctor } from "../core/pages-doctor.ts";
2
3
  import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
3
4
  import { postReply } from "../core/notify.ts";
5
+ import { loadKnownSecrets, redactSecrets, redactSummary } from "../core/secret-redact.ts";
4
6
  import { applyQueueEnv } from "../core/queue/env.ts";
5
7
  import { runAdapterInstall } from "../adapters/omp/install.ts";
6
8
  import { runDoctor } from "../adapters/omp/doctor.ts";
@@ -57,6 +59,8 @@ export function helpText(): string {
57
59
  " config + agent-dir state); prints the list, refuses outside HOME",
58
60
  " neurastream doctor report hand-edited live files and a stale install",
59
61
  " neurastream notify test post a test message to the configured Discord/Slack webhooks",
62
+ " neurastream redact filter stdin through the secret redactor: stdout gets the text,",
63
+ " stderr the hit summary (types and counts only)",
60
64
  " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
61
65
  " neurastream config [--json] print the merged config (defaults + file + env)",
62
66
  " neurastream guard <event> --json",
@@ -122,6 +126,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
122
126
  return runDoctor();
123
127
  }
124
128
  if (cmd === "notify") return runNotify(args);
129
+ if (cmd === "redact") return runRedact(args);
125
130
  if (cmd === "uninstall") return runUninstall(args);
126
131
  if (cmd === "queue" && args[0] === "migrate") {
127
132
  try {
@@ -177,6 +182,30 @@ function runNotify(args: string[]): number | Promise<number> {
177
182
  });
178
183
  }
179
184
 
185
+ const REDACT_USAGE = "usage: neurastream redact < text (stdin to stdout; the hit summary goes to stderr)";
186
+
187
+ /** `neurastream redact`: the core the adapter and notify use, as a filter, so another harness hook
188
+ * can pipe a tool result through the same rules. The text is passed through untouched except for
189
+ * the markers; stderr gets the type names and counts, never a value. */
190
+ function runRedact(args: string[]): number {
191
+ if (args.length > 0) {
192
+ console.error(REDACT_USAGE);
193
+ return 2;
194
+ }
195
+ let cfg: Config;
196
+ try {
197
+ cfg = loadConfig();
198
+ } catch (err) {
199
+ console.error(err instanceof ConfigError ? err.message : String(err));
200
+ return 1;
201
+ }
202
+ const text = readFileSync(0, "utf8");
203
+ const result = redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns);
204
+ process.stdout.write(result.text);
205
+ console.error(result.hits.length > 0 ? redactSummary(result.hits) : "secret-redact: nothing to hide");
206
+ return 0;
207
+ }
208
+
180
209
  const AGENTS_USAGE = "usage: neurastream agents list | allow <slug>... | deny <slug>...";
181
210
 
182
211
  function runAgents(args: string[]): number {
@@ -178,6 +178,18 @@ export interface Config {
178
178
  /** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
179
179
  * The values are paths to secret files holding the webhook URLs β€” never the URLs themselves. */
180
180
  notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
181
+ /** Content redaction (src/core/secret-redact.ts, plan 20261025_2204): every tool result, every
182
+ * notify post and `neurastream redact` go through it. Detection is by content, not file name. */
183
+ secrets: {
184
+ redact: boolean;
185
+ /** Files whose `KEY=value` lines are secret values; top-level dotenv files under
186
+ * paths.work_roots are read as well. */
187
+ known_value_files: string[];
188
+ /** The owner's own shapes: `{type, regex}`; a hit prints as `[REDACTED:<type>]`. */
189
+ extra_patterns: { type: string; regex: string }[];
190
+ /** A second net on the wire: wrap the harness in `secretgate wrap --` at launch. */
191
+ proxy: "none" | "secretgate";
192
+ };
181
193
  priority: { sleep_sec: number };
182
194
  alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
183
195
  snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
@@ -512,6 +524,24 @@ function check(cfg: Config): void {
512
524
  if (!Array.isArray(edges) || edges.some((v, i) => !Number.isInteger(v) || v < 1 || (i > 0 && v <= edges[i - 1]!))) {
513
525
  throw new ConfigError("traces.briefs.char_buckets must be ascending positive integers");
514
526
  }
527
+ if (cfg.secrets.proxy !== "none" && cfg.secrets.proxy !== "secretgate") {
528
+ throw new ConfigError('secrets.proxy must be "none" or "secretgate"');
529
+ }
530
+ if (typeof cfg.secrets.redact !== "boolean") throw new ConfigError("secrets.redact must be true or false");
531
+ if (!Array.isArray(cfg.secrets.known_value_files) || cfg.secrets.known_value_files.some((p) => typeof p !== "string" || p === "")) {
532
+ throw new ConfigError("secrets.known_value_files must be a list of non-empty paths");
533
+ }
534
+ if (!Array.isArray(cfg.secrets.extra_patterns)) throw new ConfigError("secrets.extra_patterns must be a list");
535
+ for (const pattern of cfg.secrets.extra_patterns) {
536
+ if (!isObj(pattern) || typeof pattern.type !== "string" || pattern.type === "" || typeof pattern.regex !== "string" || pattern.regex === "") {
537
+ throw new ConfigError("secrets.extra_patterns entries must be {type, regex} with non-empty strings");
538
+ }
539
+ try {
540
+ new RegExp(pattern.regex);
541
+ } catch {
542
+ throw new ConfigError(`secrets.extra_patterns.${pattern.type}: not a valid regex: ${pattern.regex}`);
543
+ }
544
+ }
515
545
  for (const [key, value] of Object.entries(cfg.paths)) {
516
546
  if (key === "work_roots") {
517
547
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -6,6 +6,7 @@
6
6
  import { dirname } from "node:path";
7
7
  import { readFileSync, statSync } from "node:fs";
8
8
  import { configFile, type Config } from "./config.ts";
9
+ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
9
10
 
10
11
  export type NotifyProviderName = "discord" | "slack";
11
12
 
@@ -207,6 +208,10 @@ export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]
207
208
  const providers = notifyProviders(cfg);
208
209
  const body = cfg.notify.prefix ? `${cfg.notify.prefix} ${text}` : text;
209
210
  if (body.trim() === "") return providers.map(p => ({ provider: p.name, posted: false, chunks: 0, error: "empty reply; nothing posted" }));
211
+ // The chat is where a secret does its damage (plan 20261025_2204): a reply can carry a value
212
+ // the owner pasted or one the redactor's tool_result pass never saw, so the post is scrubbed
213
+ // here too, after the prefix and before the split.
214
+ const scrubbed = cfg.secrets.redact ? redactSecrets(body, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : body;
210
215
  const out: NotifyPostResult[] = [];
211
216
  for (const p of providers) {
212
217
  const { url, why } = webhookUrl(p);
@@ -215,7 +220,7 @@ export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]
215
220
  continue;
216
221
  }
217
222
  const limit = p.name === "discord" ? DISCORD_LIMIT : SLACK_LIMIT;
218
- out.push(await postChunks(p, url, notifyChunks(body, limit)));
223
+ out.push(await postChunks(p, url, notifyChunks(scrubbed, limit)));
219
224
  }
220
225
  return out;
221
226
  });
@@ -0,0 +1,317 @@
1
+ // Secrets never reach the model, the chat or the session log (plan 20261025_2204, incident
2
+ // I-20261025-197). Detection is by CONTENT, not by file name: gitleaks-style shapes plus the exact
3
+ // values this machine holds (env vars, ~/.npmrc, dotenv files under the work roots, notify webhook
4
+ // URLs). Every hit becomes `[REDACTED:<type>]`; the value itself never appears in the returned
5
+ // text, in the hit list or in a log line β€” the hits carry a type and a count only.
6
+ //
7
+ // Pure TypeScript, no harness and no agent: the harness adapter (tool_result), notify.ts (outbound
8
+ // posts), `neurastream redact` and doctor all call this one module.
9
+
10
+ import { readFileSync, readdirSync, statSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
13
+ import type { Config } from "./config.ts";
14
+
15
+ /** One owner-defined shape: the marker type and its regex source. */
16
+ export interface SecretPattern {
17
+ type: string;
18
+ regex: string;
19
+ }
20
+
21
+ export interface RedactHit {
22
+ type: string;
23
+ count: number;
24
+ }
25
+
26
+ export interface RedactResult {
27
+ text: string;
28
+ hits: RedactHit[];
29
+ }
30
+
31
+ interface Rule {
32
+ /** Named in `[REDACTED:<type>]` and in the hit summary. */
33
+ type: string;
34
+ regex: RegExp;
35
+ /** Leading capture groups kept verbatim (a key name, an assignment prefix) before the marker. */
36
+ keep?: number;
37
+ }
38
+
39
+ // Shape rules in application order: a structural prefix (`_authToken=`, a URL's user part) is
40
+ // recognised before the bare token shapes, and the generic assignment rule runs after both so a
41
+ // token keeps its own type name. Every regex is linear: no nested quantifier over the same text.
42
+ // The `(?!\[REDACTED:)` lookahead keeps a rule from matching a value an earlier rule already
43
+ // replaced β€” `OPENAI_API_KEY=[REDACTED:sk-key]` must not become a generic hit.
44
+ const RULES: Rule[] = [
45
+ { type: "private-key", regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g },
46
+ { type: "npmrc-auth-token", regex: /(_authToken\s*=\s*)(?!\[REDACTED:)\S+/g, keep: 1 },
47
+ { type: "npmrc-password", regex: /(_password\s*=\s*)(?!\[REDACTED:)\S+/g, keep: 1 },
48
+ { type: "url-password", regex: /\b([a-z][a-z0-9+.-]*:\/\/[^\s/@:]+:)(?!\[REDACTED:)[^\s/@]+(?=@)/gi, keep: 1 },
49
+ { type: "aws-secret-access-key", regex: /(aws_secret_access_key\s*[:=]\s*['"]?)(?!\[REDACTED:)[A-Za-z0-9/+=]{16,}/gi, keep: 1 },
50
+ { type: "aws-access-key-id", regex: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
51
+ { type: "github-token", regex: /\b(?:gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,})\b/g },
52
+ { type: "gitlab-token", regex: /\bglpat-[A-Za-z0-9_-]{16,}\b/g },
53
+ { type: "npm-token", regex: /\bnpm_[A-Za-z0-9]{36}\b/g },
54
+ { type: "sk-key", regex: /\bsk-(?:ant-|or-|proj-)?[A-Za-z0-9_-]{16,}\b/g },
55
+ { type: "google-api-key", regex: /\bAIza[0-9A-Za-z_-]{35}\b/g },
56
+ { type: "slack-token", regex: /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/g },
57
+ { type: "discord-webhook", regex: /\bhttps?:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[A-Za-z0-9_-]+/g },
58
+ { type: "stripe-key", regex: /\b[rs]k_(?:live|test)_[A-Za-z0-9]{10,}\b/g },
59
+ { type: "jwt", regex: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g },
60
+ ];
61
+
62
+ // Runs after the shapes above and after the owner's own patterns, so a specific shape names the
63
+ // value first; only what nothing else recognised becomes `generic-secret`. The key name may be
64
+ // a multi-part name (`DB_PASSWORD=`, `MY_APP_TOKEN:`): the identifier is kept whole, so the reader still
65
+ // sees which key was hidden, and only the value goes.
66
+ const GENERIC_RULE: Rule = {
67
+ type: "generic-secret",
68
+ regex: /([A-Za-z0-9_.-]*(?:password|passwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret))(\s*[:=]\s*)(['"]?)(?!\[REDACTED:)([^\s'",;]{8,})/gi,
69
+ keep: 3,
70
+ };
71
+
72
+ /** The external proxy that can sit on the wire as a second net (plan 20261025_2204, P3). */
73
+ export const PROXY_BIN = "secretgate";
74
+
75
+ /** Whether the proxy binary is on PATH. Never spawned here: launch and doctor only need to know. */
76
+ export function proxyOnPath(env: NodeJS.ProcessEnv = process.env): boolean {
77
+ for (const dir of (env.PATH ?? "").split(":")) {
78
+ if (dir === "") continue;
79
+ try {
80
+ if (statSync(join(dir, PROXY_BIN)).isFile()) return true;
81
+ } catch {}
82
+ }
83
+ return false;
84
+ }
85
+
86
+ /** A known value shorter than this is not redacted: it would shred ordinary text. */
87
+ const MIN_KNOWN_LEN = 8;
88
+
89
+ /** Env var names whose values count as secrets. */
90
+ const SECRET_ENV_NAME = /KEY|TOKEN|SECRET|PASSWORD|PASS|AUTH|CREDENTIAL|WEBHOOK/i;
91
+
92
+ /** A dotenv file at the top of a repo: `.` + `env` and anything after it (`.env`, `.env.local`). */
93
+ const DOTENV_NAME = /^\.env/;
94
+
95
+ /** Files larger than this are not scanned for values: no env file or webhook file is that big. */
96
+ const MAX_FILE_BYTES = 1024 * 1024;
97
+
98
+ function bump(counts: Map<string, number>, type: string): void {
99
+ counts.set(type, (counts.get(type) ?? 0) + 1);
100
+ }
101
+
102
+ function escapeRegExp(value: string): string {
103
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
104
+ }
105
+
106
+ const extraCache = new Map<string, RegExp>();
107
+
108
+ /** Owner-defined shapes, built once per process; a bad regex cannot reach here (config.check). */
109
+ function extraRules(extra: SecretPattern[]): Rule[] {
110
+ const out: Rule[] = [];
111
+ for (const p of extra) {
112
+ if (typeof p?.type !== "string" || p.type === "" || typeof p.regex !== "string" || p.regex === "") continue;
113
+ let re = extraCache.get(p.regex);
114
+ if (!re) {
115
+ try {
116
+ re = new RegExp(p.regex, "g");
117
+ } catch {
118
+ continue;
119
+ }
120
+ extraCache.set(p.regex, re);
121
+ }
122
+ out.push({ type: p.type, regex: re });
123
+ }
124
+ return out;
125
+ }
126
+
127
+ function applyRule(text: string, rule: Rule, counts: Map<string, number>): string {
128
+ const keep = rule.keep ?? 0;
129
+ return text.replace(rule.regex, (...args: unknown[]) => {
130
+ const prefix = args
131
+ .slice(1, 1 + keep)
132
+ .map(g => (typeof g === "string" ? g : ""))
133
+ .join("");
134
+ bump(counts, rule.type);
135
+ return `${prefix}[REDACTED:${rule.type}]`;
136
+ });
137
+ }
138
+
139
+ /** Exact values, deduped, longest first so a value that contains another is matched whole. */
140
+ function knownPattern(values: Iterable<string>): RegExp | null {
141
+ const seen = new Set<string>();
142
+ for (const value of values) {
143
+ const text = value.trim();
144
+ if (text.length >= MIN_KNOWN_LEN) seen.add(text);
145
+ }
146
+ if (seen.size === 0) return null;
147
+ const pattern = [...seen]
148
+ .sort((a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0))
149
+ .map(escapeRegExp)
150
+ .join("|");
151
+ return new RegExp(pattern, "g");
152
+ }
153
+
154
+ /**
155
+ * Replaces every secret in `text` with `[REDACTED:<type>]` and reports what it hid. `known` holds
156
+ * exact values (see `loadKnownSecrets`); `extra` holds the owner's own shapes. Running it twice on
157
+ * the same text is stable: a marker matches no rule.
158
+ */
159
+ export function redactSecrets(text: string, known: Iterable<string> = [], extra: SecretPattern[] = []): RedactResult {
160
+ if (text === "") return { text, hits: [] };
161
+ const counts = new Map<string, number>();
162
+ let out = text;
163
+ for (const rule of RULES) out = applyRule(out, rule, counts);
164
+ for (const rule of extraRules(extra)) out = applyRule(out, rule, counts);
165
+ out = applyRule(out, GENERIC_RULE, counts);
166
+ const knownRe = knownPattern(known);
167
+ if (knownRe) {
168
+ out = out.replace(knownRe, () => {
169
+ bump(counts, "known-value");
170
+ return "[REDACTED:known-value]";
171
+ });
172
+ }
173
+ return { text: out, hits: [...counts].map(([type, count]) => ({ type, count })) };
174
+ }
175
+
176
+ /** The one line the adapter adds to a tool result when it hid anything. Types only, never values. */
177
+ export function redactSummary(hits: RedactHit[]): string {
178
+ const total = hits.reduce((n, h) => n + h.count, 0);
179
+ return `secret-redact: hid ${total} value(s) (${hits.map(h => h.type).join(", ")})`;
180
+ }
181
+
182
+ // --- known values ---
183
+
184
+ interface CachedFile {
185
+ mtimeMs: number;
186
+ size: number;
187
+ values: string[];
188
+ }
189
+
190
+ type FileKind = "npmrc" | "env" | "text";
191
+
192
+ const fileCache = new Map<string, CachedFile>();
193
+ let discovered: { roots: string; atMs: number; files: string[] } | null = null;
194
+ /** The work-root dotenv list is a directory walk, not a file read: rescan at this interval. */
195
+ const DISCOVERY_TTL_MS = 60_000;
196
+ const MAX_REPO_DIRS = 500;
197
+
198
+ /** Forgets every cached file and the discovered dotenv list (tests switch sandboxes). */
199
+ export function clearKnownSecretsCache(): void {
200
+ fileCache.clear();
201
+ discovered = null;
202
+ }
203
+
204
+ /** `_authToken` and `_password` values of an npmrc. */
205
+ function npmrcValues(text: string): string[] {
206
+ const out: string[] = [];
207
+ for (const line of text.split("\n")) {
208
+ const m = /^\s*(?:\/\/[^\s=]*:)?_(?:authToken|password)\s*=\s*(\S+)/i.exec(line);
209
+ if (m?.[1]) out.push(m[1]);
210
+ }
211
+ return out;
212
+ }
213
+
214
+ /** `KEY=value` values of an env-style file (quotes stripped, comments ignored). */
215
+ function envValues(text: string): string[] {
216
+ const out: string[] = [];
217
+ for (const line of text.split("\n")) {
218
+ const m = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/.exec(line);
219
+ if (!m?.[1]) continue;
220
+ let value = m[1].trim();
221
+ if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) value = value.slice(1, -1);
222
+ const hash = value.search(/\s#/);
223
+ if (hash !== -1) value = value.slice(0, hash).trim();
224
+ if (value !== "") out.push(value);
225
+ }
226
+ return out;
227
+ }
228
+
229
+ function fileValues(path: string, kind: FileKind): string[] {
230
+ const key = `${kind}\0${path}`;
231
+ let size: number;
232
+ let mtimeMs: number;
233
+ try {
234
+ const st = statSync(path);
235
+ if (!st.isFile() || st.size > MAX_FILE_BYTES) return [];
236
+ size = st.size;
237
+ mtimeMs = st.mtimeMs;
238
+ } catch {
239
+ fileCache.delete(key);
240
+ return [];
241
+ }
242
+ const hit = fileCache.get(key);
243
+ if (hit && hit.mtimeMs === mtimeMs && hit.size === size) return hit.values;
244
+ let text: string;
245
+ try {
246
+ text = readFileSync(path, "utf8");
247
+ } catch {
248
+ return hit?.values ?? [];
249
+ }
250
+ const values = kind === "npmrc" ? npmrcValues(text) : kind === "env" ? envValues(text) : [text.trim()];
251
+ fileCache.set(key, { mtimeMs, size, values });
252
+ return values;
253
+ }
254
+
255
+ /** Dotenv files at the top of `dir` (its own, not its subdirectories'). */
256
+ function envFilesIn(dir: string): string[] {
257
+ let entries;
258
+ try {
259
+ entries = readdirSync(dir, { withFileTypes: true });
260
+ } catch {
261
+ return [];
262
+ }
263
+ return entries.filter(e => e.isFile() && DOTENV_NAME.test(e.name)).map(e => join(dir, e.name));
264
+ }
265
+
266
+ /** Every top-level dotenv file under a work root, plus each repo directory's own. */
267
+ function workRootEnvFiles(roots: string[]): string[] {
268
+ const key = roots.join("\0");
269
+ const nowMs = Date.now();
270
+ if (discovered && discovered.roots === key && nowMs - discovered.atMs < DISCOVERY_TTL_MS) return discovered.files;
271
+ const files = new Set<string>();
272
+ for (const root of roots) {
273
+ for (const file of envFilesIn(root)) files.add(file);
274
+ let repos;
275
+ try {
276
+ repos = readdirSync(root, { withFileTypes: true });
277
+ } catch {
278
+ continue;
279
+ }
280
+ let seen = 0;
281
+ for (const entry of repos) {
282
+ if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules") continue;
283
+ if (seen++ >= MAX_REPO_DIRS) break;
284
+ for (const file of envFilesIn(join(root, entry.name))) files.add(file);
285
+ }
286
+ }
287
+ const list = [...files];
288
+ discovered = { roots: key, atMs: nowMs, files: list };
289
+ return list;
290
+ }
291
+
292
+ /** The notify webhook files: the URL in one is a secret like any other (config holds only paths). */
293
+ function notifyFiles(cfg: Config): string[] {
294
+ return [cfg.notify.discord_webhook_file, cfg.notify.slack_webhook_file].filter(f => typeof f === "string" && f !== "");
295
+ }
296
+
297
+ /**
298
+ * The exact values this machine holds, so a secret is hidden wherever it appears whatever the file
299
+ * is called: env vars whose name looks like a credential, `~/.npmrc`, `secrets.known_value_files`,
300
+ * every top-level dotenv file under `paths.work_roots`, and the notify webhook files. File contents
301
+ * are cached per process and re-read when a file's mtime or size changes.
302
+ */
303
+ export function loadKnownSecrets(cfg: Config, env: NodeJS.ProcessEnv = process.env): string[] {
304
+ const out = new Set<string>();
305
+ const add = (value: string): void => {
306
+ const text = value.trim();
307
+ if (text.length >= MIN_KNOWN_LEN) out.add(text);
308
+ };
309
+ for (const [name, value] of Object.entries(env)) {
310
+ if (typeof value === "string" && SECRET_ENV_NAME.test(name)) add(value);
311
+ }
312
+ for (const value of fileValues(join(homedir(), ".npmrc"), "npmrc")) add(value);
313
+ for (const file of cfg.secrets.known_value_files) for (const value of fileValues(file, "env")) add(value);
314
+ for (const file of workRootEnvFiles(cfg.paths.work_roots)) for (const value of fileValues(file, "env")) add(value);
315
+ for (const file of notifyFiles(cfg)) for (const value of fileValues(file, "text")) add(value);
316
+ return [...out];
317
+ }
@@ -186,6 +186,12 @@ notify:
186
186
  slack_webhook_file: "" # file holding the Slack webhook URL; "" = off
187
187
  prefix: "" # optional label prepended to each posted reply, e.g. "Main:"
188
188
 
189
+ secrets: # content redaction (src/core/secret-redact.ts); a hit prints as [REDACTED:<type>]
190
+ redact: true # every tool result, every notify post and `neurastream redact` go through the redactor
191
+ known_value_files: ["~/.npmrc"] # files whose KEY=value lines are secret values; every top-level `.env…` file under paths.work_roots is read too
192
+ extra_patterns: [] # your own shapes, e.g. [{type: "my-token", regex: "myapp_[A-Za-z0-9]{32}"}]
193
+ proxy: "none" # "none" | "secretgate": launch the harness as `secretgate wrap -- omp` (README: Secrets)
194
+
189
195
  priority:
190
196
  sleep_sec: 120
191
197