feat(ghidra): enable Windows x64 read-only analysis (#699)
* feat(ghidra): enable Windows x64 read-only analysis * test(ghidra): exercise native Windows runtime boundaries * test(ghidra): verify current Windows inventory and isolate ACL observer * fix(ghidra): align Windows admission and address P0 review
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
loadWindowsNativeAuthority,
|
||||
type WindowsNativeLoadHost,
|
||||
} from "./WindowsNativeLoader.js";
|
||||
|
||||
const fixture = () => {
|
||||
const bytes = Buffer.alloc(128);
|
||||
bytes.write("MZ");
|
||||
bytes.writeUInt32LE(64, 0x3c);
|
||||
bytes.write("PE\0\0", 64, "ascii");
|
||||
bytes.writeUInt16LE(0x8664, 68);
|
||||
bytes.writeUInt16LE(0x20b, 88);
|
||||
const manifest = {
|
||||
packageVersion: "1.0.0",
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
abiVersion: 1,
|
||||
nodeApiVersion: 8,
|
||||
artifact: "rea-windows-x64.node",
|
||||
artifactSha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
};
|
||||
const identity = {
|
||||
requestedPath: "D:\\fixture\\runtime",
|
||||
finalPath: "\\\\?\\D:\\fixture\\runtime",
|
||||
filesystem: "NTFS",
|
||||
volumeSerial: "0123456789abcdef",
|
||||
fileId: "0123456789abcdef0123456789abcdef",
|
||||
size: 0,
|
||||
directory: true,
|
||||
};
|
||||
let loads = 0;
|
||||
const host: WindowsNativeLoadHost = {
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
nodeApiVersion: "8",
|
||||
packageVersion: "1.0.0",
|
||||
readManifest: () => manifest,
|
||||
readArtifact: () => bytes,
|
||||
loadArtifact: () => {
|
||||
loads++;
|
||||
return {
|
||||
call: () => ({
|
||||
abiVersion: 1,
|
||||
nodeApiVersion: 8,
|
||||
architecture: "x64",
|
||||
filesystem: identity,
|
||||
privateDacl: true,
|
||||
atomicJobAssignment: true,
|
||||
killOnOwnerClose: true,
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
return { host, manifest, bytes, loads: () => loads };
|
||||
};
|
||||
|
||||
describe("packaged Windows native admission", () => {
|
||||
it("loads only after compatibility and digest checks, preserving producer identity", () => {
|
||||
const value = fixture();
|
||||
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
|
||||
available: true,
|
||||
authority: {
|
||||
inspection: { filesystem: { requestedPath: "D:\\fixture\\runtime" } },
|
||||
},
|
||||
});
|
||||
expect(value.loads()).toBe(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ platform: "linux" as const },
|
||||
{ architecture: "arm64" },
|
||||
{ nodeApiVersion: "7" },
|
||||
{ nodeApiVersion: undefined },
|
||||
{ packageVersion: "2.0.0" },
|
||||
])("rejects incompatible host metadata before loading: %j", (override) => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({ ...value.host, ...override }).available,
|
||||
).toBe(false);
|
||||
expect(value.loads()).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects tampering even when the original file was a valid PE image", () => {
|
||||
const value = fixture();
|
||||
value.bytes[127] = 1;
|
||||
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
|
||||
available: false,
|
||||
reason: expect.stringContaining("SHA-256"),
|
||||
});
|
||||
expect(value.loads()).toBe(0);
|
||||
});
|
||||
|
||||
it.each(["abiVersion", "nodeApiVersion", "architecture", "artifact"])(
|
||||
"rejects invalid manifest %s",
|
||||
(key) => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
readManifest: () => ({ ...value.manifest, [key]: "invalid" }),
|
||||
}).available,
|
||||
).toBe(false);
|
||||
expect(value.loads()).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects a digest-valid artifact for another machine", () => {
|
||||
const value = fixture();
|
||||
value.bytes.writeUInt16LE(0xaa64, 68);
|
||||
value.manifest.artifactSha256 = createHash("sha256")
|
||||
.update(value.bytes)
|
||||
.digest("hex");
|
||||
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
|
||||
available: false,
|
||||
reason: expect.stringContaining("PE32+"),
|
||||
});
|
||||
expect(value.loads()).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves host permission failure rather than promoting a partial probe", () => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
loadArtifact: () => ({
|
||||
call: () => {
|
||||
throw new Error("private DACL: access denied");
|
||||
},
|
||||
}),
|
||||
}),
|
||||
).toMatchObject({
|
||||
available: false,
|
||||
reason: expect.stringContaining("private DACL: access denied"),
|
||||
});
|
||||
});
|
||||
|
||||
it("requires every inspected native fact", () => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
loadArtifact: () => ({ call: () => ({ privateDacl: true }) }),
|
||||
}).available,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { PACKAGE_METADATA } from "../generatedPackageMetadata.js";
|
||||
|
||||
/** A native resource remains opaque until the addon validates its object tag. */
|
||||
export const windowsHandleSchema = z.custom<object>(
|
||||
(value): value is object =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value),
|
||||
);
|
||||
|
||||
/** Observed identity of an opened local NTFS object. */
|
||||
export const windowsFileIdentitySchema = z.strictObject({
|
||||
requestedPath: z.string(),
|
||||
finalPath: z.string(),
|
||||
filesystem: z.literal("NTFS"),
|
||||
volumeSerial: z.string().regex(/^[a-f0-9]{16}$/u),
|
||||
fileId: z.string().regex(/^[a-f0-9]{32}$/u),
|
||||
size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
directory: z.boolean(),
|
||||
});
|
||||
|
||||
/** Metadata bound to one packaged Windows x64 Node-API artifact. */
|
||||
export const windowsNativeManifestSchema = z.strictObject({
|
||||
packageVersion: z.string(),
|
||||
platform: z.literal("win32"),
|
||||
architecture: z.literal("x64"),
|
||||
abiVersion: z.literal(1),
|
||||
nodeApiVersion: z.literal(8),
|
||||
artifact: z.literal("rea-windows-x64.node"),
|
||||
artifactSha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
});
|
||||
|
||||
const inspectionSchema = z.strictObject({
|
||||
abiVersion: z.literal(1),
|
||||
nodeApiVersion: z.literal(8),
|
||||
architecture: z.literal("x64"),
|
||||
filesystem: windowsFileIdentitySchema,
|
||||
privateDacl: z.literal(true),
|
||||
atomicJobAssignment: z.literal(true),
|
||||
killOnOwnerClose: z.literal(true),
|
||||
});
|
||||
|
||||
type NativeCall = (
|
||||
operation: string,
|
||||
arguments_: readonly unknown[],
|
||||
) => unknown;
|
||||
const bindingSchema = z.strictObject({
|
||||
call: z.custom<NativeCall>(
|
||||
(value): value is NativeCall => typeof value === "function",
|
||||
),
|
||||
});
|
||||
|
||||
/** Validated native operations and the observations establishing readiness. */
|
||||
export interface WindowsNativeAuthority {
|
||||
readonly call: NativeCall;
|
||||
readonly inspection: z.infer<typeof inspectionSchema>;
|
||||
}
|
||||
|
||||
/** Availability of the bundled native implementation, including load failures. */
|
||||
export type WindowsNativeLoadResult =
|
||||
| { readonly available: true; readonly authority: WindowsNativeAuthority }
|
||||
| { readonly available: false; readonly reason: string };
|
||||
|
||||
/** Trusted package reads and module loading, replaceable in loader tests. */
|
||||
export interface WindowsNativeLoadHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly architecture: string;
|
||||
readonly nodeApiVersion: string | undefined;
|
||||
readonly packageVersion: string;
|
||||
readManifest(): unknown;
|
||||
readArtifact(): Buffer;
|
||||
loadArtifact(): unknown;
|
||||
}
|
||||
|
||||
/** Validate compatibility and artifact identity before invoking the native addon. */
|
||||
export const loadWindowsNativeAuthority = (
|
||||
host: WindowsNativeLoadHost,
|
||||
): WindowsNativeLoadResult => {
|
||||
if (host.platform !== "win32" || host.architecture !== "x64")
|
||||
return {
|
||||
available: false,
|
||||
reason: "REA Windows native controls require a Windows x64 host.",
|
||||
};
|
||||
try {
|
||||
const manifest = windowsNativeManifestSchema.parse(host.readManifest());
|
||||
if (manifest.packageVersion !== host.packageVersion)
|
||||
throw new Error("Windows native artifact belongs to another REA version");
|
||||
const nodeApiVersion = Number(host.nodeApiVersion);
|
||||
if (!Number.isSafeInteger(nodeApiVersion) || nodeApiVersion < 8)
|
||||
throw new Error("Windows native artifact requires Node-API 8 or newer");
|
||||
const artifact = host.readArtifact();
|
||||
if (
|
||||
createHash("sha256").update(artifact).digest("hex") !==
|
||||
manifest.artifactSha256
|
||||
)
|
||||
throw new Error(
|
||||
"Windows native artifact SHA-256 does not match package metadata",
|
||||
);
|
||||
assertWindowsX64Artifact(artifact);
|
||||
const binding = bindingSchema.parse(host.loadArtifact());
|
||||
const inspection = inspectionSchema.parse(binding.call("inspect", []));
|
||||
return { available: true, authority: { call: binding.call, inspection } };
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
available: false,
|
||||
reason: `REA Windows native controls are unavailable: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const assertWindowsX64Artifact = (bytes: Buffer): void => {
|
||||
if (bytes.length < 64 || bytes.toString("ascii", 0, 2) !== "MZ")
|
||||
throw new Error("Windows native artifact is not a PE image");
|
||||
const offset = bytes.readUInt32LE(0x3c);
|
||||
if (
|
||||
offset > bytes.length - 26 ||
|
||||
bytes.toString("ascii", offset, offset + 4) !== "PE\0\0" ||
|
||||
bytes.readUInt16LE(offset + 4) !== 0x8664 ||
|
||||
bytes.readUInt16LE(offset + 24) !== 0x20b
|
||||
)
|
||||
throw new Error("Windows native artifact is not a Windows x64 PE32+ image");
|
||||
};
|
||||
|
||||
let cached: WindowsNativeLoadResult | undefined;
|
||||
|
||||
/** Load only the package-owned artifact, lazily and once per process. */
|
||||
export const systemWindowsNativeAuthority = (): WindowsNativeLoadResult => {
|
||||
cached ??= loadWindowsNativeAuthority({
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
nodeApiVersion: process.versions.napi,
|
||||
packageVersion: PACKAGE_METADATA.version,
|
||||
readManifest: () => {
|
||||
const encoded = readFileSync(
|
||||
new URL("../../native/windows/build/manifest.json", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
const value: unknown = JSON.parse(encoded);
|
||||
return value;
|
||||
},
|
||||
readArtifact: () =>
|
||||
readFileSync(
|
||||
new URL(
|
||||
"../../native/windows/build/rea-windows-x64.node",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
loadArtifact: () => {
|
||||
const value: unknown = createRequire(import.meta.url)(
|
||||
fileURLToPath(
|
||||
new URL(
|
||||
"../../native/windows/build/rea-windows-x64.node",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
);
|
||||
return value;
|
||||
},
|
||||
});
|
||||
return cached;
|
||||
};
|
||||
|
||||
/** Require the verified backend when an operation depends on native authority. */
|
||||
export const requireWindowsNativeAuthority = (): WindowsNativeAuthority => {
|
||||
const loaded = systemWindowsNativeAuthority();
|
||||
if (!loaded.available) throw new Error(loaded.reason);
|
||||
return loaded.authority;
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { quoteWindowsProcessArgument } from "./WindowsOwnedProcess.js";
|
||||
|
||||
describe("Windows process argument representation", () => {
|
||||
it.each([
|
||||
["", '""'],
|
||||
["plain", '"plain"'],
|
||||
["two words", '"two words"'],
|
||||
['embedded"quote', '"embedded\\"quote"'],
|
||||
["D:\\folder\\", '"D:\\folder\\\\"'],
|
||||
['slash\\"quote', '"slash\\\\\\"quote"'],
|
||||
])("quotes %j without changing its CRT argument", (input, expected) => {
|
||||
expect(quoteWindowsProcessArgument(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("rejects NUL before crossing the native boundary", () => {
|
||||
expect(() => quoteWindowsProcessArgument("a\0b")).toThrow("NUL");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ProcessCleanupResult } from "../process/ProcessOwnership.js";
|
||||
import {
|
||||
requireWindowsNativeAuthority,
|
||||
windowsHandleSchema,
|
||||
type WindowsNativeAuthority,
|
||||
} from "./WindowsNativeLoader.js";
|
||||
|
||||
const launchSchema = z.strictObject({
|
||||
pid: z.number().int().positive().max(0xffff_ffff),
|
||||
handle: windowsHandleSchema,
|
||||
jobAssigned: z.literal(true),
|
||||
killOnOwnerClose: z.literal(true),
|
||||
});
|
||||
const pollSchema = z.strictObject({
|
||||
stdout: z.instanceof(Buffer),
|
||||
stderr: z.instanceof(Buffer),
|
||||
stdoutEnded: z.boolean(),
|
||||
stderrEnded: z.boolean(),
|
||||
exitCode: z.number().int().nonnegative().max(0xffff_ffff).nullable(),
|
||||
activeProcesses: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
/** Encode one ordinary Windows argv token using the CRT backslash rules. */
|
||||
export const quoteWindowsProcessArgument = (value: string): string => {
|
||||
if (value.includes("\0"))
|
||||
throw new TypeError("Windows process argument contains NUL");
|
||||
return `"${value.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\+)$/u, "$1$1")}"`;
|
||||
};
|
||||
|
||||
/** Process events and streams backed by a retained native Job Object. */
|
||||
export class WindowsOwnedProcess extends EventEmitter {
|
||||
readonly stdout = new PassThrough();
|
||||
readonly stderr = new PassThrough();
|
||||
readonly signalCode: NodeJS.Signals | null = null;
|
||||
exitCode: number | null = null;
|
||||
readonly pid: number;
|
||||
readonly #handle: object;
|
||||
readonly #authority: WindowsNativeAuthority;
|
||||
readonly #settled: Promise<void>;
|
||||
#settle: (() => void) | undefined;
|
||||
#closed = false;
|
||||
#verifiedSettlement = false;
|
||||
#failure: string | undefined;
|
||||
#timer: NodeJS.Timeout | undefined;
|
||||
#cleanup: Promise<ProcessCleanupResult> | undefined;
|
||||
|
||||
constructor(
|
||||
command: string,
|
||||
arguments_: readonly string[],
|
||||
cwd: string | undefined,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
verbatim: boolean,
|
||||
) {
|
||||
super();
|
||||
this.#authority = requireWindowsNativeAuthority();
|
||||
const entries = Object.entries(environment)
|
||||
.filter((entry): entry is [string, string] => entry[1] !== undefined)
|
||||
.map(([key, value]) => `${key}=${value}`);
|
||||
const line = [
|
||||
quoteWindowsProcessArgument(command),
|
||||
...arguments_.map((value) =>
|
||||
verbatim ? value : quoteWindowsProcessArgument(value),
|
||||
),
|
||||
].join(" ");
|
||||
const launched = launchSchema.parse(
|
||||
this.#authority.call("process_spawn", [
|
||||
command,
|
||||
line,
|
||||
cwd ?? "",
|
||||
entries,
|
||||
]),
|
||||
);
|
||||
this.pid = launched.pid;
|
||||
this.#handle = launched.handle;
|
||||
this.#settled = new Promise((resolve) => {
|
||||
this.#settle = resolve;
|
||||
});
|
||||
this.#schedule();
|
||||
}
|
||||
|
||||
/** Terminate the retained job, never a PID supplied by another caller. */
|
||||
kill(signal?: NodeJS.Signals | number): boolean {
|
||||
if (signal === 0)
|
||||
return (
|
||||
!this.#closed &&
|
||||
z
|
||||
.number()
|
||||
.parse(this.#authority.call("process_alive", [this.#handle])) > 0
|
||||
);
|
||||
return this.#closed
|
||||
? false
|
||||
: z
|
||||
.boolean()
|
||||
.parse(this.#authority.call("process_terminate", [this.#handle]));
|
||||
}
|
||||
|
||||
/** Terminate and verify that the entire job has settled before releasing it. */
|
||||
cleanup(): Promise<ProcessCleanupResult> {
|
||||
this.#cleanup ??= this.#stop();
|
||||
return this.#cleanup;
|
||||
}
|
||||
|
||||
async #stop(): Promise<ProcessCleanupResult> {
|
||||
if (this.#closed)
|
||||
return this.#verifiedSettlement
|
||||
? { cleaned: true, signaled: false }
|
||||
: {
|
||||
cleaned: false,
|
||||
reason:
|
||||
this.#failure ?? "Windows Job Object settlement was not verified",
|
||||
};
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
const signaled = this.kill();
|
||||
const settled = await Promise.race([
|
||||
this.#settled.then(() => true),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(false), 5_000);
|
||||
}),
|
||||
]);
|
||||
return settled && this.#verifiedSettlement
|
||||
? { cleaned: true, signaled }
|
||||
: {
|
||||
cleaned: false,
|
||||
reason:
|
||||
this.#failure ??
|
||||
"Windows Job Object did not settle within the cleanup deadline",
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
};
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
if (!this.#closed) this.#release();
|
||||
}
|
||||
}
|
||||
|
||||
#schedule(): void {
|
||||
this.#timer = setTimeout(() => this.#poll(), 25);
|
||||
}
|
||||
|
||||
#poll(): void {
|
||||
if (this.#closed) return;
|
||||
try {
|
||||
const state = pollSchema.parse(
|
||||
this.#authority.call("process_poll", [this.#handle]),
|
||||
);
|
||||
if (state.stdout.length > 0) this.stdout.write(state.stdout);
|
||||
if (state.stderr.length > 0) this.stderr.write(state.stderr);
|
||||
if (state.exitCode !== null && this.exitCode === null) {
|
||||
this.exitCode = state.exitCode;
|
||||
this.emit("exit", state.exitCode, null);
|
||||
}
|
||||
if (
|
||||
state.exitCode !== null &&
|
||||
state.stdoutEnded &&
|
||||
state.stderrEnded &&
|
||||
state.activeProcesses === 0
|
||||
) {
|
||||
this.#verifiedSettlement = true;
|
||||
this.#release();
|
||||
} else this.#schedule();
|
||||
} catch (cause: unknown) {
|
||||
const failure = cause instanceof Error ? cause : new Error(String(cause));
|
||||
this.#failure = failure.message;
|
||||
// Native lifecycle failures belong to the error/cleanup channels, never
|
||||
// the captured stderr observation produced by the child itself.
|
||||
if (this.listenerCount("error") > 0) this.emit("error", failure);
|
||||
this.#release();
|
||||
}
|
||||
}
|
||||
|
||||
#release(): void {
|
||||
if (this.#closed) return;
|
||||
if (this.#timer !== undefined) clearTimeout(this.#timer);
|
||||
this.#authority.call("process_close", [this.#handle]);
|
||||
this.#closed = true;
|
||||
this.stdout.end();
|
||||
this.stderr.end();
|
||||
this.#settle?.();
|
||||
this.emit("close", this.exitCode, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { win32 } from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
requireWindowsNativeAuthority,
|
||||
windowsFileIdentitySchema,
|
||||
windowsHandleSchema,
|
||||
type WindowsNativeAuthority,
|
||||
} from "./WindowsNativeLoader.js";
|
||||
|
||||
const runtimeSchema = windowsFileIdentitySchema.extend({
|
||||
path: z.string(),
|
||||
handle: windowsHandleSchema,
|
||||
privateDacl: z.literal(true),
|
||||
});
|
||||
const snapshotSchema = z.strictObject({
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
source: windowsFileIdentitySchema,
|
||||
snapshot: windowsFileIdentitySchema,
|
||||
});
|
||||
const fileSchema = windowsFileIdentitySchema.extend({
|
||||
handle: windowsHandleSchema,
|
||||
});
|
||||
const runtimes = new Map<string, WindowsPrivateRuntime>();
|
||||
|
||||
/** Retain private DACL and path handles until native recursive cleanup settles. */
|
||||
export class WindowsPrivateRuntime {
|
||||
// One native snapshot can own cancellation for this runtime at a time. A
|
||||
// second request throws ERROR_BUSY before #pending or its abort listener is
|
||||
// replaced, so aborting a rejected request cannot cancel the accepted copy.
|
||||
#pending: Promise<unknown> | undefined;
|
||||
#closed = false;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
private constructor(
|
||||
readonly observation: z.infer<typeof runtimeSchema>,
|
||||
private readonly authority: WindowsNativeAuthority,
|
||||
) {}
|
||||
|
||||
/** Create a new directory with its private DACL installed at creation. */
|
||||
static create(parent: string, prefix: string): WindowsPrivateRuntime {
|
||||
const authority = requireWindowsNativeAuthority();
|
||||
const observation = runtimeSchema.parse(
|
||||
authority.call("runtime_create", [parent, prefix]),
|
||||
);
|
||||
const runtime = new WindowsPrivateRuntime(observation, authority);
|
||||
runtimes.set(observation.path.toLowerCase(), runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
/** Open a private child directory through retained, verified parent handles. */
|
||||
mkdir(relativePath: string): void {
|
||||
this.authority.call("runtime_mkdir", [
|
||||
this.observation.handle,
|
||||
relativePath,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Write a new private file once and retain its immutable handle. */
|
||||
writeFile(relativePath: string, content: string): void {
|
||||
this.authority.call("runtime_write", [
|
||||
this.observation.handle,
|
||||
relativePath,
|
||||
Buffer.from(content),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Copy admitted source bytes and digest the bytes actually written. */
|
||||
async snapshot(
|
||||
sourcePath: string,
|
||||
relativePath: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<z.infer<typeof snapshotSchema>> {
|
||||
// Admission is synchronous; record ownership only after native acceptance.
|
||||
const pending = Promise.resolve(
|
||||
this.authority.call("runtime_snapshot", [
|
||||
this.observation.handle,
|
||||
sourcePath,
|
||||
relativePath,
|
||||
]),
|
||||
);
|
||||
this.#pending = pending;
|
||||
const cancel = (): void => {
|
||||
this.authority.call("runtime_snapshot_cancel", [this.observation.handle]);
|
||||
};
|
||||
signal?.addEventListener("abort", cancel, { once: true });
|
||||
if (signal?.aborted === true) cancel();
|
||||
try {
|
||||
return snapshotSchema.parse(await pending);
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", cancel);
|
||||
if (this.#pending === pending) this.#pending = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read a private endpoint from an opened file, without re-opening its path. */
|
||||
readFile(relativePath: string): string {
|
||||
const file = fileSchema.parse(
|
||||
this.authority.call("runtime_open", [
|
||||
this.observation.handle,
|
||||
relativePath,
|
||||
]),
|
||||
);
|
||||
try {
|
||||
const chunks: Buffer[] = [];
|
||||
for (let offset = 0; offset < file.size;) {
|
||||
const value = z
|
||||
.instanceof(Buffer)
|
||||
.parse(
|
||||
this.authority.call("read", [
|
||||
file.handle,
|
||||
offset,
|
||||
Math.min(65_536, file.size - offset),
|
||||
]),
|
||||
);
|
||||
if (value.length === 0)
|
||||
throw new Error(
|
||||
"Private runtime file ended before its observed size",
|
||||
);
|
||||
offset += value.length;
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
} finally {
|
||||
this.authority.call("close", [file.handle]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove owned objects by handle, unlinking reparse entries without traversal. */
|
||||
close(): Promise<void> {
|
||||
this.#closePromise ??= this.#remove();
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
async #remove(): Promise<void> {
|
||||
if (this.#closed) return;
|
||||
if (this.#pending !== undefined)
|
||||
this.authority.call("runtime_snapshot_cancel", [this.observation.handle]);
|
||||
await this.#pending?.catch(() => undefined);
|
||||
try {
|
||||
this.authority.call("runtime_close", [this.observation.handle]);
|
||||
} finally {
|
||||
this.#closed = true;
|
||||
runtimes.delete(this.observation.path.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Select an already-owned runtime; an arbitrary pathname cannot grant authority. */
|
||||
export const windowsPrivateRuntime = (
|
||||
rootPath: string,
|
||||
): WindowsPrivateRuntime => {
|
||||
const runtime = runtimes.get(rootPath.toLowerCase());
|
||||
if (runtime === undefined)
|
||||
throw new Error(`No native private runtime owns ${rootPath}`);
|
||||
return runtime;
|
||||
};
|
||||
|
||||
/** Read a runtime endpoint using the lease that owns its parent directory. */
|
||||
export const readWindowsPrivateRuntimeFile = (path: string): string => {
|
||||
const parent = win32.dirname(path);
|
||||
return windowsPrivateRuntime(parent).readFile(win32.basename(path));
|
||||
};
|
||||
Reference in New Issue
Block a user