Skip to content

Commit 70cbb5f

Browse files
committed
feat(ownts): parse function callbacks/cleanups; catch a real OSS leak
Hook libraries clean up by design, so the real-leak hunt moved to app-shaped component code — and found one: react-scroll-to-bottom@4.2.0 Composer.js:574 adds a `focus` listener with { capture: true } but removes it with the default capture (false), so per the DOM spec it is NEVER removed and piles up on every `target` change. That code ships transpiled ES5 (`function () {}` callbacks + `return function () {}` cleanups), which the arrow-tuned parser could not read. This teaches the frontend those shapes: - _effect_callback: detect a `function (...) {}` callback (body brace after the params via _body_brace), alongside arrow block / arrow expression. - _cleanup_span: a cleanup may be `return function () {}` (not only `return () =>`). With both, the Composer bug is caught for the RIGHT reason — the cleanup parses, and the listener key rejects the capture:true-vs-false removal — instead of by the coarse "no cleanup" path. EffectFunctionCallback.tsx pins it: a correctly-matched ES5 cleanup stays silent; the capture mismatch is the single OWN001. CI step added. The ES5 corpus (ahooks + react-use, ~93 useEffect) now parses; its 11 findings triage as FPs from the known patterns plus one new transpilation artifact (optional-chaining desugars the cleanup receiver to a temp `_a` ≠ `ref.current`), documented as residual in docs/notes/ownts-oss-benchmark.md (which also records the first confirmed true positive). Arrow corpus unchanged at 11; full suite green; ruff + mypy --strict clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PVeuchch67CtjSbizYm8gi
1 parent 4516e29 commit 70cbb5f

5 files changed

