fix: resolve triaged correctness issues
This commit is contained in:
@@ -95,11 +95,11 @@ export class AnalysisSnapshotCache {
|
||||
this.#target.architecture !== snapshot.target.architecture)
|
||||
)
|
||||
this.#entries.clear();
|
||||
this.#target = snapshot.target;
|
||||
this.#target = structuredClone(snapshot.target);
|
||||
let imported = 0;
|
||||
for (const entry of snapshot.entries) {
|
||||
if (!this.#entries.has(entry.query_id)) imported += 1;
|
||||
this.#entries.set(entry.query_id, entry);
|
||||
this.#entries.set(entry.query_id, structuredClone(entry));
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
@@ -114,7 +114,7 @@ export class AnalysisSnapshotCache {
|
||||
snapshot_version: 1,
|
||||
target: snapshotTarget(target),
|
||||
entries: this.entries(),
|
||||
evidence_bundle: evidenceBundle,
|
||||
evidence_bundle: structuredClone(evidenceBundle),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -138,9 +138,9 @@ export class AnalysisSnapshotCache {
|
||||
|
||||
/** Return canonical entries for persistence. */
|
||||
entries(): AnalysisSnapshotEntry[] {
|
||||
return [...this.#entries.values()].sort((left, right) =>
|
||||
left.query_id.localeCompare(right.query_id),
|
||||
);
|
||||
return [...this.#entries.values()]
|
||||
.sort((left, right) => left.query_id.localeCompare(right.query_id))
|
||||
.map((entry) => structuredClone(entry));
|
||||
}
|
||||
|
||||
/** Replay an exact provider-specific query, marking its cached provenance. */
|
||||
@@ -159,7 +159,7 @@ export class AnalysisSnapshotCache {
|
||||
const cached = this.#entries.get(queryId);
|
||||
if (cached === undefined) return undefined;
|
||||
const subject = cached.execution.subject;
|
||||
return {
|
||||
return structuredClone({
|
||||
result: cached.execution.result,
|
||||
rawResult: cached.execution.raw_result,
|
||||
provider: cached.execution.provider,
|
||||
@@ -183,7 +183,7 @@ export class AnalysisSnapshotCache {
|
||||
format: subject.format,
|
||||
architecture: subject.architecture,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Record one successful immutable call unless the cache is full. */
|
||||
|
||||
@@ -30,6 +30,17 @@ export interface MutableOccurrence {
|
||||
limitations: string[];
|
||||
}
|
||||
|
||||
/** Index the first occurrence for each canonical logical path. */
|
||||
export const indexOccurrencesByPath = (
|
||||
occurrences: readonly MutableOccurrence[],
|
||||
): ReadonlyMap<string, MutableOccurrence> => {
|
||||
const byPath = new Map<string, MutableOccurrence>();
|
||||
for (const occurrence of occurrences)
|
||||
if (!byPath.has(occurrence.logical_path))
|
||||
byPath.set(occurrence.logical_path, occurrence);
|
||||
return byPath;
|
||||
};
|
||||
|
||||
export const createOccurrence = (
|
||||
entry: ArtifactEntry,
|
||||
path: string,
|
||||
@@ -196,6 +207,7 @@ export const createArtifactEdges = (
|
||||
producer?: ArtifactCommand,
|
||||
): ArtifactEdge[] => {
|
||||
const byId = new Map(occurrences.map((item) => [item.occurrence_id, item]));
|
||||
const byPath = indexOccurrencesByPath(occurrences);
|
||||
const edges: ArtifactEdge[] = [];
|
||||
for (const occurrence of occurrences) {
|
||||
if (
|
||||
@@ -204,10 +216,7 @@ export const createArtifactEdges = (
|
||||
)
|
||||
continue;
|
||||
const mappedSource = occurrence.logical_path.endsWith(".map")
|
||||
? occurrences.find(
|
||||
({ logical_path: path }) =>
|
||||
path === occurrence.logical_path.slice(0, -".map".length),
|
||||
)
|
||||
? byPath.get(occurrence.logical_path.slice(0, -".map".length))
|
||||
: undefined;
|
||||
const parentArtifactId =
|
||||
mappedSource?.artifact_id ??
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
createOccurrence,
|
||||
createRootNode,
|
||||
digestCanonical,
|
||||
indexOccurrencesByPath,
|
||||
materializeDirectoryNodes,
|
||||
nearestParent,
|
||||
pageOf,
|
||||
@@ -180,11 +181,10 @@ export const scanCanonicalArtifactInventory = async (
|
||||
const occurrenceById = new Map(
|
||||
occurrences.map((occurrence) => [occurrence.occurrence_id, occurrence]),
|
||||
);
|
||||
const occurrenceByPath = indexOccurrencesByPath(occurrences);
|
||||
const integrityContradictions = pendingContradictions.map(
|
||||
(contradiction): IntegrityContradiction => {
|
||||
const occurrence = occurrences.find(
|
||||
({ logical_path: path }) => path === contradiction.logicalPath,
|
||||
);
|
||||
const occurrence = occurrenceByPath.get(contradiction.logicalPath);
|
||||
if (occurrence === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
|
||||
@@ -113,7 +113,7 @@ export class BinarySession implements BinarySessionPort {
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity {
|
||||
if (operation !== undefined) {
|
||||
const exact = this.#capabilities?.get(operation)?.provider;
|
||||
if (exact !== undefined) return exact;
|
||||
if (exact !== undefined) return structuredClone(exact);
|
||||
if (enhancedToolNameSchema.safeParse(operation).success) {
|
||||
const providers = new Map<string, ProviderIdentity>();
|
||||
for (const descriptor of this.#capabilities?.values() ?? [])
|
||||
@@ -124,11 +124,11 @@ export class BinarySession implements BinarySessionPort {
|
||||
providers.set(descriptor.provider.id, descriptor.provider);
|
||||
if (providers.size === 1) {
|
||||
const provider = providers.values().next().value;
|
||||
if (provider !== undefined) return provider;
|
||||
if (provider !== undefined) return structuredClone(provider);
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.#providerIdentity;
|
||||
return structuredClone(this.#providerIdentity);
|
||||
}
|
||||
|
||||
/** Observe runtime provider-health changes that affect discovery metadata. */
|
||||
@@ -223,18 +223,21 @@ export class BinarySession implements BinarySessionPort {
|
||||
workspaceId: string,
|
||||
revision: number,
|
||||
): InvestigationWorkspace | undefined {
|
||||
return this.#investigationWorkspaces.get(
|
||||
const workspace = this.#investigationWorkspaces.get(
|
||||
`${workspaceId}:${String(revision)}`,
|
||||
);
|
||||
return workspace === undefined ? undefined : structuredClone(workspace);
|
||||
}
|
||||
|
||||
/** List retained workspace revisions in canonical identity order. */
|
||||
investigationWorkspaces(): readonly InvestigationWorkspace[] {
|
||||
return [...this.#investigationWorkspaces.values()].sort(
|
||||
(left, right) =>
|
||||
left.workspace_id.localeCompare(right.workspace_id) ||
|
||||
left.revision - right.revision,
|
||||
);
|
||||
return [...this.#investigationWorkspaces.values()]
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.workspace_id.localeCompare(right.workspace_id) ||
|
||||
left.revision - right.revision,
|
||||
)
|
||||
.map((workspace) => structuredClone(workspace));
|
||||
}
|
||||
|
||||
/** Create an approved residual unknown and immutable mutation evidence. */
|
||||
@@ -468,7 +471,9 @@ export class BinarySession implements BinarySessionPort {
|
||||
|
||||
/** Return the immutable artifact identity captured before Hopper launched. */
|
||||
activeTarget(): BinaryTarget | undefined {
|
||||
return this.#active?.target;
|
||||
return this.#active === undefined
|
||||
? undefined
|
||||
: structuredClone(this.#active.target);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -122,9 +122,11 @@ export class EvidenceLedger {
|
||||
|
||||
/** Export records in deterministic, semantically irrelevant ID order. */
|
||||
export(): EvidenceBundle {
|
||||
return createEvidenceBundle(
|
||||
[...this.#records.values()],
|
||||
[...this.#unknownRevisions.values()],
|
||||
return structuredClone(
|
||||
createEvidenceBundle(
|
||||
[...this.#records.values()],
|
||||
[...this.#unknownRevisions.values()],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -232,7 +234,7 @@ export class EvidenceLedger {
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(unknown);
|
||||
return ok(structuredClone(unknown));
|
||||
}
|
||||
|
||||
/** Apply one approved full-state update using optimistic revision matching. */
|
||||
@@ -277,7 +279,8 @@ export class EvidenceLedger {
|
||||
unknown.severity === filters.severity) &&
|
||||
(filters.domain === undefined || unknown.domain === filters.domain),
|
||||
)
|
||||
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id));
|
||||
.sort((left, right) => left.unknown_id.localeCompare(right.unknown_id))
|
||||
.map((unknown) => structuredClone(unknown));
|
||||
}
|
||||
|
||||
/** Return current resolution validity; imported invalid states are rejected. */
|
||||
@@ -295,7 +298,7 @@ export class EvidenceLedger {
|
||||
return ok({
|
||||
valid: unknown.status === "resolved",
|
||||
truthVerified: unknown.resolution?.disposition === "verified",
|
||||
unknown,
|
||||
unknown: structuredClone(unknown),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -331,7 +334,7 @@ export class EvidenceLedger {
|
||||
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
|
||||
if (!checked.ok) return checked;
|
||||
this.#commit(pendingRecords, pendingUnknowns, checked.value);
|
||||
return ok(unknown);
|
||||
return ok(structuredClone(unknown));
|
||||
}
|
||||
|
||||
#validateCandidate(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { IPty } from "node-pty";
|
||||
@@ -401,6 +401,7 @@ export const prepareProcessCapture = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal: AbortSignal | undefined,
|
||||
host: ProcessPreparationHost = systemProcessPreparationHost,
|
||||
): Promise<{
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
@@ -416,11 +417,29 @@ export const prepareProcessCapture = async (
|
||||
await assertRealPathAuthority(scenario, policy);
|
||||
assertNotCancelled(signal);
|
||||
const before = await snapshotRoots(scenario, signal);
|
||||
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
|
||||
const runId = randomUUID();
|
||||
const home = join(temporaryRoot, "home");
|
||||
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
|
||||
return { temporaryRoot, runId, home, before };
|
||||
const temporaryRoot = await host.createTemporaryRoot();
|
||||
try {
|
||||
const runId = randomUUID();
|
||||
const home = join(temporaryRoot, "home");
|
||||
await host.createHome(home);
|
||||
return { temporaryRoot, runId, home, before };
|
||||
} catch (cause: unknown) {
|
||||
await host.cleanup(temporaryRoot);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Filesystem seam for allocating and cleaning a capture's private home. */
|
||||
export interface ProcessPreparationHost {
|
||||
createTemporaryRoot(): Promise<string>;
|
||||
createHome(path: string): Promise<void>;
|
||||
cleanup(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemProcessPreparationHost: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => mkdtemp(join(tmpdir(), "rea-process-")),
|
||||
createHome: (path) => mkdir(path),
|
||||
cleanup: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
|
||||
const processPolicyMessage = (
|
||||
|
||||
@@ -126,7 +126,7 @@ export class ProcessCheckpoints {
|
||||
effects: classifyFilesystemEffects(previous, after.files),
|
||||
truncated: after.truncated,
|
||||
});
|
||||
return this.#captures;
|
||||
return structuredClone(this.#captures);
|
||||
}
|
||||
|
||||
/** Cancel scheduled captures and await any snapshot already in progress. */
|
||||
|
||||
@@ -112,7 +112,12 @@ export const compareProcessEvidenceFiles = async (
|
||||
};
|
||||
|
||||
const parseCaptureEvidence = (input: unknown) => {
|
||||
const evidence = parseEvidence(input);
|
||||
let evidence;
|
||||
try {
|
||||
evidence = parseEvidence(input);
|
||||
} catch {
|
||||
throw invalidCaptureEvidence();
|
||||
}
|
||||
if (
|
||||
evidence.operation !== "capture_process_scenario" ||
|
||||
evidence.predicate_type !== "rea.process-capture/v4" ||
|
||||
@@ -129,12 +134,22 @@ const parseCaptureEvidence = (input: unknown) => {
|
||||
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
id: evidence.evidence_id,
|
||||
capture: parseProcessCapture(evidence.normalized_result),
|
||||
};
|
||||
try {
|
||||
return {
|
||||
id: evidence.evidence_id,
|
||||
capture: parseProcessCapture(evidence.normalized_result),
|
||||
};
|
||||
} catch {
|
||||
throw invalidCaptureEvidence();
|
||||
}
|
||||
};
|
||||
|
||||
const invalidCaptureEvidence = (): ProcessCliFailure =>
|
||||
new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Capture evidence is malformed. Create new capture evidence, then try again.",
|
||||
);
|
||||
|
||||
const readJson = async (path: string): Promise<unknown> => {
|
||||
let bytes;
|
||||
try {
|
||||
|
||||
@@ -31,7 +31,7 @@ export const normalizeProcessText = (
|
||||
);
|
||||
}
|
||||
if (scenario.normalization.pids)
|
||||
normalized = normalized.replaceAll(String(pid), "<pid>");
|
||||
normalized = normalizePidTokens(normalized, [pid]);
|
||||
if (scenario.normalization.ports)
|
||||
normalized = normalized.replaceAll(/(?<=[:=])\d{2,5}\b/g, "<port>");
|
||||
for (const pattern of scenario.normalization.patterns)
|
||||
@@ -57,6 +57,17 @@ export const normalizeProcessSamples = (
|
||||
for (const identifier of identifiers)
|
||||
if (identifier > 0 && !mapping.has(identifier))
|
||||
mapping.set(identifier, mapping.size + 1);
|
||||
const normalizeCommand = (command: string): string => {
|
||||
const normalized = normalizeProcessText(
|
||||
command,
|
||||
scenario,
|
||||
"<no-temporary-root>",
|
||||
rootPid,
|
||||
);
|
||||
return scenario.normalization.pids
|
||||
? normalizePidTokens(normalized, identifiers)
|
||||
: normalized;
|
||||
};
|
||||
return samples.map((sample) => ({
|
||||
at_ms:
|
||||
Math.floor(sample.at_ms / scenario.normalization.time_bucket_ms) *
|
||||
@@ -69,15 +80,25 @@ export const normalizeProcessSamples = (
|
||||
: (mapping.get(sample.process_group_id) ?? 0),
|
||||
session_id:
|
||||
sample.session_id === null ? null : (mapping.get(sample.session_id) ?? 0),
|
||||
command: normalizeProcessText(
|
||||
sample.command,
|
||||
scenario,
|
||||
"<no-temporary-root>",
|
||||
rootPid,
|
||||
),
|
||||
command: normalizeCommand(sample.command),
|
||||
}));
|
||||
};
|
||||
|
||||
const normalizePidTokens = (
|
||||
value: string,
|
||||
identifiers: readonly number[],
|
||||
): string => {
|
||||
const tokens = [...new Set(identifiers)]
|
||||
.filter((identifier) => Number.isSafeInteger(identifier) && identifier > 0)
|
||||
.sort((left, right) => right - left)
|
||||
.map(String);
|
||||
if (tokens.length === 0) return value;
|
||||
return value.replace(
|
||||
new RegExp(`(?<!\\d)(?:${tokens.join("|")})(?!\\d)`, "gu"),
|
||||
"<pid>",
|
||||
);
|
||||
};
|
||||
|
||||
export const redactProtocolEvents = (
|
||||
events: readonly ProcessCapture["protocol_events"][number][],
|
||||
scenario: ProcessScenario,
|
||||
|
||||
@@ -40,11 +40,14 @@ export type ProcessGroupObservation =
|
||||
| { readonly state: "alive" }
|
||||
| { readonly state: "unverifiable"; readonly reason: string };
|
||||
|
||||
const parseEnvironment = (value: string): Readonly<Record<string, string>> =>
|
||||
/** Parse the NUL-delimited Linux process environment without nameless keys. */
|
||||
export const parseProcessEnvironment = (
|
||||
value: string,
|
||||
): Readonly<Record<string, string>> =>
|
||||
Object.fromEntries(
|
||||
value
|
||||
.split("\0")
|
||||
.filter((entry) => entry.includes("="))
|
||||
.filter((entry) => entry.indexOf("=") > 0)
|
||||
.map((entry) => {
|
||||
const separator = entry.indexOf("=");
|
||||
return [entry.slice(0, separator), entry.slice(separator + 1)];
|
||||
@@ -72,7 +75,9 @@ const systemHost: ProcessOwnershipHost = {
|
||||
},
|
||||
async environment(pid) {
|
||||
if (process.platform === "linux") {
|
||||
return parseEnvironment(await readFile(`/proc/${pid}/environ`, "utf8"));
|
||||
return parseProcessEnvironment(
|
||||
await readFile(`/proc/${pid}/environ`, "utf8"),
|
||||
);
|
||||
}
|
||||
const { stdout } = await execFileAsync("ps", ["eww", "-p", String(pid)]);
|
||||
const environment: Record<string, string> = {};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import type { ProcessSample } from "../domain/processCapture.js";
|
||||
|
||||
@@ -104,25 +104,79 @@ const readProcessCommand = async (
|
||||
}
|
||||
};
|
||||
|
||||
const readLinuxChildren = async (
|
||||
/** Procfs reads used to enumerate children created by every process thread. */
|
||||
export interface LinuxChildrenHost {
|
||||
taskIds(
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<readonly number[] | undefined>;
|
||||
children(
|
||||
pid: number,
|
||||
taskId: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<string | undefined>;
|
||||
}
|
||||
|
||||
const systemLinuxChildrenHost: LinuxChildrenHost = {
|
||||
async taskIds(pid, signal) {
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
const entries = await readdir(`/proc/${String(pid)}/task`);
|
||||
signal.throwIfAborted();
|
||||
return entries
|
||||
.filter((entry) => /^\d+$/.test(entry))
|
||||
.map(Number)
|
||||
.filter((taskId) => Number.isSafeInteger(taskId) && taskId > 0)
|
||||
.sort((left, right) => left - right);
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
},
|
||||
async children(pid, taskId, signal) {
|
||||
try {
|
||||
return await readFile(
|
||||
`/proc/${String(pid)}/task/${String(taskId)}/children`,
|
||||
{ encoding: "utf8", signal },
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/** Read the deduplicated children created by every thread in a Linux process. */
|
||||
export const readLinuxChildren = async (
|
||||
pid: number,
|
||||
signal: AbortSignal,
|
||||
host: LinuxChildrenHost = systemLinuxChildrenHost,
|
||||
): Promise<readonly number[] | undefined> => {
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(`/proc/${String(pid)}/task/${String(pid)}/children`, {
|
||||
encoding: "utf8",
|
||||
signal,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
const taskIds = await host.taskIds(pid, signal);
|
||||
if (taskIds === undefined) return undefined;
|
||||
const children = new Set<number>();
|
||||
let successfulReads = 0;
|
||||
for (
|
||||
let offset = 0;
|
||||
offset < taskIds.length;
|
||||
offset += PROC_READ_CONCURRENCY
|
||||
) {
|
||||
const texts = await Promise.all(
|
||||
taskIds
|
||||
.slice(offset, offset + PROC_READ_CONCURRENCY)
|
||||
.map((taskId) => host.children(pid, taskId, signal)),
|
||||
);
|
||||
for (const text of texts) {
|
||||
if (text === undefined) continue;
|
||||
successfulReads += 1;
|
||||
for (const value of text.trim().split(/\s+/)) {
|
||||
if (!/^\d+$/.test(value)) continue;
|
||||
const child = Number(value);
|
||||
if (Number.isSafeInteger(child) && child > 0) children.add(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
return text
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((value) => /^\d+$/.test(value))
|
||||
.map(Number)
|
||||
.filter((child) => Number.isSafeInteger(child) && child > 0);
|
||||
return successfulReads === 0
|
||||
? undefined
|
||||
: [...children].sort((left, right) => left - right);
|
||||
};
|
||||
|
||||
const inspectProcess = async (
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, realpath, stat } from "node:fs/promises";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
stat,
|
||||
unlink,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { z } from "zod";
|
||||
@@ -49,7 +59,12 @@ export class ProjectPermissionStoreError extends Error {
|
||||
readonly _tag = "ProjectPermissionStoreError" as const;
|
||||
|
||||
constructor(
|
||||
readonly reason: "project_not_found" | "not_owner_only" | "invalid" | "io",
|
||||
readonly reason:
|
||||
| "project_not_found"
|
||||
| "not_owner_only"
|
||||
| "invalid"
|
||||
| "locked"
|
||||
| "io",
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Project permission store failed: ${reason}`, options);
|
||||
@@ -143,5 +158,114 @@ export const writeProjectPermissionStore = async (
|
||||
}
|
||||
};
|
||||
|
||||
const isNotFound = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
||||
/** Revoke one grant while serializing the complete read-modify-write cycle. */
|
||||
export const revokeProjectPermissionGrant = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
grantId: string,
|
||||
): Promise<Result<boolean, ProjectPermissionStoreError>> => {
|
||||
let lock: PermissionStoreLock | undefined;
|
||||
try {
|
||||
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const acquired = await acquirePermissionStoreLock(path);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
const current = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!current.ok) return current;
|
||||
const grants = current.value?.grants ?? [];
|
||||
const retained = grants.filter(({ grant_id }) => grant_id !== grantId);
|
||||
if (retained.length === grants.length) return ok(false);
|
||||
const written = await writeProjectPermissionStore(
|
||||
path,
|
||||
projectRoot,
|
||||
retained,
|
||||
);
|
||||
return written.ok ? ok(true) : written;
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await releasePermissionStoreLock(lock);
|
||||
}
|
||||
};
|
||||
|
||||
interface PermissionStoreLock {
|
||||
readonly path: string;
|
||||
readonly handle: FileHandle;
|
||||
}
|
||||
|
||||
const acquirePermissionStoreLock = async (
|
||||
destination: string,
|
||||
): Promise<Result<PermissionStoreLock, ProjectPermissionStoreError>> => {
|
||||
const path = `${destination}.lock`;
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
try {
|
||||
return ok(await createPermissionStoreLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (!isAlreadyExists(cause))
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
if (await removeStalePermissionStoreLock(path)) continue;
|
||||
if (attempt === 99)
|
||||
return err(new ProjectPermissionStoreError("locked", { cause }));
|
||||
await delay(10);
|
||||
}
|
||||
}
|
||||
return err(new ProjectPermissionStoreError("locked"));
|
||||
};
|
||||
|
||||
const createPermissionStoreLock = async (
|
||||
path: string,
|
||||
): Promise<PermissionStoreLock> => {
|
||||
const handle = await open(path, "wx", 0o600);
|
||||
try {
|
||||
await handle.writeFile(`${String(process.pid)}\n`, "utf8");
|
||||
await handle.sync();
|
||||
return { path, handle };
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
await unlink(path).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const removeStalePermissionStoreLock = async (
|
||||
path: string,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const metadata = await lstat(path);
|
||||
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 32)
|
||||
return false;
|
||||
const encoded = (await readFile(path, "utf8")).trim();
|
||||
if (!/^[1-9][0-9]{0,9}$/u.test(encoded)) return false;
|
||||
if (processIsAlive(Number(encoded))) return false;
|
||||
await unlink(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const processIsAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) !== "ESRCH";
|
||||
}
|
||||
};
|
||||
|
||||
const releasePermissionStoreLock = async (
|
||||
lock: PermissionStoreLock,
|
||||
): Promise<void> => {
|
||||
await lock.handle.close().catch(() => undefined);
|
||||
await unlink(lock.path).catch(() => undefined);
|
||||
};
|
||||
|
||||
const isNotFound = (cause: unknown): boolean => errorCode(cause) === "ENOENT";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "EEXIST";
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
|
||||
@@ -69,7 +69,7 @@ export class TerminalRenderer {
|
||||
/** Await all queued parsing and return immutable rendered observations. */
|
||||
async frames(): Promise<readonly RenderedTerminalFrame[]> {
|
||||
await this.#pending;
|
||||
return this.#frames;
|
||||
return structuredClone(this.#frames);
|
||||
}
|
||||
|
||||
/** Whether a rendered observation exceeded its independent capture budget. */
|
||||
|
||||
Reference in New Issue
Block a user