feat(notebooks): manage and author notebooks in the web UI (#9)
Add atomic, versioned notebook mutations, a searchable folder tree, and editor insertion forms. Validate notebook paths and symlink roots and retain drafts after external changes. Add yaml as a direct web dependency, reusing the existing workspace library for comment-preserving frontmatter edits.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { atomicNotebookWrite, notebookDestination, notebookRoot, notebookManagement } from "./notebooks";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile, readdir, realpath, lstat } from "node:fs/promises";
|
||||
import { readFile, readdir, realpath, lstat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { parse } from "yaml";
|
||||
import { parseNotebook, type HostInfo } from "@shellbook/core";
|
||||
@@ -34,6 +35,7 @@ export async function safeFile(root: string, name: string): Promise<string> {
|
||||
}
|
||||
|
||||
export async function readNotebook(config: ServerConfig, name: string) {
|
||||
await notebookDestination(config, name);
|
||||
if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed");
|
||||
const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name);
|
||||
return { file, source: await readFile(file, "utf8") };
|
||||
@@ -71,6 +73,7 @@ export class SerialQueue {
|
||||
|
||||
export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) {
|
||||
const saves = new SerialQueue();
|
||||
notebookManagement(app, config, saves);
|
||||
app.get("/api/hosts", async () => ({ hosts: await readHosts(config) }));
|
||||
app.get("/api/notebooks", async () => {
|
||||
const notebooks: { path: string; title: string }[] = [];
|
||||
@@ -84,6 +87,7 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
|
||||
}
|
||||
}
|
||||
}
|
||||
await notebookRoot(config);
|
||||
await walk(path.join(config.workspaceDir, "notebooks"));
|
||||
return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) };
|
||||
});
|
||||
@@ -93,10 +97,10 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
|
||||
});
|
||||
app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => {
|
||||
if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request");
|
||||
return saves.run(req.params.path, async () => {
|
||||
return saves.run("notebooks", async () => {
|
||||
const { file, source } = await readNotebook(config, req.params.path);
|
||||
if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed");
|
||||
await writeFile(file, req.body.source, "utf8");
|
||||
await atomicNotebookWrite(file, req.body.source);
|
||||
return { version: version(req.body.source) };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
realpath,
|
||||
writeFile,
|
||||
rename,
|
||||
unlink,
|
||||
rmdir,
|
||||
link,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type {
|
||||
CreateNotebookRequest,
|
||||
MoveNotebookRequest,
|
||||
DeleteNotebookRequest,
|
||||
} from "@shellbook/core";
|
||||
import { httpError, readNotebook, SerialQueue, version } from "./index";
|
||||
import type { ServerConfig } from "../config";
|
||||
|
||||
export function notebookName(name: string): string {
|
||||
if (
|
||||
typeof name !== "string" ||
|
||||
name.length > 240 ||
|
||||
!name.endsWith(".md") ||
|
||||
name
|
||||
.split("/")
|
||||
.some(
|
||||
(p) =>
|
||||
!/^[A-Za-z0-9][A-Za-z0-9 _.-]*$/.test(p) ||
|
||||
p.includes("..") ||
|
||||
/[. ]$/.test(p) ||
|
||||
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p),
|
||||
)
|
||||
) {
|
||||
throw httpError(
|
||||
400,
|
||||
"Use a relative .md path with letters, numbers, spaces, dots, underscores or hyphens",
|
||||
);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/** Validate the root before resolving any notebook path. */
|
||||
export async function notebookRoot(config: ServerConfig): Promise<string> {
|
||||
const root = path.join(await realpath(config.workspaceDir), "notebooks");
|
||||
try {
|
||||
const info = await lstat(root);
|
||||
if (info.isSymbolicLink() || !info.isDirectory())
|
||||
throw httpError(
|
||||
400,
|
||||
"Symlinks and non-directory parents are not allowed",
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Walk every component; never follow symlinks. */
|
||||
export async function notebookDestination(
|
||||
config: ServerConfig,
|
||||
name: string,
|
||||
): Promise<string> {
|
||||
notebookName(name);
|
||||
let current = await notebookRoot(config);
|
||||
const parts = name.split("/");
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
current = path.join(current, parts[i]!);
|
||||
try {
|
||||
const info = await lstat(current);
|
||||
if (
|
||||
info.isSymbolicLink() ||
|
||||
(i < parts.length - 1 && !info.isDirectory())
|
||||
)
|
||||
throw httpError(
|
||||
400,
|
||||
"Symlinks and non-directory parents are not allowed",
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
export async function atomicNotebookWrite(
|
||||
file: string,
|
||||
source: string,
|
||||
exclusive = false,
|
||||
) {
|
||||
await mkdir(path.dirname(file), { recursive: true });
|
||||
const temp = path.join(path.dirname(file), `.shellbook-${randomUUID()}.tmp`);
|
||||
try {
|
||||
await writeFile(temp, source, {
|
||||
encoding: "utf8",
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
// link publishes a complete file without replacing an existing destination.
|
||||
if (exclusive) await link(temp, file);
|
||||
else await rename(temp, file);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === "EEXIST")
|
||||
throw httpError(409, "Notebook already exists");
|
||||
throw e;
|
||||
} finally {
|
||||
await unlink(temp).catch(() => {});
|
||||
}
|
||||
}
|
||||
async function prune(config: ServerConfig, file: string) {
|
||||
const root = path.resolve(config.workspaceDir, "notebooks");
|
||||
for (let dir = path.dirname(file); dir !== root; dir = path.dirname(dir)) {
|
||||
try {
|
||||
await rmdir(dir);
|
||||
} catch (e) {
|
||||
if (
|
||||
["ENOTEMPTY", "EEXIST", "ENOENT"].includes(
|
||||
(e as NodeJS.ErrnoException).code ?? "",
|
||||
)
|
||||
)
|
||||
return;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
export function notebookManagement(
|
||||
app: FastifyInstance,
|
||||
config: ServerConfig,
|
||||
queue: SerialQueue,
|
||||
) {
|
||||
app.post<{ Body: CreateNotebookRequest }>("/api/notebooks", async (req) =>
|
||||
queue.run("notebooks", async () => {
|
||||
if (!req.body || typeof req.body.source !== "string")
|
||||
throw httpError(400, "Invalid notebook");
|
||||
const file = await notebookDestination(config, req.body.path);
|
||||
await atomicNotebookWrite(file, req.body.source, true);
|
||||
return { path: req.body.path, version: version(req.body.source) };
|
||||
}),
|
||||
);
|
||||
for (const operation of ["rename", "duplicate"] as const) {
|
||||
app.post<{ Params: { path: string }; Body: MoveNotebookRequest }>(
|
||||
`/api/notebooks/:path/${operation}`,
|
||||
async (req) =>
|
||||
queue.run("notebooks", async () => {
|
||||
if (!req.body || typeof req.body.baseVersion !== "string")
|
||||
throw httpError(400, "Missing baseVersion");
|
||||
const original = await notebookDestination(config, req.params.path);
|
||||
const { source } = await readNotebook(config, req.params.path);
|
||||
if (version(source) !== req.body.baseVersion)
|
||||
throw httpError(409, "Notebook changed");
|
||||
const target = await notebookDestination(config, req.body.path);
|
||||
await atomicNotebookWrite(target, source, true);
|
||||
if (operation === "rename") {
|
||||
try {
|
||||
await unlink(original);
|
||||
} catch (e) {
|
||||
await unlink(target);
|
||||
throw e;
|
||||
}
|
||||
await prune(config, original);
|
||||
}
|
||||
return { path: req.body.path, version: version(source) };
|
||||
}),
|
||||
);
|
||||
}
|
||||
app.delete<{ Params: { path: string }; Body: DeleteNotebookRequest }>(
|
||||
"/api/notebooks/:path",
|
||||
async (req) =>
|
||||
queue.run("notebooks", async () => {
|
||||
if (!req.body || typeof req.body.baseVersion !== "string")
|
||||
throw httpError(400, "Missing baseVersion");
|
||||
const file = await notebookDestination(config, req.params.path);
|
||||
const { source } = await readNotebook(config, req.params.path);
|
||||
if (version(source) !== req.body.baseVersion)
|
||||
throw httpError(409, "Notebook changed");
|
||||
await unlink(file);
|
||||
await prune(config, file);
|
||||
return { deleted: true };
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user