Files
reverse-engineering-anything/scripts/lint/rules/no-raw-file-handle-close.mjs
T
morluto 428e006f66 fix(filesystem): close file handles only through the owned-handle owners (#10578)
* fix(filesystem): close file handles only through the owned-handle owners

Three sites still closed a fs/promises FileHandle in a finally block, where a
failed close replaced the operation's own failure or result: the agentenv
runner head read, the Linux cgroup kernel-file read and the JavaScript
analysis transfer writer. They now use withOwnedFileHandle, which retains the
operation outcome alongside a failed close.

A lint rule, rea/no-raw-file-handle-close, refuses close() on a handle opened
from fs/promises or declared as FileHandle, and fs close/closeSync on a
descriptor, in src outside src/filesystem/Owned*.

* fix(lint): distinguish owned handle class fields

* fix(filesystem): retain diagnostic file cleanup owners

* test(hopper): retry after confirmed application exit

* fix(filesystem): settle doctor peers, sample cgroup outside admission, and bind lint this

Desktop doctor waits for every client inspection before reporting a retained close failure. Ghidra memory cgroup sampling no longer passes the resource scope's admission gate, so a pending owner cannot mask the provider failure; failed closes are still retained for session cleanup. The raw FileHandle close rule resolves this through arrow functions only, treats static blocks as static, and keeps #name distinct from constructor parameter properties.

* fix(ghidra): join in-flight cgroup samples before session cleanup

ArtifactResourceScope.track runs optional work outside the admission gate while cleanup drains still join it, so a cancelled request's final retry cannot finish before a sample retains a failed close.

* fix(filesystem): join work tracked during a cleanup drain and report doctor file cleanup as typed errors

A cleanup retry now repeats until no tracked work is active and every retained owner has had one attempt, so diagnostic work admitted while an earlier owner is releasing is joined. Doctor reports a retained runner or configuration file close as a ProviderCleanupError bound to its lease instead of rethrowing a raw file failure, so the error document keeps the retained file.

* fix(desktop): read the agentenv runner head through the artifact file owner

The runner read retained a failed close under one lease while the reported failure carried another, so a successful cleanup retry left the doctor error reporting an already-closed file. withArtifactFileHandle binds one lease to both.
2026-11-15 18:08:56 +08:00

245 lines
8.0 KiB
JavaScript

import { findBinding } from "../bindings.mjs";
const FS_PROMISES = new Set(["node:fs/promises", "fs/promises"]);
const FS = new Set(["node:fs", "fs"]);
const unwrap = (node) => {
let current = node;
while (
current?.type === "AwaitExpression" ||
current?.type === "TSAsExpression" ||
current?.type === "TSNonNullExpression" ||
current?.type === "TSSatisfiesExpression" ||
current?.type === "ParenthesizedExpression" ||
current?.type === "ChainExpression"
)
current = current.argument ?? current.expression;
return current;
};
/** The module and imported name an identifier binds to, when it is an import. */
const importedFrom = (sourceCode, identifier) => {
const definition = findBinding(sourceCode, identifier)?.defs?.[0];
if (definition?.type !== "ImportBinding") return undefined;
const declaration = definition.parent;
const specifier = definition.node;
return {
source: declaration?.source?.value,
imported:
specifier.type === "ImportSpecifier"
? (specifier.imported.name ?? specifier.imported.value)
: "*",
};
};
/** `name(...)` or `namespace.name(...)` imported from one of `modules`. */
const callsImport = (sourceCode, call, modules, names) => {
if (call?.type !== "CallExpression") return false;
const callee = unwrap(call.callee);
if (callee?.type === "Identifier") {
const binding = importedFrom(sourceCode, callee);
return (
binding !== undefined &&
modules.has(binding.source) &&
names.has(binding.imported)
);
}
if (
callee?.type === "MemberExpression" &&
!callee.computed &&
names.has(callee.property.name) &&
callee.object.type === "Identifier"
) {
const binding = importedFrom(sourceCode, callee.object);
return (
binding !== undefined &&
binding.imported === "*" &&
modules.has(binding.source)
);
}
return false;
};
const OPEN = new Set(["open"]);
const DESCRIPTOR_CLOSE = new Set(["close", "closeSync"]);
/** Whether an expression evaluates to a FileHandle from fs/promises open(). */
const opensFileHandle = (sourceCode, expression) => {
const value = unwrap(expression);
if (callsImport(sourceCode, value, FS_PROMISES, OPEN)) return true;
// open(...).catch(...) still resolves to the opened handle.
return (
value?.type === "CallExpression" &&
value.callee.type === "MemberExpression" &&
!value.callee.computed &&
value.callee.property.name === "catch" &&
callsImport(sourceCode, unwrap(value.callee.object), FS_PROMISES, OPEN)
);
};
/** Whether a type annotation names fs/promises' FileHandle, alone or in a union. */
const namesFileHandle = (sourceCode, annotation) => {
const type = annotation?.typeAnnotation ?? annotation;
if (type?.type === "TSUnionType")
return type.types.some((member) => namesFileHandle(sourceCode, member));
if (type?.type !== "TSTypeReference") return false;
const name = type.typeName;
if (name?.type === "Identifier") {
const binding = importedFrom(sourceCode, name);
return (
binding !== undefined &&
FS_PROMISES.has(binding.source) &&
binding.imported === "FileHandle"
);
}
// fsp.FileHandle through a namespace import.
if (name?.type === "TSQualifiedName" && name.right.name === "FileHandle") {
const binding =
name.left.type === "Identifier"
? importedFrom(sourceCode, name.left)
: undefined;
return (
binding !== undefined &&
binding.imported === "*" &&
FS_PROMISES.has(binding.source)
);
}
return false;
};
/**
* The class body whose instance (or, when `isStatic`, whose constructor) the
* `this` at `node` refers to. Arrow functions borrow the enclosing `this`;
* ordinary functions and object methods bind their own, which is no class.
*/
const thisClass = (node) => {
for (let current = node.parent; current; current = current.parent) {
if (current.type === "ArrowFunctionExpression") continue;
if (
current.type === "FunctionExpression" ||
current.type === "FunctionDeclaration"
) {
const method = current.parent;
return method?.type === "MethodDefinition" &&
method.value === current &&
method.parent?.type === "ClassBody"
? { body: method.parent, isStatic: method.static === true }
: undefined;
}
if (
(current.type === "PropertyDefinition" ||
current.type === "AccessorProperty") &&
current.parent?.type === "ClassBody"
)
return { body: current.parent, isStatic: current.static === true };
if (current.type === "StaticBlock" && current.parent?.type === "ClassBody")
return { body: current.parent, isStatic: true };
}
return undefined;
};
/** A class field declared as a FileHandle, for `this.field.close()`. */
const fieldHoldsFileHandle = (sourceCode, member) => {
if (
member.type !== "MemberExpression" ||
member.computed ||
member.object.type !== "ThisExpression"
)
return false;
const property = member.property;
const owner = thisClass(member);
if (owner === undefined) return false;
return owner.body.body.some((element) => {
// Constructor parameter properties are public or TS-private names, never `#name`.
if (
!owner.isStatic &&
property.type === "Identifier" &&
element.type === "MethodDefinition" &&
element.kind === "constructor"
)
return element.value.params.some((parameter) => {
if (parameter.type !== "TSParameterProperty") return false;
const value = parameter.parameter;
const id = value.type === "AssignmentPattern" ? value.left : value;
return (
id.type === "Identifier" &&
id.name === property.name &&
namesFileHandle(sourceCode, id.typeAnnotation)
);
});
return (
element.type === "PropertyDefinition" &&
(element.static === true) === owner.isStatic &&
element.key.type === property.type &&
element.key.name === property.name &&
(namesFileHandle(sourceCode, element.typeAnnotation) ||
opensFileHandle(sourceCode, element.value))
);
});
};
/** Whether `identifier` is a variable declared or ever assigned as a FileHandle. */
const holdsFileHandle = (sourceCode, identifier) => {
const variable = findBinding(sourceCode, identifier);
if (variable === undefined) return false;
for (const definition of variable.defs ?? []) {
if (namesFileHandle(sourceCode, definition.name?.typeAnnotation))
return true;
if (
definition.node?.type === "VariableDeclarator" &&
opensFileHandle(sourceCode, definition.node.init)
)
return true;
}
for (const reference of variable.references ?? []) {
const parent = reference.identifier?.parent;
if (
parent?.type === "AssignmentExpression" &&
parent.left === reference.identifier &&
opensFileHandle(sourceCode, parent.right)
)
return true;
}
return false;
};
export default {
meta: {
type: "problem",
docs: {
description:
"Close file handles and descriptors only through the src/filesystem/Owned* owners.",
},
schema: [],
messages: {
raw: "Close file handles and descriptors through OwnedFileHandle or withOwnedFileHandle (src/filesystem), which retain a failed close instead of losing it or masking the operation's own failure.",
},
},
create(context) {
const { sourceCode } = context;
return {
CallExpression(node) {
if (callsImport(sourceCode, node, FS, DESCRIPTOR_CLOSE)) {
context.report({ node, messageId: "raw" });
return;
}
const callee = node.callee;
if (
callee.type !== "MemberExpression" ||
callee.computed ||
callee.property.name !== "close"
)
return;
const target = unwrap(callee.object);
if (
(target?.type === "Identifier" &&
holdsFileHandle(sourceCode, target)) ||
fieldHoldsFileHandle(sourceCode, target) ||
opensFileHandle(sourceCode, target)
)
context.report({ node, messageId: "raw" });
},
};
},
};