feat(artifacts): triage desktop installation directories (#5207)
* feat(artifacts): triage desktop installation directories * fix(artifacts): retain completed probes through failed file cleanup * perf(artifacts): decode only assembly reference names for desktop triage * fix(artifacts): enforce exact signatures and responsive directory probes * fix(artifacts): recognize Unity bundles and bound FORM chunks * fix(artifacts): retain bounded desktop omission evidence * fix(artifacts): select ASAR targets before inventory probes * chore: preserve tested upstream HTTP owner during integration * fix(artifacts): reuse Mach-O signatures for FAT64 desktop probes * fix(artifacts): expose bounded desktop probe diagnostics * fix(artifacts): derive desktop snapshots from observed source identities * fix(artifacts): admit desktop facts before JSON expansion
This commit is contained in:
1 parent
71ae02c6ef
commit
b4938aed58
63 files changed
+4122
-165
No files matched your search
@@ -0,0 +1,48 @@
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import {
|
||||
artifactFileCancellationCause,
|
||||
bindArtifactFileCleanup,
|
||||
} from "./ArtifactFileOperation.js";
|
||||
|
||||
/** Translate one artifact boundary failure while retaining cleanup evidence. */
|
||||
export const translateArtifactFailure = (
|
||||
operation: ArtifactOperationError["operation"],
|
||||
cause: unknown,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof ArtifactReaderFailure) {
|
||||
const error = new ArtifactOperationError(
|
||||
operation,
|
||||
cause.reason,
|
||||
cause.details,
|
||||
cause.message,
|
||||
{
|
||||
cause:
|
||||
cause.reason === "cancelled"
|
||||
? artifactFileCancellationCause(cause)
|
||||
: cause,
|
||||
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
|
||||
...(cause.partialObservation === undefined
|
||||
? {}
|
||||
: { partialObservation: cause.partialObservation }),
|
||||
},
|
||||
);
|
||||
bindArtifactFileCleanup(cause, error);
|
||||
return error;
|
||||
}
|
||||
// Caller-selection and unsupported-target failures are already typed; keep
|
||||
// their correction details instead of reducing them to an I/O failure.
|
||||
if (
|
||||
cause instanceof AnalysisInputError ||
|
||||
cause instanceof AnalysisCancelledError ||
|
||||
cause instanceof AnalysisUnsupportedTargetError
|
||||
)
|
||||
return cause;
|
||||
return new ArtifactOperationError(operation, "io");
|
||||
};
|
||||
@@ -1,3 +1,6 @@
|
||||
import { bindArtifactFileCleanup } from "./ArtifactFileOperation.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { translateArtifactFailure } from "./ArtifactOperationFailure.js";
|
||||
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
@@ -27,21 +30,14 @@ import {
|
||||
} from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { interfaceBuilderLimitsSchema } from "../domain/apple/interfaceBuilderGraph.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
|
||||
import {
|
||||
artifactFileCancellationCause,
|
||||
bindArtifactFileCleanup,
|
||||
} from "./ArtifactFileOperation.js";
|
||||
import { artifactCapabilities } from "./ArtifactProviderMetadata.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
@@ -408,42 +404,6 @@ const isArtifactOperation = (
|
||||
operation as (typeof ARTIFACT_ANALYSIS_OPERATIONS)[number],
|
||||
);
|
||||
|
||||
/** Translate one artifact boundary failure while retaining cleanup evidence. */
|
||||
export const translateArtifactFailure = (
|
||||
operation: ArtifactAnalysisOperation,
|
||||
cause: unknown,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof ArtifactReaderFailure) {
|
||||
const error = new ArtifactOperationError(
|
||||
operation,
|
||||
cause.reason,
|
||||
cause.details,
|
||||
cause.message,
|
||||
{
|
||||
cause:
|
||||
cause.reason === "cancelled"
|
||||
? artifactFileCancellationCause(cause)
|
||||
: cause,
|
||||
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
|
||||
...(cause.partialObservation === undefined
|
||||
? {}
|
||||
: { partialObservation: cause.partialObservation }),
|
||||
},
|
||||
);
|
||||
bindArtifactFileCleanup(cause, error);
|
||||
return error;
|
||||
}
|
||||
// Caller-selection and unsupported-target failures are already typed; keep
|
||||
// their correction details instead of reducing them to an I/O failure.
|
||||
if (
|
||||
cause instanceof AnalysisInputError ||
|
||||
cause instanceof AnalysisCancelledError ||
|
||||
cause instanceof AnalysisUnsupportedTargetError
|
||||
)
|
||||
return cause;
|
||||
return new ArtifactOperationError(operation, "io");
|
||||
};
|
||||
|
||||
const subjectFor = (
|
||||
path: string,
|
||||
manifest: {
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { Readable } from "node:stream";
|
||||
import type {
|
||||
ArtifactCommand,
|
||||
ArtifactInventoryCoverage,
|
||||
ArtifactTraversalOmissionKind,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
|
||||
import type {
|
||||
@@ -106,13 +107,7 @@ export const sameArtifactEntry = (
|
||||
/** One entry or subtree deliberately excluded from a traversal. */
|
||||
export interface ArtifactTraversalOmission {
|
||||
readonly path: string;
|
||||
readonly kind:
|
||||
| "fifo"
|
||||
| "socket"
|
||||
| "block-device"
|
||||
| "character-device"
|
||||
| "unsupported"
|
||||
| "directory-descendants";
|
||||
readonly kind: ArtifactTraversalOmissionKind;
|
||||
}
|
||||
|
||||
/** Facts from an exhausted traversal, separate from entry content certainty. */
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import { translateArtifactFailure } from "./ArtifactProvider.js";
|
||||
import { translateArtifactFailure } from "./ArtifactOperationFailure.js";
|
||||
import { ArtifactResourceScope } from "./ArtifactResourceScope.js";
|
||||
|
||||
const deferred = <T>() => {
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
import { desktopPathConventions } from "../domain/nativeConvention.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import {
|
||||
DirectoryArtifactReader,
|
||||
DirectoryArtifactTraversalLimit,
|
||||
type DirectoryArtifactEntry,
|
||||
} from "./DirectoryArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import {
|
||||
ArtifactFileCancelled,
|
||||
ArtifactFileCleanupFailure,
|
||||
} from "./ArtifactFileOperation.js";
|
||||
import {
|
||||
ArtifactResourceScope,
|
||||
type ArtifactResourceOwner,
|
||||
} from "./ArtifactResourceScope.js";
|
||||
import { abortIfNeeded } from "./ArtifactHash.js";
|
||||
import { translateArtifactFailure } from "./ArtifactOperationFailure.js";
|
||||
import {
|
||||
inspectDesktopFile,
|
||||
type DesktopReadBudget,
|
||||
} from "./DesktopFileInspection.js";
|
||||
import type { DesktopApplicationPort } from "../application/artifacts/DesktopApplicationPort.js";
|
||||
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
|
||||
import type {
|
||||
DesktopApplication,
|
||||
DesktopFile,
|
||||
DesktopOmission,
|
||||
InspectDesktopApplicationInput,
|
||||
} from "../domain/desktopApplication.js";
|
||||
import { projectDesktopApplication } from "../domain/desktopApplicationProjection.js";
|
||||
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { createDesktopApplicationEvidence } from "../domain/desktopApplicationEvidence.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
|
||||
|
||||
const RETAINED_METADATA_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/** Stop traversal without discarding the preceding bounded observations. */
|
||||
class DesktopRepresentationLimit extends ArtifactReaderFailure {
|
||||
constructor() {
|
||||
super(
|
||||
"limit",
|
||||
"Directory metadata reached the 32 MiB representation budget; remaining entry and omission facts are unavailable.",
|
||||
{ boundary: "memory" },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Existing artifact ownership with bounded metadata, serial probes and no payload cache. */
|
||||
export class DesktopApplicationReader implements DesktopApplicationPort {
|
||||
readonly #resources = new ArtifactResourceScope();
|
||||
#running = false;
|
||||
constructor(
|
||||
private readonly directoryReaderFor: (
|
||||
path: string,
|
||||
) => DirectoryArtifactReader = (path) => new DirectoryArtifactReader(path),
|
||||
) {}
|
||||
|
||||
async inspect(
|
||||
input: InspectDesktopApplicationInput,
|
||||
options?: ExecutionOptions,
|
||||
) {
|
||||
if (this.#running)
|
||||
return err(
|
||||
new AnalysisResourceConstraintError(
|
||||
"inspect_desktop_application",
|
||||
"capacity",
|
||||
"This artifact reader already owns a directory inspection",
|
||||
{ max_concurrent_inspections: 1 },
|
||||
{
|
||||
retryable: true,
|
||||
remediationAction:
|
||||
"Wait for this directory inspection to finish before submitting another.",
|
||||
},
|
||||
),
|
||||
);
|
||||
this.#running = true;
|
||||
try {
|
||||
return ok(
|
||||
await this.#resources.run(() => this.#inspect(input, options?.signal)),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
const error = translateArtifactFailure(
|
||||
"inspect_desktop_application",
|
||||
cause,
|
||||
);
|
||||
return err(error);
|
||||
} finally {
|
||||
this.#running = false;
|
||||
}
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.#resources.close();
|
||||
}
|
||||
|
||||
async #inspect(
|
||||
input: InspectDesktopApplicationInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<DesktopApplication> {
|
||||
if (!isAbsolute(input.path))
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Expected an absolute directory path",
|
||||
);
|
||||
const reader = this.directoryReaderFor(input.path);
|
||||
const owner: ArtifactResourceOwner = {
|
||||
kind: "reader",
|
||||
resource: input.path,
|
||||
reader,
|
||||
};
|
||||
let outcome:
|
||||
| { kind: "completed"; value: DesktopApplication }
|
||||
| { kind: "failed"; cause: unknown };
|
||||
let report: DesktopApplication | undefined;
|
||||
try {
|
||||
const scanned = await scanDirectory(reader, input, signal);
|
||||
report = scanned.report;
|
||||
outcome =
|
||||
scanned.failure === undefined
|
||||
? { kind: "completed", value: report }
|
||||
: { kind: "failed", cause: scanned.failure.cause };
|
||||
} catch (cause: unknown) {
|
||||
outcome = { kind: "failed", cause };
|
||||
}
|
||||
const closed = await this.#resources.release(owner);
|
||||
const partial =
|
||||
report === undefined ||
|
||||
(closed.kind !== "failed" &&
|
||||
outcome.kind !== "failed" &&
|
||||
signal?.aborted !== true)
|
||||
? undefined
|
||||
: createDesktopApplicationEvidence(
|
||||
input,
|
||||
report,
|
||||
ARTIFACT_GRAPH_PROVIDER,
|
||||
);
|
||||
if (closed.kind === "failed")
|
||||
throw this.#resources.cleanupFailure(outcome, [closed], partial);
|
||||
if (outcome.kind === "failed") {
|
||||
const cause = outcome.cause;
|
||||
if (!(cause instanceof ArtifactReaderFailure) || partial === undefined)
|
||||
throw cause;
|
||||
throw new ArtifactReaderFailure(
|
||||
cause.reason,
|
||||
cause.message,
|
||||
{
|
||||
cause,
|
||||
cancellation: cause.cancellation,
|
||||
cleanup: cause.cleanup,
|
||||
cleanupLeases: cause.cleanupLeases,
|
||||
partialObservation: partial,
|
||||
...(cause.boundary === undefined ? {} : { boundary: cause.boundary }),
|
||||
},
|
||||
cause.details,
|
||||
);
|
||||
}
|
||||
if (signal?.aborted)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Directory inspection cancelled during final cleanup",
|
||||
{ cause: signal.reason, partialObservation: partial },
|
||||
);
|
||||
return outcome.value;
|
||||
}
|
||||
}
|
||||
|
||||
const scanDirectory = async (
|
||||
reader: DirectoryArtifactReader,
|
||||
input: InspectDesktopApplicationInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{
|
||||
readonly report: DesktopApplication;
|
||||
readonly failure?: { readonly cause: unknown };
|
||||
}> => {
|
||||
const admittedRoot = await reader.rootObservation();
|
||||
const root = {
|
||||
canonical_path: admittedRoot.canonicalPath,
|
||||
identity: {
|
||||
device: admittedRoot.identity.dev.toString(),
|
||||
inode: admittedRoot.identity.ino.toString(),
|
||||
},
|
||||
};
|
||||
const namespaceId = `dsr_${digestCanonicalValue(root, "Admitted desktop directory namespace")}`;
|
||||
const files: DesktopFile[] = [];
|
||||
const omissions: DesktopOmission[] = [];
|
||||
const unityWitnessRoots = new Set<string>();
|
||||
const budget: DesktopReadBudget = {
|
||||
bytes: 0,
|
||||
maximum: input.max_probe_bytes,
|
||||
retainedBytes: 1024 + (input.path.length + root.canonical_path.length) * 24,
|
||||
maximumRetainedBytes: RETAINED_METADATA_BYTES,
|
||||
};
|
||||
const reserve = (bytes: number) => {
|
||||
if (bytes > budget.maximumRetainedBytes - budget.retainedBytes)
|
||||
throw new DesktopRepresentationLimit();
|
||||
budget.retainedBytes += bytes;
|
||||
};
|
||||
let entries = 0;
|
||||
let probed = 0;
|
||||
let symlinks = 0;
|
||||
let special = 0;
|
||||
let partial = false;
|
||||
let failure: { readonly cause: unknown } | undefined;
|
||||
const limitations = [
|
||||
"Runtime candidates and component markers do not establish loaded code, execution, or build correspondence.",
|
||||
"The directory SHA-256 commits only to retained paths, omission kinds, available filesystem metadata and read-range digests, not to every file's contents. Unread bytes are unknown.",
|
||||
"Special-entry payloads are not read. Their paths and kinds are retained; other special-entry metadata is unavailable in this report.",
|
||||
"Child symlinks are not followed. Executable section-embedded PCKs without a trailer and encrypted contents remain unexamined.",
|
||||
"This is a sequence of stable entry observations, not an atomic snapshot of the entire directory.",
|
||||
"Unity reference decoding stops after a witness in each Data/Managed directory; other assemblies' references are unexamined. Header facts remain per-file.",
|
||||
];
|
||||
try {
|
||||
for await (const entry of reader.entries(signal, {
|
||||
maximumEntries: input.max_entries,
|
||||
onOmission: (omission) => {
|
||||
if (omission.kind !== "directory-descendants") {
|
||||
special++;
|
||||
entries++;
|
||||
}
|
||||
partial = true;
|
||||
reserve(512 + omission.path.length * 24);
|
||||
const semantic = {
|
||||
root_namespace_id: namespaceId,
|
||||
path: omission.path,
|
||||
kind: omission.kind,
|
||||
};
|
||||
omissions.push({
|
||||
omission_id: `dso_${digestCanonicalValue(semantic, "Desktop traversal omission")}`,
|
||||
path: omission.path,
|
||||
kind: omission.kind,
|
||||
});
|
||||
},
|
||||
})) {
|
||||
entries++;
|
||||
abortIfNeeded(signal);
|
||||
// Reserve a conservative representation estimate before retaining path-dependent objects.
|
||||
const reservation =
|
||||
1024 + (entry.path.length + entry.adapterKey.length) * 24;
|
||||
reserve(reservation);
|
||||
const row = fileRow(entry, namespaceId);
|
||||
files.push(row);
|
||||
if (entry.kind === "symlink") {
|
||||
symlinks++;
|
||||
continue;
|
||||
}
|
||||
if (entry.kind !== "file") continue;
|
||||
const managedRoot = addPathFacts(row);
|
||||
if (!probeSelected(entry)) continue;
|
||||
if (budget.bytes >= budget.maximum) {
|
||||
row.read_status = "unavailable";
|
||||
row.issues.push(
|
||||
"Probe byte budget exhausted; bytes were not inspected.",
|
||||
);
|
||||
partial = true;
|
||||
continue;
|
||||
}
|
||||
probed++;
|
||||
try {
|
||||
await reader.inspectFile(
|
||||
entry,
|
||||
(file) =>
|
||||
inspectDesktopFile(
|
||||
file,
|
||||
row,
|
||||
budget,
|
||||
signal,
|
||||
managedRoot !== null && !unityWitnessRoots.has(managedRoot)
|
||||
? managedRoot
|
||||
: null,
|
||||
),
|
||||
signal,
|
||||
);
|
||||
row.read_status = row.issues.length === 0 ? "examined" : "partial";
|
||||
if (
|
||||
managedRoot !== null &&
|
||||
row.facts.some((fact) => fact.kind === "unity-assembly-reference")
|
||||
)
|
||||
unityWitnessRoots.add(managedRoot);
|
||||
if (row.issues.length > 0) partial = true;
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
|
||||
const probeIssueCount = row.issues.length;
|
||||
row.read_status = "unavailable";
|
||||
row.issues.push(cause.message);
|
||||
partial = true;
|
||||
const completedRead =
|
||||
cause instanceof ArtifactFileCancelled ||
|
||||
(cause instanceof ArtifactFileCleanupFailure &&
|
||||
cause.fileCleanupFailure.outcome.kind === "completed");
|
||||
if (completedRead)
|
||||
row.read_status = probeIssueCount === 0 ? "examined" : "partial";
|
||||
if (
|
||||
!completedRead &&
|
||||
(cause.reason === "integrity" ||
|
||||
cause.reason === "io" ||
|
||||
cause.reason === "cancelled")
|
||||
) {
|
||||
row.facts = row.facts.filter((fact) => fact.offset === null);
|
||||
row.ranges = [];
|
||||
}
|
||||
if (cause.cleanup !== undefined || cause.reason === "cancelled")
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
partial = true;
|
||||
if (cause instanceof DirectoryArtifactTraversalLimit) {
|
||||
entries = cause.examinedEntries;
|
||||
limitations.push(
|
||||
"Directory traversal reached max_entries; unvisited paths and candidate families remain unknown.",
|
||||
);
|
||||
} else if (cause instanceof DesktopRepresentationLimit) {
|
||||
limitations.push(cause.message);
|
||||
} else {
|
||||
failure = { cause };
|
||||
limitations.push(
|
||||
"Inspection was interrupted; only preceding stable entry observations are retained.",
|
||||
);
|
||||
}
|
||||
}
|
||||
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
||||
omissions.sort((a, b) =>
|
||||
a.path < b.path
|
||||
? -1
|
||||
: a.path > b.path
|
||||
? 1
|
||||
: a.kind < b.kind
|
||||
? -1
|
||||
: a.kind > b.kind
|
||||
? 1
|
||||
: 0,
|
||||
);
|
||||
const coverage: DesktopApplication["coverage"] = {
|
||||
status: partial ? "partial" : "complete-within-scan",
|
||||
entries_examined: entries,
|
||||
files_probed: probed,
|
||||
bytes_read: budget.bytes,
|
||||
symlinks_not_followed: symlinks,
|
||||
special_entries_omitted: special,
|
||||
limits: {
|
||||
max_entries: input.max_entries,
|
||||
max_probe_bytes: input.max_probe_bytes,
|
||||
},
|
||||
};
|
||||
// Compose identities already owned by admitted root/entry observations and
|
||||
// retained reads. Caller policy, interpretations and cleanup diagnostics stay
|
||||
// in Evidence without renaming the same examined source.
|
||||
const snapshot = digestCanonicalValue(
|
||||
{
|
||||
root_namespace_id: namespaceId,
|
||||
files: files.map(({ file_id, bytes, ranges }) => ({
|
||||
file_id,
|
||||
bytes,
|
||||
ranges,
|
||||
})),
|
||||
omissions: omissions.map(({ omission_id }) => omission_id),
|
||||
},
|
||||
"Examined desktop directory facts",
|
||||
);
|
||||
const report: DesktopApplication = {
|
||||
root: {
|
||||
path: input.path,
|
||||
...root,
|
||||
namespace_id: namespaceId,
|
||||
snapshot_sha256: snapshot,
|
||||
identity_scope: "examined-metadata-and-read-ranges",
|
||||
},
|
||||
files,
|
||||
omissions,
|
||||
...projectDesktopApplication(files),
|
||||
coverage,
|
||||
limitations,
|
||||
};
|
||||
return { report, ...(failure === undefined ? {} : { failure }) };
|
||||
};
|
||||
|
||||
const fileRow = (
|
||||
entry: DirectoryArtifactEntry,
|
||||
rootNamespaceId: string,
|
||||
): DesktopFile => {
|
||||
const source = entry.sourceIdentity;
|
||||
const identity =
|
||||
source === undefined
|
||||
? null
|
||||
: {
|
||||
device: source.device.toString(),
|
||||
inode: source.inode.toString(),
|
||||
size: source.size.toString(),
|
||||
mode: source.mode.toString(),
|
||||
mtime_ns: source.mtimeNs.toString(),
|
||||
ctime_ns: source.ctimeNs.toString(),
|
||||
};
|
||||
const semantic = {
|
||||
root_namespace_id: rootNamespaceId,
|
||||
path: entry.path,
|
||||
kind: entry.kind,
|
||||
identity,
|
||||
};
|
||||
return {
|
||||
file_id: `dsf_${digestCanonicalValue(semantic, "Desktop directory entry")}`,
|
||||
path: entry.path,
|
||||
local_path: entry.adapterKey,
|
||||
kind: entry.kind,
|
||||
bytes: entry.declaredSize,
|
||||
identity,
|
||||
read_status: "not-selected",
|
||||
ranges: [],
|
||||
facts: [],
|
||||
issues: [],
|
||||
};
|
||||
};
|
||||
|
||||
const addPathFacts = (row: DesktopFile): string | null => {
|
||||
const conventions = desktopPathConventions(row.path);
|
||||
if (conventions.electronArchive)
|
||||
row.facts.push({
|
||||
kind: "electron-asar-convention",
|
||||
offset: null,
|
||||
value: row.path,
|
||||
});
|
||||
if (conventions.unrealContainer)
|
||||
row.facts.push({
|
||||
kind: "unreal-container-convention",
|
||||
offset: null,
|
||||
value: row.path,
|
||||
});
|
||||
if (conventions.il2cppLibrary)
|
||||
row.facts.push({
|
||||
kind: "il2cpp-library-convention",
|
||||
offset: null,
|
||||
value: row.path,
|
||||
});
|
||||
return conventions.unityManagedDirectory;
|
||||
};
|
||||
|
||||
const probeSelected = (entry: DirectoryArtifactEntry): boolean =>
|
||||
entry.executable ||
|
||||
/(?:\.(?:exe|dll|so|dylib|pck|utoc)|(?:^|\/)global-metadata\.dat|(?:^|\/)data\.win)$/iu.test(
|
||||
entry.path,
|
||||
);
|
||||
@@ -0,0 +1,358 @@
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
import type { DesktopFile, DesktopFact } from "../domain/desktopApplication.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonStringByteLength } from "../domain/jsonStringByteLength.js";
|
||||
import { parsePeRecord, peRvaToFileOffset } from "../domain/binaryTarget.js";
|
||||
import { readManagedMetadataLayout } from "../dotnet/ManagedMetadataLayout.js";
|
||||
import { readAssemblyReferenceName } from "../dotnet/ManagedMetadataInventoryRows.js";
|
||||
import { ManagedReaderFailure } from "../dotnet/ManagedReaderFailure.js";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import { abortIfNeeded } from "./ArtifactHash.js";
|
||||
import { hasMachoMagic } from "./apple/MachoLoadCommandReader.js";
|
||||
|
||||
export interface DesktopReadBudget {
|
||||
bytes: number;
|
||||
readonly maximum: number;
|
||||
retainedBytes: number;
|
||||
readonly maximumRetainedBytes: number;
|
||||
}
|
||||
|
||||
/** A resource refusal is separate from malformed format declarations. */
|
||||
class DesktopProbeLimit extends ArtifactReaderFailure {
|
||||
constructor() {
|
||||
super("limit", "Directory probe byte budget exhausted", {
|
||||
boundary: "capacity",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Count the producer-owned, shallow fact shape without expanding target strings. */
|
||||
const factJsonBytes = (value: JsonValue): number => {
|
||||
if (typeof value === "string") return jsonStringByteLength(value);
|
||||
if (Array.isArray(value)) {
|
||||
let bytes = 2 + Math.max(0, value.length - 1);
|
||||
for (const child of value) bytes += factJsonBytes(child);
|
||||
return bytes;
|
||||
}
|
||||
if (value !== null && typeof value === "object") {
|
||||
const entries = Object.entries(value);
|
||||
let bytes = 2 + Math.max(0, entries.length - 1);
|
||||
for (const [key, child] of entries)
|
||||
bytes += jsonStringByteLength(key) + 1 + factJsonBytes(child);
|
||||
return bytes;
|
||||
}
|
||||
return String(value).length;
|
||||
};
|
||||
|
||||
/** Inspect selected ranges on an already admitted descriptor; never hash payloads. */
|
||||
export const inspectDesktopFile = async (
|
||||
file: FileHandle,
|
||||
row: DesktopFile,
|
||||
budget: DesktopReadBudget,
|
||||
signal?: AbortSignal,
|
||||
unityManagedDirectory: string | null = null,
|
||||
): Promise<void> => {
|
||||
const size = row.bytes;
|
||||
if (size === null)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"File extent exceeds exact host offsets",
|
||||
{ boundary: "file-size" },
|
||||
);
|
||||
const read = async (offset: number, bytes: number): Promise<Buffer> => {
|
||||
abortIfNeeded(signal);
|
||||
if (
|
||||
!Number.isSafeInteger(offset) ||
|
||||
offset < 0 ||
|
||||
!Number.isSafeInteger(bytes) ||
|
||||
bytes < 0 ||
|
||||
offset > size ||
|
||||
bytes > size - offset
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"Declared byte range lies outside the file",
|
||||
);
|
||||
if (bytes > budget.maximum - budget.bytes) throw new DesktopProbeLimit();
|
||||
const result = Buffer.alloc(bytes);
|
||||
let consumed = 0;
|
||||
while (consumed < bytes) {
|
||||
abortIfNeeded(signal);
|
||||
const part = await file.read(
|
||||
result,
|
||||
consumed,
|
||||
bytes - consumed,
|
||||
offset + consumed,
|
||||
);
|
||||
budget.bytes += part.bytesRead;
|
||||
if (part.bytesRead === 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"File ended before its observed extent",
|
||||
);
|
||||
consumed += part.bytesRead;
|
||||
}
|
||||
abortIfNeeded(signal);
|
||||
row.ranges.push({
|
||||
offset,
|
||||
bytes,
|
||||
sha256: createHash("sha256").update(result).digest("hex"),
|
||||
});
|
||||
return result;
|
||||
};
|
||||
const fact = (observation: DesktopFact) => {
|
||||
const reservation = 512 + factJsonBytes(observation.value) * 12;
|
||||
if (reservation > budget.maximumRetainedBytes - budget.retainedBytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Directory facts reached the retained metadata budget",
|
||||
{ boundary: "memory" },
|
||||
);
|
||||
budget.retainedBytes += reservation;
|
||||
row.facts.push(observation);
|
||||
};
|
||||
const prefix = await read(0, Math.min(size, 64));
|
||||
if (prefix.length >= 8 && prefix.readUInt32LE(0) === 0xfab11baf)
|
||||
fact({
|
||||
kind: "il2cpp-metadata-header",
|
||||
offset: 0,
|
||||
value: {
|
||||
magic: "0xfab11baf",
|
||||
raw_version: prefix.readUInt32LE(4),
|
||||
},
|
||||
});
|
||||
if (prefix.length >= 20 && prefix.toString("latin1", 0, 4) === "GDPC")
|
||||
fact({
|
||||
kind: "godot-pck-header",
|
||||
offset: 0,
|
||||
value: {
|
||||
pack_version: prefix.readUInt32LE(4),
|
||||
engine_version: [
|
||||
prefix.readUInt32LE(8),
|
||||
prefix.readUInt32LE(12),
|
||||
prefix.readUInt32LE(16),
|
||||
],
|
||||
placement: "standalone",
|
||||
},
|
||||
});
|
||||
if (
|
||||
prefix.length >= 16 &&
|
||||
prefix.toString("latin1", 0, 4) === "FORM" &&
|
||||
prefix.toString("latin1", 8, 12) === "GEN8"
|
||||
) {
|
||||
const containerBytes = prefix.readUInt32LE(4);
|
||||
const chunkBytes = prefix.readUInt32LE(12);
|
||||
if (
|
||||
containerBytes >= 8 &&
|
||||
containerBytes <= size - 8 &&
|
||||
chunkBytes <= containerBytes - 8
|
||||
)
|
||||
fact({
|
||||
kind: "gamemaker-form-header",
|
||||
offset: 0,
|
||||
value: {
|
||||
container: "FORM",
|
||||
first_chunk: "GEN8",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (
|
||||
prefix.length >= 16 &&
|
||||
prefix.toString("latin1", 0, 16) === "-==--==--==--==-"
|
||||
)
|
||||
fact({
|
||||
kind: "unreal-container-convention",
|
||||
offset: 0,
|
||||
value: { format: "IoStore TOC" },
|
||||
});
|
||||
const native =
|
||||
prefix.length >= 4 &&
|
||||
(prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) ||
|
||||
hasMachoMagic(prefix));
|
||||
if (native)
|
||||
fact({
|
||||
kind: "native-image-header",
|
||||
offset: 0,
|
||||
value: {
|
||||
format: prefix[0] === 0x7f ? "elf" : "mach-o",
|
||||
signature: prefix.subarray(0, 4).toString("hex"),
|
||||
},
|
||||
});
|
||||
const observe = async (operation: () => Promise<void>) => {
|
||||
try {
|
||||
await operation();
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
!(cause instanceof ArtifactReaderFailure) ||
|
||||
(cause.reason !== "format" && cause.reason !== "limit")
|
||||
)
|
||||
throw cause;
|
||||
if (!row.issues.includes(cause.message)) row.issues.push(cause.message);
|
||||
}
|
||||
};
|
||||
if (prefix.length === 64 && prefix.readUInt16LE(0) === 0x5a4d)
|
||||
await observe(() =>
|
||||
inspectPeFile(prefix, row, read, fact, unityManagedDirectory, signal),
|
||||
);
|
||||
if (
|
||||
(native || (prefix.length >= 2 && prefix.readUInt16LE(0) === 0x5a4d)) &&
|
||||
size >= 12
|
||||
)
|
||||
await observe(() => inspectPckTrailer(size, read, fact));
|
||||
};
|
||||
|
||||
type DesktopByteRead = (offset: number, bytes: number) => Promise<Buffer>;
|
||||
type RecordDesktopFact = (observation: DesktopFact) => void;
|
||||
|
||||
const inspectPeFile = async (
|
||||
prefix: Buffer,
|
||||
row: DesktopFile,
|
||||
read: DesktopByteRead,
|
||||
fact: RecordDesktopFact,
|
||||
unityManagedDirectory: string | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
const peOffset = prefix.readUInt32LE(0x3c);
|
||||
const coff = await read(peOffset, 24);
|
||||
if (coff.toString("latin1", 0, 4) !== "PE\0\0") return;
|
||||
const optionalSize = coff.readUInt16LE(20);
|
||||
if (optionalSize > 4096)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"PE optional header exceeds the supported format bound",
|
||||
);
|
||||
const optional = await read(peOffset + 24, optionalSize);
|
||||
const parsed = parsePeRecord(Buffer.concat([coff, optional]), undefined);
|
||||
if (!parsed.ok) {
|
||||
row.issues.push(parsed.error);
|
||||
return;
|
||||
}
|
||||
if (parsed.value.format !== "pe") return;
|
||||
fact({
|
||||
kind: "native-image-header",
|
||||
offset: peOffset,
|
||||
value: { format: "pe", machine: coff.readUInt16LE(4) },
|
||||
});
|
||||
if (!parsed.value.managed) return;
|
||||
const directories = optional.readUInt16LE(0) === 0x20b ? 112 : 96;
|
||||
const cliRva = optional.readUInt32LE(directories + 14 * 8);
|
||||
const cliSize = optional.readUInt32LE(directories + 14 * 8 + 4);
|
||||
fact({
|
||||
kind: "pe-cli-directory",
|
||||
offset: peOffset + 24 + directories + 14 * 8,
|
||||
value: { rva: cliRva, bytes: cliSize },
|
||||
});
|
||||
if (unityManagedDirectory === null) return;
|
||||
const sectionCount = coff.readUInt16LE(6);
|
||||
const sections = await read(peOffset + 24 + optionalSize, sectionCount * 40);
|
||||
const mapped = (rva: number, bytes: number) =>
|
||||
peRvaToFileOffset(
|
||||
rva,
|
||||
sections,
|
||||
sectionCount,
|
||||
optional.readUInt32LE(60),
|
||||
bytes,
|
||||
);
|
||||
const cliOffset = mapped(cliRva, 16);
|
||||
if (cliOffset === undefined || cliSize < 72)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"CLI metadata directory cannot be mapped",
|
||||
);
|
||||
const cli = await read(cliOffset, 16);
|
||||
if (cli.readUInt32LE(0) < 72)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"CLI header declares a truncated runtime header",
|
||||
);
|
||||
const metadataBytes = cli.readUInt32LE(12);
|
||||
const metadataOffset = mapped(cli.readUInt32LE(8), metadataBytes);
|
||||
if (metadataOffset === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"CLI metadata range cannot be mapped",
|
||||
);
|
||||
const bytes = await read(metadataOffset, metadataBytes);
|
||||
try {
|
||||
const layout = readManagedMetadataLayout(bytes, 0, bytes.length);
|
||||
const refs = layout.table(35);
|
||||
for (let index = 1; index <= (refs?.rowCount ?? 0); index++) {
|
||||
// Yield between bounded batches so metadata names cannot monopolize MCP.
|
||||
if ((index - 1) % 256 === 0) {
|
||||
await setImmediate();
|
||||
abortIfNeeded(signal);
|
||||
}
|
||||
const reference = readAssemblyReferenceName(
|
||||
bytes,
|
||||
layout,
|
||||
index,
|
||||
layout.strings.size,
|
||||
);
|
||||
if (
|
||||
reference.name !== "UnityEngine" &&
|
||||
!reference.name.startsWith("UnityEngine.")
|
||||
)
|
||||
continue;
|
||||
fact({
|
||||
kind: "unity-assembly-reference",
|
||||
offset: metadataOffset + reference.row_offset,
|
||||
value: {
|
||||
name: reference.name,
|
||||
token: reference.token,
|
||||
managed_directory: unityManagedDirectory,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ManagedReaderFailure)) throw cause;
|
||||
throw new ArtifactReaderFailure(
|
||||
cause.issue.code === "resource-limit" ? "limit" : "format",
|
||||
cause.message,
|
||||
{
|
||||
cause,
|
||||
...(cause.issue.code === "resource-limit"
|
||||
? { boundary: "memory" as const }
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const inspectPckTrailer = async (
|
||||
size: number,
|
||||
read: DesktopByteRead,
|
||||
fact: RecordDesktopFact,
|
||||
): Promise<void> => {
|
||||
const trailer = await read(size - 12, 12);
|
||||
if (trailer.toString("latin1", 8, 12) === "GDPC") {
|
||||
const packSize = trailer.readBigUInt64LE(0);
|
||||
if (packSize < 20n || packSize > BigInt(size - 12))
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"Embedded PCK trailer declares an invalid pack extent",
|
||||
);
|
||||
const offset = size - 12 - Number(packSize);
|
||||
const header = await read(offset, 20);
|
||||
if (header.toString("latin1", 0, 4) !== "GDPC")
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
"Embedded PCK trailer does not locate a pack header",
|
||||
);
|
||||
fact({
|
||||
kind: "godot-pck-header",
|
||||
offset,
|
||||
value: {
|
||||
pack_version: header.readUInt32LE(4),
|
||||
engine_version: [
|
||||
header.readUInt32LE(8),
|
||||
header.readUInt32LE(12),
|
||||
header.readUInt32LE(16),
|
||||
],
|
||||
placement: "embedded-trailer",
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -21,6 +21,26 @@ import { hostExecutableMarking } from "./hostExecutableMarking.js";
|
||||
import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { readArtifactFileChunks } from "./readArtifactFileChunks.js";
|
||||
import {
|
||||
withOwnedFileHandle,
|
||||
RegularFileCleanupFailure,
|
||||
RegularFileCancelled,
|
||||
} from "../filesystem/OwnedRegularFile.js";
|
||||
import { RegularFileOperationCancelled } from "../filesystem/RegularFile.js";
|
||||
import {
|
||||
ArtifactFileCancelled,
|
||||
ArtifactFileCleanupFailure,
|
||||
} from "./ArtifactFileOperation.js";
|
||||
import { AnalysisCleanupLease } from "./AnalysisCleanupLease.js";
|
||||
|
||||
export type DirectoryArtifactEntry = ArtifactEntry & {
|
||||
readonly kind: "file" | "directory" | "symlink";
|
||||
};
|
||||
|
||||
interface DirectoryArtifactRoot {
|
||||
readonly canonicalPath: string;
|
||||
readonly identity: { readonly dev: bigint; readonly ino: bigint };
|
||||
}
|
||||
|
||||
interface DirectoryTraversalOptions extends ArtifactTraversalOptions {
|
||||
readonly descendInto?: (path: string) => boolean;
|
||||
@@ -43,11 +63,11 @@ export class DirectoryArtifactTraversalLimit extends ArtifactReaderFailure {
|
||||
/** Non-symlink-following directory reader. */
|
||||
export class DirectoryArtifactReader implements ArtifactReader {
|
||||
readonly format = "directory" as const;
|
||||
#rootPromise: Promise<string> | undefined;
|
||||
#rootIdentity: { readonly dev: bigint; readonly ino: bigint } | undefined;
|
||||
#rootPromise: Promise<DirectoryArtifactRoot> | undefined;
|
||||
readonly #rootPath: string;
|
||||
readonly #directories = new Set<OwnedDirectoryHandle>();
|
||||
readonly #files = new Map<OwnedFileHandle, string>();
|
||||
readonly #fileCleanup = new WeakMap<OwnedFileHandle, AnalysisCleanupLease>();
|
||||
|
||||
constructor(root: string) {
|
||||
this.#rootPath = root;
|
||||
@@ -57,8 +77,9 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
async *entries(
|
||||
signal?: AbortSignal,
|
||||
selection?: DirectoryTraversalOptions | ((path: string) => boolean),
|
||||
): AsyncIterable<ArtifactEntry> {
|
||||
const root = await this.#resolveRoot();
|
||||
): AsyncIterable<DirectoryArtifactEntry> {
|
||||
const admittedRoot = await this.#resolveRoot();
|
||||
const root = admittedRoot.canonicalPath;
|
||||
const options =
|
||||
typeof selection === "function" ? { descendInto: selection } : selection;
|
||||
const maximum = options?.maximumEntries;
|
||||
@@ -81,7 +102,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
const directory = pending.pop();
|
||||
if (directory === undefined) break;
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory, this.#rootIdentity),
|
||||
assertContainedDirectory(root, directory, admittedRoot.identity),
|
||||
);
|
||||
for await (const entry of this.#readDirectory(
|
||||
directory,
|
||||
@@ -92,22 +113,34 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
))
|
||||
yield entry;
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory, this.#rootIdentity),
|
||||
assertContainedDirectory(root, directory, admittedRoot.identity),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async #resolveRoot(): Promise<string> {
|
||||
/** Admission facts, shared with traversal; the selected root may be a symlink. */
|
||||
rootObservation(): Promise<DirectoryArtifactRoot> {
|
||||
return this.#resolveRoot();
|
||||
}
|
||||
|
||||
async #resolveRoot(): Promise<DirectoryArtifactRoot> {
|
||||
return (this.#rootPromise ??= (async () => {
|
||||
const root = await realpath(this.#rootPath);
|
||||
const metadata = await lstat(root, { bigint: true });
|
||||
if (metadata.isSymbolicLink() || !metadata.isDirectory())
|
||||
if (metadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Artifact root changed during traversal",
|
||||
);
|
||||
this.#rootIdentity = { dev: metadata.dev, ino: metadata.ino };
|
||||
return root;
|
||||
if (!metadata.isDirectory())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Artifact root must be a directory",
|
||||
);
|
||||
return Object.freeze({
|
||||
canonicalPath: root,
|
||||
identity: Object.freeze({ dev: metadata.dev, ino: metadata.ino }),
|
||||
});
|
||||
})().catch((cause: unknown) => {
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
throw directoryIoFailure("resolve artifact root", this.#rootPath, cause);
|
||||
@@ -120,8 +153,9 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
signal: AbortSignal | undefined,
|
||||
options: DirectoryTraversalOptions | undefined,
|
||||
examine: () => void,
|
||||
): AsyncIterable<ArtifactEntry> {
|
||||
const root = await this.#resolveRoot();
|
||||
): AsyncIterable<DirectoryArtifactEntry> {
|
||||
const admittedRoot = await this.#resolveRoot();
|
||||
const root = admittedRoot.canonicalPath;
|
||||
const handle = new OwnedDirectoryHandle(
|
||||
await opendir(directory).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open directory", directory, cause);
|
||||
@@ -137,7 +171,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
try {
|
||||
for (;;) {
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory, this.#rootIdentity),
|
||||
assertContainedDirectory(root, directory, admittedRoot.identity),
|
||||
);
|
||||
const child = await handle.handle.read();
|
||||
if (child === null) break;
|
||||
@@ -199,7 +233,10 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
|
||||
async #openFile(
|
||||
entry: ArtifactEntry,
|
||||
signal?: AbortSignal,
|
||||
): Promise<OwnedFileHandle<FileHandle>> {
|
||||
abortIfNeeded(signal);
|
||||
if (entry.kind !== "file")
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -234,14 +271,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
);
|
||||
}
|
||||
abortIfNeeded(signal);
|
||||
const source = Readable.from(
|
||||
mapStableFileRead(owner.handle, entry, signal),
|
||||
{ objectMode: false },
|
||||
);
|
||||
source.once("close", () => {
|
||||
void this.#closeFile(owner).catch(() => undefined);
|
||||
});
|
||||
return source;
|
||||
return owner;
|
||||
} catch (cause: unknown) {
|
||||
try {
|
||||
await this.#closeFile(owner);
|
||||
@@ -262,11 +292,89 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
/** Borrow an admitted entry for bounded random reads; retain failed cleanup. */
|
||||
async inspectFile<Value>(
|
||||
entry: ArtifactEntry,
|
||||
inspect: (file: FileHandle) => Promise<Value>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Value> {
|
||||
const owner = await this.#openFile(entry, signal);
|
||||
try {
|
||||
const value = await withOwnedFileHandle(
|
||||
entry.adapterKey,
|
||||
owner,
|
||||
signal === undefined ? {} : { signal },
|
||||
async (file) => {
|
||||
let outcome:
|
||||
| { kind: "completed"; value: Value }
|
||||
| { kind: "failed"; cause: unknown };
|
||||
try {
|
||||
outcome = { kind: "completed", value: await inspect(file) };
|
||||
} catch (cause: unknown) {
|
||||
outcome = { kind: "failed", cause };
|
||||
}
|
||||
const [opened, named] = await Promise.all([
|
||||
file.stat({ bigint: true }),
|
||||
lstat(entry.adapterKey, { bigint: true }),
|
||||
]);
|
||||
abortIfNeeded(signal);
|
||||
if (
|
||||
!opened.isFile() ||
|
||||
!named.isFile() ||
|
||||
!sameArtifactSourceIdentity(entry.sourceIdentity, opened) ||
|
||||
!sameArtifactSourceIdentity(entry.sourceIdentity, named)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Directory entry changed during inspection: ${entry.path}`,
|
||||
);
|
||||
if (outcome.kind === "failed") throw outcome.cause;
|
||||
return outcome.value;
|
||||
},
|
||||
);
|
||||
this.#files.delete(owner);
|
||||
return value;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) {
|
||||
const lease = new AnalysisCleanupLease(
|
||||
() => this.#closeFile(owner),
|
||||
[entry.adapterKey],
|
||||
);
|
||||
this.#fileCleanup.set(owner, lease);
|
||||
throw new ArtifactFileCleanupFailure(cause, lease);
|
||||
}
|
||||
this.#files.delete(owner);
|
||||
if (cause instanceof RegularFileCancelled)
|
||||
throw new ArtifactFileCancelled(cause);
|
||||
if (cause instanceof RegularFileOperationCancelled)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Directory inspection cancelled",
|
||||
{ cause: cause.reason },
|
||||
);
|
||||
throw directoryIoFailure("inspect entry", entry.adapterKey, cause);
|
||||
}
|
||||
}
|
||||
|
||||
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
|
||||
const owner = await this.#openFile(entry, signal);
|
||||
const source = Readable.from(
|
||||
mapStableFileRead(owner.handle, entry, signal),
|
||||
{ objectMode: false },
|
||||
);
|
||||
source.once("close", () => {
|
||||
void this.#closeFile(owner).catch(() => undefined);
|
||||
});
|
||||
return source;
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const failures: unknown[] = [];
|
||||
for (const [owner, path] of this.#files) {
|
||||
try {
|
||||
await this.#closeFile(owner);
|
||||
const lease = this.#fileCleanup.get(owner);
|
||||
if (lease === undefined) await this.#closeFile(owner);
|
||||
else await lease.release();
|
||||
} catch (cause: unknown) {
|
||||
failures.push(directoryIoFailure("close opened entry", path, cause));
|
||||
}
|
||||
@@ -303,6 +411,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
async #closeFile(owner: OwnedFileHandle<FileHandle>): Promise<void> {
|
||||
await owner.close();
|
||||
this.#files.delete(owner);
|
||||
this.#fileCleanup.delete(owner);
|
||||
}
|
||||
|
||||
provenance(): readonly [] {
|
||||
@@ -327,7 +436,7 @@ const artifactEntry = (
|
||||
path: string,
|
||||
absolute: string,
|
||||
metadata: BigIntStats,
|
||||
): ArtifactEntry | undefined => {
|
||||
): DirectoryArtifactEntry | undefined => {
|
||||
const kind = metadata.isSymbolicLink()
|
||||
? "symlink"
|
||||
: metadata.isDirectory()
|
||||
|
||||
Reference in new issue
Block a user