mirror of
https://github.com/morluto/rea.git
synced 2026-11-11 09:21:16 +00:00
* feat(windows): inspect Shell Link (.lnk) shortcut files Add inspect_windows_shortcut / inspect-windows-shortcut to read one local Shell Link without resolving or executing the target. The report keeps header flags and FILETIMEs, IDList items, LinkInfo volume and network names, StringData, ExtraData including Tracker droid facts labelled derived, and derived observations such as argument length and a minimized ShowCommand. * fix(windows): tighten Shell Link string reads and coverage - Decode counted StringData over its full CountCharacters payload. - Locate LinkInfo string terminators before charging max_string_bytes and before decoding; an unterminated string is a coverage issue. - Mark an IDList without a TerminalID and an out-of-range LinkInfoHeaderSize as partial coverage. - Report arguments_present and argument_length as null when HasArguments is set but the field could not be read. - Derive target_extension from the joined base path and suffix. - Keep ISO dates for FILETIME and UUIDv1 timestamps before 1970. - Retain the completed file snapshot on parse failures. - Reject an empty CLI path before normalization. - Select the shortcut contract from its family in focused tests. - Fixture StringData no longer writes a NUL into the counted payload. * style: format docs index and Shell Link boundary type Apply oxfmt to the two files format:check reports so Static checks passes. * fix(windows): reject network share paths for Shell Link reads inspect_windows_shortcut is advertised as offline, but the Windows path schema admits UNC paths, and lstat on one can contact an SMB server and offer the caller's credentials. Reject UNC, extended UNC, and other host-prefixed device paths in the provider before any filesystem call. Extended drive paths such as \\?\C:\x stay allowed. A mapped network drive cannot be told from a local drive by its path, and the docs say so. * fix(windows): decode Unicode Shell Link file-entry names File-entry items with bit 0x04 of the type byte, such as 0x36, store a UTF-16LE name, but the parser always read it as Latin-1. The read stopped at the first zero byte, so report.exe became r and an IDList-only shortcut reported the wrong target_extension. Read those names as UTF-16LE. * fix(windows): read volume labels by exact Shell Link discriminator VolumeLabelOffset 0x14 selects VolumeLabelOffsetUnicode and is not itself a label offset, and that Unicode field exists for no other value. The parser treated any offset of 0x14 or more as having both, so a Unicode-only label such as "OS" also produced a false ANSI label "O", and an ANSI label stored past 0x14 had its own bytes read as a Unicode offset. Branch on the exact value in parseVolume, the one place that interprets it, and report a VolumeID too short to hold the selected field. The fixture wrote both encodings for a Unicode volume, which hid the false label, so it now writes one. * fix(windows): limit network share rejection to Windows hosts POSIX hosts read repeated leading slashes as one local root, so an accepted selection such as ///tmp/shortcut.lnk is a local file there. Apply the host-prefixed path check only on Windows, and take the platform through the provider constructor so the Windows path forms stay covered on every test host. * fix(windows): compare shortcut icons only against full paths A stored IDList filename or relative path cannot show that an icon at a full path is elsewhere, so the comparison reported a false difference. Report null unless the icon and a recorded target are both full paths, and assert the missing TerminalID issue by code and offset instead of its message. * fix(windows): keep unread ExtraData blocks unknown A walk that stopped before or inside ExtraData still reported the blocks that HasExpString and HasExpIcon expect as absent, though they were never checked for. Report a block as absent only after the TerminalBlock shows the section was read in full. Without one the block stays unknown and coverage stays partial. * fix(native): ignore LNK network provider type unless ValidNetType is set CommonNetworkRelativeLink NetworkProviderType is only meaningful when the ValidNetType flag (0x2) is set. Return null otherwise. * fix(native): accept any ExtraData TerminalSize below 4 as the terminal MS-SHLLINK requires TerminalSize to be less than 4, not exactly 0. Treat 1, 2 and 3 as the terminal block instead of a malformed block. * fix(native): derive shortcut target facts from the stored environment target Include the EnvironmentVariableDataBlock literal target among the target candidates for target_extension and the icon comparison. Variables are not expanded and the target is not opened. * fix(windows-shortcut): keep unexpanded variable paths unresolved in icon comparison A stored environment target such as C:\Users\%USERNAME%\app.exe could be compared as different from C:\Users\Alice\app.exe. Variable-bearing paths are never expanded, so the icon comparison now returns null unless a fixed target matches the icon exactly. * test: drop redundant ok assertion before typed error guard The testing guide asks for the typed error to be thrown before asserting a successful Result value, and says a preceding .ok assertion adds no coverage. * fix(windows): point out-of-range LinkInfo offsets at their field A LinkInfo, VolumeID or CommonNetworkRelativeLink offset that points past its structure was reported at base + offset. With an offset such as 0xffffffff that position exceeds uint32, so the report failed its schema and the service discarded the whole partial result. Report such issues at the offending offset field instead, which keeps every issue offset and coverage.failing_offset inside the file. Cover each LinkInfo offset field in the parser tests and the LocalBasePathOffset case through the stable filesystem service. * fix(windows): require RFC 4122 variant before deriving Tracker UUID facts A version nibble of 1 alone does not identify a version-1 UUID. Also require the clock_seq_hi_and_reserved top bits to be 10, so other GUID layouts keep their raw value and derive no MAC or timestamp. * fix(windows): ignore DeviceNameOffset fields unless ValidDevice is set MS-SHLLINK 2.3.2 says DeviceNameOffset and DeviceNameOffsetUnicode are ignored when the ValidDevice flag is clear. parseNetwork read both regardless, so garbage in those fields became device-name facts or malformed_structure issues. Read the flags once and only read the device name fields when ValidDevice is set. * fix(windows): keep unsupported Tracker headers as raw data Check TrackerDataBlock Length (0x58) and Version (0) before decoding. A block with any other header is retained as raw bytes with a malformed_structure issue, so it no longer yields MAC and timestamp facts under complete coverage. * fix(windows): compare shortcut icon paths by normalized location Collapse "." and ".." segments and repeated separators in the icon comparison as text only, never opening a path. ".." stops at the drive or UNC share root, and \\?\ and \\.\ paths stay verbatim. Join LocalBasePath with CommonPathSuffix as the target and use the bare base only when the suffix is empty, as the network share branch does. Read the selected shortcut with lstat and open only, so a rejected symlink's destination is never resolved. * fix(windows): keep the UNC share in the root after repeated separators normalizePath took the host and the next split part as the UNC root, so \\server\\share\..\app.exe kept an empty share and let .. remove the real share. Drop empty parts before picking the root so paths on different shares stay different. * fix(cli): parse windows shortcut limits as decimals The four inspect-windows-shortcut limit options now go through cliDecimalField like the other inspection commands, so values such as 0x10 are rejected and cliDecimalArguments.test.ts passes. * fix(native): reject linked parents of windows shortcuts A parent directory symlink or junction pointing at a UNC share was followed by the first lstat, since the network check reads only the path text and the symlink rejection covers only the final component. On Windows, lstat each ancestor from the drive root down and reject the path at the first link, before anything follows it. * docs(native): move Windows shortcut guide and add its feature spec Move the Shell Link guide to docs/guides/native/windows-shortcut.md and list it under Native binaries in the site navigation, keeping the /windows-shortcut public route. Update README, translated README, CLI page and authored skill links to the new physical path. Add docs/specs/native/windows-shortcut/ with spec.md, plan.md and tasks.md, as required by docs/development/documentation.md. * fix(native): admit the windows shortcut parent walk On Windows the ancestor link walk ran before the provider's resource admission, so close() could finish while the walk kept calling lstat. Run the walk inside the same admission as the read, and check the caller's signal before each ancestor lstat. * fix(native): walk the effective parents of windows shortcuts The ancestor link walk checked every prefix of the path as written, so C:\alias\..\real\a.lnk was refused when C:\alias is a directory link, although Windows removes alias\.. before opening the file. Walk the ancestors left after removing . and .. components, keeping the caller's spelling, never climbing above an absolute root, and leaving \\?\ paths as written since Windows does not normalize them. * test(native): assert the linked parent as a structured fact The parent link regression matched the phrase "junction, which" in the refusal message, so a wording edit would fail it. Report the linked ancestor as observed.linked_ancestor on the input issue and assert that fact instead of the explanatory text. * test(native): bound the shortcut close gate and release it in finally Race the parent walk lstat acknowledgement against inspection settling with awaitAcknowledgement, then release the gate and join the inspect and close work in finally so a failure reports its cause instead of waiting for the Vitest timeout. * fix(native): walk Windows shortcut parents lazily windowsAncestors built and kept every parent prefix before the first lstat, so a path with thousands of components allocated memory quadratic in its length. It now keeps only the normalized components and yields each parent from a running prefix as the walk reaches it. --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
374 lines
13 KiB
TypeScript
374 lines
13 KiB
TypeScript
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
import { createWindowsShortcutService } from "../../../src/composition/binaryDiagnostics.js";
|
|
import { WindowsShortcutProvider } from "../../../src/native/windows/WindowsShortcutProvider.js";
|
|
import {
|
|
powershellHiddenIconSpoofShortcut,
|
|
windowsShortcutBytes,
|
|
} from "../../fixtures/binaryDiagnostics/windowsShortcut.js";
|
|
import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
|
|
const { realpathCalls, lstatCalls, lstatGate } = vi.hoisted(() => ({
|
|
realpathCalls: vi.fn(),
|
|
lstatCalls: vi.fn(),
|
|
// When set, the next lstat reports its path and waits for the gate.
|
|
lstatGate: {} as {
|
|
hold?:
|
|
| { entered: (path: string) => void; release: Promise<void> }
|
|
| undefined;
|
|
},
|
|
}));
|
|
|
|
vi.mock("node:fs/promises", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
|
return {
|
|
...actual,
|
|
realpath: (async (...args: Parameters<typeof actual.realpath>) => {
|
|
realpathCalls(...args);
|
|
return actual.realpath(...args);
|
|
}) as typeof actual.realpath,
|
|
lstat: (async (...args: Parameters<typeof actual.lstat>) => {
|
|
lstatCalls(String(args[0]));
|
|
const hold = lstatGate.hold;
|
|
if (hold !== undefined) {
|
|
lstatGate.hold = undefined;
|
|
hold.entered(String(args[0]));
|
|
await hold.release;
|
|
}
|
|
return actual.lstat(...args);
|
|
}) as typeof actual.lstat,
|
|
};
|
|
});
|
|
|
|
// The input schema admits Windows path forms only on a Windows host, so these
|
|
// reach the provider directly to run on every host.
|
|
const providerInput = (path: string) => ({
|
|
path,
|
|
max_file_bytes: 1048576,
|
|
max_id_list_items: 256,
|
|
max_extra_data_blocks: 64,
|
|
max_string_bytes: 1048576,
|
|
});
|
|
|
|
describe("Windows shortcut stable filesystem boundary", () => {
|
|
it("reports non-file and malformed Shell Link selections as caller input errors", async () => {
|
|
const root = await createTestTempDirectory("rea-windows-shortcut-files-");
|
|
const path = join(root, "shortcut.lnk");
|
|
const alias = join(root, "alias.lnk");
|
|
const malformed = join(root, "malformed.lnk");
|
|
await writeFile(path, powershellHiddenIconSpoofShortcut());
|
|
await writeFile(malformed, Buffer.from("not a shell link"));
|
|
await symlink(path, alias);
|
|
const service = createWindowsShortcutService();
|
|
for (const [candidate, reason] of [
|
|
[root, "invalid_format"],
|
|
[alias, "invalid_format"],
|
|
[malformed, "invalid_format"],
|
|
[join(root, "missing.lnk"), "invalid_value"],
|
|
[join(path, "child.lnk"), "invalid_value"],
|
|
] as const) {
|
|
const result = await service.inspect({ path: candidate });
|
|
if (result.ok) throw new Error("Expected file acquisition failure");
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisInputError",
|
|
operation: "inspect_windows_shortcut",
|
|
issues: [
|
|
{
|
|
path: ["path"],
|
|
reason,
|
|
message: expect.any(String),
|
|
},
|
|
],
|
|
});
|
|
}
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"rejects a symlinked shortcut without resolving its destination",
|
|
async () => {
|
|
const root = await createTestTempDirectory("rea-windows-shortcut-link-");
|
|
const path = join(root, "shortcut.lnk");
|
|
const alias = join(root, "alias.lnk");
|
|
await writeFile(path, powershellHiddenIconSpoofShortcut());
|
|
await symlink(path, alias);
|
|
realpathCalls.mockClear();
|
|
|
|
const result = await new WindowsShortcutProvider().inspect(
|
|
providerInput(alias),
|
|
);
|
|
if (result.ok) throw new Error("Expected symlink rejection");
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisInputError",
|
|
issues: [{ path: ["path"], reason: "invalid_format" }],
|
|
});
|
|
expect(realpathCalls).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it("rejects network share paths without opening them", async () => {
|
|
const provider = new WindowsShortcutProvider("win32");
|
|
for (const path of [
|
|
"\\\\server\\share\\shortcut.lnk",
|
|
"//server/share/shortcut.lnk",
|
|
"\\\\?\\UNC\\server\\share\\shortcut.lnk",
|
|
"//./UNC/server/share/shortcut.lnk",
|
|
"\\\\?\\GLOBALROOT\\Device\\Mup\\server\\share\\shortcut.lnk",
|
|
]) {
|
|
const result = await provider.inspect(providerInput(path));
|
|
if (result.ok) throw new Error("Expected network share rejection");
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisInputError",
|
|
operation: "inspect_windows_shortcut",
|
|
issues: [
|
|
{
|
|
path: ["path"],
|
|
reason: "invalid_value",
|
|
message: expect.stringContaining("network share"),
|
|
},
|
|
],
|
|
});
|
|
}
|
|
});
|
|
|
|
it("does not treat an extended drive path as a network share", async () => {
|
|
const provider = new WindowsShortcutProvider("win32");
|
|
for (const path of [
|
|
"\\\\?\\C:\\shortcuts\\missing.lnk",
|
|
"\\\\.\\C:\\shortcuts\\missing.lnk",
|
|
]) {
|
|
const result = await provider.inspect(providerInput(path));
|
|
if (result.ok) throw new Error("Expected a missing file");
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisInputError",
|
|
issues: [
|
|
{
|
|
path: ["path"],
|
|
message: expect.not.stringContaining("network share"),
|
|
},
|
|
],
|
|
});
|
|
}
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"reads repeated leading slashes as a local POSIX path",
|
|
async () => {
|
|
const root = await createTestTempDirectory("rea-windows-shortcut-posix-");
|
|
const path = join(root, "shortcut.lnk");
|
|
await writeFile(path, powershellHiddenIconSpoofShortcut());
|
|
|
|
const result = await new WindowsShortcutProvider("linux").inspect(
|
|
providerInput(`//${path}`),
|
|
);
|
|
expect(result.ok).toBe(true);
|
|
},
|
|
);
|
|
|
|
it("keeps a partial report when a LinkInfo offset points past the file", async () => {
|
|
const root = await createTestTempDirectory("rea-windows-shortcut-offset-");
|
|
const path = join(root, "shortcut.lnk");
|
|
const bytes = windowsShortcutBytes({ idList: null });
|
|
// LocalBasePathOffset sits 16 bytes into LinkInfo, which follows the header.
|
|
bytes.writeUInt32LE(0xffffffff, 76 + 16);
|
|
await writeFile(path, bytes);
|
|
const result = await createWindowsShortcutService().inspect({ path });
|
|
if (!result.ok) throw result.error;
|
|
expect(result.value.normalized_result).toMatchObject({
|
|
header: { header_size: 76 },
|
|
coverage: { status: "partial", failing_offset: 92 },
|
|
});
|
|
});
|
|
|
|
it("returns typed resource and cancellation failures", async () => {
|
|
const root = await createTestTempDirectory("rea-windows-shortcut-budget-");
|
|
const path = join(root, "shortcut.lnk");
|
|
await writeFile(path, powershellHiddenIconSpoofShortcut());
|
|
const service = createWindowsShortcutService();
|
|
const tooSmall = await service.inspect({ path, max_file_bytes: 76 });
|
|
if (tooSmall.ok) throw new Error("Expected resource budget failure");
|
|
expect(tooSmall.error._tag).toBe("AnalysisResourceConstraintError");
|
|
const items = await service.inspect({ path, max_id_list_items: 1 });
|
|
if (items.ok) throw new Error("Expected IDList budget failure");
|
|
expect(items.error).toMatchObject({
|
|
_tag: "AnalysisResourceConstraintError",
|
|
reportedLimits: { boundary: "id_list_items", maximum: 1 },
|
|
remediationAction: expect.stringContaining("max_id_list_items"),
|
|
retryable: false,
|
|
});
|
|
const cancelled = await service.inspect(
|
|
{ path },
|
|
{ signal: AbortSignal.abort() },
|
|
);
|
|
if (cancelled.ok) throw new Error("Expected cancellation");
|
|
expect(cancelled.error._tag).toBe("AnalysisCancelledError");
|
|
});
|
|
});
|
|
|
|
describe("Windows shortcut parent directory links", () => {
|
|
it.skipIf(process.platform === "win32")(
|
|
"rejects a parent directory link before reading through it",
|
|
async () => {
|
|
const root = await createTestTempDirectory(
|
|
"rea-windows-shortcut-parent-",
|
|
);
|
|
const real = join(root, "real");
|
|
const linked = join(root, "linked");
|
|
await mkdir(real);
|
|
await writeFile(
|
|
join(real, "shortcut.lnk"),
|
|
powershellHiddenIconSpoofShortcut(),
|
|
);
|
|
await symlink(real, linked);
|
|
const provider = new WindowsShortcutProvider("win32");
|
|
|
|
const result = await provider.inspect(
|
|
providerInput(join(linked, "shortcut.lnk")),
|
|
);
|
|
if (result.ok) throw new Error("Expected parent link rejection");
|
|
expect(result.error).toMatchObject({
|
|
_tag: "AnalysisInputError",
|
|
issues: [
|
|
{
|
|
path: ["path"],
|
|
reason: "invalid_value",
|
|
observed: { linked_ancestor: linked },
|
|
},
|
|
],
|
|
});
|
|
expect(
|
|
await provider.inspect(providerInput(join(real, "shortcut.lnk"))),
|
|
).toMatchObject({ ok: true });
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"admits the parent walk so close waits for it and a later call is refused",
|
|
async () => {
|
|
const root = await createTestTempDirectory(
|
|
"rea-windows-shortcut-parent-close-",
|
|
);
|
|
const path = join(root, "shortcut.lnk");
|
|
await writeFile(path, powershellHiddenIconSpoofShortcut());
|
|
const provider = new WindowsShortcutProvider("win32");
|
|
let release!: () => void;
|
|
const entered = new Promise<string>((resolve) => {
|
|
lstatGate.hold = {
|
|
entered: resolve,
|
|
release: new Promise<void>((done) => {
|
|
release = done;
|
|
}),
|
|
};
|
|
});
|
|
|
|
const inspecting = provider.inspect(providerInput(path));
|
|
let closing: Promise<void> | undefined;
|
|
try {
|
|
await awaitAcknowledgement(
|
|
entered.then(() => undefined),
|
|
inspecting,
|
|
"parent walk lstat",
|
|
);
|
|
let closed = false;
|
|
closing = provider.close().then(() => {
|
|
closed = true;
|
|
});
|
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
expect(closed).toBe(false);
|
|
} finally {
|
|
lstatGate.hold = undefined;
|
|
release();
|
|
await inspecting;
|
|
await closing;
|
|
}
|
|
|
|
const after = await provider.inspect(providerInput(path));
|
|
if (after.ok) throw new Error("Expected a closed provider to refuse");
|
|
expect(after.error._tag).not.toBe("AnalysisInputError");
|
|
},
|
|
);
|
|
|
|
it("checks the caller's signal before walking parents", async () => {
|
|
const root = await createTestTempDirectory(
|
|
"rea-windows-shortcut-parent-abort-",
|
|
);
|
|
const path = join(root, "shortcut.lnk");
|
|
await writeFile(path, powershellHiddenIconSpoofShortcut());
|
|
const entered = vi.fn();
|
|
lstatGate.hold = { entered, release: Promise.resolve() };
|
|
|
|
const result = await new WindowsShortcutProvider("win32").inspect(
|
|
providerInput(path),
|
|
{ signal: AbortSignal.abort() },
|
|
);
|
|
lstatGate.hold = undefined;
|
|
if (result.ok) throw new Error("Expected cancellation");
|
|
expect(result.error._tag).toBe("AnalysisCancelledError");
|
|
expect(entered).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"walks the parents Windows reaches after removing dot components",
|
|
async () => {
|
|
const root = await createTestTempDirectory(
|
|
"rea-windows-shortcut-parent-dots-",
|
|
);
|
|
const real = join(root, "real");
|
|
await mkdir(real);
|
|
await writeFile(
|
|
join(real, "shortcut.lnk"),
|
|
powershellHiddenIconSpoofShortcut(),
|
|
);
|
|
// A sibling link, so the POSIX host's own `..` lands where Windows would.
|
|
// The paths are spelled out, since `join` would remove the dots itself.
|
|
await symlink(real, join(root, "alias"));
|
|
const provider = new WindowsShortcutProvider("win32");
|
|
|
|
expect(
|
|
await provider.inspect(
|
|
providerInput(`${root}/alias/../real/shortcut.lnk`),
|
|
),
|
|
).toMatchObject({ ok: true });
|
|
expect(
|
|
await provider.inspect(providerInput(`${root}/./alias/./shortcut.lnk`)),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "AnalysisInputError",
|
|
issues: [{ observed: { linked_ancestor: `${root}/alias` } }],
|
|
},
|
|
});
|
|
},
|
|
);
|
|
|
|
it("starts the walk at the first parent of the effective Windows path", async () => {
|
|
const provider = new WindowsShortcutProvider("win32");
|
|
for (const [path, first] of [
|
|
["C:\\alias\\..\\real\\a.lnk", "C:\\real"],
|
|
["C:/alias/../real/a.lnk", "C:/real"],
|
|
["C:\\..\\.\\real\\a.lnk", "C:\\real"],
|
|
["\\\\.\\C:\\alias\\..\\real\\a.lnk", "\\\\.\\C:\\real"],
|
|
["\\\\?\\C:\\alias\\..\\real\\a.lnk", "\\\\?\\C:\\alias"],
|
|
["..\\real\\a.lnk", ".."],
|
|
] as const) {
|
|
const entered = vi.fn();
|
|
lstatGate.hold = { entered, release: Promise.resolve() };
|
|
await provider.inspect(providerInput(path));
|
|
lstatGate.hold = undefined;
|
|
expect(entered).toHaveBeenCalledWith(first);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("Windows shortcut deep parent paths", () => {
|
|
it("stops a deep missing Windows path at its first unreadable parent", async () => {
|
|
const provider = new WindowsShortcutProvider("win32");
|
|
const path = `C:\\missing${"\\a".repeat(8_000)}\\a.lnk`;
|
|
lstatCalls.mockClear();
|
|
await provider.inspect(providerInput(path));
|
|
expect(lstatCalls.mock.calls[0]).toEqual(["C:\\missing"]);
|
|
expect(lstatCalls).not.toHaveBeenCalledWith("C:\\missing\\a");
|
|
});
|
|
});
|