Files
reverse-engineering-anything/src/native/windows/WindowsShortcutProvider.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

354 lines
12 KiB
TypeScript

import { HOST_PLATFORM } from "../../platform/HostPlatform.js";
import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js";
import { lstat, open } from "node:fs/promises";
import {
projectSelectedArtifactFileFailure,
projectOwnedArtifactIdentityFailure,
projectStableArtifactFailure,
projectArtifactCloseFailure,
ArtifactReaderFailure,
readStableArtifact,
type StableArtifactFileSystem,
type StableArtifactSnapshot,
artifactFilePrimaryFacts,
type ArtifactFilePrimaryFacts,
assertArtifactReadActive,
ArtifactResourceScope,
} from "../../resources/index.js";
import { fileSnapshotPartialObservationSchema } from "../../domain/fileSnapshotObservation.js";
import type { WindowsShortcutPort } from "../../ports/binaryDiagnostics/WindowsShortcutPort.js";
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import {
MAX_INSPECT_WINDOWS_SHORTCUT_EXTRA_DATA_BLOCKS,
MAX_INSPECT_WINDOWS_SHORTCUT_FILE_BYTES,
MAX_INSPECT_WINDOWS_SHORTCUT_ID_LIST_ITEMS,
MAX_INSPECT_WINDOWS_SHORTCUT_STRING_BYTES,
type InspectWindowsShortcutInput,
} from "../../domain/native/windowsShortcut.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { err, ok } from "../../domain/result.js";
import { WINDOWS_SHORTCUT_PROVIDER } from "../../domain/investigationProviders.js";
import {
WindowsShortcutResourceFailure,
type WindowsShortcutSelectedBoundary,
} from "./WindowsShortcut.errors.js";
import { parseWindowsShortcut } from "./WindowsShortcutParser.js";
import { errorMessage } from "../../kernel/errorMessage.js";
const OPERATION = "inspect_windows_shortcut";
/** A path that starts with two separators: UNC, extended UNC, or another device path. */
const HOST_PREFIXED_PATH = /^[\\/]{2}/u;
/** An extended or device form of a drive path, such as `\\?\C:\x`, which stays on this host. */
const LOCAL_DRIVE_DEVICE_PATH = /^[\\/]{2}[?.][\\/][A-Za-z]:(?:[\\/]|$)/u;
/**
* A path Windows could open through a remote host. Even `lstat` on such a path
* can reach an SMB server and offer the caller's credentials, so this is decided
* from the text alone. A mapped network drive looks like a local drive here.
* POSIX hosts read repeated leading slashes as one local root.
*/
const namesNetworkShare = (path: string, platform: NodeJS.Platform): boolean =>
platform === "win32" &&
HOST_PREFIXED_PATH.test(path) &&
!LOCAL_DRIVE_DEVICE_PATH.test(path);
/**
* `lstat` and `open` only. Without `realpath`, a rejected symlink's destination
* is never resolved, so a link pointing at a UNC path cannot reach an SMB host.
*/
const LINK_BLIND_FILE_SYSTEM: StableArtifactFileSystem = {
lstat: (path) => lstat(path, { bigint: true }),
open,
};
/** Where a Windows path's ancestors begin: past a drive root or device prefix. */
const WINDOWS_PATH_ROOT = /^(?:[\\/]{2}[?.][\\/])?(?:[A-Za-z]:)?[\\/]*/u;
/** A `\\?\` path, which Windows opens as spelled, without removing `.` or `..`. */
const LITERAL_DEVICE_PATH = /^[\\/]{2}\?[\\/]/u;
/** One path component and the separators the caller wrote after it. */
const WINDOWS_PATH_COMPONENT = /([^\\/]+)([\\/]*)/gu;
/**
* The ancestor directories Windows reaches when it opens `path`, spelled as
* the caller wrote them. Win32 removes `.` and `..` components before opening
* a path, so `C:\alias\..\real\a.lnk` reaches only `C:\real`, and `..`
* cannot climb above an absolute root. A `\\?\` path skips that
* normalization, so its components are walked as written. A relative path
* keeps a leading `..` that has nothing to remove.
*
* Only the normalized components are retained, which is linear in the path.
* Each ancestor is built from the running prefix as the walk reaches it, so a
* deep path never holds every parent spelling at once.
*/
function* windowsAncestors(path: string): Generator<string, void, undefined> {
const root = WINDOWS_PATH_ROOT.exec(path)?.[0] ?? "";
const literal = LITERAL_DEVICE_PATH.test(root);
const absolute = /[\\/]$/u.test(root);
const kept: { readonly name: string; readonly spelled: string }[] = [];
for (const [spelled, name = ""] of path
.slice(root.length)
.matchAll(WINDOWS_PATH_COMPONENT)) {
if (!literal && name === ".") continue;
if (!literal && name === "..") {
const last = kept.at(-1);
if (last !== undefined && last.name !== "..") {
kept.pop();
continue;
}
if (absolute) continue;
}
kept.push({ name, spelled });
}
// The final component is the shortcut itself, not an ancestor.
let prefix = root;
for (const { name, spelled } of kept.slice(0, -1)) {
yield prefix + name;
prefix += spelled;
}
}
/**
* The first ancestor directory of a Windows path that is a symbolic link or
* junction, walked from the root down. Each `lstat` reaches only directories
* already checked, so a link to a UNC path is found before anything follows it.
* An ancestor that cannot be read ends the walk and leaves the error to the reader.
* The caller's signal is checked before each read.
*/
const linkedWindowsAncestor = async (
path: string,
signal: AbortSignal | undefined,
): Promise<string | undefined> => {
for (const ancestor of windowsAncestors(path)) {
assertArtifactReadActive(signal);
try {
if ((await LINK_BLIND_FILE_SYSTEM.lstat(ancestor)).isSymbolicLink())
return ancestor;
} catch {
return undefined;
}
}
return undefined;
};
/** Portable Shell Link reader over one bounded, identity-checked regular file. */
export class WindowsShortcutProvider implements WindowsShortcutPort {
readonly identity = WINDOWS_SHORTCUT_PROVIDER;
readonly #resources = new ArtifactResourceScope();
constructor(
private readonly platform: NodeJS.Platform = HOST_PLATFORM.platform,
) {}
async close(): Promise<void> {
try {
await this.#resources.close();
} catch (cause: unknown) {
throw projectArtifactCloseFailure(
cause,
WINDOWS_SHORTCUT_PROVIDER.id,
OPERATION,
);
}
}
async inspect(
input: InspectWindowsShortcutInput,
options?: ExecutionOptions,
) {
if (namesNetworkShare(input.path, this.platform))
return err(
new AnalysisInputError(OPERATION, {}, [
{
path: ["path"],
reason: "invalid_value",
message: `Selected shortcut is on a network share, which this offline operation does not open: ${input.path}. Copy it to a local path first.`,
},
]),
);
let completed: StableArtifactSnapshot | undefined;
try {
return await this.#resources.run(async () => {
// Inside the admission, so close() waits for the walk's reads too.
const linkedAncestor =
this.platform === "win32"
? await linkedWindowsAncestor(input.path, options?.signal)
: undefined;
if (linkedAncestor !== undefined)
return err(
new AnalysisInputError(OPERATION, {}, [
{
path: ["path"],
reason: "invalid_value",
message: `Selected shortcut path passes through a directory link or junction, which this offline operation does not follow: ${linkedAncestor}. Select the shortcut by a path without links.`,
observed: { linked_ancestor: linkedAncestor },
},
]),
);
const snapshot = await readStableArtifact(
input.path,
input.max_file_bytes,
options?.signal,
LINK_BLIND_FILE_SYSTEM,
this.#resources,
);
completed = snapshot;
assertArtifactReadActive(options?.signal);
const report = await parseWindowsShortcut(
snapshot.bytes,
{
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
input,
options?.signal,
);
assertArtifactReadActive(options?.signal);
return ok(report);
});
} catch (cause) {
const failure = windowsShortcutFailure(cause, input);
if (completed !== undefined)
failure.retainPartialObservation(
fileSnapshotPartialObservationSchema.parse({
kind: "file-snapshot-hash",
path: input.path,
sha256: completed.sha256,
bytes: completed.bytes.length,
}),
);
return err(failure);
}
}
}
const fileSizeRemediation = (input: InspectWindowsShortcutInput): string =>
input.max_file_bytes >= MAX_INSPECT_WINDOWS_SHORTCUT_FILE_BYTES
? `The shortcut exceeds the ${String(MAX_INSPECT_WINDOWS_SHORTCUT_FILE_BYTES)}-byte input ceiling this operation accepts. This release has no runtime override. Select a smaller artifact.`
: `Raise max_file_bytes above ${String(input.max_file_bytes)} bytes or select a smaller artifact; the limit is the caller-selected input read budget.`;
const SELECTED_BUDGETS = {
id_list_items: {
argument: "max_id_list_items",
maximum: MAX_INSPECT_WINDOWS_SHORTCUT_ID_LIST_ITEMS,
unit: "entries",
},
extra_data_blocks: {
argument: "max_extra_data_blocks",
maximum: MAX_INSPECT_WINDOWS_SHORTCUT_EXTRA_DATA_BLOCKS,
unit: "entries",
},
string_bytes: {
argument: "max_string_bytes",
maximum: MAX_INSPECT_WINDOWS_SHORTCUT_STRING_BYTES,
unit: "bytes",
},
} as const satisfies Record<
WindowsShortcutSelectedBoundary,
{
readonly argument: keyof InspectWindowsShortcutInput;
readonly maximum: number;
readonly unit: string;
}
>;
const budgetRemediation = (
input: InspectWindowsShortcutInput,
boundary: WindowsShortcutSelectedBoundary,
): string => {
const { argument, maximum, unit } = SELECTED_BUDGETS[boundary];
const selected = input[argument];
const recovery =
selected >= maximum
? `This release has no override above the ${String(maximum)} ${unit} ceiling; select a smaller shortcut.`
: `Raise ${argument} on the next call, up to ${String(maximum)} ${unit}, or select a smaller shortcut; no restart is required.`;
return `Effective ${argument} is ${String(selected)} ${unit}. ${recovery}`;
};
const windowsShortcutFailurePrimary = (
facts: ArtifactFilePrimaryFacts,
input: InspectWindowsShortcutInput,
): AnalysisError => {
const { cause, origin } = facts;
if (origin === "owned-or-classified" && cause instanceof AnalysisError)
return cause;
const identityFailure = projectOwnedArtifactIdentityFailure(
facts,
OPERATION,
input.path,
);
if (identityFailure !== undefined) return identityFailure;
if (cause instanceof WindowsShortcutResourceFailure)
return new AnalysisResourceConstraintError(
OPERATION,
"capacity",
`Selected artifact ${input.path}: ${cause.message}`,
{ boundary: cause.boundary, maximum: cause.maximum },
{
cause,
retryable: false,
remediationAction: budgetRemediation(input, cause.boundary),
},
);
const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause);
if (formatFailure !== undefined) return formatFailure;
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure
) {
if (cause.reason === "limit")
return new AnalysisResourceConstraintError(
OPERATION,
"file-size",
cause.message,
{ max_file_bytes: input.max_file_bytes },
{
cause,
retryable: false,
remediationAction: fileSizeRemediation(input),
},
);
if (cause.reason === "path" || cause.reason === "format")
return new AnalysisInputError(OPERATION, { cause }, [
{ path: ["path"], reason: "invalid_format", message: cause.message },
]);
}
const fileFailure = projectSelectedArtifactFileFailure(
cause,
OPERATION,
input.path,
"shortcut",
);
if (fileFailure !== undefined) return fileFailure;
return new ProviderAdapterError(WINDOWS_SHORTCUT_PROVIDER.id, OPERATION, {
cause,
diagnostics: {
path: input.path,
reason: errorMessage(cause),
},
});
};
const windowsShortcutFailure = (
cause: unknown,
input: InspectWindowsShortcutInput,
): AnalysisError => {
const primary = windowsShortcutFailurePrimary(
artifactFilePrimaryFacts(cause),
input,
);
return projectStableArtifactFailure(
cause,
primary,
input.path,
WINDOWS_SHORTCUT_PROVIDER.id,
OPERATION,
);
};