Files
reverse-engineering-anything/src/application/javascript/ElectronActiveObservationService.ts
T
morluto 5f718ce30e refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)
* refactor(kernel): give error-to-message text one owner in a new src/kernel layer

* fix(kernel): keep the regex worker's own error text inside its isolated source

* refactor(kernel): exclude copies that run in another realm from the error-message guard by name

The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them.

* refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552)

Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560)

byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out.

Refs #11548

* refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562)

sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted.

Refs #11548

* refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563)

All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567)

All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
2026-11-16 07:05:30 +08:00

255 lines
8.1 KiB
TypeScript

import { HOST_PLATFORM } from "../../platform/HostPlatform.js";
import { dirname } from "node:path";
import { constants, type Stats } from "node:fs";
import { access, realpath, stat } from "node:fs/promises";
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
import type {
CanonicalElectronActiveObservationInput,
ElectronActiveObservationPort,
} from "../../ports/javascript/ElectronActiveObservationPort.js";
import {
AnalysisAccessDeniedError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
type AnalysisInputIssue,
cancelledBy,
} from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import {
electronActiveObservationResultSchema,
type ElectronActiveObservationInput,
} from "../../domain/javascript/electronActiveObservation.js";
import { err, ok, type Result } from "../../domain/result.js";
import { createElectronActiveEvidence } from "./ElectronActiveEvidence.js";
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { errorMessage } from "../../kernel/errorMessage.js";
const OPERATION = "capture_electron_scenario" as const;
const PROVIDER_ID = "rea-playwright-electron-active";
type ElectronPathField =
| "executable_path"
| "application_path"
| "application_root";
/**
* Why a selected path was not admitted. Host permission denial is not
* malformed caller input: the path may be correct, but REA cannot read it.
*/
type PathAdmissionFailure =
| {
readonly kind: "invalid";
readonly issue: AnalysisInputIssue;
readonly cause: unknown;
}
| { readonly kind: "denied"; readonly error: AnalysisAccessDeniedError };
const hostAccessDenial = (
selected: string,
cause: unknown,
): PathAdmissionFailure | undefined => {
const code: unknown =
cause instanceof Error ? Reflect.get(cause, "code") : undefined;
return code === "EACCES" || code === "EPERM"
? {
kind: "denied",
error: new AnalysisAccessDeniedError(OPERATION, selected, code, {
cause,
}),
}
: undefined;
};
const resolveInputPath = async (
field: ElectronPathField,
selected: string,
): Promise<Result<string, PathAdmissionFailure>> => {
try {
// Darwin realpath can collapse file/.. even though native lookup rejects
// that traversal. Admit the selected path before canonicalizing it.
const metadata = await stat(selected);
if (field === "application_root" && !metadata.isDirectory()) {
const cause = new Error("not a directory");
return err({
kind: "invalid",
issue: {
path: [field],
reason: "invalid_value",
message: `application_root ${selected} is not a directory`,
},
cause,
});
}
return ok(await realpath(selected));
} catch (cause: unknown) {
return err(
hostAccessDenial(selected, cause) ?? {
kind: "invalid",
issue: {
path: [field],
reason: "invalid_value",
message: `Cannot resolve ${field} ${selected}: ${errorMessage(cause)}`,
},
cause,
},
);
}
};
/**
* Resolve the executable and require a launchable regular file before any
* spawn. Denied resolution or metadata reads are host access failures; a
* readable file without execute permission is an invalid selection.
*/
const resolveExecutablePath = async (
selected: string,
): ReturnType<typeof resolveInputPath> => {
const resolved = await resolveInputPath("executable_path", selected);
if (!resolved.ok) return resolved;
let metadata: Stats;
try {
metadata = await stat(resolved.value);
} catch (cause: unknown) {
return err(
hostAccessDenial(selected, cause) ?? notExecutable(selected, cause),
);
}
if (!metadata.isFile())
return err(notExecutable(selected, new Error("not a regular file")));
if (HOST_PLATFORM.platform !== "win32")
try {
await access(resolved.value, constants.X_OK);
} catch (cause: unknown) {
return err(notExecutable(selected, cause));
}
return resolved;
};
const notExecutable = (
selected: string,
cause: unknown,
): PathAdmissionFailure => ({
kind: "invalid",
issue: {
path: ["executable_path"],
reason: "invalid_value",
message: `executable_path ${selected} is not an executable file: ${errorMessage(cause)}`,
},
cause,
});
/**
* Admit every selected path before any provider work. Invalid selections are
* reported together as input issues; a host access denial is reported only
* when no selection is invalid, because correcting the request comes first.
*/
const canonicalizeInput = async (
input: ElectronActiveObservationInput,
): Promise<Result<CanonicalElectronActiveObservationInput, AnalysisError>> => {
const [executable, application, root] = await Promise.all([
resolveExecutablePath(input.executable_path),
resolveInputPath("application_path", input.application_path),
input.application_root === undefined
? Promise.resolve(ok(undefined))
: resolveInputPath("application_root", input.application_root),
]);
if (!executable.ok || !application.ok || !root.ok) {
const failures = [executable, application, root].flatMap((result) =>
result.ok ? [] : [result.error],
);
const issues = failures.flatMap((failure) =>
failure.kind === "invalid" ? [failure.issue] : [],
);
const denial = failures.find((failure) => failure.kind === "denied");
if (issues.length === 0 && denial !== undefined) return err(denial.error);
return err(
new AnalysisInputError(
OPERATION,
{
cause: new AggregateError(
failures.map((failure) =>
failure.kind === "invalid" ? failure.cause : failure.error,
),
"Electron paths could not be resolved",
),
},
issues,
),
);
}
return ok({
...input,
executable_path: executable.value,
application_path: application.value,
application_root: root.value ?? dirname(application.value),
});
};
/** Canonicalize request paths and execute one provider-owned Electron run. */
export const captureElectronScenario = async (
provider: ElectronActiveObservationPort | undefined,
input: ElectronActiveObservationInput,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
if (options.signal?.aborted)
return err(cancelledBy(OPERATION, options.signal));
const canonical = await canonicalizeInput(input);
if (!canonical.ok) return canonical;
if (options.signal?.aborted)
return err(cancelledBy(OPERATION, options.signal));
if (provider === undefined)
return err(
new AnalysisCapabilityUnavailableError(
PROVIDER_ID,
OPERATION,
"active Electron observation provider is not configured",
),
);
const captured = await provider.capture(canonical.value, options);
if (!captured.ok) return captured;
const json = jsonValueSchema.safeParse(captured.value);
if (!json.success)
return err(
new AnalysisOutputError(
OPERATION,
"Electron provider returned non-JSON active capture data.",
{ cause: json.error },
),
);
const report = electronActiveObservationResultSchema.safeParse(json.data);
if (!report.success)
return err(
new AnalysisOutputError(
OPERATION,
"Electron provider returned a malformed active capture.",
{ cause: report.error },
),
);
if (
report.data.application.executable_path !==
canonical.value.executable_path ||
report.data.application.application_path !==
canonical.value.application_path
)
return err(
new AnalysisOutputError(
OPERATION,
"Electron provider changed the selected executable or application.",
{ partialObservation: report.data },
),
);
return completeProviderEvidence(
createElectronActiveEvidence(
input,
report.data,
provider.identity(),
canonical.value,
),
options.signal,
);
};