fix(figma): write .media and component outputs without following links (#8111)

* fix(figma): write .media and component outputs without following links

The figma importer's writers (index.md, manifest.jsonl, figma-bindings.jsonl,
figma-tokens.json and component files) used writeFileSync, appendFileSync and
recursive mkdirSync, which follow a link at the target or in its folders.

- Folders under the project (.media, .media/images,
  compositions/components/<name>) are created one level at a time and refused
  when one is a link or resolves outside the project.
- Whole-file rewrites go through replaceFileAtomically (temp file + rename),
  so a link at the target is replaced rather than written through.
- Appends open with O_NOFOLLOW and refuse a link at the target.
- index.md cells collapse line breaks, matching media-use's index-gen.mjs
  byte for byte, so each record stays on one line.

* chore(figma): trim added comments; check the component folder right before writing

* fix(figma): open appends first, then check the path holds that same file

appendWithoutFollowing checked the path with lstat and then opened it, leaving
a gap between check and use. It now opens with O_NOFOLLOW first and writes
through the descriptor only when lstat finds the same single-link plain file at
the path, the pattern projectRecords' appendRecord already uses.
This commit is contained in:
andybpan
2026-11-17 21:36:57 +00:00
committed by GitHub
parent ba62d77489
commit a765c93791
12 changed files with 350 additions and 40 deletions
+87 -1
View File
@@ -1,6 +1,16 @@
// @vitest-environment node
import { describe, expect, it, afterEach } from "vitest";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import {
linkSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -334,3 +344,79 @@ describe("runAssetImport", () => {
expect(out.record.description).toBe("line one line two");
});
});
describe("runAssetImport with links in the project", () => {
const posixOnly = it.skipIf(process.platform === "win32");
function outsideFile(): string {
const file = join(scratch(), "outside.txt");
writeFileSync(file, "keep me\n");
return file;
}
posixOnly("replaces a linked index.md instead of writing through it", async () => {
const dir = scratch();
const outside = outsideFile();
mkdirSync(join(dir, ".media"));
symlinkSync(outside, join(dir, ".media", "index.md"));
await runAssetImport("FILEKEY:1-2", { format: "png" }, deps(dir));
expect(readFileSync(outside, "utf8")).toBe("keep me\n");
expect(lstatSync(join(dir, ".media", "index.md")).isFile()).toBe(true);
});
posixOnly("refuses to append to a linked manifest.jsonl", async () => {
const dir = scratch();
const outside = outsideFile();
mkdirSync(join(dir, ".media"));
symlinkSync(outside, join(dir, ".media", "manifest.jsonl"));
await expect(runAssetImport("FILEKEY:1-2", { format: "png" }, deps(dir))).rejects.toThrow(
/link/,
);
expect(readFileSync(outside, "utf8")).toBe("keep me\n");
});
posixOnly("refuses to append to a manifest.jsonl hard-linked to another file", async () => {
const dir = scratch();
const outside = outsideFile();
mkdirSync(join(dir, ".media"));
linkSync(outside, join(dir, ".media", "manifest.jsonl"));
await expect(runAssetImport("FILEKEY:1-2", { format: "png" }, deps(dir))).rejects.toThrow(
/not a plain file/,
);
expect(readFileSync(outside, "utf8")).toBe("keep me\n");
});
posixOnly("does not rewrite a linked manifest.jsonl when a reuse updates a row", async () => {
const dir = scratch();
await runAssetImport("FILEKEY:1-2", { format: "png" }, deps(dir));
const outside = join(scratch(), "manifest.jsonl");
const manifest = join(dir, ".media", "manifest.jsonl");
const rows = readFileSync(manifest, "utf8");
writeFileSync(outside, rows);
rmSync(manifest);
symlinkSync(outside, manifest);
await runAssetImport("FILEKEY:1-2", { format: "png", description: "new" }, deps(dir));
expect(readFileSync(outside, "utf8")).toBe(rows);
});
posixOnly("refuses a .media folder that is a link", async () => {
const dir = scratch();
const outsideDir = scratch();
symlinkSync(outsideDir, join(dir, ".media"));
await expect(runAssetImport("FILEKEY:1-2", { format: "png" }, deps(dir))).rejects.toThrow(
/outside the project/,
);
expect(readdirSync(outsideDir)).toEqual([]);
});
posixOnly("refuses a linked images folder inside .media", async () => {
const dir = scratch();
const outsideDir = scratch();
mkdirSync(join(dir, ".media"));
symlinkSync(outsideDir, join(dir, ".media", "images"));
await expect(runAssetImport("FILEKEY:1-2", { format: "png" }, deps(dir))).rejects.toThrow(
/outside the project/,
);
expect(readdirSync(outsideDir)).toEqual([]);
});
});
+2 -2
View File
@@ -13,10 +13,10 @@ import {
findAllByFigmaNode,
freezeBytes,
nextId,
ownTypeDir,
parseFigmaRef,
regenerateIndex,
sanitizeSvg,
typeDirPath,
updateRecord,
type AssetSnippet,
type FigmaAssetFormat,
@@ -134,7 +134,7 @@ async function freezeAndRecord(
bytes = new TextEncoder().encode(sanitizeSvg(new TextDecoder().decode(bytes)));
}
const id = nextId(deps.projectDir, "image");
const destAbs = join(typeDirPath(deps.projectDir, "image"), `${id}.${ext}`);
const destAbs = join(ownTypeDir(deps.projectDir, "image"), `${id}.${ext}`);
freezeBytes(bytes, destAbs);
const record: FigmaManifestRecord = {
id,
@@ -1,6 +1,15 @@
// @vitest-environment node
import { describe, expect, it, afterEach, beforeEach, vi } from "vitest";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import {
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runComponentImport } from "./component.js";
@@ -209,3 +218,42 @@ describe("runComponentImport", () => {
expect(html).toMatch(/^<div id="hero-actions"/);
});
});
describe("runComponentImport with links in the project", () => {
const posixOnly = it.skipIf(process.platform === "win32");
const outsideDirs: string[] = [];
afterEach(() => {
for (const d of outsideDirs.splice(0)) rmSync(d, { recursive: true, force: true });
});
function outsideDir(): string {
const d = mkdtempSync(join(tmpdir(), "hf-figma-outside-"));
outsideDirs.push(d);
return d;
}
posixOnly.each([
["compositions"],
["compositions/components"],
["compositions/components/hero-card"],
])("refuses when %s is a link out of the project", async (linked) => {
const outside = outsideDir();
mkdirSync(join(dir, linked, ".."), { recursive: true });
symlinkSync(outside, join(dir, linked));
await expect(importHero()).rejects.toThrow(/outside the project/);
expect(readdirSync(outside)).toEqual([]);
});
posixOnly.each([["hero-card.html"], ["registry-item.json"]])(
"replaces a linked %s instead of writing through it",
async (file) => {
const outside = join(outsideDir(), "outside.txt");
writeFileSync(outside, "keep me\n");
const componentDir = join(dir, "compositions", "components", "hero-card");
mkdirSync(componentDir, { recursive: true });
symlinkSync(outside, join(componentDir, file));
await importHero();
expect(readFileSync(outside, "utf8")).toBe("keep me\n");
expect(lstatSync(join(componentDir, file)).isFile()).toBe(true);
},
);
});
+6 -4
View File
@@ -9,6 +9,7 @@ import {
createFigmaClient,
FigmaClientError,
nodeToHtml,
ownProjectDir,
parseFigmaRef,
readBindings,
resolveBindings,
@@ -18,7 +19,8 @@ import {
type NodeToHtmlResult,
type RasterizeRequest,
} from "@hyperframes/core/figma";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { existsSync } from "node:fs";
import { join, relative } from "node:path";
function escapeAttr(value: string): string {
@@ -68,7 +70,6 @@ export async function runComponentImport(
console.warn(
`component dir compositions/components/${name} already exists — overwriting (rename the figma frame for a separate import)`,
);
mkdirSync(componentDir, { recursive: true });
const { html, frozenAssets, failedRasterize } = await rasterizeFallback(
mapped,
@@ -76,9 +77,10 @@ export async function runComponentImport(
componentDir,
deps,
);
ownProjectDir(deps.projectDir, componentDir);
const htmlFile = join(componentDir, `${name}.html`);
writeFileSync(htmlFile, html + "\n");
replaceFileAtomically(htmlFile, html + "\n");
const registryItem = {
name,
@@ -99,7 +101,7 @@ export async function runComponentImport(
})),
],
};
writeFileSync(
replaceFileAtomically(
join(componentDir, "registry-item.json"),
JSON.stringify(registryItem, null, 2) + "\n",
);
+44 -1
View File
@@ -1,6 +1,16 @@
// @vitest-environment node
import { describe, expect, it, afterEach, beforeEach } from "vitest";
import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs";
import {
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runTokensImport } from "./tokens.js";
@@ -85,3 +95,36 @@ describe("runTokensImport", () => {
expect(existsSync(join(dir, "figma-tokens.json"))).toBe(false);
});
});
describe("runTokensImport with links in the project", () => {
const posixOnly = it.skipIf(process.platform === "win32");
let outside = "";
beforeEach(() => {
outside = mkdtempSync(join(tmpdir(), "hf-figma-outside-"));
writeFileSync(join(outside, "outside.txt"), "keep me\n");
});
afterEach(() => rmSync(outside, { recursive: true, force: true }));
posixOnly("replaces a linked figma-tokens.json instead of writing through it", async () => {
symlinkSync(join(outside, "outside.txt"), join(dir, "figma-tokens.json"));
await runTokensImport("FILEKEY", { projectDir: dir, client: client({}) });
expect(readFileSync(join(outside, "outside.txt"), "utf8")).toBe("keep me\n");
expect(lstatSync(join(dir, "figma-tokens.json")).isFile()).toBe(true);
});
posixOnly("replaces a linked figma-bindings.jsonl instead of writing through it", async () => {
mkdirSync(join(dir, ".media"));
symlinkSync(join(outside, "outside.txt"), join(dir, ".media", "figma-bindings.jsonl"));
await runTokensImport("FILEKEY", { projectDir: dir, client: client({}) });
expect(readFileSync(join(outside, "outside.txt"), "utf8")).toBe("keep me\n");
expect(lstatSync(join(dir, ".media", "figma-bindings.jsonl")).isFile()).toBe(true);
});
posixOnly("refuses a .media folder that is a link", async () => {
symlinkSync(outside, join(dir, ".media"));
await expect(
runTokensImport("FILEKEY", { projectDir: dir, client: client({}) }),
).rejects.toThrow(/outside the project/);
expect(readdirSync(outside)).toEqual(["outside.txt"]);
});
});
+3 -3
View File
@@ -17,7 +17,7 @@ import {
type FigmaClient,
type FigmaTokensSidecar,
} from "@hyperframes/core/figma";
import { writeFileSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { join } from "node:path";
import { withFigmaErrors } from "./cliError.js";
@@ -55,7 +55,7 @@ export async function runTokensImport(
if (vars !== null) {
const out = tokensToVariables(vars, { fileKey, version });
upsertBindings(deps.projectDir, out.bindings);
writeFileSync(sidecarPath, JSON.stringify(out.sidecar, null, 2) + "\n");
replaceFileAtomically(sidecarPath, JSON.stringify(out.sidecar, null, 2) + "\n");
return { mode: "variables", entries: out.entries, sidecarPath };
}
@@ -71,7 +71,7 @@ export async function runTokensImport(
value: null,
})),
};
writeFileSync(sidecarPath, JSON.stringify(sidecar, null, 2) + "\n");
replaceFileAtomically(sidecarPath, JSON.stringify(sidecar, null, 2) + "\n");
return { mode: "styles", entries: [], sidecarPath, styleCount: styles.length };
}
+7 -6
View File
@@ -8,10 +8,11 @@
* color at the next brand refresh. Never match by value or name.
*/
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { replaceFileAtomically } from "../atomicFile";
import { readJsonlValues } from "./jsonl";
import { mediaDir } from "./manifest";
import { mediaDir, ownMediaDir } from "./manifest";
import { appendWithoutFollowing } from "./projectFiles";
const BINDINGS_FILE = "figma-bindings.jsonl";
@@ -69,8 +70,8 @@ function readLines(projectDir: string): unknown[] {
}
function appendLine(projectDir: string, record: unknown): void {
mkdirSync(mediaDir(projectDir), { recursive: true });
appendFileSync(bindingsPath(projectDir), JSON.stringify(record) + "\n");
ownMediaDir(projectDir);
appendWithoutFollowing(bindingsPath(projectDir), JSON.stringify(record) + "\n");
}
export function readBindings(projectDir: string): FigmaBindingRecord[] {
@@ -92,9 +93,9 @@ export function upsertBindings(projectDir: string, records: FigmaBindingRecord[]
const survivors = readLines(projectDir).filter(
(line) => !(isBindingRecord(line) && incoming.has(line.figmaId)),
);
mkdirSync(mediaDir(projectDir), { recursive: true });
ownMediaDir(projectDir);
const lines = [...survivors, ...records].map((r) => JSON.stringify(r)).join("\n");
writeFileSync(bindingsPath(projectDir), lines.length > 0 ? lines + "\n" : "");
replaceFileAtomically(bindingsPath(projectDir), lines.length > 0 ? lines + "\n" : "");
}
/** Exact-ID lookup, checking alias chains too. Never value/name matching. */
+2
View File
@@ -25,6 +25,7 @@ export {
mediaDir,
manifestPath,
typeDirPath,
ownTypeDir,
updateRecord,
isFigmaManifestRecord,
readManifest,
@@ -34,6 +35,7 @@ export {
nextId,
} from "./manifest";
export { regenerateIndex } from "./mediaIndex";
export { ownProjectDir } from "./projectFiles";
export { buildAssetSnippet } from "./assetSnippet";
export { sanitizeSvg } from "./sanitizeSvg";
export {
+15 -4
View File
@@ -1,6 +1,8 @@
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { replaceFileAtomically } from "../atomicFile";
import { readJsonlValues } from "./jsonl";
import { appendWithoutFollowing, ownProjectDir } from "./projectFiles";
import type { FigmaManifestRecord } from "./types";
const MANIFEST_FILE = "manifest.jsonl";
@@ -23,6 +25,14 @@ export function typeDirPath(projectDir: string, type: FigmaManifestRecord["type"
return join(mediaDir(projectDir), TYPE_DIRS[type]);
}
export function ownMediaDir(projectDir: string): string {
return ownProjectDir(projectDir, mediaDir(projectDir));
}
export function ownTypeDir(projectDir: string, type: FigmaManifestRecord["type"]): string {
return ownProjectDir(projectDir, typeDirPath(projectDir, type));
}
/**
* Guards figma-OWNED rows only — media-use rows (bgm/sfx/icon, no
* provenance.source) legitimately fail this and are filtered out of
@@ -59,8 +69,8 @@ export function readManifest(projectDir: string): FigmaManifestRecord[] {
}
export function appendRecord(projectDir: string, record: FigmaManifestRecord): void {
mkdirSync(typeDirPath(projectDir, record.type), { recursive: true });
appendFileSync(manifestPath(projectDir), JSON.stringify(record) + "\n");
ownTypeDir(projectDir, record.type);
appendWithoutFollowing(manifestPath(projectDir), JSON.stringify(record) + "\n");
}
export function findByFigmaNode(
@@ -102,7 +112,8 @@ export function updateRecord(projectDir: string, record: FigmaManifestRecord): v
}
return line;
});
writeFileSync(p, out.join("\n"));
ownMediaDir(projectDir);
replaceFileAtomically(p, out.join("\n"));
}
export function nextId(projectDir: string, type: FigmaManifestRecord["type"]): string {
@@ -125,3 +125,28 @@ describe("regenerateIndex", () => {
expect(ours).toBe(theirs);
});
});
describe("generateIndexContent with line breaks in a row", () => {
const BROKEN_ROWS = [
{ ...IMAGE_ROW, id: "image_009\r\n", description: "first line\nsecond line\r\n third" },
{ ...ICON_ROW, path: ".media/images/\nicon.svg", description: "\n" },
];
it("keeps each row on one line", () => {
const lines = generateIndexContent(BROKEN_ROWS).trimEnd().split("\n");
// Title, blank line, column heading, then one line per row.
expect(lines).toHaveLength(3 + BROKEN_ROWS.length);
expect(lines[3]).toContain("first line second line third");
});
it("matches media-use's index-gen output byte-for-byte", () => {
const script = `
import { generateIndexContent } from ${JSON.stringify(genUrl)};
process.stdout.write(generateIndexContent(${JSON.stringify(BROKEN_ROWS)}));
`;
const theirs = execFileSync("node", ["--input-type=module", "-e", script], {
encoding: "utf8",
});
expect(generateIndexContent(BROKEN_ROWS)).toBe(theirs);
});
});
+16 -18
View File
@@ -2,16 +2,15 @@
* Regenerate .media/index.md — the agent-readable inventory table — after a
* figma import, exactly the way media-use does after a resolve. Both writers
* regenerate the SAME file from the manifest's current rows (all writers'), so the
* output format AND row selection here must stay byte-identical with
* skills/media-use/scripts/lib/index-gen.mjs — including rendering every
* JSON-parseable row (no shape filtering), or the file would flip-flop
* output format AND row selection (every JSON-parseable row, no shape filtering) must stay
* byte-identical with skills/media-use/scripts/lib/index-gen.mjs, or the file would flip-flop
* depending on which writer ran last.
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { join } from "node:path";
import { replaceFileAtomically } from "../atomicFile";
import { readJsonlValues } from "./jsonl";
import { manifestPath, mediaDir } from "./manifest";
import { manifestPath, mediaDir, ownMediaDir } from "./manifest";
type IndexRow = Record<string, unknown>;
@@ -23,8 +22,12 @@ export function indexPath(projectDir: string): string {
return join(mediaDir(projectDir), "index.md");
}
function singleLineCell(value: unknown): string {
return String(value ?? "").replace(/\s*[\r\n]+\s*/g, " ");
}
function pad(str: unknown, len: number): string {
return String(str ?? "").padEnd(len);
return singleLineCell(str).padEnd(len);
}
function formatDur(r: IndexRow): string {
@@ -38,10 +41,6 @@ function formatDims(r: IndexRow): string {
return "—";
}
function len(value: unknown): number {
return String(value ?? "").length;
}
export function generateIndexContent(records: IndexRow[]): string {
const count = records.length;
const header = `# .media · ${count} asset${count === 1 ? "" : "s"}\n`;
@@ -49,11 +48,11 @@ export function generateIndexContent(records: IndexRow[]): string {
const cols = { id: 4, type: 5, dur: 4, dims: 5, path: 5 };
for (const r of records) {
cols.id = Math.max(cols.id, len(r.id));
cols.type = Math.max(cols.type, len(r.type));
cols.id = Math.max(cols.id, singleLineCell(r.id).length);
cols.type = Math.max(cols.type, singleLineCell(r.type).length);
cols.dur = Math.max(cols.dur, formatDur(r).length);
cols.dims = Math.max(cols.dims, formatDims(r).length);
cols.path = Math.max(cols.path, len(r.path));
cols.path = Math.max(cols.path, singleLineCell(r.path).length);
}
const heading =
@@ -72,7 +71,7 @@ export function generateIndexContent(records: IndexRow[]): string {
pad(formatDur(r), cols.dur + 2) +
pad(formatDims(r), cols.dims + 2) +
pad(r.path, cols.path + 2) +
String(r.description ?? ""),
singleLineCell(r.description),
);
}
return lines.join("\n") + "\n";
@@ -84,8 +83,7 @@ export function regenerateIndex(projectDir: string): string {
const last = new Map(rows.map((row, index) => [row.path, index]));
const records = rows.filter((row, index) => !row.path || last.get(row.path) === index);
const content = generateIndexContent(records);
const p = indexPath(projectDir);
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, content);
ownMediaDir(projectDir);
replaceFileAtomically(indexPath(projectDir), content);
return content;
}
+94
View File
@@ -0,0 +1,94 @@
/**
* Folders and appends for figma's project writes that never follow a link out
* of the project. Whole-file rewrites use `replaceFileAtomically`, whose rename
* replaces a link instead of writing through it.
*/
import {
closeSync,
constants,
fstatSync,
lstatSync,
mkdirSync,
openSync,
realpathSync,
statSync,
writeSync,
} from "node:fs";
import { isAbsolute, join, relative, resolve, sep } from "node:path";
function leadsOutside(dir: string): Error {
return new Error(`${dir} leads outside the project folder; nothing was written there`);
}
/**
* Creates `dir` under `projectDir` one folder at a time and returns it. Throws
* when any folder on the way is a link or not a folder.
*/
export function ownProjectDir(projectDir: string, dir: string): string {
const root = resolve(projectDir);
const target = resolve(dir);
const rel = relative(root, target);
if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw leadsOutside(target);
mkdirSync(root, { recursive: true });
let current = root;
// The JS realpathSync, not .native: it keeps the case asked for, as `expected` does.
let expected = realpathSync(root);
for (const segment of rel.split(sep).filter(Boolean)) {
current = join(current, segment);
expected = join(expected, segment);
try {
mkdirSync(current);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
if (lstatSync(current).isSymbolicLink() || realpathSync(current) !== expected) {
throw leadsOutside(current);
}
if (!statSync(current).isDirectory()) {
throw new Error(`${current} is not a folder; nothing was written there`);
}
}
return target;
}
function notPlainFile(path: string): Error {
return new Error(`${path} is a link or not a plain file; nothing was written through it`);
}
/**
* Throws on a link at `path` instead of appending through it. Opened first, then
* written only when `lstat` finds the same single-link plain file at the path, as
* projectRecords' appendRecord does; O_NOFOLLOW is undefined on Windows.
*/
export function appendWithoutFollowing(path: string, text: string): void {
let fd: number;
try {
fd = openSync(
path,
constants.O_WRONLY |
constants.O_APPEND |
constants.O_CREAT |
(constants.O_NOFOLLOW ?? 0) |
(constants.O_NONBLOCK ?? 0),
0o666,
);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ELOOP") throw notPlainFile(path);
throw error;
}
try {
const opened = fstatSync(fd);
const named = lstatSync(path);
const samePlainFile =
opened.isFile() &&
named.isFile() &&
opened.nlink === 1 &&
named.ino === opened.ino &&
named.dev === opened.dev;
if (!samePlainFile) throw notPlainFile(path);
writeSync(fd, text);
} finally {
closeSync(fd);
}
}