Lines changed: 109 additions & 11 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1142,6 +1142,18 @@ jobs:
11421142
# over-suppressed — all three controls stay OWN001
11431143
[ "$(echo "$leak" | grep -c 'OWN001')" -eq 3 ] \
11441144
|| { echo "FAIL: broadened matchers must not over-suppress real leaks"; exit 1; }
1145+
- name: ES5 `function` callbacks parse; capture-mismatch leak caught (real bug shape)
1146+
run: |
1147+
python frontend/ownts/ownts.py frontend/ownts/examples/EffectFunctionCallback.tsx \
1148+
-o "$RUNNER_TEMP/fn.facts.json"
1149+
fn=$(python -m ownlang ownir "$RUNNER_TEMP/fn.facts.json" || true)
1150+
echo "$fn"
1151+
# the matched ES5 cleanup is silent; the capture:true-vs-default mismatch
1152+
# (react-scroll-to-bottom@4.2.0 shape) is the one OWN001
1153+
[ "$(echo "$fn" | grep -c 'OWN001')" -eq 1 ] \
1154+
|| { echo "FAIL: expected exactly the capture-mismatch leak"; exit 1; }
1155+
echo "$fn" | grep -q "focus" \
1156+
|| { echo "FAIL: the leak must be the capture-mismatched focus listener"; exit 1; }
11451157
- name: The clean fixture (cleanups + useMemo'd dep) is silent
11461158
run: |
11471159
python frontend/ownts/ownts.py frontend/ownts/examples/DashboardClean.tsx \

‎docs/notes/ownts-oss-benchmark.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,39 @@ The honest takeaway: OwnTS is now quiet on idiomatic cleanup, with its remaining
123123
false alarms confined to four named, understood patterns — a real step toward the
124124
"low false positives" bar P-020 set, without a single guessed release.
125125

126+
## First confirmed TRUE positive — a real hanging effect
127+
128+
Hook *libraries* clean up by design, so the honest hunt for a real leak moved to
129+
*application-shaped* component code. In **`react-scroll-to-bottom@4.2.0`**
130+
(`ScrollToBottom/Composer.js:574`):
131+
132+
```js
133+
target.addEventListener('focus', handleFocus, { capture: true, passive: true });
134+
return () => target.removeEventListener('focus', handleFocus); // default capture (false)
135+
```
136+
137+
`removeEventListener` must match the capture flag; `capture: true` is added but the
138+
removal uses the default `false`, so the listener is **never removed** — a new one
139+
piles up every time `target` changes. This is exactly the capture-mismatch class the
140+
listener-key matching (P-148/#145) models, and OwnTS flags it. A second real one:
141+
**`@reactuses/core@6.4.0`** passes `onPressed('mouse')` (a freshly *returned*
142+
function) to both add and remove, so the drag/touch listeners can never be removed.
143+
144+
## ES5 (`function () {}`) build coverage
145+
146+
The benchmark above is arrow-ESM only. To reach the capture-mismatch bug for the
147+
*right* reason — and to widen the corpus to transpiled output (`ahooks`,
148+
`react-use`, and the Composer file above ship ES5 `function(){}`) — the frontend now
149+
parses `function` callbacks and `return function () {}` cleanups
150+
(`EffectFunctionCallback.tsx` pins it: a matched ES5 cleanup is silent, the
151+
capture-mismatch is the one finding). The ES5 corpus (`ahooks` + `react-use`, ~93
152+
`useEffect`) then yields 11 findings, again triaged as FPs from the known patterns
153+
plus one new transpilation artifact: **optional-chaining desugaring**
154+
(`ref.current?.removeEventListener` → `(_a = ref.current) ? … : _a.removeEventListener`)
155+
makes the cleanup receiver a temp `_a ≠ ref.current`, which the exact-receiver match
156+
rejects. Documented as residual; alias-resolving `_a` back to `ref.current` is the
157+
next increment.
158+
126159
### Reproduce
127160

128161
```bash
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Transpiled-ES5 shape: `useEffect(function () { … return function () { … } }, …)`.
2+
// Proves the parser handles `function` callbacks AND `return function` cleanups —
3+
// a correctly-matched ES5 cleanup stays silent, while a real capture-flag mismatch
4+
// (the react-scroll-to-bottom@4.2.0 bug) is caught for the right reason. Run:
5+
// python frontend/ownts/ownts.py frontend/ownts/examples/EffectFunctionCallback.tsx --check
6+
// Expect exactly ONE OWN001 (the capture-mismatched focus listener).
7+
import { useEffect } from "react";
8+
9+
export function Composer({ target }: { target: HTMLElement }) {
10+
// Correctly cleaned ES5 effect: same handler, same (default) capture -> silent.
11+
useEffect(function () {
12+
window.addEventListener("resize", onResize);
13+
return function () {
14+
window.removeEventListener("resize", onResize);
15+
};
16+
}, []);
17+
18+
// Real leak: added with { capture: true } but removed with the default (false)
19+
// capture, so the listener is never actually removed (react-scroll-to-bottom bug).
20+
useEffect(function () {
21+
target.addEventListener("focus", handleFocus, { capture: true, passive: true });
22+
return function () {
23+
return target.removeEventListener("focus", handleFocus);
24+
};
25+
}, [target]);
26+
27+
return <div>composer</div>;
28+
}

‎frontend/ownts/ownts.py‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -412,19 +412,30 @@ def _expr_end(text: str, i: int) -> int:
412412
def _effect_callback(masked: str, after_open: int) -> tuple[str, int, list[str] | None, int]:
413413
"""Parse `useEffect(<cb>, [deps])` from just past the `(`, over the STRING-MASKED
414414
source (so literals never truncate a body or split a dep). Returns
415-
(body, body_start, deps, end). Handles BOTH a block `() => { ... }` and an
416-
expression `() => fetch(url)` callback — calling `_match_block` blindly on the
417-
latter would jump to an unrelated `{` or run off the end. `deps` is None when no
415+
(body, body_start, deps, end). Handles a block arrow `() => { ... }`, an
416+
expression arrow `() => fetch(url)`, AND a `function () { ... }` expression
417+
(transpiled ES5 output) — calling `_match_block` blindly, or keying on `=>`,
418+
would jump to an unrelated `{`/arrow or run off the end. `deps` is None when no
418419
dependency array is present; the array is matched by BALANCED brackets so a dep
419420
like `items[i]` survives. `body` includes the braces for a block callback."""
420-
arrow = masked.find("=>", after_open)
421-
i = (arrow + 2) if arrow != -1 else after_open
422-
while i < len(masked) and masked[i] in " \t\r\n":
423-
i += 1
424-
if i < len(masked) and masked[i] == "{":
425-
end = _match_block(masked, i)
421+
j0 = after_open
422+
while j0 < len(masked) and masked[j0] in " \t\r\n":
423+
j0 += 1
424+
if re.match(r"(?:async\s+)?function\b", masked[j0:]):
425+
# function-expression callback: the body `{` follows the parameter list.
426+
i = _body_brace(masked, after_open)
427+
end = _match_block(masked, i) if i != -1 else len(masked)
428+
if i == -1:
429+
i = after_open
426430
else:
427-
end = _expr_end(masked, i)
431+
arrow = masked.find("=>", after_open)
432+
i = (arrow + 2) if arrow != -1 else after_open
433+
while i < len(masked) and masked[i] in " \t\r\n":
434+
i += 1
435+
if i < len(masked) and masked[i] == "{":
436+
end = _match_block(masked, i)
437+
else:
438+
end = _expr_end(masked, i)
428439
body = masked[i:end]
429440
# the dependency array is the balanced `[ ... ]` after an optional `, `
430441
deps: list[str] | None = None
@@ -462,7 +473,8 @@ def _cleanup_span(mbody: str) -> tuple[int, int, int] | None:
462473
fn_braces.add(fm.end() - 1)
463474
for fm in re.finditer(r"\bfunction\b[^{;]*?\)\s*\{", mbody):
464475
fn_braces.add(fm.end() - 1)
465-
ret_re = re.compile(r"return\s*(?:\(\s*\)|\w+)\s*=>")
476+
# a cleanup is `return <arrow>` or `return <function expression>` (ES5 output).
477+
ret_re = re.compile(r"return\s*(?:(?:\(\s*\)|\w+)\s*=>|(?:async\s+)?function\b)")
466478
stack: list[tuple[bool, int]] = [] # (is_function_body, open_index) per open brace
467479
fdepth = 0
468480
i, n = 0, len(mbody)
@@ -487,6 +499,12 @@ def _cleanup_span(mbody: str) -> tuple[int, int, int] | None:
487499
mbody.rfind("}", 0, i))
488500
if re.search(r"\b(?:if|else|for|while)\b", mbody[b + 1:i]):
489501
cov_start = m.start() # braceless conditional guard -> covers nothing
502+
if "function" in m.group(): # `return function () { ... }` (ES5 cleanup)
503+
brace = _body_brace(mbody, m.end()) # body brace after the params
504+
if brace != -1:
505+
return (m.start(), _match_block(mbody, brace), cov_start)
506+
i += 1
507+
continue
490508
rest = mbody[m.end():]
491509
stripped = rest.lstrip()
492510
if stripped.startswith("{"): # block-bodied cleanup: `=> { ... }`

‎frontend/ownts/test_ownts.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,13 @@ def main() -> int:
7070
leaks = codes("EffectLeakControl.tsx")
7171
assert leaks == ["OWN001", "OWN001", "OWN001"], f"EffectLeakControl -> {leaks}"
7272

73+
# Transpiled-ES5 shape: `function () { … return function () { … } }`. The parser
74+
# handles `function` callbacks + `return function` cleanups — a matched cleanup is
75+
# silent, and a real capture-flag mismatch (the react-scroll-to-bottom@4.2.0 bug)
76+
# is caught precisely via the listener key.
77+
fn_cb = codes("EffectFunctionCallback.tsx")
78+
assert fn_cb == ["OWN001"], f"EffectFunctionCallback -> {fn_cb}"
79+
7380
# an expression-bodied cleanup whose removeEventListener carries an options
7481
# object must parse (the `{` belongs to the call, not the cleanup block) — the
7582
# listener is released, so no false-positive leak.

0 commit comments

Comments
 (0)