Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(security): add five JS/TS patterns to the registry (#2047)
tacopiek4068ed48ede8
diff --git a/docs/README.md b/docs/README.mdindex c7c5ed1ac..6ab9cb6d8 100644--- a/docs/README.md+++ b/docs/README.md@@ -58,7 +58,7 @@ your agent in under five minutes, with no API key.| [layers/GRAPH.md](layers/GRAPH.md) | The dependency graph: what is in it, how every edge is resolved, and how much to trust each one || [layers/DECISIONS.md](layers/DECISIONS.md) | Architectural decisions mined from your repo and from your own agent sessions || [layers/DEAD_CODE.md](layers/DEAD_CODE.md) | Unreachable files, unused exports, and zombie packages by confidence tier |-| [layers/SECURITY.md](layers/SECURITY.md) | The local pattern scan: what the eleven patterns catch, what they do not, and how far to trust the result |+| [layers/SECURITY.md](layers/SECURITY.md) | The local pattern scan: what the sixteen patterns catch, what they do not, and how far to trust the result || [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 19 parsed to a full AST, 35 on the five-rung ladder || [layers/WIKI.md](layers/WIKI.md) | The generated wiki: page types, what `update` re-renders, styles, output language |diff --git a/docs/layers/SECURITY.md b/docs/layers/SECURITY.mdindex d95f9bd0a..4d1e4ee18 100644--- a/docs/layers/SECURITY.md+++ b/docs/layers/SECURITY.md@@ -4,7 +4,7 @@ Repowise records a small set of security signals while it indexes: patternmatches over source text, and symbol names that look security-relevant. Pureregex and SQL, no LLM calls, no network, no dependency resolution.-This is a floor, not a scanner. The registry holds eleven patterns. It has no+This is a floor, not a scanner. The registry holds sixteen patterns. It has nomodel of your framework, no notion of which inputs are attacker-controlled, andno dataflow: it cannot tell a parameterised query from a concatenated one beyondwhat the surrounding characters give away, and it cannot tell whether a@@ -44,7 +44,7 @@ Findings also appear on the Security tab of the code-health page, and at## What the registry catches-Eleven patterns plus a symbol-name scan, giving twelve kinds across three+Sixteen patterns plus a symbol-name scan, giving seventeen kinds across threeseverities. Severity is a fixed property of the pattern; nothing is scored,ranked, or aggregated.@@ -61,6 +61,11 @@ ranked, or aggregated.| `concat_sql` | med | `.execute("SELECT ... +` || `tls_verify_false` | med | `verify = False` || `weak_hash` | low | the words `md5` or `sha1` |+| `unsafe_inner_html` | med | `__html:` (React's `dangerouslySetInnerHTML` shape) assigned a non-literal value |+| `template_literal_sql` | med | a JS/TS template literal containing `SELECT`+`FROM` or `UPDATE`+`SET` and an interpolation |+| `public_env_secret` | high | a secret-shaped name (`API_KEY`, `SECRET`, `TOKEN`, `PASSWORD`) behind a `NEXT_PUBLIC_` or `VITE_` prefix, excluding `..._ANON_...` |+| `new_function_call` | high | `new Function(...)` |+| `reject_unauthorized_false` | med | `rejectUnauthorized: false` || `security_sensitive_symbol` | low | a symbol whose name contains `auth`, `token`, `password`, `jwt`, `session` or `crypto` |The last one is informational. It flags nothing wrong; it marks where the@@ -88,12 +93,13 @@ characters, so a closed call cannot reach forward into an unrelated one.Stated plainly, because the table above reads like more coverage than it is.-**Most languages.** The registry is shaped by Python. `pickle.loads`,-`os.system`, `subprocess(shell=True)` and `verify=False` are Python idioms;-`fstring_sql` is a Python f-string. On a JavaScript, TypeScript, Go, Rust or-Java codebase, `eval` / `exec` and the two secret patterns are most of what can-fire. A repo in one of those languages reporting few findings is reporting the-registry's shape, not its own health.+**Most languages.** The registry is shaped by Python, with five patterns added+for JavaScript and TypeScript (below). `pickle.loads`, `os.system`,+`subprocess(shell=True)` and `verify=False` are still Python-only idioms;+`fstring_sql` is a Python f-string. On a Go, Rust or Java codebase, `eval` /+`exec` and the two secret patterns are most of what can fire. A repo in one of+those languages reporting few findings is reporting the registry's shape, not+its own health.**Anything needing framework semantics.** Missing authorization on a routehandler, permissive CORS on a mutating endpoint, an unvalidated redirect, an@@ -137,6 +143,36 @@ spells out a credential assignment reports itself as a `hardcoded_secret`, and`weak_hash` fires on a comment explaining why md5 was removed. Only the`eval`/`exec` path masks comments and string literals; nothing else does.+**Five patterns for JavaScript and TypeScript, measured the same way as the+`exec_call` and secret-case fixes above** — a 17-repository, 1109-file corpus,+every hit adjudicated by hand. Three of the five needed tightening before they+were worth shipping:++| Kind | First cut | Verified real | After tightening | The noise |+|---|---|---|---|---|+| `unsafe_inner_html` | 15 | 0 | 4 | every hit a source-pinned stylesheet constant referenced by name |+| `template_literal_sql` | 10 | 2 | 2 | prose (`` `Order update failed: ${status}` ``) and a Tailwind class (`select-none`) |+| `public_env_secret` | 9 | 3 | 3 | Supabase anon keys — public by design, protected by row-level security |+| `new_function_call` | 0 | 0 | 0 | — |+| `reject_unauthorized_false` | 0 | 0 | 0 | — |++`unsafe_inner_html` ships at `med`, not `high`, because of that first row: a+name reference cannot be told apart from a pinned constant without dataflow,+so the pattern is a places-to-read signal, not a confirmed sink. The same+gap explains why the value test (`__html:` followed by an identifier, `$`, or+`(`) is written as a positive lookahead rather than a negative one excluding+quotes — tried at the position *before* the preceding `\s*`, a negative+lookahead would trivially pass and let a string literal through anyway.++`public_env_secret` excludes any name containing `ANON`, which is the one+carve-out narrow enough to state as a rule rather than a heuristic: an+`..._ANON_...` key is meant to be public. Nothing else in the corpus noise was+worth a similarly specific exclusion.++`template_literal_sql` requires the SQL verb's companion clause —+`SELECT`+`FROM`, `UPDATE`+`SET` — because the bare verb is an ordinary English+word and fires on both prose and a Tailwind utility class otherwise.+## Working tree versus historyTwo scan surfaces share the registry and the storage.diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.pyindex 2748d94ba..4b1fcfe8d 100644--- a/packages/core/src/repowise/core/analysis/security_scan.py+++ b/packages/core/src/repowise/core/analysis/security_scan.py@@ -84,6 +84,52 @@ _PATTERNS: list[tuple[re.Pattern, str, str]] = [(re.compile(r"\.execute\(\s*[\'\"]\s*SELECT.*\+"), "concat_sql", "med"),(re.compile(r"verify\s*=\s*False"), "tls_verify_false", "med"),(re.compile(r"\bmd5\b|\bsha1\b"), "weak_hash", "low"),+ # -- JS/TS patterns (#1935 Tier 1) -------------------------------------+ # Measured on the same 17-repo, 1109-file corpus as the exec_call/secret+ # fixes in #1947. Three of these five needed tightening before they were+ # shippable; see docs/layers/SECURITY.md and the PR body for the+ # first-cut vs. after-tightening counts per pattern.+ #+ # ``__html: <value>`` is the React ``dangerouslySetInnerHTML`` shape. A+ # pinned string literal there is inert; the interesting case is a value+ # that is an identifier, a member access or a call. The value test has to+ # be stated positively (an identifier/`$`/`(` lead character) rather than+ # as a negative lookahead excluding quotes: after the variable-width+ # `\s*` before it, a negative lookahead is tried at the position *before*+ # the whitespace, where "not a quote" trivially succeeds and a string+ # literal slips through anyway. Severity is ``med``, not ``high``: on the+ # measured corpus every hit was a name reference to a source-pinned+ # constant (a stylesheet string assigned to a module-level name), which+ # this test cannot distinguish from a genuinely dynamic value without+ # dataflow, so the pattern is a places-to-read signal rather than a+ # confirmed sink.+ (re.compile(r"__html\s*:\s*(?=[A-Za-z_$(])"), "unsafe_inner_html", "med"),+ # Analogue of ``fstring_sql`` for a JS/TS template literal. The bare verb+ # `SELECT` or `UPDATE` is an ordinary English word and fires on prose+ # (`` `Order update failed: ${status}` ``) and even on class names+ # (`select-none`), so each verb needs its companion clause —+ # `SELECT`..`FROM`, `UPDATE`..`SET` — before an interpolation counts.+ (+ re.compile(r"`[^`\n]*\b(?:SELECT\b[^`\n]*\bFROM|UPDATE\b[^`\n]*\bSET)\b[^`\n]*\$\{"),+ "template_literal_sql",+ "med",+ ),+ # A secret-shaped name exposed through a `NEXT_PUBLIC_`/`VITE_` prefix+ # ships straight into the client bundle. The prefix needing the most care+ # against legitimate public config: an `..._ANON_...` name (a Supabase+ # anon key, public by design and meant to be paired with RLS) is excluded+ # rather than flagged, since that class made up most of the corpus noise.+ (+ re.compile(+ r"\b(?:NEXT_PUBLIC|VITE)_(?!\w*ANON)[A-Z0-9_]*"+ r"(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Z0-9_]*\b"+ ),+ "public_env_secret",+ "high",+ ),+ (re.compile(r"\bnew\s+Function\s*\("), "new_function_call", "high"),+ # Analogue of ``tls_verify_false`` for Node's https/tls agent options.+ (re.compile(r"rejectUnauthorized\s*:\s*false"), "reject_unauthorized_false", "med"),]# Combined prefilter: one search per line rejects the (overwhelmingly common)diff --git a/tests/unit/analysis/test_security_scan.py b/tests/unit/analysis/test_security_scan.pyindex 34b82aac5..69467f0ce 100644--- a/tests/unit/analysis/test_security_scan.py+++ b/tests/unit/analysis/test_security_scan.py@@ -219,6 +219,101 @@ class TestScanFile:hits = [f for f in findings if f["kind"] == "subprocess_shell_true"]assert hits == []+ # -- JS/TS patterns (#1935 Tier 1) -------------------------------------++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ # Non-literal values: a call, a variable, a member expression.+ ("<div dangerouslySetInnerHTML={{ __html: sanitize(raw) }} />\n", True),+ ("<div dangerouslySetInnerHTML={{ __html: markup }} />\n", True),+ ("<div dangerouslySetInnerHTML={{ __html: props.body }} />\n", True),+ # A SCREAMING_CASE constant is still a non-literal reference and+ # still fires — the pattern cannot tell "this name is pinned in+ # source" from "this name holds a request body" without+ # dataflow. This is the corpus noise the docs page calls out,+ # not a regression.+ ("<div dangerouslySetInnerHTML={{ __html: DOCS_CSS }} />\n", True),+ # A string literal is inert and must not fire. This is the case+ # the positive-lookahead value test exists for: a naive negative+ # lookahead excluding a quote, tried before the preceding+ # whitespace, would let this through.+ ('<div dangerouslySetInnerHTML={{ __html: "<b>ok</b>" }} />\n', False),+ ("<div dangerouslySetInnerHTML={{ __html: '' }} />\n", False),+ ],+ )+ def test_unsafe_inner_html_fires_on_non_literal_values(+ self, source: str, expected: bool+ ) -> None:+ scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]+ findings = asyncio.run(scanner.scan_file("component.tsx", source, symbols=[]))+ assert bool([f for f in findings if f["kind"] == "unsafe_inner_html"]) is expected++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ("const q = `SELECT * FROM users WHERE id = ${id}`;\n", True),+ ("const q = `UPDATE users SET name = ${name} WHERE id = ${id}`;\n", True),+ # The bare verb is an ordinary English word without its clause.+ ("const msg = `Order update failed: ${status}`;\n", False),+ ("const cls = `select-none ${active ? 'opacity-50' : ''}`;\n", False),+ # No interpolation: a literal query is not a finding here.+ ("const q = `SELECT * FROM users`;\n", False),+ ],+ )+ def test_template_literal_sql_requires_verb_and_clause(+ self, source: str, expected: bool+ ) -> None:+ scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]+ findings = asyncio.run(scanner.scan_file("db.ts", source, symbols=[]))+ assert bool([f for f in findings if f["kind"] == "template_literal_sql"]) is expected++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ("const k = process.env.NEXT_PUBLIC_API_KEY;\n", True),+ ("const k = process.env.NEXT_PUBLIC_N8N_API_KEY;\n", True),+ ("const k = import.meta.env.VITE_SECRET;\n", True),+ ("const k = import.meta.env.VITE_AUTH_TOKEN;\n", True),+ # Public by design, protected by row-level security: excluded+ # rather than flagged, per the corpus noise it made up.+ ("const k = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;\n", False),+ ("const url = process.env.NEXT_PUBLIC_APP_URL;\n", False),+ ("const k = process.env.API_KEY;\n", False), # not client-exposed+ ],+ )+ def test_public_env_secret_excludes_anon_keys(self, source: str, expected: bool) -> None:+ scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]+ findings = asyncio.run(scanner.scan_file("config.ts", source, symbols=[]))+ assert bool([f for f in findings if f["kind"] == "public_env_secret"]) is expected++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ('const f = new Function("a", "return a + 1");\n', True),+ ("const f = new Function(body);\n", True),+ ("const f = someFunction(a, b);\n", False),+ ("class Function extends Base {}\n", False),+ ],+ )+ def test_new_function_call(self, source: str, expected: bool) -> None:+ scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]+ findings = asyncio.run(scanner.scan_file("dynamic.ts", source, symbols=[]))+ assert bool([f for f in findings if f["kind"] == "new_function_call"]) is expected++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ("const agent = new https.Agent({ rejectUnauthorized: false });\n", True),+ ("axios.get(url, { httpsAgent, rejectUnauthorized: false });\n", True),+ ("const agent = new https.Agent({ rejectUnauthorized: true });\n", False),+ ],+ )+ def test_reject_unauthorized_false(self, source: str, expected: bool) -> None:+ scanner = SecurityScanner(session=None, repo_id="r1") # type: ignore[arg-type]+ findings = asyncio.run(scanner.scan_file("client.ts", source, symbols=[]))+ assert bool([f for f in findings if f["kind"] == "reject_unauthorized_false"]) is expected+class TestPersistSecurityFindings:"""The persist.py wiring: source_map in, idempotent rows out."""