Files
Florian Schmidt 2e907b75f2 fix(server): keep existing notebooks manageable and pruning inside notebooks/ (#9)
Reading, saving, renaming and deleting applied the create-time name rules
to existing files, so notebooks named outside those rules (umlauts,
brackets; written by git or Claude) were listed but returned 400. Name rules
now apply to new paths only; existing paths keep the traversal/symlink checks.

Empty-folder pruning compared a realpath against an unresolved root. With a
symlinked workspace path it walked past notebooks/ and removed the
notebooks folder itself. It now uses the resolved root and stops at it.
2026-11-16 10:19:02 +01:00

305 lines
9.8 KiB
TypeScript

import { afterEach, expect, it } from "vitest";
import { mkdtemp, mkdir, rm, symlink, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildApp } from "../src/app";
import { notebookName, notebookDestination } from "../src/workspace/notebooks";
import { setPassword } from "../src/auth/credentials";
const dirs: string[] = [];
afterEach(async () => {
for (const dir of dirs.splice(0))
await rm(dir, { recursive: true, force: true });
});
async function setup(auth = false) {
const dir = await mkdtemp(join(tmpdir(), "shellbook-notebooks-"));
dirs.push(dir);
await mkdir(join(dir, "notebooks"));
await setPassword(dir, "test password");
return {
dir,
app: await buildApp({
config: { workspaceDir: dir, dataDir: dir },
auth: auth ? { dataDir: dir } : false,
}),
};
}
it.each([
"../x.md",
"/x.md",
"C:/x.md",
"a\\x.md",
"a/../x.md",
"a//x.md",
"a.txt",
"a/./x.md",
"nul.md",
"x\u0000.md",
"a./x.md",
])("rejects invalid notebook path %s", (name) => {
expect(() => notebookName(name)).toThrow();
});
it("rejects symlink parents, files and notebook root", async () => {
const { app, dir } = await setup();
try {
await mkdir(join(dir, "outside"));
await symlink(
join(dir, "outside"),
join(dir, "notebooks", "linked"),
"junction",
);
await expect(
notebookDestination({ workspaceDir: dir } as never, "linked/new.md"),
).rejects.toThrow("Symlinks");
await rm(join(dir, "notebooks"), { recursive: true });
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
await expect(
notebookDestination({ workspaceDir: dir } as never, "new.md"),
).rejects.toThrow("Symlinks");
} finally {
await app.close();
}
});
it("creates, duplicates, moves, saves and deletes with conflicts and prunes folders", async () => {
const { app, dir } = await setup();
const url = (p: string) => `/api/notebooks/${encodeURIComponent(p)}`;
try {
const created = await app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "old/a.md", source: "# A\n" },
});
expect(created.statusCode).toBe(200);
let baseVersion = created.json().version;
expect(
(
await app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "old/a.md", source: "overwrite" },
})
).statusCode,
).toBe(409);
for (const op of ["rename", "duplicate"]) {
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + `/${op}`,
payload: { path: "new/b.md", baseVersion: "stale" },
})
).statusCode,
).toBe(409);
}
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + "/duplicate",
payload: { path: "copy.md", baseVersion },
})
).statusCode,
).toBe(200);
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + "/rename",
payload: { path: "copy.md", baseVersion },
})
).statusCode,
).toBe(409);
expect(
(
await app.inject({
method: "POST",
url: url("old/a.md") + "/rename",
payload: { path: "new/b.md", baseVersion },
})
).statusCode,
).toBe(200);
await expect(stat(join(dir, "notebooks", "old"))).rejects.toThrow();
expect((await app.inject(url("new/b.md"))).json().source).toBe("# A\n");
const saved = await app.inject({
method: "PUT",
url: url("new/b.md"),
payload: { source: "# B", baseVersion },
});
expect(saved.statusCode).toBe(200);
baseVersion = saved.json().version;
expect(
(
await app.inject({
method: "DELETE",
url: url("new/b.md"),
payload: { baseVersion: "stale" },
})
).statusCode,
).toBe(409);
expect(
(
await app.inject({
method: "DELETE",
url: url("new/b.md"),
payload: { baseVersion },
})
).statusCode,
).toBe(200);
await expect(stat(join(dir, "notebooks", "new"))).rejects.toThrow();
expect((await app.inject(url("new/b.md"))).statusCode).toBe(404);
} finally {
await app.close();
}
});
it("guards every management route with session and origin checks", async () => {
const { app } = await setup(true);
try {
const login = await app.inject({
method: "POST",
url: "/api/auth/login",
payload: { password: "test password" },
});
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
for (const [method, url] of [
["POST", "/api/notebooks"],
["POST", "/api/notebooks/a.md/rename"],
["POST", "/api/notebooks/a.md/duplicate"],
["DELETE", "/api/notebooks/a.md"],
] as const) {
expect((await app.inject({ method, url, payload: {} })).statusCode).toBe(
401,
);
expect(
(
await app.inject({
method,
url,
payload: {},
headers: { cookie, origin: "https://evil.test" },
})
).statusCode,
).toBe(403);
}
} finally {
await app.close();
}
});
it("rejects notebook reads through a symlinked notebooks root", async () => {
const { app, dir } = await setup();
try {
const { writeFile } = await import("node:fs/promises");
await mkdir(join(dir, "outside"));
await writeFile(join(dir, "outside", "secret.md"), "private");
await rm(join(dir, "notebooks"), { recursive: true });
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
expect((await app.inject("/api/notebooks/secret.md")).statusCode).toBe(400);
} finally {
await app.close();
}
});
it("publishes create/move/delete changes to other tabs through the watcher", async () => {
const { vi } = await import("vitest");
const { EventsHub } = await import("../src/runs");
const dir = await mkdtemp(join(tmpdir(), "shellbook-events-"));
dirs.push(dir);
await mkdir(join(dir, "notebooks"));
const hub = new EventsHub();
const events: unknown[] = [];
hub.subscribe((event) => events.push(event));
const app = await buildApp({
config: { workspaceDir: dir, dataDir: dir },
auth: false,
events: hub,
watchNotebooks: true,
});
try {
const created = await app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "old/a.md", source: "# A" },
});
await vi.waitFor(() =>
expect(events).toContainEqual({ type: "file.changed", path: "old/a.md" }),
);
expect(
(
await app.inject({
method: "POST",
url: "/api/notebooks/old%2Fa.md/rename",
payload: { path: "new/a.md", baseVersion: created.json().version },
})
).statusCode,
).toBe(200);
await vi.waitFor(() => {
expect(events).toContainEqual({ type: "file.deleted", path: "old/a.md" });
expect(events).toContainEqual({ type: "file.changed", path: "new/a.md" });
});
await app.inject({
method: "DELETE",
url: "/api/notebooks/new%2Fa.md",
payload: { baseVersion: created.json().version },
});
await vi.waitFor(() =>
expect(events).toContainEqual({ type: "file.deleted", path: "new/a.md" }),
);
} finally {
await app.close();
}
});
it("does not overwrite concurrent creates", async () => {
const { app } = await setup();
try {
const responses = await Promise.all(
["one", "two"].map((source) =>
app.inject({
method: "POST",
url: "/api/notebooks",
payload: { path: "race.md", source },
}),
),
);
expect(responses.map((r) => r.statusCode).sort()).toEqual([200, 409]);
} finally {
await app.close();
}
});
it("still opens and saves existing notebooks whose names the create rules would reject", async () => {
const { app, dir } = await setup();
try {
const { writeFile } = await import("node:fs/promises");
// Written by git or Claude, not through the create API.
await writeFile(join(dir, "notebooks", "Übersicht (alt).md"), "# Old\n");
const name = encodeURIComponent("Übersicht (alt).md");
const read = await app.inject(`/api/notebooks/${name}`);
expect(read.statusCode).toBe(200);
const save = await app.inject({ method: "PUT", url: `/api/notebooks/${name}`, payload: { source: "# New\n", baseVersion: read.json().version } });
expect(save.statusCode).toBe(200);
const moved = await app.inject({ method: "POST", url: `/api/notebooks/${name}/rename`, payload: { path: "uebersicht.md", baseVersion: save.json().version } });
expect(moved.statusCode).toBe(200);
expect((await app.inject("/api/notebooks/uebersicht.md")).statusCode).toBe(200);
} finally {
await app.close();
}
});
it("never removes folders outside notebooks/ when the workspace path is a symlink", async () => {
const real = await mkdtemp(join(tmpdir(), "shellbook-real-"));
const linkParent = await mkdtemp(join(tmpdir(), "shellbook-link-"));
dirs.push(real, linkParent);
await mkdir(join(real, "notebooks"));
const workspace = join(linkParent, "ws");
await symlink(real, workspace, "junction");
const app = await buildApp({ config: { workspaceDir: workspace, dataDir: real }, auth: false });
try {
const created = await app.inject({ method: "POST", url: "/api/notebooks", payload: { path: "a/x.md", source: "# X\n" } });
expect(created.statusCode).toBe(200);
const deleted = await app.inject({ method: "DELETE", url: `/api/notebooks/${encodeURIComponent("a/x.md")}`, payload: { baseVersion: created.json().version } });
expect(deleted.statusCode).toBe(200);
expect((await stat(join(real, "notebooks"))).isDirectory()).toBe(true);
} finally {
await app.close();
}
});