Skip to content

Commit 7a1eec8

Browse files
committed
fix(studio): harden conditional file writes
1 parent 5efd5b1 commit 7a1eec8

3 files changed

Lines changed: 94 additions & 20 deletions

File tree

‎packages/studio-server/src/routes/files.ts‎

Lines changed: 82 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@
55
import type { Hono } from "hono";
66
import { bodyLimit } from "hono/body-limit";
77
import {
8+
closeSync,
89
existsSync,
10+
ftruncateSync,
11+
openSync,
912
readFileSync,
1013
writeFileSync,
14+
writeSync,
1115
mkdirSync,
1216
unlinkSync,
1317
rmSync,
@@ -1959,36 +1963,95 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
19591963
if ("error" in res) return res.error;
19601964

19611965
const body = await c.req.text();
1962-
const existed = existsSync(res.absPath);
1963-
const currentContent = existed ? readFileSync(res.absPath, "utf-8") : null;
1964-
const currentVersion = currentContent === null ? null : fileContentVersion(currentContent);
19651966
const expectedVersion = c.req.header("If-Match")?.trim() ?? null;
19661967
const createOnly = c.req.header("If-None-Match")?.trim() === "*";
19671968
if (expectedVersion === null && !createOnly) {
1968-
return c.json(
1969-
{ error: "precondition required", path: res.filePath, currentVersion, currentContent },
1970-
428,
1971-
);
1972-
}
1973-
if (
1974-
(createOnly && existed) ||
1975-
(expectedVersion !== null && expectedVersion !== currentVersion)
1976-
) {
1969+
let currentContent: string | null = null;
1970+
try {
1971+
currentContent = readFileSync(res.absPath, "utf-8");
1972+
} catch (error) {
1973+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") {
1974+
throw error;
1975+
}
1976+
}
19771977
return c.json(
19781978
{
1979-
error: "file conflict",
1979+
error: "precondition required",
19801980
path: res.filePath,
1981-
currentVersion,
1981+
currentVersion: currentContent === null ? null : fileContentVersion(currentContent),
19821982
currentContent,
19831983
},
1984-
409,
1984+
428,
19851985
);
19861986
}
19871987

1988-
ensureDir(res.absPath);
1989-
const backup = snapshotBeforeWrite(res.project.dir, res.absPath);
1990-
if (backup.error) console.warn(`Failed to create backup for ${res.filePath}: ${backup.error}`);
1991-
writeFileSync(res.absPath, body, "utf-8");
1988+
let backup: ReturnType<typeof snapshotBeforeWrite> = { backupPath: null };
1989+
if (createOnly) {
1990+
ensureDir(res.absPath);
1991+
let fd: number;
1992+
try {
1993+
fd = openSync(res.absPath, "wx");
1994+
} catch (error) {
1995+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
1996+
throw error;
1997+
}
1998+
const currentContent = readFileSync(res.absPath, "utf-8");
1999+
return c.json(
2000+
{
2001+
error: "file conflict",
2002+
path: res.filePath,
2003+
currentVersion: fileContentVersion(currentContent),
2004+
currentContent,
2005+
},
2006+
409,
2007+
);
2008+
}
2009+
try {
2010+
writeSync(fd, body, 0, "utf-8");
2011+
} finally {
2012+
closeSync(fd);
2013+
}
2014+
} else {
2015+
let fd: number;
2016+
try {
2017+
fd = openSync(res.absPath, "r+");
2018+
} catch (error) {
2019+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") {
2020+
throw error;
2021+
}
2022+
return c.json(
2023+
{
2024+
error: "file conflict",
2025+
path: res.filePath,
2026+
currentVersion: null,
2027+
currentContent: null,
2028+
},
2029+
409,
2030+
);
2031+
}
2032+
try {
2033+
const currentContent = readFileSync(fd, "utf-8");
2034+
const currentVersion = fileContentVersion(currentContent);
2035+
if (expectedVersion !== currentVersion) {
2036+
return c.json(
2037+
{
2038+
error: "file conflict",
2039+
path: res.filePath,
2040+
currentVersion,
2041+
currentContent,
2042+
},
2043+
409,
2044+
);
2045+
}
2046+
backup = snapshotBeforeWrite(res.project.dir, res.absPath);
2047+
if (backup.error)
2048+
console.warn(`Failed to create backup for ${res.filePath}: ${backup.error}`);
2049+
ftruncateSync(fd, 0);
2050+
writeSync(fd, body, 0, "utf-8");
2051+
} finally {
2052+
closeSync(fd);
2053+
}
2054+
}
19922055
const version = fileContentVersion(body);
19932056
const writeToken = createWriteToken(c.req.header("X-Hyperframes-Write-Token"));
19942057
recordFileWriteReceipt(res.absPath, { path: res.filePath, version, writeToken });

‎packages/studio/src/hooks/useFileManager.projectOwnership.test.tsx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ describe("useFileManager project ownership", () => {
3838
resolveProjectARead = resolve;
3939
});
4040
const fetchMock = vi.fn((url: string, init?: RequestInit) => {
41+
if (url.endsWith("/files/missing.html") && !init?.method) {
42+
return Promise.resolve({ ok: false, status: 404 } as Response);
43+
}
4144
if (url.includes("project-a") && !init?.method) return projectARead;
4245
if (!init?.method) {
4346
return Promise.resolve({
@@ -78,6 +81,7 @@ describe("useFileManager project ownership", () => {
7881
} as Response);
7982
await expect(delayedRead).resolves.toBe("PROJECT_A");
8083
await managerA.writeProjectFile("index.html", "A_AFTER");
84+
await managerA.writeProjectFile("missing.html", "A_NEW");
8185
await expect(managerB.readProjectFile("index.html")).resolves.toBe("PROJECT_B");
8286
await expect(managerB.readOptionalProjectFile("index.html")).resolves.toBe("PROJECT_B");
8387

@@ -88,6 +92,13 @@ describe("useFileManager project ownership", () => {
8892
"/api/projects/project-a%2F..%2Fother%3Fx%3D1/files/index.html",
8993
expect.objectContaining({ method: "PUT", body: "A_AFTER" }),
9094
);
95+
expect(fetchMock).toHaveBeenCalledWith(
96+
"/api/projects/project-a%2F..%2Fother%3Fx%3D1/files/missing.html",
97+
);
98+
expect(fetchMock).toHaveBeenCalledWith(
99+
"/api/projects/project-a%2F..%2Fother%3Fx%3D1/files/missing.html",
100+
expect.objectContaining({ method: "PUT", body: "A_NEW" }),
101+
);
91102
expect(fetchMock).toHaveBeenCalledWith("/api/projects/project-b%23fragment/files/index.html");
92103
expect(fetchMock).toHaveBeenCalledWith(
93104
"/api/projects/project-b%23fragment/files/index.html?optional=1",

‎packages/studio/src/hooks/useFileManager.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ export function useFileManager({
101101
let expectedVersion = await studioExpectedFileVersion(fileVersions, path, expectedContent);
102102
if (expectedVersion === undefined) {
103103
const preflight = await fetch(
104-
`/api/projects/${writeProjectId}/files/${encodeURIComponent(path)}`,
104+
`/api/projects/${encodeURIComponent(writeProjectId)}/files/${encodeURIComponent(path)}`,
105105
);
106106
if (preflight.ok) {
107107
const data = (await preflight.json()) as { content?: string; version?: string };

0 commit comments

Comments
 (0)