GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(server): theme publish refuses a directory under the theme's file… · pingdotgg/t3code@2585493

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/cli
    • theme.test.ts
    • theme.ts
  • scripts/scenarios
    • cli-theme-publish-keeps-existing-directory.e2e.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/cli/theme.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/cli/theme.test.ts
+72Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@ import * as Effect from "effect/Effect";
1212
import * as Layer from "effect/Layer";
1313
import * as TestConsole from "effect/testing/TestConsole";
1414
import { Command } from "effect/cli";
15+
import { vi } from "vite-plus/test";
1516

1617
import { cli } from "../binCli.ts";
1718
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
1819
import * as HostProcess from "@t3tools/shared/HostProcess";
1920

21+
vi.mock("node:fs", { spy: true });
22+
2023
// Windows chmod cannot force these directory or file permission failures.
2124
const windowsHost = HostProcess.Platform.defaultValue() === "win32";
2225

@@ -133,6 +136,75 @@ describe("t3 theme", () => {
133136
}),
134137
);
135138

139+
it.effect("refuses to publish over a directory with the theme's file name", () =>
140+
Effect.gen(function* () {
141+
const baseDir = makeBaseDir();
142+
const taken = NodePath.join(baseDir, "userdata", "themes", "nightfall.json");
143+
NodeFS.mkdirSync(taken, { recursive: true });
144+
NodeFS.writeFileSync(NodePath.join(taken, "notes.txt"), "notes");
145+
const themeFile = NodePath.join(baseDir, "nightfall.json");
146+
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
147+
148+
const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
149+
Effect.flip,
150+
);
151+
152+
assert.include(String(failure), "is a directory");
153+
assert.equal(NodeFS.readFileSync(NodePath.join(taken, "notes.txt"), "utf8"), "notes");
154+
assert.deepEqual(NodeFS.readdirSync(NodePath.dirname(taken)), ["nightfall.json"]);
155+
assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
156+
}),
157+
);
158+
159+
it.effect("refuses to publish over a directory created just before backup", () =>
160+
Effect.gen(function* () {
161+
const baseDir = makeBaseDir();
162+
const themeFile = NodePath.join(baseDir, "nightfall.json");
163+
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
164+
const themesDir = NodePath.join(baseDir, "userdata", "themes");
165+
const destination = NodePath.join(themesDir, "nightfall.json");
166+
const notes = NodePath.join(destination, "notes.txt");
167+
const { renameSync } = yield* Effect.promise(() => vi.importActual<typeof NodeFS>("node:fs"));
168+
using _insertDirectory = vi.spyOn(NodeFS, "renameSync").mockImplementationOnce((from, to) => {
169+
NodeFS.mkdirSync(destination);
170+
NodeFS.writeFileSync(notes, "notes");
171+
renameSync(from, to);
172+
});
173+
174+
const failure = yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]).pipe(
175+
Effect.flip,
176+
);
177+
178+
assert.include(String(failure), "is a directory");
179+
assert.equal(NodeFS.readFileSync(notes, "utf8"), "notes");
180+
assert.deepEqual(NodeFS.readdirSync(themesDir), ["nightfall.json"]);
181+
assert.equal(NodeFS.existsSync(settingsPathFor(baseDir)), false);
182+
}),
183+
);
184+
185+
it.effect("publishes a theme despite a rollback file left by an earlier process", () =>
186+
Effect.gen(function* () {
187+
const baseDir = makeBaseDir();
188+
const themeFile = NodePath.join(baseDir, "nightfall.json");
189+
NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON);
190+
const themesDir = NodePath.join(baseDir, "userdata", "themes");
191+
const destination = NodePath.join(themesDir, "nightfall.json");
192+
const staleBackup = `${destination}.rollback-${process.pid}`;
193+
NodeFS.mkdirSync(themesDir, { recursive: true });
194+
NodeFS.writeFileSync(staleBackup, "previous theme");
195+
196+
yield* runCli(["theme", "set", themeFile, "--base-dir", baseDir]);
197+
198+
assert.equal(readSettings(baseDir).defaultTheme, "nightfall");
199+
assert.equal(NodeFS.readFileSync(destination, "utf8"), NIGHTFALL_THEME_JSON);
200+
assert.equal(NodeFS.readFileSync(staleBackup, "utf8"), "previous theme");
201+
assert.deepEqual(NodeFS.readdirSync(themesDir).sort(), [
202+
"nightfall.json",
203+
NodePath.basename(staleBackup),
204+
]);
205+
}),
206+
);
207+
136208
it.effect("rejects a file that is not a theme and sets nothing", () =>
137209
Effect.gen(function* () {
138210
const baseDir = makeBaseDir();
Collapse file

‎apps/server/src/cli/theme.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/cli/theme.ts
+52-11Lines changed: 52 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// @effect-diagnostics nodeBuiltinImport:off - publish commits and rollbacks
22
// move exact directory entries with rename, which the FileSystem service does
33
// not expose atomically.
4+
import * as NodeCrypto from "node:crypto";
45
import * as NodeFS from "node:fs";
56

67
import {
@@ -120,6 +121,17 @@ export class ThemePublishError extends Schema.TaggedError<ThemePublishError>()(
120121
}
121122
}
122123

124+
export class ThemeDestinationDirectoryError extends Schema.TaggedError<ThemeDestinationDirectoryError>()(
125+
"ThemeDestinationDirectoryError",
126+
{ themeId: Schema.String, destinationPath: Schema.String },
127+
) {
128+
override get message(): string {
129+
return `${this.destinationPath} is a directory, so the theme cannot be published as "${this.themeId}". Move it, or pass another id with --id.`;
130+
}
131+
}
132+
133+
const isThemeDestinationDirectoryError = Schema.is(ThemeDestinationDirectoryError);
134+
123135
const INVALID_THEME_ID_REASON =
124136
"is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword)";
125137

@@ -306,8 +318,6 @@ const publishThemeFile = Effect.fn(function* (input: {
306318
}
307319

308320
const destinationPath = path.join(input.themesDir, `${themeId}.json`);
309-
// Non-JSON suffixes hide these from the watcher; PIDs isolate concurrent publishers.
310-
const backupPath = `${destinationPath}.rollback-${process.pid}`;
311321
const stagingPath = `${destinationPath}.staging-${process.pid}`;
312322
yield* fs
313323
.makeDirectory(input.themesDir, { recursive: true })
@@ -316,6 +326,14 @@ const publishThemeFile = Effect.fn(function* (input: {
316326
const publishFailure = (cause: unknown) =>
317327
new ThemePublishError({ themesDir: input.themesDir, cause });
318328

329+
const destinationIsDirectory = yield* Effect.try({
330+
try: () => NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory() ?? false,
331+
catch: publishFailure,
332+
});
333+
if (destinationIsDirectory) {
334+
return yield* new ThemeDestinationDirectoryError({ themeId, destinationPath });
335+
}
336+
319337
// O_EXCL prevents following a symlink at the predictable staging path.
320338
// Preserve bytes exactly: even an added newline could exceed the watcher's size limit.
321339
const stagedIno = yield* Effect.try({
@@ -338,19 +356,42 @@ const publishThemeFile = Effect.fn(function* (input: {
338356
catch: publishFailure,
339357
});
340358

341-
// Atomic rename avoids a check/replace race and preserves the exact entry for rollback.
342-
const hadPrevious = yield* Effect.try({
359+
const backupPath = yield* Effect.try({
343360
try: () => {
361+
// A fresh path leaves any backup from a crashed publish intact.
362+
const rollbackPath = `${destinationPath}.rollback-${NodeCrypto.randomUUID()}`;
363+
// A rename onto a regular file rejects a directory even if it appeared after lstat.
364+
const fd = NodeFS.openSync(rollbackPath, "wx", 0o600);
365+
let saved = false;
344366
try {
345-
NodeFS.renameSync(destinationPath, backupPath);
346-
return true;
367+
NodeFS.closeSync(fd);
368+
NodeFS.renameSync(destinationPath, rollbackPath);
369+
saved = true;
370+
return rollbackPath;
347371
} catch (error) {
348-
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
372+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
373+
if (NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory()) {
374+
throw new ThemeDestinationDirectoryError({ themeId, destinationPath });
375+
}
349376
throw error;
377+
} finally {
378+
if (!saved) {
379+
try {
380+
NodeFS.unlinkSync(rollbackPath);
381+
} catch {}
382+
}
350383
}
351384
},
352-
catch: publishFailure,
353-
});
385+
catch: (cause) => (isThemeDestinationDirectoryError(cause) ? cause : publishFailure(cause)),
386+
}).pipe(
387+
Effect.onError(() =>
388+
Effect.sync(() => {
389+
try {
390+
NodeFS.unlinkSync(stagingPath);
391+
} catch {}
392+
}),
393+
),
394+
);
354395

355396
const revert = Effect.sync(() => {
356397
try {
@@ -365,7 +406,7 @@ const publishThemeFile = Effect.fn(function* (input: {
365406
return null;
366407
}
367408
})();
368-
if (hadPrevious) {
409+
if (backupPath !== null) {
369410
if (destinationIno === null || destinationIno === stagedIno) {
370411
NodeFS.renameSync(backupPath, destinationPath);
371412
} else {
@@ -378,7 +419,7 @@ const publishThemeFile = Effect.fn(function* (input: {
378419
});
379420
const cleanup = Effect.sync(() => {
380421
try {
381-
if (hadPrevious) NodeFS.unlinkSync(backupPath);
422+
if (backupPath !== null) NodeFS.unlinkSync(backupPath);
382423
} catch {}
383424
});
384425

Collapse file

‎scripts/scenarios/cli-theme-publish-keeps-existing-directory.e2e.ts‎

Copy file name to clipboard
+50Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/// <reference lib="dom" />
2+
import { expect } from "e2e";
3+
4+
import { makeState, runPromise, test, WEB } from "./t3.ts";
5+
6+
const NOTE = "userdata/themes/nightfall.json/notes.txt";
7+
const BODY = "Notes for the original Nightfall palette";
8+
9+
test(
10+
"Publishing a theme preserves files in an existing directory under the same name",
11+
WEB,
12+
async ({ t3, app, browser, screen }) => {
13+
const project = await t3.project("theme-workspace", {
14+
[NOTE]: BODY,
15+
"nightfall.json": JSON.stringify({
16+
name: "Nightfall",
17+
appearance: "dark",
18+
canvas: "#1a1b26",
19+
accent: "#7aa2f7",
20+
}),
21+
});
22+
const thread = await t3.thread({
23+
project,
24+
title: "Theme notes",
25+
messages: [`See :codex-file-citation{path="${NOTE}" line_range_start="1"}`],
26+
});
27+
const { cli } = makeState(project);
28+
await runPromise(cli(["theme", "set", `${project}/nightfall.json`], [0, 1]));
29+
30+
await t3.open(thread);
31+
await screen.getByRole("button", /^Agent See/).tap();
32+
await screen.getByRole("link", /^notes\.txt/).tap();
33+
34+
try {
35+
await expect
36+
.poll(() =>
37+
browser.evaluate(() => {
38+
for (const host of document.querySelectorAll("*")) {
39+
const content = host.shadowRoot?.querySelector("[data-content]");
40+
if (content) return content.textContent ?? "";
41+
}
42+
return null;
43+
}),
44+
)
45+
.toContain(BODY);
46+
} finally {
47+
await app.screenshot("open-original-theme-notes");
48+
}
49+
},
50+
);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.