Files
rea/src/application/javascript/JavaScriptApplicationService.ts
T
morluto 0f53849160 feat(javascript): make the member-mutation work allowance a runtime setting (#11181)
* feat(javascript): make the member-mutation work allowance a runtime setting

The member-mutation alias-state allowance from #11144 was a fixed constant, so a refused source could not be admitted without a code change.

Register javascript.member_mutation_alias_states (default 524288, 1 to 8388608 alias states) with the launch seed REA_JAVASCRIPT_MEMBER_MUTATION_ALIAS_STATES. The application, web bundle and reference-source boundaries resolve it from the accepted operation snapshot and launch environment, refuse a malformed seed before analysis, and send it to the workers with each source. A refusal names the setting, its effective value, source and range, and the recovery; worker parents rebuild it from the allowance they sent.

Refs #8294

* fix(javascript): keep the setting and recovery of a refused web script

A web bundle script refused by the member-mutation allowance kept only its reason and reported limits, so the public unknown lost the setting, value, source and recovery. Carry the refusal's structured limit and remediation on the per-script result and its javascript_analysis unknown, grouping scripts only when that recovery agrees. Assert structured limit facts and the owning formatter's recovery instead of fixed wording.

* fix(browser): keep only registered setting limits on a refused web script

* feat(javascript): keep syntax facts for a source whose member-mutation phase is refused (#11187)

* feat(javascript): keep syntax facts for a source whose member-mutation phase is refused

A source refused by the member-mutation work allowance during static analysis lost every fact, so the application graph counted it as skipped. Reference-source import failed outright on such a file.

Checkpoint the parser, comment and text facts the static owner can still state, with parse status partial, examination not-examined and refused_phase member-mutations, before reporting the refusal; the semantic phase is not started because it indexes the same mutations. Reference-source import keeps the file's declaration-level imports and records that its CommonJS require calls were not examined.

Refs #8294

* test(javascript): compare the reference-source refusal with its owning formatter

* feat(javascript): keep a refused web script's parse and text facts

A captured script whose member-mutation phase was refused lost every fact in analyze_web_bundle, so it was neither counted as parsed nor kept its vendor markers.

The analyzer now returns the script as unavailable with partial facts: refused phase, parse status and the inferences read from script text alone. Findings gathered before the refusal are dropped, because they may have read an incomplete mutation index. The worker parent states the refusal and its setting recovery from the allowance it sent, through the same helper the isolated analyzer uses for every unavailable script. The bundle counts the script as parsed, keeps its text inferences, and its javascript_analysis unknown carries refused_phase.

Refs #8294

* chore(mcp): record the member-mutation setting in the advertised summary

* fix(javascript): rebuild a parked source worker when the member-mutation allowance changes

A worker parked on a resource scope was reused when heap, timeout and precision matched, but its requests carry the allowance it was built with. After update_analysis_settings accepted a new allowance, the next analysis on that scope kept the old one.

The reuse check now compares the allowance's value and source, so a changed setting gets a worker built with it. The web bundle worker already takes the allowance per script.
2026-11-16 00:05:14 +08:00

276 lines
9.9 KiB
TypeScript

import { escapeJsonPointerToken } from "../../domain/jsonPointer.js";
import type { AnalysisSettingsReader } from "../../domain/analysisSettings.js";
import {
ASAR_HEADER_ADMISSION_SETTING,
parseAsarHeaderAdmission,
} from "../../config/asarHeaderAdmission.js";
import { parseAsarListingAdmission } from "../../config/asarListingAdmission.js";
import { resolveJavaScriptMemberMutationAllowance } from "../../config/javascriptMemberMutationAllowance.js";
import { z } from "zod";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { translateArtifactFailure } from "../../artifacts/ArtifactOperationFailure.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import {
analyzeJavaScriptApplicationInputSchema,
type JavaScriptApplicationAnalysisResult,
parseOwnedJavaScriptApplicationAnalysisSteps,
} from "../../domain/javascript/javascriptApplicationAnalysis.js";
import {
AnalysisAccessDeniedError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import { createOwnedJavaScriptApplicationEvidenceCooperatively } from "./JavaScriptApplicationEvidence.js";
import {
assertJavaScriptAnalysisActive,
checkpointJavaScriptAnalysis,
completeJavaScriptAnalysisSteps,
} from "./JavaScriptAnalysisControl.js";
import {
reconstructJavaScriptArtifact,
type JavaScriptArtifactReconstructionResult,
} from "./JavaScriptArtifactReconstruction.js";
import { JAVASCRIPT_APPLICATION_PROVIDER } from "../../domain/investigationProviders.js";
const OPERATION = "analyze_javascript_application" as const;
/** Execution options plus the composition root's environment for admission settings. */
export interface JavaScriptApplicationOptions extends ExecutionOptions {
readonly settings?: AnalysisSettingsReader;
readonly environment?: Readonly<Record<string, string | undefined>>;
}
/** Statically analyze one local JavaScript/Electron application. */
export const analyzeJavaScriptApplication = async (
rawInput: unknown,
scope: ArtifactResourceScope,
options: JavaScriptApplicationOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const parsed = analyzeJavaScriptApplicationInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(OPERATION, parsed.error.issues, rawInput),
);
return analyzeJavaScriptApplicationValidated(parsed.data, scope, options);
};
/** Analyze input already parsed by a trusted adapter boundary. */
export const analyzeJavaScriptApplicationValidated = async (
input: z.output<typeof analyzeJavaScriptApplicationInputSchema>,
scope: ArtifactResourceScope,
options: JavaScriptApplicationOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
// An invalid setting is refused before analysis, never replaced by the default.
const asarHeaderAdmission = parseAsarHeaderAdmission(
options.environment?.[ASAR_HEADER_ADMISSION_SETTING],
);
if (!asarHeaderAdmission.ok) return asarHeaderAdmission;
const listingAdmission = parseAsarListingAdmission(
options.environment?.REA_ASAR_MAX_LISTING_BYTES,
);
if (!listingAdmission.ok) return listingAdmission;
const overrides = options.settings?.().overrides;
const memberMutationAllowance = resolveJavaScriptMemberMutationAllowance(
options.environment,
overrides,
);
if (!memberMutationAllowance.ok) return memberMutationAllowance;
const header = overrides?.["asar.max_header_bytes"];
const listing = overrides?.["asar.max_listing_bytes"];
const acceptedAdmission = {
...(header === undefined
? asarHeaderAdmission.value
: { maximumBytes: header, source: "runtime" as const }),
listing:
listing === undefined
? listingAdmission.value
: { maximumBytes: listing, source: "runtime" as const },
};
let reconstructed: JavaScriptArtifactReconstructionResult | undefined;
let result: JavaScriptApplicationAnalysisResult | undefined;
let evidence: Evidence | undefined;
try {
assertJavaScriptAnalysisActive(options.signal);
await options.progress?.report({
phase: "analyze_javascript_application",
completed: 0,
total: 1,
message: "Inventorying and parsing application artifacts",
});
await checkpointJavaScriptAnalysis(options.signal);
reconstructed = await reconstructJavaScriptArtifact(
input,
scope,
options.signal,
options.progress,
acceptedAdmission,
overrides,
memberMutationAllowance.value,
);
const { electron_summary: summary, ...application } = reconstructed;
await options.progress?.report({
phase: "validate_javascript_application_result",
completed: 0,
total: 1,
message: "Validating result metadata and cross-graph bindings",
});
await checkpointJavaScriptAnalysis(options.signal);
result = await completeJavaScriptAnalysisSteps(
parseOwnedJavaScriptApplicationAnalysisSteps({
...application,
summary,
limitations: reconstructed.graph.limitations,
}),
options.signal,
);
await options.progress?.report({
phase: "create_javascript_application_evidence",
completed: 0,
total: 1,
message: "Creating and hashing application analysis Evidence",
});
await checkpointJavaScriptAnalysis(options.signal);
evidence = await createOwnedJavaScriptApplicationEvidenceCooperatively(
input,
result,
options.signal,
options.progress,
);
await checkpointJavaScriptAnalysis(options.signal);
await options.progress?.report({
phase: "analyze_javascript_application",
completed: 1,
total: 1,
message: "Application graph and Electron boundaries reconstructed",
terminal: true,
});
assertJavaScriptAnalysisActive(options.signal);
return ok(evidence);
} catch (caught: unknown) {
let cause = caught;
if (
cause instanceof ArtifactReaderFailure &&
cause.reason === "cancelled" &&
reconstructed !== undefined
) {
try {
if (result === undefined) {
const { electron_summary: summary, ...application } = reconstructed;
result = await completeJavaScriptAnalysisSteps(
parseOwnedJavaScriptApplicationAnalysisSteps({
...application,
summary,
limitations: reconstructed.graph.limitations,
}),
);
}
evidence ??=
await createOwnedJavaScriptApplicationEvidenceCooperatively(
input,
result,
);
return err(
translateArtifactFailure(OPERATION, cause).retainPartialObservation(
evidence,
),
);
} catch (completionCause: unknown) {
// A validation or Evidence failure while finishing the partial result
// remains the primary failure instead of being hidden by cancellation.
cause = completionCause;
}
}
// Preserve execution constraints and their completed partial Evidence.
if (cause instanceof AnalysisError) return err(cause);
if (cause instanceof ArtifactReaderFailure)
return err(translateArtifactFailure(OPERATION, cause));
if (cause instanceof z.ZodError)
return err(
new AnalysisOutputError(OPERATION, describeResultSchemaFailure(cause), {
cause,
}),
);
if (
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string" &&
FILESYSTEM_ERROR_CODES.has(cause.code)
) {
const path: unknown = Reflect.get(cause, "path");
const syscall: unknown = Reflect.get(cause, "syscall");
const diagnostics = {
input_path: input.input_path,
system_code: cause.code,
...(typeof path === "string" ? { path } : {}),
...(typeof syscall === "string" ? { syscall } : {}),
};
return err(
cause.code === "EACCES" || cause.code === "EPERM"
? new AnalysisAccessDeniedError(
OPERATION,
input.input_path,
cause.code,
{ cause, diagnostics },
)
: new ArtifactOperationError(
OPERATION,
"io",
undefined,
cause.message,
{ cause, diagnostics },
),
);
}
return err(
new ProviderAdapterError(JAVASCRIPT_APPLICATION_PROVIDER.id, OPERATION, {
cause,
diagnostics: {
input_path: input.input_path,
error_name: cause instanceof Error ? cause.name : "UnknownError",
error_message:
cause instanceof Error
? cause.message
: typeof cause === "string"
? cause
: "JavaScript analysis failed with a non-Error value",
},
}),
);
}
};
const describeResultSchemaFailure = (cause: z.ZodError): string => {
const issue = cause.issues[0];
if (issue === undefined) return "Result schema rejected an unknown issue";
const path = issue.path.flatMap((part) =>
typeof part === "string" || typeof part === "number" ? [part] : [],
);
const pointer =
path.length === 0
? "/"
: `/${path.map((part) => escapeJsonPointerToken(String(part))).join("/")}`;
return `Result schema rejected ${String(cause.issues.length)} ${cause.issues.length === 1 ? "issue" : "issues"} at ${pointer} (${issue.code})`;
};
const FILESYSTEM_ERROR_CODES = new Set([
"ENOENT",
"EACCES",
"EPERM",
"ENOTDIR",
"EISDIR",
"EIO",
"ELOOP",
"ENAMETOOLONG",
"EMFILE",
"ENFILE",
"ENOSPC",
"EROFS",
]);