Files
gstack/lib/redact-patterns.ts
T
Garry Tan 9cc41b7163 v1.57.6.0 fix wave: 8 community bugs (4 security guards failing open) (#1911)
* fix(ship): adversarial subagent no longer trips usage-policy denial on own security fixtures (#1899)

The Claude adversarial subagent in /review and /ship was told to "think like an
attacker" over the full diff. When the diff includes the repo's own security
regression fixtures (real attack payloads, by design), reasoning adversarially
over that material triggered Anthropic's real-time usage-policy safeguards and
the subagent call was denied — blocking the review.

Fix at the prompt's source of truth (scripts/resolvers/review.ts {{ADVERSARIAL_STEP}}):
- Authorized-defensive-testing framing: declares this is the maintainer's own repo
  and that attack-pattern strings inside test/fixture paths are the project's own
  regression corpus to analyze, not material to expand on.
- Fixture summary-mode diff: full content for non-fixture source, --stat/--name-status
  for test/fixture files, so raw exploit bytes aren't fed into adversarial reasoning.
  The subagent must state fixtures were reviewed in summary mode (no silent coverage cut).

Reported by @bmajewski. Regenerated review/SKILL.md + ship/sections/adversarial.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(redact): detect modern sk-proj-/sk-svcacct-/sk-admin- OpenAI keys (#1868)

openai.key (HIGH/block) used /\b(sk-(?:proj-)?[A-Za-z0-9]{32,})\b/, which stops
at the first - or _ in the body. Modern OpenAI project/service-account/admin keys
use base64url bodies containing - and _, so they never reached the 32-char run and
produced ZERO findings — a HIGH credential failing open through /spec, /ship, /cso,
and /document-*.

Replace with explicit alternation, bare vs prefixed (not a globally-optional prefix,
which would match malformed sk--... or separator-less sk-projabc...):
  sk-{proj,svcacct,admin}- + [A-Za-z0-9_-]{20,}  |  sk-[A-Za-z0-9]{32,} (legacy)

Tests: the three previously-missed shapes now block; FP guards pin that hyphenated
prose and malformed sk- strings do NOT match (HIGH tier blocks, so calibration matters).

Reported by @jbetala7.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(redact): reject malformed --max-bytes instead of silently disabling the size guard (#1824)

The oversize check is designed to fail CLOSED, but a malformed --max-bytes turned
it fail-OPEN. bin/gstack-redact did parseInt(maxBytes,10) and passed it straight
through; parseInt("foo") is NaN. The engine guarded with `opts.maxBytes ?? DEFAULT`,
and ?? does not catch NaN, so `byteLen > NaN` was always false and the fail-closed
block never fired. A negative value made `byteLen > -5` always true, blocking
everything.

Two layers:
- bin/gstack-redact validates the RAW string (parseInt accepts "123abc"->123,
  "1.5"->1): require /^\d+$/ and > 0, else exit 1 with a clear message.
- lib/redact-engine.ts hardens the fallback to Number.isFinite && > 0 else the
  default cap — a guardrail so the engine never silently runs uncapped even if a
  bad value reaches it directly.

Tests: NaN and negative both fall back to the default cap (oversize still blocks);
CLI rejects garbage/negative with exit 1.

Reported by @jbetala7.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(learnings): cross-project trust gate is an allowlist, not a denylist (#1745)

gstack-learnings-search --cross-project is documented as an allowlist — foreign
learnings load only when user-stated/trusted, to stop one project's AI-generated
learnings from injecting into another project's reviews. It was implemented as a
denylist: `if (isCrossProject && e.trusted === false) continue`. Any row where
`trusted` is missing/undefined (legacy rows from before the field existed,
hand-edited rows, rows from other tools) passed `undefined === false` → false →
admitted. Those rows leaked across projects.

Flip to `e.trusted !== true`. Test: a foreign row with no `trusted` field is now
excluded (true still included, false still excluded).

Reported by @jbetala7.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(safety): one-way-door classifier catches "rotate ... password" (#1839)

scripts/one-way-doors.ts is the secondary safety net for ad-hoc AskUserQuestion
ids with no registry entry; a false negative auto-approves a destructive op. The
revoke and reset credential patterns both include `password`, but the rotate
pattern omitted it, so the most common phrasing ("rotate the database password")
classified as a reversible two-way question.

Add `password` to the rotate alternation so all three verbs are parallel. New test
covers rotate+password, the revoke/reset/rotate parallel, and rotate's other nouns.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(review): route .mjs/.cjs/.mts/.cts changes to the backend reviewer (#1810)

gstack-diff-scope backend detection matched only *.ts|*.js. Modern Node ships
backend code as ESM (.mjs) / CommonJS (.cjs) and explicit-module TS (.mts/.cts);
none matched any category, so a PR touching only those files reported no backend
scope and the Review Army skipped the backend reviewer.

Add the four module extensions to the backend case. Test covers all four.

Reported by @jbetala7.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(brain-cache): loadMeta tolerates malformed _meta.json without crashing (#1879)

loadMeta returned the parsed JSON verbatim. A valid JSON file that lacked the
last_refresh map made three consumers (isStale, cmdInvalidate, refreshEntity)
throw a TypeError dereferencing meta.last_refresh — the sibling last_attempt was
already guarded, last_refresh wasn't.

Fix in loadMeta:
- Shape-guard: JSON.parse can return null/array/string/number; non-object → fresh meta.
- Normalize ONLY the dereferenced maps (last_refresh, last_attempt).
- Deliberately do NOT default schema_version/endpoint_hash. Leaving them absent
  makes schemaVersionMismatch()/endpointSwitched() force a rebuild (missing
  identity = mismatch = safe); defaulting them would suppress cache invalidation
  and trust a stale file of unknown provenance.

Tests: missing last_refresh no longer throws; null/array/primitive treated as cold;
missing schema_version forces rebuild instead of a trusted warm hit.

Reported by @jbetala7.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(skills): anchor guard/freeze/careful hook paths so they survive CC 2.1.162 (#1871)

The PreToolUse frontmatter hooks for guard, freeze, and careful invoked
`bash ${CLAUDE_SKILL_DIR}/.../check-*.sh`. Claude Code 2.1.162 no longer populates
${CLAUDE_SKILL_DIR} in the skill-hook execution env, so it expanded to empty and
every Edit/Write/Bash ran `bash /...` and errored — breaking the safety skills
entirely.

Frontmatter hooks run before any skill-body bash, so no runtime-resolved variable
can fix this; the command must be a path that's valid at hook time. Anchor to the
installed checkout: $HOME/.claude/skills/gstack/{careful,freeze}/bin/check-*.sh,
where the scripts actually live. ($HOME is expanded by the hook shell.)

Reported by @omariani-howdy. Regenerated the three SKILL.md from templates.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: v1.58.0.0 — fix-wave release notes, VERSION bump, #1882 TODO

CHANGELOG entry for the 8-fix safety wave (#1899, #1868, #1824, #1745, #1839,
#1810, #1879, #1871). VERSION + package.json to 1.58.0.0 (MINOR — coordinated
multi-file safety fixes on top of main's 1.57.3.0). #1882 filed as the top
TODOS.md item (scoped out of this wave per decision; host-config change touching
all 52 skills, distinct from the #1871 hook fix).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(learnings): strip backticks from #1745 comment inside the bun -e block

The #1745 trust-gate fix added an explanatory comment containing backticks
(`=== false`) and the JS block is a double-quoted `bun -e "..."` bash string, so
bash command-substituted the backtick contents on every cross-project search —
polluting stderr with "command not found" and leaving a latent shell-injection /
source-corruption surface in a security gate. Caught by the wave's own adversarial
review (#1899 framing working as intended). Reworded the comments to avoid backticks
and dollar-paren entirely; the gate logic is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(golden): refresh ship golden baselines (#1899 prompt + main's PR-title line)

The three ship golden fixtures were stale: main's v1.57.3.0 added the always-loaded
PR-title invariant to ship/SKILL.md but did not regenerate the goldens (the golden
regression test fails on main too), and the codex golden still carried an unresolved
${ctx.paths.binDir} token. Regenerated from the current generated ship skills, which
also picks up this wave's #1899 adversarial-prompt framing (inlined for codex/factory).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 06:39:38 -07:00

475 lines
16 KiB
TypeScript

/**
* redact-patterns — the canonical redaction taxonomy.
*
* Single source of truth shared by `lib/redact-engine.ts`, `bin/gstack-redact`,
* `bin/gstack-redact-prepush`, and (via `scripts/resolvers/redact-doc.ts`) the
* generated SKILL.md docs for /spec, /ship, /cso, /document-release, and
* /document-generate.
*
* Design notes (locked in /plan-eng-review + two Codex passes):
*
* - Three tiers. HIGH = genuinely-secret credentials (block). MEDIUM = PII,
* legal/damaging, internal-leak, plus credential-shaped patterns that have
* high false-positive rates (confirm via AskUserQuestion). LOW = surface only.
* - NO wholesale MEDIUM->HIGH promotion on public repos (TENSION-2-followup).
* Public repos get sterner per-finding confirmation, not auto-block. The
* engine never mutates a finding's tier based on visibility.
* - Tier-1 calibration: a gate that cries wolf gets ignored. Stripe
* publishable keys, Google AIza keys, JWTs, and env-style KV are MEDIUM, not
* HIGH (they are context-variable / high-FP). Only genuinely-secret
* credentials block.
* - ReDoS safety: every pattern here MUST be linear-time (no nested unbounded
* quantifiers). `test/redact-pattern-lint.test.ts` fails CI on a catastrophic
* form. The engine also enforces a hard input-size cap that fails CLOSED.
* - Placeholder suppression is per-matched-span, not per-line.
*
* Pattern matching contract: every `regex` is used with the global+multiline
* flags the engine applies (`g`, `m`). Capture group 1, when present, is the
* "secret span" the engine masks and (for proximity rules) anchors on; when
* absent, match[0] is the span.
*/
export type Tier = "HIGH" | "MEDIUM" | "LOW";
export type Category =
| "secret"
| "pii"
| "legal"
| "internal"
| "hygiene";
export interface RedactPattern {
/** Stable dotted id, e.g. "aws.access_key". Used in findings + tests. */
id: string;
tier: Tier;
category: Category;
/** Human-readable one-liner for the findings table + docs. */
description: string;
/**
* The detection regex. Linter-enforced linear-time. The engine adds the
* `gm` flags; do not bake `g`/`m` into the source here (keeps `.source`
* clean for the docs table and avoids double-global bugs).
*/
regex: RegExp;
/**
* Patterns whose redaction is unambiguous enough to offer one-keystroke
* auto-redact at MEDIUM tier (email / phone / ssn / cc). The engine wires
* the `<REDACTED-*>` replacement token from `redactToken`.
*/
autoRedactable?: boolean;
/** Replacement token for auto-redact, e.g. "<REDACTED-EMAIL>". */
redactToken?: string;
/**
* Extra validators run AFTER the regex matches, ALL must pass for the match
* to count. Used for Luhn (credit cards), entropy (env-KV), checksum
* (crypto wallets), RFC1918-exclusion (public IPs), etc. Receives the
* matched secret span (group 1 or match[0]) and the full match array.
*/
validate?: (span: string, match: RegExpExecArray) => boolean;
/**
* Proximity requirement: the pattern only counts if `nearRegex` also matches
* within `nearWindow` chars of the match. Used for AWS secret keys (need
* `aws_secret_access_key` nearby) and Twilio auth tokens (need an SID nearby).
*/
nearRegex?: RegExp;
nearWindow?: number;
}
// ── Validators ──────────────────────────────────────────────────────────────
/** Luhn checksum — credit-card validity. Strips spaces/dashes first. */
export function luhnValid(span: string): boolean {
const digits = span.replace(/[ \-]/g, "");
if (!/^\d{13,19}$/.test(digits)) return false;
let sum = 0;
let alt = false;
for (let i = digits.length - 1; i >= 0; i--) {
let d = digits.charCodeAt(i) - 48;
if (alt) {
d *= 2;
if (d > 9) d -= 9;
}
sum += d;
alt = !alt;
}
return sum % 10 === 0;
}
/** Shannon entropy in bits/char. Used to gate env-style KV (skip placeholders). */
export function shannonEntropy(s: string): number {
if (!s.length) return 0;
const freq: Record<string, number> = {};
for (const ch of s) freq[ch] = (freq[ch] || 0) + 1;
let h = 0;
for (const ch in freq) {
const p = freq[ch] / s.length;
h -= p * Math.log2(p);
}
return h;
}
/** True when an IPv4 string is a public address (not RFC1918/loopback/etc). */
export function isPublicIPv4(ip: string): boolean {
const m = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (!m) return false;
const o = m.slice(1, 5).map(Number);
if (o.some((n) => n > 255)) return false;
const [a, b] = o;
if (a === 10) return false; // 10.0.0.0/8
if (a === 127) return false; // loopback
if (a === 0) return false; // this-network
if (a === 192 && b === 168) return false; // 192.168.0.0/16
if (a === 169 && b === 254) return false; // link-local
if (a === 172 && b >= 16 && b <= 31) return false; // 172.16.0.0/12
if (a === 100 && b >= 64 && b <= 127) return false; // CGNAT 100.64.0.0/10
if (a >= 224) return false; // multicast / reserved
return true;
}
// EIP-55 checksum is out of scope (heavy); we require a length+charset match and
// reject all-same-char vanity strings to cut the worst FPs.
function looksLikeWallet(span: string): boolean {
if (/^0x[a-fA-F0-9]{40}$/.test(span)) {
// reject 0x000...0 / 0xfff...f style
const body = span.slice(2).toLowerCase();
return !/^(.)\1{39}$/.test(body);
}
// bech32 / base58 — length sanity only
return span.length >= 26 && span.length <= 62;
}
// ── Placeholder suppression (per-matched-span, NOT per-line) ─────────────────
/**
* A finding is suppressed only if the MATCHED SPAN itself is a placeholder
* form — not merely co-located on a line with the word EXAMPLE. This is the
* tightened rule from the Codex review (line-based suppression was dangerous).
*/
// Structural placeholder forms — apply to ANY span (including URLs).
const PLACEHOLDER_STRUCTURAL = [
/^your[_-]/i,
/^<[^>]*>$/, // <REDACTED-FOO>, <your-key>
/^\*+$/, // all-asterisks mask
/^x{6,}$/i, // xxxxxx mask
];
// Substring placeholder words (example/test/dummy/...). These are NOT applied to
// compound spans containing `://` or `@`, because a legit URL/host can contain
// "example" (e.g. db.example.com) without being a placeholder secret. AWS docs
// keys like AKIAIOSFODNN7EXAMPLE are bare tokens, so the guard still catches them.
const PLACEHOLDER_SUBSTRING = [
/example/i, // AKIAIOSFODNN7EXAMPLE etc — AWS docs convention
/^changeme$/i,
/^redacted/i,
/^placeholder/i,
/^dummy/i,
/^fake/i,
/test[_-]?(key|token|secret)/i,
];
export function isPlaceholderSpan(span: string): boolean {
if (PLACEHOLDER_STRUCTURAL.some((re) => re.test(span))) return true;
const isCompound = span.includes("://") || span.includes("@");
if (!isCompound && PLACEHOLDER_SUBSTRING.some((re) => re.test(span))) return true;
return false;
}
// ── The taxonomy ─────────────────────────────────────────────────────────────
export const PATTERNS: RedactPattern[] = [
// ===== HIGH — genuinely-secret credentials (block) =====
{
id: "aws.access_key",
tier: "HIGH",
category: "secret",
description: "AWS access key ID (AKIA…)",
regex: /\b(AKIA[0-9A-Z]{16})\b/,
},
{
id: "aws.secret_key",
tier: "HIGH",
category: "secret",
description: "AWS secret access key (with aws_secret_access_key nearby)",
regex: /\b([A-Za-z0-9/+=]{40})\b/,
nearRegex: /aws.{0,3}secret.{0,3}access.{0,3}key/i,
nearWindow: 100,
},
{
id: "github.pat",
tier: "HIGH",
category: "secret",
description: "GitHub personal access token (classic)",
regex: /\b(ghp_[A-Za-z0-9]{36})\b/,
},
{
id: "github.oauth",
tier: "HIGH",
category: "secret",
description: "GitHub OAuth token",
regex: /\b(gho_[A-Za-z0-9]{36})\b/,
},
{
id: "github.server",
tier: "HIGH",
category: "secret",
description: "GitHub server-to-server token",
regex: /\b(ghs_[A-Za-z0-9]{36})\b/,
},
{
id: "github.fine_grained",
tier: "HIGH",
category: "secret",
description: "GitHub fine-grained PAT",
regex: /\b(github_pat_[A-Za-z0-9_]{82})\b/,
},
{
id: "anthropic.key",
tier: "HIGH",
category: "secret",
description: "Anthropic API key",
regex: /\b(sk-ant-[A-Za-z0-9_\-]{20,})\b/,
},
{
id: "openai.key",
tier: "HIGH",
category: "secret",
description: "OpenAI API key (incl. sk-proj-/sk-svcacct-/sk-admin-)",
// Two explicit shapes (NOT a globally-optional prefix, which would match
// malformed sk--... or separator-less sk-projabc...):
// prefixed: sk-{proj,svcacct,admin}- + base64url-ish body (allows -_)
// bare: sk- + contiguous alphanumeric run (legacy), keeps {32,} floor
regex:
/\b(sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{32,})\b/,
},
{
id: "sendgrid.key",
tier: "HIGH",
category: "secret",
description: "SendGrid API key",
regex: /\b(SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43})\b/,
},
{
id: "stripe.secret",
tier: "HIGH",
category: "secret",
description: "Stripe live SECRET key",
regex: /\b(sk_live_[A-Za-z0-9]{24,})\b/,
},
{
id: "slack.token",
tier: "HIGH",
category: "secret",
description: "Slack token (bot/user/app)",
regex: /\b(xox[baprs]-[A-Za-z0-9-]{10,})\b/,
},
{
id: "slack.webhook",
tier: "HIGH",
category: "secret",
description: "Slack incoming webhook URL",
regex: /(https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{24})/,
},
{
id: "discord.webhook",
tier: "HIGH",
category: "secret",
description: "Discord webhook URL",
regex: /(https:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/[0-9]{17,20}\/[A-Za-z0-9_\-]{60,})/,
},
{
id: "twilio.auth_token",
tier: "HIGH",
category: "secret",
description: "Twilio auth token (32 hex, with an Account SID nearby)",
regex: /\b([a-f0-9]{32})\b/,
nearRegex: /\bAC[a-f0-9]{32}\b/,
nearWindow: 200,
},
{
id: "pem.private_key",
tier: "HIGH",
category: "secret",
description: "PEM private key block",
regex: /(-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----)/,
},
{
id: "db.url_with_password",
tier: "HIGH",
category: "secret",
description: "Database URL with embedded password",
regex: /\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^:\s/@]+:[^@\s/]+@[^\s/]+)/,
// Skip when the password segment is itself a placeholder.
validate: (span) => {
const m = span.match(/:\/\/[^:]+:([^@]+)@/);
const pw = m?.[1] ?? "";
return !isPlaceholderSpan(pw) && pw !== "" && !/^\$\{?[A-Z_]+\}?$/.test(pw);
},
},
{
id: "creds.basic_auth_url",
tier: "HIGH",
category: "secret",
description: "HTTP(S) URL with embedded basic-auth credentials",
regex: /(https?:\/\/[^:\s/@]+:[^@\s/]+@[^\s/]+)/,
validate: (span) => {
const m = span.match(/:\/\/[^:]+:([^@]+)@/);
const pw = m?.[1] ?? "";
return !isPlaceholderSpan(pw) && pw !== "" && !/^\$\{?[A-Z_]+\}?$/.test(pw);
},
},
// ===== MEDIUM — demoted credential-shaped (high-FP / context-variable) =====
{
id: "stripe.publishable",
tier: "MEDIUM",
category: "secret",
description: "Stripe live publishable key (often intentionally public)",
regex: /\b(pk_live_[A-Za-z0-9]{24,})\b/,
},
{
id: "google.api_key",
tier: "MEDIUM",
category: "secret",
description: "Google API key (AIza…; sometimes a public client key)",
regex: /\b(AIza[0-9A-Za-z\-_]{35})\b/,
},
{
id: "jwt",
tier: "MEDIUM",
category: "secret",
description: "JSON Web Token (3-segment base64url)",
regex: /\b(eyJ[A-Za-z0-9_\-]{8,}\.eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,})\b/,
},
{
id: "env.kv",
tier: "MEDIUM",
category: "secret",
description: "Env-style SECRET assignment with high-entropy value",
regex: /^[ \t]*(?:export[ \t]+)?[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|DSN|AUTH|COOKIE|SESSION|PRIVATE)[ \t]*=[ \t]*['"]?([^\s'"]{8,})['"]?/,
// Only fire on high-entropy values — kills `FOO_KEY=changeme` FPs.
validate: (span) =>
!isPlaceholderSpan(span) &&
!/^\$\{?[A-Za-z_]/.test(span) &&
shannonEntropy(span) >= 3.0,
},
// ===== MEDIUM — PII (auto-redactable subset) =====
{
id: "pii.email",
tier: "MEDIUM",
category: "pii",
description: "Email address",
regex: /\b([A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,})\b/,
autoRedactable: true,
redactToken: "<REDACTED-EMAIL>",
// Engine layers the email allowlist (example.com, noreply@, user's own,
// repo-public authors) on top of this — see redact-engine.ts.
},
{
id: "pii.phone.e164",
tier: "MEDIUM",
category: "pii",
description: "Phone number (E.164 / common national formats; US/EU-biased)",
regex: /(?<![\w.])(\+?[1-9]\d{0,2}[ \-.]?\(?\d{2,4}\)?[ \-.]?\d{3,4}[ \-.]?\d{3,4})(?![\w.])/,
autoRedactable: true,
redactToken: "<REDACTED-PHONE>",
validate: (span) => span.replace(/\D/g, "").length >= 10,
},
{
id: "pii.ssn",
tier: "MEDIUM",
category: "pii",
description: "US Social Security Number",
regex: /\b(\d{3}-\d{2}-\d{4})\b/,
autoRedactable: true,
redactToken: "<REDACTED-SSN>",
// Reject the all-zero-octet placeholders SSNs never use.
validate: (span) => {
const [a, b, c] = span.split("-");
return a !== "000" && b !== "00" && c !== "0000" && a !== "666" && a[0] !== "9";
},
},
{
id: "pii.cc",
tier: "MEDIUM",
category: "pii",
description: "Credit-card number (Luhn-valid)",
regex: /\b((?:\d[ \-]?){13,19})\b/,
autoRedactable: true,
redactToken: "<REDACTED-CC>",
validate: (span) => luhnValid(span),
},
{
id: "pii.ip_public",
tier: "MEDIUM",
category: "pii",
description: "Public IPv4 address",
regex: /\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/,
validate: (span) => isPublicIPv4(span),
},
{
id: "pii.wallet",
tier: "MEDIUM",
category: "pii",
description: "Crypto wallet address (ETH/BTC)",
regex: /\b(0x[a-fA-F0-9]{40}|bc1[a-z0-9]{25,39}|[13][a-km-zA-HJ-NP-Z1-9]{25,34})\b/,
validate: (span) => looksLikeWallet(span),
},
// ===== MEDIUM — internal-leak =====
{
id: "internal.hostname",
tier: "MEDIUM",
category: "internal",
description: "Internal hostname (*.internal/.corp/.local/.prod/.staging)",
regex: /\b([a-z0-9][a-z0-9\-]*\.(?:internal|corp|local|lan|prod|staging))\b/i,
},
{
id: "internal.url_private",
tier: "MEDIUM",
category: "internal",
description: "localhost URL with a non-trivial path",
regex: /(https?:\/\/(?:localhost|127\.0\.0\.1):\d{2,5}\/[^\s)]+)/,
},
// ===== MEDIUM — legal / damaging =====
{
id: "legal.nda_marker",
tier: "MEDIUM",
category: "legal",
description: "Confidentiality / NDA marker",
regex: /\b(CONFIDENTIAL|UNDER NDA|ATTORNEY[- ]CLIENT|PRIVILEGED|DO NOT DISTRIBUTE|EYES ONLY)\b/,
},
{
id: "legal.named_criticism",
tier: "MEDIUM",
category: "legal",
description: "Negative judgment near a capitalized full name (semantic pass is primary)",
regex: /\b(incompetent|negligent|fraudulent|fraud|fired|terminated|harassed|underperforming)\b/i,
// Require a Capitalized Two-Word name within the window.
nearRegex: /\b[A-Z][a-z]+ [A-Z][a-z]+\b/,
nearWindow: 80,
},
// ===== LOW — surface only =====
{
id: "internal.user_path",
tier: "LOW",
category: "internal",
description: "Absolute path under a user home dir",
regex: /(\/(?:Users|home)\/[a-z][a-z0-9_\-]+\/[^\s)]*)/,
},
{
id: "hygiene.todo",
tier: "LOW",
category: "hygiene",
description: "TODO(owner) marker carried into the artifact",
regex: /\b(TODO\([^)]+\))/,
},
];
/** Lookup by id. */
export const PATTERNS_BY_ID: Record<string, RedactPattern> = Object.fromEntries(
PATTERNS.map((p) => [p.id, p]),
);