Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: share notebooks recursively with live public reading

tianma-if13f8b3f407b6
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index f6eee182..a60fc3cb 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -124,6 +124,7 @@ import {
registerUserRoutes,
} from "./user-routes";
import { registerNotebookRoutes } from "./notebook-routes";
+import { registerNotebookShareRoutes, registerPublicNotebookShareRoutes } from "./notebook-share-routes";
import { registerMemoShareRoutes, registerPublicShareRoutes } from "./share-routes";
import { registerPublicTableFormRoutes, registerTableFormRoutes } from "./table-form-routes";
import {
@@ -249,6 +250,7 @@ app.get("/api/health", async (c) => {
app.get("/api/openapi.json", (c) => c.json(apiProbe));
registerPublicShareRoutes(app);
+registerPublicNotebookShareRoutes(app);
registerPublicTableFormRoutes(app);
registerAuthRoutes(app, {
@@ -337,6 +339,7 @@ registerPluginDistributionRoutes(app);
registerScheduledTaskRoutes(app);
registerWorkspaceExtensionRoutes(app, { isDemoMode: (...args) => isDemoMode(...args) });
registerMemoShareRoutes(app);
+registerNotebookShareRoutes(app);
registerTableFormRoutes(app);
registerTemplateRoutes(app, {
createMemoRecord: (...args) => createMemoRecord(...args),
diff --git a/apps/api/src/notebook-share-routes.test.mjs b/apps/api/src/notebook-share-routes.test.mjs
new file mode 100644
index 00000000..fe85a833
--- /dev/null
+++ b/apps/api/src/notebook-share-routes.test.mjs
@@ -0,0 +1,360 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+import { globSync, readFileSync } from "node:fs";
+import { Hono } from "hono";
+import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter";
+import {
+ registerNotebookShareRoutes,
+ registerPublicNotebookShareRoutes,
+} from "./notebook-share-routes";
+import { registerPublicShareRoutes } from "./share-routes";
+
+const databases = [];
+afterEach(() => databases.splice(0).forEach((db) => db.close()));
+const token = "n".repeat(43);
+const individualToken = "s".repeat(43);
+const auth = {
+ kind: "user",
+ actorType: "user",
+ actorId: null,
+ workspaceId: "ws_test",
+ role: "member",
+ scopes: [],
+ username: "test",
+};
+const fixture = () => {
+ const db = new Database(":memory:");
+ databases.push(db);
+ // Populate a real pre-feature schema first, then upgrade it in place.
+ const migrations = globSync("migrations/*.sql").sort();
+ for (const file of migrations.filter(
+ (file) => !file.endsWith("0067_notebook_shares.sql"),
+ ))
+ db.exec(readFileSync(file, "utf8"));
+ db.run(
+ "INSERT INTO workspaces (id, name) VALUES ('ws_test', 'Test'), ('ws_other', 'Other')",
+ );
+ for (const [id, parent, workspace] of [
+ ["root", null, "ws_test"],
+ ["child", "root", "ws_test"],
+ ["grandchild", "child", "ws_test"],
+ ["private", null, "ws_test"],
+ ["foreign", "root", "ws_other"],
+ ]) {
+ db.run(
+ "INSERT INTO notebooks (id, parent_id, workspace_id, name) VALUES (?, ?, ?, ?)",
+ [id, parent, workspace, id],
+ );
+ }
+ const addMemo = (id, notebookId, workspace = "ws_test") => {
+ db.run(
+ "INSERT INTO memos (id, notebook_id, workspace_id, title) VALUES (?, ?, ?, ?)",
+ [id, notebookId, workspace, id],
+ );
+ db.run(
+ "INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_hash) VALUES (?, ?, ?, ?)",
+ [id, '{"type":"doc","content":[]}', id, id],
+ );
+ db.run(
+ "INSERT INTO resources (id, memo_id, object_key, kind, mime_type, byte_size) VALUES (?, ?, ?, 'image', 'image/png', 10)",
+ [`res_${id}`, id, id],
+ );
+ };
+ addMemo("memo_root", "root");
+ addMemo("memo_child", "child");
+ addMemo("memo_grand", "grandchild");
+ addMemo("memo_private", "private");
+ addMemo("memo_other", "foreign", "ws_other");
+ db.run(
+ "INSERT INTO memo_shares (id, memo_id, workspace_id, token) VALUES ('individual', 'memo_child', 'ws_test', ?)",
+ [individualToken],
+ );
+ db.exec(readFileSync("migrations/0067_notebook_shares.sql", "utf8"));
+ db.run(
+ "INSERT INTO notebook_shares (id, notebook_id, workspace_id, token) VALUES ('shared', 'root', 'ws_test', ?)",
+ [token],
+ );
+ const environment = {
+ storage: createSelfHostedStorageAdapter(
+ db,
+ "/tmp/edgeever-notebook-share-unused",
+ ),
+ };
+ let blobReads = 0;
+ environment.storage.resources = {
+ get: async (_key, options) => {
+ blobReads++;
+ return {
+ body: new Blob([options ? "2345" : "0123456789"]).stream(),
+ size: 10,
+ range: options?.range,
+ writeHttpMetadata: () => {},
+ };
+ },
+ };
+ const app = new Hono();
+ app.use("/api/v1/*", async (c, next) => {
+ if (c.req.header("test-auth") !== "none")
+ c.set(
+ "auth",
+ c.req.header("test-auth") === "agent"
+ ? { ...auth, kind: "agent" }
+ : auth,
+ );
+ await next();
+ });
+ registerPublicNotebookShareRoutes(app);
+ registerNotebookShareRoutes(app);
+ registerPublicShareRoutes(app);
+ const request = (path = "", init = {}) =>
+ app.request(
+ `/api/public/notebook-shares/${token}${path}`,
+ init,
+ environment,
+ );
+ return { db, app, environment, request, addMemo, blobReads: () => blobReads };
+};
+
+describe("live recursive notebook sharing", () => {
+ test("upgrades existing data without creating individual shares; exposes only the live workspace subtree", async () => {
+ const { db, request } = fixture();
+ const response = await request();
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");
+ const { share } = await response.json();
+ expect(share.notebooks.map((n) => n.id).sort()).toEqual([
+ "child",
+ "grandchild",
+ "root",
+ ]);
+ expect(share.notebooks.find((n) => n.id === "root").parentId).toBeNull();
+ expect(share.memos.map((m) => m.id).sort()).toEqual([
+ "memo_child",
+ "memo_grand",
+ "memo_root",
+ ]);
+ expect(
+ db.query("SELECT COUNT(*) AS total FROM memo_shares").get().total,
+ ).toBe(1);
+ expect(
+ db
+ .query(
+ "SELECT content_markdown FROM memo_contents WHERE memo_id = 'memo_private'",
+ )
+ .get().content_markdown,
+ ).toBe("memo_private");
+ for (const id of ["memo_private", "memo_other"]) {
+ expect((await request(`/memos/${id}`)).status).toBe(404);
+ expect((await request(`/resources/res_${id}/blob`)).status).toBe(404);
+ }
+ });
+
+ test("publishes new and moved-in notes, edits, and moved-in subtrees without changing the token", async () => {
+ const { db, request, addMemo } = fixture();
+ addMemo("new_note", "grandchild");
+ db.run("UPDATE memos SET notebook_id = 'child' WHERE id = 'memo_private'");
+ db.run(
+ "UPDATE memo_contents SET content_markdown = 'edited live' WHERE memo_id = 'memo_child'",
+ );
+ const { share } = await (await request()).json();
+ expect(share.memos.some((m) => m.id === "new_note")).toBe(true);
+ expect(share.memos.some((m) => m.id === "memo_private")).toBe(true);
+ expect(
+ (await (await request("/memos/memo_child")).json()).share.contentMarkdown,
+ ).toBe("edited live");
+ db.run("UPDATE notebooks SET parent_id = 'root' WHERE id = 'private'");
+ addMemo("new_private_child", "private");
+ expect((await request("/memos/new_private_child")).status).toBe(200);
+ });
+
+ test("moving a note or subtree out immediately denies its note and resource endpoints", async () => {
+ const { db, request, blobReads } = fixture();
+ expect((await request("/resources/res_memo_child/blob")).status).toBe(200);
+ db.run("UPDATE memos SET notebook_id = 'private' WHERE id = 'memo_child'");
+ db.run(
+ "UPDATE notebooks SET parent_id = 'private' WHERE id = 'grandchild'",
+ );
+ for (const id of ["memo_child", "memo_grand"]) {
+ expect((await request(`/memos/${id}`)).status).toBe(404);
+ expect((await request(`/resources/res_${id}/blob`)).status).toBe(404);
+ }
+ expect(blobReads()).toBe(1);
+ });
+
+ test("deleted notes, resources, ancestors, and roots cannot be read", async () => {
+ const { db, request } = fixture();
+ db.run("UPDATE memos SET is_deleted = 1 WHERE id = 'memo_root'");
+ expect((await request("/memos/memo_root")).status).toBe(404);
+ expect((await request("/resources/res_memo_root/blob")).status).toBe(404);
+ db.run("UPDATE resources SET is_deleted = 1 WHERE id = 'res_memo_child'");
+ expect((await request("/resources/res_memo_child/blob")).status).toBe(404);
+ db.run("UPDATE notebooks SET is_deleted = 1 WHERE id = 'child'");
+ expect((await request("/memos/memo_grand")).status).toBe(404);
+ expect((await request("/resources/res_memo_grand/blob")).status).toBe(404);
+ db.run("UPDATE notebooks SET is_deleted = 1 WHERE id = 'root'");
+ expect((await request()).status).toBe(404);
+ });
+
+ test("revocation closes every endpoint, keeps independent shares, and recreation gets a fresh token", async () => {
+ const { db, app, environment, request } = fixture();
+ const revoke = await app.request(
+ "/api/v1/notebooks/root/share",
+ { method: "DELETE" },
+ environment,
+ );
+ expect(revoke.status).toBe(200);
+ for (const path of [
+ "",
+ "/memos/memo_child",
+ "/resources/res_memo_child/blob",
+ ])
+ expect((await request(path)).status).toBe(404);
+ expect(
+ (
+ await app.request(
+ `/api/public/shares/${individualToken}`,
+ {},
+ environment,
+ )
+ ).status,
+ ).toBe(200);
+ expect(
+ db.query("SELECT COUNT(*) AS total FROM memo_shares").get().total,
+ ).toBe(1);
+ const created = await (
+ await app.request(
+ "/api/v1/notebooks/root/share",
+ { method: "POST" },
+ environment,
+ )
+ ).json();
+ expect(created.share.token).not.toBe(token);
+ expect(created.share.token).toHaveLength(43);
+ const again = await (
+ await app.request(
+ "/api/v1/notebooks/root/share",
+ { method: "POST" },
+ environment,
+ )
+ ).json();
+ expect(again.share.token).toBe(created.share.token);
+ });
+
+ test("interactive management is workspace scoped and rejects anonymous and API-token callers", async () => {
+ const { app, environment, db } = fixture();
+ for (const kind of ["none", "agent"]) {
+ for (const method of ["GET", "POST", "DELETE"])
+ expect(
+ (
+ await app.request(
+ "/api/v1/notebooks/root/share",
+ { method, headers: { "test-auth": kind } },
+ environment,
+ )
+ ).status,
+ ).toBe(403);
+ }
+ expect(
+ (
+ await app.request(
+ "/api/v1/notebooks/foreign/share",
+ { method: "POST" },
+ environment,
+ )
+ ).status,
+ ).toBe(404);
+ await app.request(
+ "/api/v1/notebooks/foreign/share",
+ { method: "DELETE" },
+ environment,
+ );
+ const response = await app.request(
+ "/api/v1/notebook-shares",
+ {},
+ environment,
+ );
+ expect((await response.json()).shares.map((s) => s.notebookId)).toEqual([
+ "root",
+ ]);
+ expect(
+ db.query("SELECT COUNT(*) AS total FROM notebook_shares").get().total,
+ ).toBe(1);
+ });
+
+ test("internal links resolve only within the shared tree, even if an outside note has an independent share", async () => {
+ const { db, request } = fixture();
+ const doc = {
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: ["memo_child", "memo_private", "memo_other"].map((id) => ({
+ type: "text",
+ text: id,
+ marks: [{ type: "link", attrs: { href: `#memo=${id}` } }],
+ })),
+ },
+ ],
+ };
+ db.run(
+ "UPDATE memo_contents SET content_json = ? WHERE memo_id = 'memo_root'",
+ [JSON.stringify(doc)],
+ );
+ const response = await (await request("/memos/memo_root")).json();
+ expect(response.memoUrls).toEqual({
+ memo_child: `/share/notebook/${token}/memo_child`,
+ });
+ expect(response.share.memoShareTokens).toEqual({});
+ });
+
+ test("resource streaming keeps range, MIME, and no-store behavior", async () => {
+ const { request } = fixture();
+ const response = await request("/resources/res_memo_child/blob", {
+ headers: { Range: "bytes=2-5" },
+ });
+ expect(response.status).toBe(206);
+ expect(response.headers.get("Content-Type")).toBe("image/png");
+ expect(response.headers.get("Content-Range")).toBe("bytes 2-5/10");
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");
+ expect(await response.text()).toBe("2345");
+ });
+ test("independent child notebook shares survive parent revocation", async () => {
+ const { app, environment, request } = fixture();
+ const created = await (
+ await app.request(
+ "/api/v1/notebooks/child/share",
+ { method: "POST" },
+ environment,
+ )
+ ).json();
+ await app.request(
+ "/api/v1/notebooks/root/share",
+ { method: "DELETE" },
+ environment,
+ );
+ expect((await request("/memos/memo_child")).status).toBe(404);
+ const base = `/api/public/notebook-shares/${created.share.token}`;
+ expect((await app.request(base, {}, environment)).status).toBe(200);
+ expect(
+ (await app.request(`${base}/memos/memo_grand`, {}, environment)).status,
+ ).toBe(200);
+ expect(
+ (
+ await app.request(
+ `${base}/resources/res_memo_grand/blob`,
+ {},
+ environment,
+ )
+ ).status,
+ ).toBe(200);
+ });
+
+ test("even inconsistent cross-workspace notebook references do not grant access", async () => {
+ const { db, request } = fixture();
+ db.run("UPDATE memos SET notebook_id = 'root' WHERE id = 'memo_other'");
+ expect((await request("/memos/memo_other")).status).toBe(404);
+ expect((await request("/resources/res_memo_other/blob")).status).toBe(404);
+ const { share } = await (await request()).json();
+ expect(share.memos.some((memo) => memo.id === "memo_other")).toBe(false);
+ });
+});
diff --git a/apps/api/src/notebook-share-routes.ts b/apps/api/src/notebook-share-routes.ts
new file mode 100644
index 00000000..fdd3f862
--- /dev/null
+++ b/apps/api/src/notebook-share-routes.ts
@@ -0,0 +1,275 @@
+import {
+ collectMemoLinkIds,
+ accountNoteProseFromRow,
+ publicNoteProseFromAccount,
+ sanitizeNoteProseCss,
+ parsePublishedNoteBodyFont,
+ resolveMemoContentDoc,
+ type NotebookShare,
+ type PublicNotebookShare,
+ type PublicMemoShare,
+ type NoteProseAccountRow,
+ type TiptapDoc,
+} from "@edgeever/shared";
+import type { Hono } from "hono";
+import type { AppEnv } from "./api-context";
+import { randomToken } from "./auth-crypto";
+import { audit } from "./audit";
+import { createId, isoNow, parseJsonArray } from "./entity-utils";
+import { notFound } from "./http-errors";
+import { getAuditActor, getWorkspaceId, requireUser } from "./request-auth";
+import { serveSharedResource } from "./share-routes";
+
+// Every public query starts at the live share, and constrains every level to
+// its workspace. Deleted ancestors stop traversal; UNION also tolerates cycles.
+const publicTreeSql = `WITH RECURSIVE tree(id, workspace_id) AS (
+ SELECT n.id, n.workspace_id FROM notebook_shares ns
+ JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
+ WHERE ns.token = ? AND n.is_deleted = 0
+ UNION
+ SELECT n.id, n.workspace_id FROM notebooks n JOIN tree t ON n.parent_id = t.id
+ WHERE n.workspace_id = t.workspace_id AND n.is_deleted = 0
+)`;
+
+type ShareRow = {
+ notebook_id: string;
+ notebook_name: string;
+ token: string;
+ created_at: string;
+ updated_at: string;
+};
+const mapShare = (row: ShareRow): NotebookShare => ({
+ notebookId: row.notebook_id,
+ notebookName: row.notebook_name,
+ token: row.token,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+});
+const selectShareSql = `SELECT ns.notebook_id, n.name AS notebook_name, ns.token, ns.created_at, ns.updated_at
+ FROM notebook_shares ns JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
+ WHERE ns.workspace_id = ? AND n.is_deleted = 0`;
+const validToken = (token: string) => /^[A-Za-z0-9_-]{43}$/.test(token);
+
+export const registerNotebookShareRoutes = (app: Hono<AppEnv>) => {
+ app.get("/api/v1/notebook-shares", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const rows = await c.env.storage.db
+ .prepare(`${selectShareSql} ORDER BY ns.created_at DESC, ns.id`)
+ .bind(getWorkspaceId(c))
+ .all<ShareRow>();
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ shares: rows.results.map(mapShare) });
+ });
+ app.get("/api/v1/notebooks/:id/share", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const row = await c.env.storage.db
+ .prepare(`${selectShareSql} AND ns.notebook_id = ?`)
+ .bind(getWorkspaceId(c), c.req.param("id"))
+ .first<ShareRow>();
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ share: row ? mapShare(row) : null });
+ });
+ app.post("/api/v1/notebooks/:id/share", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ const workspaceId = getWorkspaceId(c);
+ const notebookId = c.req.param("id");
+ const notebook = await c.env.storage.db
+ .prepare(
+ "SELECT id FROM notebooks WHERE id = ? AND workspace_id = ? AND is_deleted = 0",
+ )
+ .bind(notebookId, workspaceId)
+ .first();
+ if (!notebook) return notFound(c, "Notebook not found");
+ const token = randomToken(32);
+ const now = isoNow();
+ await c.env.storage.db
+ .prepare(
+ `INSERT OR IGNORE INTO notebook_shares (id, notebook_id, workspace_id, token, created_by, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .bind(
+ createId("nbshare"),
+ notebookId,
+ workspaceId,
+ token,
+ getAuditActor(c).actorId,
+ now,
+ now,
+ )
+ .run();
+ const row = await c.env.storage.db
+ .prepare(`${selectShareSql} AND ns.notebook_id = ?`)
+ .bind(workspaceId, notebookId)
+ .first<ShareRow>();
+ if (!row) throw new Error("Could not allocate notebook share");
+ if (row.token === token)
+ await audit(
+ c.env.storage.db,
+ getAuditActor(c).actorType,
+ getAuditActor(c).actorId,
+ "notebook.share.create",
+ "notebook",
+ notebookId,
+ {},
+ );
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ share: mapShare(row) });
+ });
+ app.delete("/api/v1/notebooks/:id/share", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+ await c.env.storage.db
+ .prepare(
+ "DELETE FROM notebook_shares WHERE notebook_id = ? AND workspace_id = ?",
+ )
+ .bind(c.req.param("id"), getWorkspaceId(c))
+ .run();
+ await audit(
+ c.env.storage.db,
+ getAuditActor(c).actorType,
+ getAuditActor(c).actorId,
+ "notebook.share.revoke",
+ "notebook",
+ c.req.param("id"),
+ {},
+ );
+ c.header("Cache-Control", "private, no-store");
+ return c.json({ ok: true });
+ });
+};
+
+export const registerPublicNotebookShareRoutes = (app: Hono<AppEnv>) => {
+ app.use("/api/public/notebook-shares/*", async (c, next) => {
+ c.header("Cache-Control", "private, no-store");
+ c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
+ await next();
+ });
+ app.get("/api/public/notebook-shares/:token", async (c) => {
+ const token = c.req.param("token");
+ if (!validToken(token)) return notFound(c, "Shared notebook not found");
+ const root = await c.env.storage.db
+ .prepare(
+ `SELECT n.id, n.name FROM notebook_shares ns
+ JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_id
+ WHERE ns.token = ? AND n.is_deleted = 0`,
+ )
+ .bind(token)
+ .first<{ id: string; name: string }>();
+ if (!root) return notFound(c, "Shared notebook not found");
+ const notebooks = await c.env.storage.db
+ .prepare(
+ `${publicTreeSql}
+ SELECT n.id, n.parent_id AS parentId, n.name FROM notebooks n JOIN tree t ON n.id = t.id AND n.workspace_id = t.workspace_id
+ ORDER BY n.sort_order, n.name, n.id`,
+ )
+ .bind(token)
+ .all<PublicNotebookShare["notebooks"][number]>();
+ if (!notebooks.results.length)
+ return notFound(c, "Shared notebook not found");
+ const memos = await c.env.storage.db
+ .prepare(
+ `${publicTreeSql}
+ SELECT m.id, m.notebook_id AS notebookId, m.title FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ WHERE m.is_deleted = 0 ORDER BY m.is_pinned DESC, m.updated_at DESC, m.id`,
+ )
+ .bind(token)
+ .all<PublicNotebookShare["memos"][number]>();
+ const share: PublicNotebookShare = {
+ notebookId: root.id,
+ name: root.name,
+ notebooks: notebooks.results.map((n) => ({
+ ...n,
+ parentId: n.id === root.id ? null : n.parentId,
+ })),
+ memos: memos.results,
+ };
+ return c.json({ share });
+ });
+ app.get("/api/public/notebook-shares/:token/memos/:memoId", async (c) => {
+ const token = c.req.param("token");
+ if (!validToken(token)) return notFound(c, "Shared note not found");
+ const row = await c.env.storage.db
+ .prepare(
+ `${publicTreeSql}
+ SELECT m.title, mc.content_json, mc.content_markdown, m.tags_json, m.updated_at, u.note_body_font,
+ u.note_prose_font_size, u.note_prose_line_height, u.note_prose_palette, u.note_prose_custom_css, u.note_prose_custom_colors
+ FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ JOIN memo_contents mc ON mc.memo_id = m.id
+ JOIN notebook_shares ns ON ns.token = ?
+ LEFT JOIN users u ON u.id = ns.created_by
+ WHERE m.id = ? AND m.is_deleted = 0`,
+ )
+ .bind(token, token, c.req.param("memoId"))
+ .first<
+ NoteProseAccountRow & {
+ title: string | null;
+ content_json: string;
+ content_markdown: string;
+ tags_json: string;
+ updated_at: string;
+ note_body_font: string | null;
+ }
+ >();
+ if (!row) return notFound(c, "Shared note not found");
+ const contentJson = JSON.parse(row.content_json) as TiptapDoc;
+ const memoUrls: Record<string, string> = {};
+ const ids = collectMemoLinkIds(
+ resolveMemoContentDoc(contentJson, row.content_markdown),
+ );
+ for (let offset = 0; offset < ids.length; offset += 80) {
+ const batch = ids.slice(offset, offset + 80);
+ const linked = await c.env.storage.db
+ .prepare(
+ `${publicTreeSql}
+ SELECT m.id FROM memos m JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ WHERE m.is_deleted = 0 AND m.id IN (${batch.map(() => "?").join(",")})`,
+ )
+ .bind(token, ...batch)
+ .all<{ id: string }>();
+ for (const memo of linked.results)
+ memoUrls[memo.id] =
+ `/share/notebook/${encodeURIComponent(token)}/${encodeURIComponent(memo.id)}`;
+ }
+ const account = accountNoteProseFromRow(row);
+ const share: PublicMemoShare = {
+ title: row.title,
+ contentJson,
+ contentMarkdown: row.content_markdown,
+ tags: parseJsonArray(row.tags_json),
+ updatedAt: row.updated_at,
+ memoShareTokens: {},
+ bodyFont: parsePublishedNoteBodyFont(row.note_body_font),
+ prose: publicNoteProseFromAccount({
+ ...account,
+ customCss:
+ account.customCss === null
+ ? null
+ : sanitizeNoteProseCss(account.customCss),
+ }),
+ };
+ return c.json({ share, memoUrls });
+ });
+ app.get(
+ "/api/public/notebook-shares/:token/resources/:resourceId/blob",
+ async (c) => {
+ const token = c.req.param("token");
+ if (!validToken(token)) return notFound(c, "Shared resource not found");
+ const resource = await c.env.storage.db
+ .prepare(
+ `${publicTreeSql}
+ SELECT r.object_key, r.storage_config_id, r.kind, r.mime_type, r.filename, r.byte_size,
+ m.workspace_id, NULL AS password_hash
+ FROM resources r JOIN memos m ON r.memo_id = m.id
+ JOIN tree t ON m.notebook_id = t.id AND m.workspace_id = t.workspace_id
+ WHERE r.id = ? AND r.is_deleted = 0 AND m.is_deleted = 0`,
+ )
+ .bind(token, c.req.param("resourceId"))
+ .first<Parameters<typeof serveSharedResource>[1]>();
+ if (!resource) return notFound(c, "Shared resource not found");
+ return serveSharedResource(c, resource);
+ },
+ );
+};
diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.ts
index 83a0202b..7418b1df 100644
--- a/apps/api/src/share-routes.ts
+++ b/apps/api/src/share-routes.ts
@@ -151,6 +151,50 @@ const loadAccountNoteProse = async (c: AppContext, actorId: string) => {
return row ? presentAccountNoteProse(row) : null;
};
+/** The caller must authorize the resource against its live share scope first. */
+export const serveSharedResource = async (c: AppContext, resource: SharedResourceRow) => {
+ const byteRange = parseByteRange(c.req.header("Range"), resource.byte_size);
+ if (byteRange.kind === "invalid") {
+ const response = rangeNotSatisfiable(resource.byte_size);
+ response.headers.set("Cache-Control", "private, no-store");
+ response.headers.set("X-Robots-Tag", "noindex, nofollow, noarchive");
+ return response;
+ }
+
+ const source = await resolveObjectStorage(c.env, resource.storage_config_id);
+ const object = await source.store.get(
+ resource.object_key,
+ byteRange.kind === "range" ? { range: byteRange.range } : undefined,
+ );
+ if (!object) return notFound(c, "Shared resource not found");
+
+ const headers = new Headers();
+ object.writeHttpMetadata(headers);
+ const playableMimeType = resolvePlayableMediaMimeType(resource.mime_type, resource.filename);
+ headers.set(
+ "Content-Type",
+ isPdfAttachment(resource.mime_type, resource.filename)
+ ? "application/pdf"
+ : playableMimeType ?? resource.mime_type ?? headers.get("Content-Type") ?? "application/octet-stream",
+ );
+ headers.set("Accept-Ranges", "bytes");
+ if (byteRange.kind === "range") {
+ const length = object.range?.length ?? byteRange.range.length;
+ headers.set("Content-Length", String(length));
+ headers.set(
+ "Content-Range",
+ `bytes ${byteRange.range.offset}-${byteRange.range.offset + length - 1}/${resource.byte_size}`,
+ );
+ } else {
+ headers.set("Content-Length", String(resource.byte_size));
+ }
+ headers.set("Content-Disposition", contentDisposition(resource.kind, resource.mime_type, resource.filename));
+ headers.set("Cache-Control", "private, no-store");
+ headers.set("X-Content-Type-Options", "nosniff");
+ headers.set("X-Robots-Tag", "noindex, nofollow, noarchive");
+ return new Response(object.body, { headers, status: byteRange.kind === "range" ? 206 : 200 });
+};
+
export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
app.get("/api/public/shares/:token", async (c) => {
const token = normalizeShareToken(c.req.param("token"));
@@ -257,46 +301,7 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
return sharePasswordRequired(c);
}
- const byteRange = parseByteRange(c.req.header("Range"), resource.byte_size);
- if (byteRange.kind === "invalid") {
- const response = rangeNotSatisfiable(resource.byte_size);
- response.headers.set("Cache-Control", "private, no-store");
- response.headers.set("X-Robots-Tag", "noindex, nofollow, noarchive");
- return response;
- }
-
- const source = await resolveObjectStorage(c.env, resource.storage_config_id);
- const object = await source.store.get(
- resource.object_key,
- byteRange.kind === "range" ? { range: byteRange.range } : undefined,
- );
- if (!object) return notFound(c, "Shared resource not found");
-
- const headers = new Headers();
- object.writeHttpMetadata(headers);
- const playableMimeType = resolvePlayableMediaMimeType(resource.mime_type, resource.filename);
- headers.set(
- "Content-Type",
- isPdfAttachment(resource.mime_type, resource.filename)
- ? "application/pdf"
- : playableMimeType ?? resource.mime_type ?? headers.get("Content-Type") ?? "application/octet-stream",
- );
- headers.set("Accept-Ranges", "bytes");
- if (byteRange.kind === "range") {
- const length = object.range?.length ?? byteRange.range.length;
- headers.set("Content-Length", String(length));
- headers.set(
- "Content-Range",
- `bytes ${byteRange.range.offset}-${byteRange.range.offset + length - 1}/${resource.byte_size}`,
- );
- } else {
- headers.set("Content-Length", String(resource.byte_size));
- }
- headers.set("Content-Disposition", contentDisposition(resource.kind, resource.mime_type, resource.filename));
- headers.set("Cache-Control", "private, no-store");
- headers.set("X-Content-Type-Options", "nosniff");
- headers.set("X-Robots-Tag", "noindex, nofollow, noarchive");
- return new Response(object.body, { headers, status: byteRange.kind === "range" ? 206 : 200 });
+ return serveSharedResource(c, resource);
});
};
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index 92ff296e..afaa1757 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -26,6 +26,7 @@ const EvernoteImportGuidePane = lazy(() =>
);
const LoginScreen = lazy(() => import("@/components/LoginScreen").then((module) => ({ default: module.LoginScreen })));
const WorkspaceApp = lazy(() => import("@/components/WorkspaceApp").then((module) => ({ default: module.WorkspaceApp })));
+const PublicNotebookSharePage = lazy(() => import("@/components/PublicNotebookSharePage").then(module => ({ default: module.PublicNotebookSharePage })));
const PublicSharePage = lazy(() => import("@/components/PublicSharePage").then((module) => ({ default: module.PublicSharePage })));
const PublicTableFormPage = lazy(() => import("@/components/PublicTableFormPage").then((module) => ({ default: module.PublicTableFormPage })));
@@ -228,6 +229,7 @@ export const App = () => {
<TooltipProvider delayDuration={0} skipDelayDuration={0}>
<PwaInstallProvider>
<Routes>
+ <Route path="/share/notebook/:token/:memoId?" element={<Suspense fallback={<AuthLoadingScreen />}><PublicNotebookSharePage /></Suspense>} />
<Route path="/share/:token" element={<Suspense fallback={<AuthLoadingScreen />}><PublicSharePage /></Suspense>} />
<Route path="/form/:token" element={<Suspense fallback={<AuthLoadingScreen />}><PublicTableFormPage /></Suspense>} />
<Route path={EVERNOTE_MIGRATION_PATH} element={<EvernoteMigrationRoute />} />
diff --git a/apps/web/src/components/NotebookPane.tsx b/apps/web/src/components/NotebookPane.tsx
index 70218fb4..09951619 100644
--- a/apps/web/src/components/NotebookPane.tsx
+++ b/apps/web/src/components/NotebookPane.tsx
@@ -48,6 +48,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { NotebookTreeItem } from "./NotebookTreeItem";
+import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
import { cn } from "@/lib/utils";
import { useShowDescendantNotesPreference } from "@/lib/descendant-notes-preference";
import { BETA_BADGE_CLASSNAME } from "@/lib/workspace-ui";
@@ -637,6 +638,14 @@ export const NotebookPane = ({
const notebooks = notebooksQuery.data?.notebooks ?? [];
const notebookSortOptions = useMemo(() => getNotebookSortOptions(t), [t]);
+ const notebookSharesQuery = useQuery({
+ queryKey: ["notebook-shares", getConfiguredDesktopApiBaseUrl(), user?.id],
+ queryFn: () => api.listNotebookShares(),
+ enabled: isOnline,
+ retry: false,
+ refetchOnMount: "always",
+ });
+ const sharedNotebookIds = useMemo(() => new Set(notebookSharesQuery.data?.shares.map(share => share.notebookId) ?? []), [notebookSharesQuery.data]);
const tree = useMemo(() => buildNotebookTree(notebooks, getNotebookSortComparator(notebookSortMode)), [notebooks, notebookSortMode]);
const isLoading = notebooksQuery.isLoading;
const activeNotebookSortLabel = notebookSortOptions.find((option) => option.value === notebookSortMode)?.label ?? t("options.notebookSort.nameAsc");
@@ -866,6 +875,7 @@ export const NotebookPane = ({
onOpenChange={handleNotebookOpenChange}
expandSiblingsRequest={expandSiblingsRequest}
onExpandSiblings={handleExpandNotebookSiblings}
+ sharedNotebookIds={sharedNotebookIds}
showDescendantNotes={showDescendantNotes}
/>
))}
diff --git a/apps/web/src/components/NotebookTreeItem.tsx b/apps/web/src/components/NotebookTreeItem.tsx
index 2bc0ecce..4b00fd27 100644
--- a/apps/web/src/components/NotebookTreeItem.tsx
+++ b/apps/web/src/components/NotebookTreeItem.tsx
@@ -1,7 +1,7 @@
-import { useState, useEffect, useRef, type DragEvent } from "react";
+import { lazy, Suspense, useState, useEffect, useRef, type DragEvent } from "react";
import { useTranslation } from "react-i18next";
import * as m from "motion/react-m";
-import { ChevronDown, MoreHorizontal, Notebook as NotebookIcon, Plus, Pencil, Trash2 } from "lucide-react";
+import { ChevronDown, MoreHorizontal, Notebook as NotebookIcon, Plus, Pencil, Trash2, Share2, Globe } from "lucide-react";
import type { NotebookNode, NotebookDropPosition } from "@/lib/app-helpers";
import {
hasMemoDragData,
@@ -21,8 +21,11 @@ import {
ContextMenuSeparator,
ContextMenuTrigger,
} from "@/components/ui/context-menu";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { contentEnterMotion, treeEnterMotion } from "@/lib/motion";
+const ShareNotebookDialog = lazy(() => import("./dialogs/ShareNotebookDialog").then(module => ({ default: module.ShareNotebookDialog })));
+
const NOTEBOOK_DRAG_EXPAND_DELAY_MS = 520;
export const NotebookTreeItem = ({
@@ -41,6 +44,8 @@ export const NotebookTreeItem = ({
expandSiblingsRequest,
onExpandSiblings,
showDescendantNotes,
+ sharedNotebookIds,
+ inheritedPublic = false,
}: {
node: NotebookNode;
depth: number;
@@ -57,8 +62,12 @@ export const NotebookTreeItem = ({
expandSiblingsRequest: { parentId: string | null; token: number } | null;
onExpandSiblings: (parentId: string | null) => void;
showDescendantNotes: boolean;
+ sharedNotebookIds?: ReadonlySet<string>;
+ inheritedPublic?: boolean;
}) => {
const { t } = useTranslation();
+ const [shareOpen, setShareOpen] = useState(false);
+ const publicNotebook = inheritedPublic || Boolean(sharedNotebookIds?.has(node.id));
const open = !collapsedNotebookIds.has(node.id);
const hasChildren = node.children.length > 0;
const showsSplitCount = !showDescendantNotes && hasChildren;
@@ -204,104 +213,109 @@ export const NotebookTreeItem = ({
style={{ paddingLeft: `${8 + depth * 14}px` }}
>
{hasChildren ? (
- <button
- className="flex h-6 w-5 items-center justify-center rounded hover:bg-slate-100/50 transition-colors"
- type="button"
- onClick={() => onOpenChange(node.id, !open)}
- title={t("notebookTree.expandCollapse")}
- aria-label={open ? t("notebookTree.collapse", { name: node.name }) : t("notebookTree.expand", { name: node.name })}
- aria-expanded={open}
- >
- <ChevronDown
- className={cn(
- "h-4 w-4 transition-transform duration-150 ease-out",
- open ? "rotate-0" : "-rotate-90"
- )}
- aria-hidden="true"
- />
- </button>
+ <TooltipProvider><Tooltip><TooltipTrigger asChild>
+ <button
+ className="flex h-6 w-5 items-center justify-center rounded hover:bg-slate-100/50 transition-colors"
+ type="button"
+ onClick={() => onOpenChange(node.id, !open)}
+ aria-label={open ? t("notebookTree.collapse", { name: node.name }) : t("notebookTree.expand", { name: node.name })}
+ aria-expanded={open}
+ >
+ <ChevronDown
+ className={cn(
+ "h-4 w-4 transition-transform duration-150 ease-out",
+ open ? "rotate-0" : "-rotate-90"
+ )}
+ aria-hidden="true"
+ />
+ </button>
+ </TooltipTrigger><TooltipContent>{t("notebookTree.expandCollapse")}</TooltipContent></Tooltip></TooltipProvider>
) : (
<span className="h-6 w-5 shrink-0" aria-hidden="true" />
)}
- <button
- data-notebook-tree-button
- className="flex min-w-0 flex-1 items-center gap-2 text-left"
- type="button"
- aria-label={showsSplitCount
- ? t(selected ? "notebookTree.currentWithSplitCount" : "notebookTree.switchToWithSplitCount", { name: node.name, direct: node.directMemoCount, total: node.memoCount })
- : t(selected ? "notebookTree.currentWithCount" : "notebookTree.switchToWithCount", { name: node.name, count: showDescendantNotes ? node.memoCount : node.directMemoCount })}
- aria-current={selected ? "page" : undefined}
- aria-expanded={hasChildren ? open : undefined}
- onClick={() => onSelect(node.id)}
- onKeyDown={(event) => {
- if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Home" || event.key === "End") {
- event.preventDefault();
- event.stopPropagation();
- focusNotebookTreeButton(
- event.currentTarget,
- event.key === "Home" ? "first" : event.key === "End" ? "last" : event.key === "ArrowDown" ? "next" : "previous"
- );
- return;
- }
+ <TooltipProvider><Tooltip><TooltipTrigger asChild>
+ <button
+ data-notebook-tree-button
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ type="button"
+ aria-label={showsSplitCount
+ ? t(selected ? "notebookTree.currentWithSplitCount" : "notebookTree.switchToWithSplitCount", { name: node.name, direct: node.directMemoCount, total: node.memoCount })
+ : t(selected ? "notebookTree.currentWithCount" : "notebookTree.switchToWithCount", { name: node.name, count: showDescendantNotes ? node.memoCount : node.directMemoCount })}
+ aria-current={selected ? "page" : undefined}
+ aria-expanded={hasChildren ? open : undefined}
+ onClick={() => onSelect(node.id)}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Home" || event.key === "End") {
+ event.preventDefault();
+ event.stopPropagation();
+ focusNotebookTreeButton(
+ event.currentTarget,
+ event.key === "Home" ? "first" : event.key === "End" ? "last" : event.key === "ArrowDown" ? "next" : "previous"
+ );
+ return;
+ }
- if (event.key === "*" || event.key === "Multiply") {
- event.preventDefault();
- event.stopPropagation();
- onExpandSiblings(node.parentId);
- return;
- }
+ if (event.key === "*" || event.key === "Multiply") {
+ event.preventDefault();
+ event.stopPropagation();
+ onExpandSiblings(node.parentId);
+ return;
+ }
- if (event.key === "ArrowRight" && hasChildren && !open) {
- event.preventDefault();
- event.stopPropagation();
- onOpenChange(node.id, true);
- return;
- }
+ if (event.key === "ArrowRight" && hasChildren && !open) {
+ event.preventDefault();
+ event.stopPropagation();
+ onOpenChange(node.id, true);
+ return;
+ }
- if (event.key === "ArrowLeft" && hasChildren && open) {
- event.preventDefault();
- event.stopPropagation();
- onOpenChange(node.id, false);
- return;
- }
- }}
- >
- <NotebookIcon className={cn("h-4 w-4 shrink-0 transition-colors duration-200", selected ? "text-slate-950" : "text-slate-500")} />
- <span
- className={cn(
- "truncate transition-colors duration-200",
- selected ? "font-semibold text-black dark:text-slate-950" : "font-medium text-slate-800 group-hover:text-slate-950"
- )}
- >
- {node.name}
- </span>
- <span
- className={cn(
- "shrink-0 tabular-nums text-xs font-normal transition-colors duration-200",
- selected ? "text-slate-900 font-medium" : "text-slate-400 group-hover:text-slate-500"
- )}
- aria-hidden="true"
+ if (event.key === "ArrowLeft" && hasChildren && open) {
+ event.preventDefault();
+ event.stopPropagation();
+ onOpenChange(node.id, false);
+ return;
+ }
+ }}
>
- {formatNotebookMemoCount({ directCount: node.directMemoCount, totalCount: node.memoCount, hasChildren }, showDescendantNotes)}
- </span>
- </button>
- <div ref={actionsRef} className="relative shrink-0">
- <button
+ <NotebookIcon className={cn("h-4 w-4 shrink-0 transition-colors duration-200", selected ? "text-slate-950" : "text-slate-500")} />
+ <span
className={cn(
- "edgeever-reveal-on-touch hidden h-6 w-6 items-center justify-center rounded-md group-focus-within:flex group-hover:flex transition-colors duration-150",
- selected ? "hover:bg-slate-200" : "hover:bg-slate-100"
+ "truncate transition-colors duration-200",
+ selected ? "font-semibold text-black dark:text-slate-950" : "font-medium text-slate-800 group-hover:text-slate-950"
)}
- type="button"
- title={t("notebookTree.actions")}
- aria-label={t("notebookTree.actionsAria", { name: node.name })}
- aria-expanded={actionsOpen}
- onClick={(event) => {
- event.stopPropagation();
- setActionsOpen((openValue) => !openValue);
- }}
>
- <MoreHorizontal className="h-3.5 w-3.5" />
- </button>
+ {node.name}
+ </span>
+ {publicNotebook ? <Globe className={cn("h-3.5 w-3.5 shrink-0", selected ? "text-slate-700" : "text-slate-500")} aria-label={t("sharing.notebookPublic")} /> : null}
+ <span
+ className={cn(
+ "shrink-0 tabular-nums text-xs font-normal transition-colors duration-200",
+ selected ? "text-slate-900 font-medium" : "text-slate-400 group-hover:text-slate-500"
+ )}
+ aria-hidden="true"
+ >
+ {formatNotebookMemoCount({ directCount: node.directMemoCount, totalCount: node.memoCount, hasChildren }, showDescendantNotes)}
+ </span>
+ </button>
+ </TooltipTrigger><TooltipContent>{publicNotebook ? t("sharing.notebookPublic") : node.name}</TooltipContent></Tooltip></TooltipProvider>
+ <div ref={actionsRef} className="relative shrink-0">
+ <TooltipProvider><Tooltip><TooltipTrigger asChild>
+ <button
+ className={cn(
+ "edgeever-reveal-on-touch hidden h-6 w-6 items-center justify-center rounded-md group-focus-within:flex group-hover:flex transition-colors duration-150",
+ selected ? "hover:bg-slate-200" : "hover:bg-slate-100"
+ )}
+ type="button"
+ aria-label={t("notebookTree.actionsAria", { name: node.name })}
+ aria-expanded={actionsOpen}
+ onClick={(event) => {
+ event.stopPropagation();
+ setActionsOpen((openValue) => !openValue);
+ }}
+ >
+ <MoreHorizontal className="h-3.5 w-3.5" />
+ </button>
+ </TooltipTrigger><TooltipContent>{t("notebookTree.actions")}</TooltipContent></Tooltip></TooltipProvider>
{actionsOpen && (
<m.div className="absolute right-0 top-8 z-50 w-44 overflow-hidden rounded-md border border-slate-200 bg-card p-1 text-slate-950 shadow-lg" {...contentEnterMotion}>
<button
@@ -328,6 +342,13 @@ export const NotebookTreeItem = ({
<Pencil className="h-4 w-4" />
{t("notebookTree.rename")}
</button>
+ <button
+ className="flex h-9 w-full items-center gap-2 rounded-sm px-2 text-left text-xs outline-none hover:bg-slate-100"
+ type="button"
+ onClick={event => { event.stopPropagation(); setActionsOpen(false); setShareOpen(true); }}
+ >
+ <Share2 className="h-4 w-4" />{t("sharing.notebookTitle")}
+ </button>
{isInbox ? (
<>
<div className="-mx-1 my-1 h-px bg-slate-100" />
@@ -390,6 +411,9 @@ export const NotebookTreeItem = ({
<Pencil className="h-4 w-4" />
{t("notebookTree.rename")}
</ContextMenuItem>
+ <ContextMenuItem className="flex h-9 items-center gap-2 px-3 text-xs cursor-pointer" onClick={() => setShareOpen(true)}>
+ <Share2 className="h-4 w-4" />{t("sharing.notebookTitle")}
+ </ContextMenuItem>
{isInbox ? (
<>
<ContextMenuSeparator className="my-1 h-px bg-slate-100" />
@@ -421,6 +445,12 @@ export const NotebookTreeItem = ({
</ContextMenuContent>
</ContextMenu>
+ {shareOpen ? (
+ <Suspense fallback={null}>
+ <ShareNotebookDialog notebookId={node.id} notebookName={node.name} inherited={inheritedPublic} open onOpenChange={setShareOpen} />
+ </Suspense>
+ ) : null}
+
{hasChildren && open ? (
<m.div className="mt-1 space-y-1" {...treeEnterMotion}>
{node.children.map((child) => (
@@ -440,6 +470,8 @@ export const NotebookTreeItem = ({
onOpenChange={onOpenChange}
expandSiblingsRequest={expandSiblingsRequest}
onExpandSiblings={onExpandSiblings}
+ sharedNotebookIds={sharedNotebookIds}
+ inheritedPublic={publicNotebook}
showDescendantNotes={showDescendantNotes}
/>
))}
diff --git a/apps/web/src/components/PublicNotebookSharePage.tsx b/apps/web/src/components/PublicNotebookSharePage.tsx
new file mode 100644
index 00000000..c725e0d1
--- /dev/null
+++ b/apps/web/src/components/PublicNotebookSharePage.tsx
@@ -0,0 +1,196 @@
+import { useQuery } from "@tanstack/react-query";
+import { BookOpen, FileText, Folder, LoaderCircle } from "lucide-react";
+import { useEffect, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { Link, useParams } from "react-router";
+import type { PublicNotebookShare } from "@edgeever/shared";
+import { api } from "@/lib/api";
+import { Button } from "@/components/ui/button";
+import { PublicShareArticle } from "./PublicSharePage";
+
+const NotebookContents = ({
+ share,
+ token,
+ selectedId,
+}: {
+ share: PublicNotebookShare;
+ token: string;
+ selectedId?: string;
+}) => {
+ const { t } = useTranslation();
+ const tree = useMemo(() => {
+ const children = new Map<string | null, PublicNotebookShare["notebooks"]>();
+ const memos = new Map<string, PublicNotebookShare["memos"]>();
+ for (const notebook of share.notebooks) {
+ const siblings = children.get(notebook.parentId) ?? [];
+ siblings.push(notebook);
+ children.set(notebook.parentId, siblings);
+ }
+ for (const memo of share.memos) {
+ const siblings = memos.get(memo.notebookId) ?? [];
+ siblings.push(memo);
+ memos.set(memo.notebookId, siblings);
+ }
+ return { children, memos };
+ }, [share]);
+ const renderNotebook = (id: string, visited: ReadonlySet<string>) => {
+ if (visited.has(id)) return null;
+ const path = new Set(visited).add(id);
+ return (
+ <ul className="space-y-1 border-l border-slate-200 pl-3">
+ {(tree.memos.get(id) ?? []).map((memo) => (
+ <li key={memo.id}>
+ <Link
+ to={`/share/notebook/${encodeURIComponent(token)}/${encodeURIComponent(memo.id)}`}
+ aria-current={selectedId === memo.id ? "page" : undefined}
+ className={`flex items-start gap-2 rounded-md px-2 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500 ${selectedId === memo.id ? "bg-emerald-50 font-medium text-emerald-800" : "text-slate-600 hover:bg-slate-100"}`}
+ >
+ <FileText className="mt-0.5 h-4 w-4 shrink-0" />
+ <span className="break-words">
+ {memo.title?.trim() || t("common.untitledMemo")}
+ </span>
+ </Link>
+ </li>
+ ))}
+ {(tree.children.get(id) ?? []).map((notebook) => (
+ <li key={notebook.id}>
+ <details open>
+ <summary className="flex cursor-pointer items-center gap-2 px-2 py-2 text-sm font-medium text-slate-800">
+ <Folder className="h-4 w-4 shrink-0" />
+ <span className="break-words">{notebook.name}</span>
+ </summary>
+ {renderNotebook(notebook.id, path)}
+ </details>
+ </li>
+ ))}
+ </ul>
+ );
+ };
+ return (
+ <nav aria-label={t("sharing.notebookContents")}>
+ {renderNotebook(share.notebookId, new Set())}
+ </nav>
+ );
+};
+
+export const PublicNotebookSharePage = () => {
+ const { t } = useTranslation();
+ const { token = "", memoId } = useParams();
+ const directory = useQuery({
+ queryKey: ["public-notebook-share", token],
+ queryFn: () => api.getPublicNotebookShare(token),
+ retry: false,
+ staleTime: 0,
+ refetchOnMount: "always",
+ refetchInterval: 30_000,
+ });
+ const memo = useQuery({
+ queryKey: ["public-notebook-memo", token, memoId],
+ queryFn: () => api.getPublicNotebookMemo(token, memoId!),
+ enabled: Boolean(memoId),
+ retry: false,
+ staleTime: 0,
+ refetchOnMount: "always",
+ refetchInterval: 30_000,
+ });
+ const share = directory.isError ? undefined : directory.data?.share;
+ const note = memo.isError ? undefined : memo.data?.share;
+ const access = useMemo(
+ () => ({
+ resourceBasePath: `/api/public/notebook-shares/${encodeURIComponent(token)}/resources`,
+ memoUrls: memo.data?.memoUrls ?? {},
+ }),
+ [token, memo.data?.memoUrls],
+ );
+ useEffect(() => {
+ const robots = document.createElement("meta");
+ robots.name = "robots";
+ robots.content = "noindex,nofollow,noarchive";
+ document.head.appendChild(robots);
+ const previous = document.title;
+ document.title = `${note?.title?.trim() || share?.name || t("sharing.notebookTitle")} · EdgeEver`;
+ return () => {
+ robots.remove();
+ document.title = previous;
+ };
+ }, [note?.title, share?.name, t]);
+ if (directory.isPending)
+ return (
+ <main className="flex min-h-[100dvh] items-center justify-center">
+ <LoaderCircle
+ className="h-6 w-6 animate-spin"
+ aria-label={t("sharing.publicLoading")}
+ />
+ </main>
+ );
+ if (!share)
+ return (
+ <main className="flex min-h-[100dvh] flex-col items-center justify-center gap-4 p-6">
+ <h1 className="text-xl font-semibold">
+ {t("sharing.notebookUnavailable")}
+ </h1>
+ <p>{t("sharing.notebookUnavailableHint")}</p>
+ <Button variant="outline" onClick={() => void directory.refetch()}>
+ {t("sharing.retry")}
+ </Button>
+ </main>
+ );
+ return (
+ <main className="min-h-[100dvh] bg-slate-50 lg:flex lg:items-start">
+ <aside className="border-b border-slate-200 bg-card p-4 lg:sticky lg:top-0 lg:max-h-[100dvh] lg:w-72 lg:shrink-0 lg:overflow-auto lg:border-b-0 lg:border-r">
+ <Link
+ to={`/share/notebook/${encodeURIComponent(token)}`}
+ className="mb-4 flex items-center gap-2 break-words text-lg font-semibold text-slate-900"
+ >
+ <BookOpen className="h-5 w-5 shrink-0 text-emerald-700" />
+ {share.name}
+ </Link>
+ <details className="lg:hidden">
+ <summary className="cursor-pointer py-2 text-sm font-medium">
+ {t("sharing.notebookContents")}
+ </summary>
+ <NotebookContents share={share} token={token} selectedId={memoId} />
+ </details>
+ <div className="hidden lg:block">
+ <NotebookContents share={share} token={token} selectedId={memoId} />
+ </div>
+ </aside>
+ <div className="min-w-0 flex-1">
+ {!memoId ? (
+ <section className="mx-auto max-w-3xl p-8">
+ <h1 className="text-3xl font-bold">{share.name}</h1>
+ <p className="my-5 text-slate-500">
+ {t(
+ share.memos.length
+ ? "sharing.notebookWelcome"
+ : "sharing.notebookEmpty",
+ )}
+ </p>
+ <NotebookContents share={share} token={token} />
+ </section>
+ ) : memo.isPending ? (
+ <div className="flex min-h-60 items-center justify-center">
+ <LoaderCircle
+ className="h-6 w-6 animate-spin"
+ aria-label={t("sharing.publicLoading")}
+ />
+ </div>
+ ) : note && share.memos.some((item) => item.id === memoId) ? (
+ <PublicShareArticle share={note} token={token} access={access} />
+ ) : (
+ <section className="space-y-4 p-8">
+ <h1 className="text-xl font-semibold">
+ {t("sharing.publicUnavailable")}
+ </h1>
+ <p className="text-slate-500">
+ {t("sharing.notebookNoteUnavailableHint")}
+ </p>
+ <Button variant="outline" onClick={() => void memo.refetch()}>
+ {t("sharing.retry")}
+ </Button>
+ </section>
+ )}
+ </div>
+ </main>
+ );
+};
diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsx
index c6f56da3..fa94ebcf 100644
--- a/apps/web/src/components/PublicSharePage.tsx
+++ b/apps/web/src/components/PublicSharePage.tsx
@@ -22,6 +22,7 @@ import {
parsePublishedNoteBodyFont,
resolveNoteProse,
type PublicMemoShare,
+ type ShareBodyAccess,
} from "@edgeever/shared";
import { applyEditorBodyFontPreference } from "@/lib/editor-body-font";
import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
@@ -139,12 +140,14 @@ const SharedDocument = ({
locale,
share,
token,
+ access,
}: {
locale: "zh-CN" | "en-US" | "ja" | "pl";
share: PublicMemoShare;
token: string;
+ access?: ShareBodyAccess;
}) => {
- const body = useMemo(() => resolvePublicShareBody(share, token), [share, token]);
+ const body = useMemo(() => resolvePublicShareBody(share, token, access), [share, token, access]);
if (body.type === "diagram") {
return (
<Suspense
@@ -225,20 +228,6 @@ export const PublicSharePage = () => {
});
const share = shareQuery.data?.share;
const passwordRequired = isSharePasswordError(shareQuery.error, "share_password_required");
- const publishedBodyFont = share ? parsePublishedNoteBodyFont(share.bodyFont) : undefined;
-
- useEffect(() => {
- if (publishedBodyFont === undefined) return undefined;
- if (!publishedBodyFont) {
- delete document.documentElement.dataset.editorBodyFont;
- document.documentElement.style.removeProperty("--editor-body-font-family");
- } else {
- applyEditorBodyFontPreference({ choice: publishedBodyFont, customFamily: "" });
- }
- return () => {
- applyEditorBodyFontPreference();
- };
- }, [publishedBodyFont]);
useEffect(() => {
const previousTitle = document.title;
@@ -287,13 +276,33 @@ export const PublicSharePage = () => {
);
}
+ return <main className="min-h-[100dvh] bg-slate-50"><PublicShareArticle share={share} token={token} /></main>;
+};
+
+export const PublicShareArticle = ({ share, token, access }: { share: PublicMemoShare; token: string; access?: ShareBodyAccess }) => {
+ const { t, i18n } = useTranslation();
+ const publishedBodyFont = parsePublishedNoteBodyFont(share.bodyFont);
+
+ useEffect(() => {
+ if (publishedBodyFont === undefined) return undefined;
+ if (!publishedBodyFont) {
+ delete document.documentElement.dataset.editorBodyFont;
+ document.documentElement.style.removeProperty("--editor-body-font-family");
+ } else {
+ applyEditorBodyFontPreference({ choice: publishedBodyFont, customFamily: "" });
+ }
+ return () => {
+ applyEditorBodyFontPreference();
+ };
+ }, [publishedBodyFont]);
+
const prose = resolveNoteProse(share.prose);
return (
- <main className="edgeever-public-share min-h-[100dvh] bg-slate-50 px-4 py-6 sm:px-8 sm:py-10">
+ <div className="edgeever-public-share px-4 py-6 sm:px-8 sm:py-10">
<article className="mx-auto max-w-4xl overflow-hidden rounded-2xl border border-slate-200 bg-card shadow-sm">
<header className="border-b border-slate-200 px-5 py-6 sm:px-10 sm:py-8">
- <div className="mb-5 flex items-center justify-between gap-4 text-xs text-slate-500">
- <span className="flex items-center gap-1.5 font-semibold text-slate-700">
+ <div className="mb-5 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-slate-500">
+ <span className="flex shrink-0 items-center gap-1.5 font-semibold text-slate-700">
<ShieldCheck className="h-4 w-4" /> EdgeEver · {t("sharing.readOnly")}
</span>
<span className="flex items-center gap-1.5">
@@ -325,9 +334,10 @@ export const PublicSharePage = () => {
locale={(i18n.resolvedLanguage || i18n.language || "zh-CN").startsWith("en") ? "en-US" : "zh-CN"}
share={share}
token={token}
+ access={access}
/>
</div>
</article>
- </main>
+ </div>
);
};
diff --git a/apps/web/src/components/dialogs/ShareNotebookDialog.tsx b/apps/web/src/components/dialogs/ShareNotebookDialog.tsx
new file mode 100644
index 00000000..521c66c3
--- /dev/null
+++ b/apps/web/src/components/dialogs/ShareNotebookDialog.tsx
@@ -0,0 +1,171 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Copy, ExternalLink, LoaderCircle, Share2, Trash2 } from "lucide-react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
+import { copyTextToClipboard } from "@/lib/clipboard";
+
+export const getPublicNotebookShareUrl = (token: string) =>
+ `${(getConfiguredDesktopApiBaseUrl() || window.location.origin).replace(/\/$/, "")}/share/notebook/${encodeURIComponent(token)}`;
+
+export const ShareNotebookDialog = ({
+ notebookId,
+ notebookName,
+ inherited = false,
+ open,
+ onOpenChange,
+}: {
+ notebookId: string;
+ notebookName: string;
+ inherited?: boolean;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const [copyResult, setCopyResult] = useState<boolean | null>(null);
+ const queryKey = [
+ "notebook-share",
+ getConfiguredDesktopApiBaseUrl(),
+ notebookId,
+ ];
+ const query = useQuery({
+ queryKey,
+ queryFn: () => api.getNotebookShare(notebookId),
+ enabled: open,
+ retry: false,
+ refetchOnMount: "always",
+ });
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ["notebook-shares"] });
+ const create = useMutation({
+ mutationFn: () => api.createNotebookShare(notebookId),
+ onSuccess: (data) => {
+ queryClient.setQueryData(queryKey, data);
+ void invalidate();
+ },
+ });
+ const revoke = useMutation({
+ mutationFn: () => api.revokeNotebookShare(notebookId),
+ onSuccess: () => {
+ queryClient.setQueryData(queryKey, { share: null });
+ setCopyResult(null);
+ void invalidate();
+ },
+ });
+ const share = query.data?.share;
+ const busy = query.isFetching || create.isPending || revoke.isPending;
+ const failed = query.isError || create.isError || revoke.isError;
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Share2 className="h-5 w-5" />
+ {t("sharing.notebookTitle")}
+ </DialogTitle>
+ <DialogDescription>{notebookName}</DialogDescription>
+ </DialogHeader>
+ <p className="rounded-lg bg-amber-50 p-3 text-sm leading-6 text-amber-900">
+ {t("sharing.notebookScopeHint")}
+ </p>
+ {inherited ? (
+ <p className="text-sm leading-6 text-slate-600">
+ {t("sharing.notebookInheritedHint")}
+ </p>
+ ) : null}
+ {query.isPending ? (
+ <LoaderCircle
+ className="mx-auto h-5 w-5 animate-spin"
+ aria-label={t("sharing.publicLoading")}
+ />
+ ) : share ? (
+ <>
+ <Input
+ value={getPublicNotebookShareUrl(share.token)}
+ readOnly
+ aria-label={t("sharing.linkLabel")}
+ />
+ <div className="flex flex-wrap gap-2">
+ <Button
+ variant="outline"
+ onClick={async () =>
+ setCopyResult(
+ await copyTextToClipboard(
+ getPublicNotebookShareUrl(share.token),
+ ),
+ )
+ }
+ >
+ <Copy className="h-4 w-4" />
+ {t(
+ copyResult === null
+ ? "sharing.copy"
+ : copyResult
+ ? "sharing.copied"
+ : "sharing.copyFailed",
+ )}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={() =>
+ window.open(
+ getPublicNotebookShareUrl(share.token),
+ "_blank",
+ "noopener,noreferrer",
+ )
+ }
+ >
+ <ExternalLink className="h-4 w-4" />
+ {t("sharing.open")}
+ </Button>
+ <Button
+ variant="outline"
+ disabled={busy}
+ onClick={() => revoke.mutate()}
+ >
+ <Trash2 className="h-4 w-4" />
+ {t("sharing.revoke")}
+ </Button>
+ </div>
+ <p className="text-xs leading-5 text-slate-500">
+ {t("sharing.notebookRevokeHint")}
+ </p>
+ </>
+ ) : !query.isError ? (
+ <Button disabled={busy} onClick={() => create.mutate()}>
+ {create.isPending ? (
+ <LoaderCircle className="h-4 w-4 animate-spin" />
+ ) : (
+ <Share2 className="h-4 w-4" />
+ )}
+ {t("sharing.create")}
+ </Button>
+ ) : null}
+ {failed ? (
+ <div role="alert" className="space-y-2 text-sm text-rose-600">
+ <p>{t("sharing.error")}</p>
+ {query.isError ? (
+ <Button
+ variant="outline"
+ disabled={busy}
+ onClick={() => void query.refetch()}
+ >
+ {t("sharing.retry")}
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/apps/web/src/components/settings/NotebookShareManagement.tsx b/apps/web/src/components/settings/NotebookShareManagement.tsx
new file mode 100644
index 00000000..971241b5
--- /dev/null
+++ b/apps/web/src/components/settings/NotebookShareManagement.tsx
@@ -0,0 +1,186 @@
+import { useQuery } from "@tanstack/react-query";
+import { ExternalLink, Globe, LoaderCircle, Settings2 } from "lucide-react";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { getNotebookDescendantIds, type NotebookShare } from "@edgeever/shared";
+import { getNotebookMoveOptions } from "@/lib/app-helpers";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Button } from "@/components/ui/button";
+import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
+import {
+ ShareNotebookDialog,
+ getPublicNotebookShareUrl,
+} from "../dialogs/ShareNotebookDialog";
+
+export const NotebookShareManagement = ({
+ userId,
+}: {
+ userId: string | null;
+}) => {
+ const { t } = useTranslation();
+ const [managed, setManaged] = useState<Pick<
+ NotebookShare,
+ "notebookId" | "notebookName"
+ > | null>(null);
+ const [selecting, setSelecting] = useState(false);
+ const notebooks = useQuery({
+ queryKey: ["shareable-notebooks", getConfiguredDesktopApiBaseUrl(), userId],
+ queryFn: () => api.listNotebooks(),
+ enabled: selecting || Boolean(managed),
+ retry: false,
+ refetchOnMount: "always",
+ });
+ const options = useMemo(
+ () => getNotebookMoveOptions(notebooks.data?.notebooks ?? []),
+ [notebooks.data],
+ );
+ const query = useQuery({
+ queryKey: ["notebook-shares", getConfiguredDesktopApiBaseUrl(), userId],
+ queryFn: () => api.listNotebookShares(),
+ retry: false,
+ refetchOnMount: "always",
+ });
+ return (
+ <section className="border-t border-slate-100">
+ <h3 className="flex items-center gap-2 px-4 pt-4 text-sm font-medium">
+ <Globe className="h-4 w-4" />
+ {t("sharing.notebookManagementTitle")}
+ </h3>
+ <div className="px-4 pt-3">
+ {selecting ? (
+ <>
+ <Select
+ onValueChange={(id) => {
+ const notebook = options.find((item) => item.id === id);
+ if (notebook) {
+ setManaged({ notebookId: id, notebookName: notebook.name });
+ setSelecting(false);
+ }
+ }}
+ >
+ <SelectTrigger
+ disabled={notebooks.isPending || notebooks.isError}
+ aria-label={t("sharing.notebookChoose")}
+ >
+ <SelectValue placeholder={t("sharing.notebookChoose")} />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.id} value={option.id}>
+ {option.selectLabel}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {notebooks.isError ? (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void notebooks.refetch()}
+ >
+ {t("sharing.retry")}
+ </Button>
+ ) : null}
+ </>
+ ) : (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setSelecting(true)}
+ >
+ {t("sharing.notebookTitle")}
+ </Button>
+ )}
+ </div>
+ {query.isPending ? (
+ <div className="p-4">
+ <LoaderCircle
+ className="h-4 w-4 animate-spin"
+ aria-label={t("sharing.managementLoading")}
+ />
+ </div>
+ ) : query.isError ? (
+ <div className="space-y-2 p-4">
+ <p role="alert" className="text-xs text-rose-600">
+ {t("sharing.managementLoadFailed")}
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void query.refetch()}
+ >
+ {t("sharing.retry")}
+ </Button>
+ </div>
+ ) : !query.data.shares.length ? (
+ <p className="p-4 text-xs text-slate-500">
+ {t("sharing.notebookManagementEmpty")}
+ </p>
+ ) : (
+ <div className="divide-y divide-slate-100">
+ {query.data.shares.map((share) => (
+ <div
+ key={share.notebookId}
+ className="flex flex-wrap items-center justify-between gap-3 p-4"
+ >
+ <span className="min-w-0 break-words text-sm">
+ {share.notebookName}
+ </span>
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() =>
+ window.open(
+ getPublicNotebookShareUrl(share.token),
+ "_blank",
+ "noopener,noreferrer",
+ )
+ }
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ {t("sharing.open")}
+ </Button>
+ <Button
+ size="sm"
+ variant="soft"
+ onClick={() => setManaged(share)}
+ >
+ <Settings2 className="h-3.5 w-3.5" />
+ {t("sharing.manage")}
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ {managed ? (
+ <ShareNotebookDialog
+ key={managed.notebookId}
+ notebookId={managed.notebookId}
+ notebookName={managed.notebookName}
+ inherited={
+ query.data?.shares.some(
+ (share) =>
+ share.notebookId !== managed.notebookId &&
+ getNotebookDescendantIds(
+ notebooks.data?.notebooks ?? [],
+ share.notebookId,
+ ).includes(managed.notebookId),
+ ) ?? false
+ }
+ open
+ onOpenChange={(open) => {
+ if (!open) setManaged(null);
+ }}
+ />
+ ) : null}
+ </section>
+ );
+};
diff --git a/apps/web/src/components/settings/ShareManagementCard.tsx b/apps/web/src/components/settings/ShareManagementCard.tsx
index cc016ce2..19a5fa20 100644
--- a/apps/web/src/components/settings/ShareManagementCard.tsx
+++ b/apps/web/src/components/settings/ShareManagementCard.tsx
@@ -3,6 +3,7 @@ import { Copy, ExternalLink, Link2, LoaderCircle, LockKeyhole, Settings2 } from
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { ManagedMemoShare } from "@edgeever/shared";
+import { NotebookShareManagement } from "./NotebookShareManagement";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { getPublicShareUrl, ShareMemoDialog } from "@/components/dialogs/ShareMemoDialog";
@@ -111,6 +112,7 @@ export const ShareManagementCard = ({ userId, onOpenMemo }: Props) => {
) : null}
</div>
)}
+ <NotebookShareManagement userId={userId} />
</CardContent>
{managedMemoId ? (
<ShareMemoDialog memoId={managedMemoId} open onOpenChange={(open) => { if (!open) setManagedMemoId(null); }} />
diff --git a/apps/web/src/lib/public-share-body.ts b/apps/web/src/lib/public-share-body.ts
index 399a97f9..7311bac7 100644
--- a/apps/web/src/lib/public-share-body.ts
+++ b/apps/web/src/lib/public-share-body.ts
@@ -12,6 +12,7 @@ import {
type DiagramDocument,
type PublicMemoShare,
type TiptapDoc,
+ type ShareBodyAccess,
} from "@edgeever/shared";
export type PublicShareBody =
@@ -19,18 +20,18 @@ export type PublicShareBody =
| { type: "rich-text"; content: TiptapDoc };
/** Visual diagram notes share through IR → X6. Ordinary notes, including embedded Mermaid fences, stay on TipTap. */
-export const resolvePublicShareBody = (share: PublicMemoShare, token: string): PublicShareBody => {
+export const resolvePublicShareBody = (share: PublicMemoShare, token: string, access?: ShareBodyAccess): PublicShareBody => {
const diagram = parseDiagramDocument(share.contentMarkdown);
if (diagram) return { type: "diagram", diagram };
const table = parseTableDocument(share.contentMarkdown);
if (table) {
- return { type: "rich-text", content: rewriteMemoResourcesForShare(markdownToDoc(tableFallbackMarkdown(table)), token, share.memoShareTokens) };
+ return { type: "rich-text", content: rewriteMemoResourcesForShare(markdownToDoc(tableFallbackMarkdown(table)), token, share.memoShareTokens, access) };
}
const richText = hasDiagramDocumentMarker(share.contentMarkdown) || hasTableDocumentMarker(share.contentMarkdown)
? markdownToDoc(hasTableDocumentMarker(share.contentMarkdown) ? stripTableDocumentMarker(share.contentMarkdown) : stripDiagramDocumentMarker(share.contentMarkdown))
: resolveMemoContentDoc(share.contentJson, share.contentMarkdown);
return {
type: "rich-text",
- content: rewriteMemoResourcesForShare(richText, token, share.memoShareTokens),
+ content: rewriteMemoResourcesForShare(richText, token, share.memoShareTokens, access),
};
};
diff --git a/migrations/0067_notebook_shares.sql b/migrations/0067_notebook_shares.sql
new file mode 100644
index 00000000..ae8d9bf7
--- /dev/null
+++ b/migrations/0067_notebook_shares.sql
@@ -0,0 +1,12 @@
+PRAGMA foreign_keys = ON;
+
+CREATE TABLE notebook_shares (
+ id TEXT PRIMARY KEY,
+ notebook_id TEXT NOT NULL UNIQUE REFERENCES notebooks(id) ON UPDATE CASCADE ON DELETE CASCADE,
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON UPDATE CASCADE ON DELETE CASCADE,
+ token TEXT NOT NULL UNIQUE,
+ created_by TEXT,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
+);
+CREATE INDEX idx_notebook_shares_workspace ON notebook_shares(workspace_id, updated_at DESC);
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index d6e11a8b..eec67483 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -34,6 +34,8 @@ import type {
MemoRevision,
MemoSummary,
MemoShare,
+ NotebookShare,
+ PublicNotebookShare,
ManagedMemoShare,
PublicTableForm,
TableFormSettings,
@@ -837,6 +839,15 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
getSession: () => request<AuthSession>("/api/v1/auth/session"),
+ getPublicNotebookShare: (token: string) =>
+ request<{ share: PublicNotebookShare }>(`/api/public/notebook-shares/${encodeURIComponent(token)}`),
+ getPublicNotebookMemo: (token: string, memoId: string) =>
+ request<{ share: PublicMemoShare; memoUrls: Record<string, string> }>(`/api/public/notebook-shares/${encodeURIComponent(token)}/memos/${encodeURIComponent(memoId)}`),
+ listNotebookShares: () => request<{ shares: NotebookShare[] }>("/api/v1/notebook-shares"),
+ getNotebookShare: (id: string) => request<{ share: NotebookShare | null }>(`/api/v1/notebooks/${encodeURIComponent(id)}/share`),
+ createNotebookShare: (id: string) => request<{ share: NotebookShare }>(`/api/v1/notebooks/${encodeURIComponent(id)}/share`, { method: "POST" }),
+ revokeNotebookShare: (id: string) => request<{ ok: true }>(`/api/v1/notebooks/${encodeURIComponent(id)}/share`, { method: "DELETE" }),
+
getPublicMemoShare: (token: string) =>
request<PublicMemoShareResponse>(`/api/public/shares/${encodeURIComponent(token)}`),
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 9884e2d1..fdac7be0 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2550,8 +2550,23 @@ export const enUS = {
expandOutlineHeading: "Expand {{name}}",
},
sharing: {
+ notebookChoose: "Choose a notebook to share",
+ notebookTitle: "Share notebook",
+ notebookScopeHint: "All notes and attachments in this notebook and its sub-notebooks will be public. New or moved-in content is shared automatically, and saved edits appear live. Anyone with the link can view without signing in.",
+ notebookInheritedHint: "This notebook is already public through a parent notebook. Revoking its own link does not revoke the parent share. Stop sharing the parent or move the content outside the public scope.",
+ notebookRevokeHint: "Revoking disables this link for the entire directory, notes, and attachments. Other notebook shares and individual note shares keep their own settings.",
+ notebookPublic: "Public notebook (including sub-notebooks and future content)",
+ notebookContents: "Contents",
+ notebookUnavailable: "This shared notebook is unavailable",
+ notebookUnavailableHint: "The link may have been revoked, or the notebook deleted.",
+ notebookNoteUnavailableHint: "This note may have moved outside the public directory, been deleted, or the link is invalid.",
+ notebookWelcome: "Choose a note from the contents to start reading.",
+ notebookEmpty: "This notebook has no notes to read yet.",
+ notebookManagementTitle: "Notebook shares",
+ notebookManagementEmpty: "No notebooks are currently shared.",
+
managementTitle: "Share management",
- managementDescription: "See notes currently accessible through public links and manage each share.",
+ managementDescription: "See notes and notebooks accessible through public links and manage their sharing settings.",
managementLoading: "Loading shared notes",
managementLoadFailed: "Could not load the latest shares. Check your connection and try again.",
managementEmpty: "No notes are currently shared.",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index a2933ab9..5770d0bc 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2539,8 +2539,23 @@ export const ja = {
expandOutlineHeading: "{{name}} を開く",
},
sharing: {
+ notebookChoose: "共有するノートブックを選択",
+ notebookTitle: "ノートブックを共有",
+ notebookScopeHint: "このノートブックとすべての子ノートブックのノートや添付ファイルが公開されます。新規・移動した内容は自動で公開され、保存した編集も反映されます。リンクがあればログインせずに閲覧できます。",
+ notebookInheritedHint: "このノートブックは親ノートブックから公開されています。独自の共有を解除しても親の共有は継続します。親の共有を解除するか、公開範囲外に移動してください。",
+ notebookRevokeHint: "解除すると、このリンクからディレクトリ全体・ノート・添付ファイルにアクセスできなくなります。他のノートブックや単独のノート共有は継続します。",
+ notebookPublic: "公開ノートブック(子ノートブックと今後の内容を含む)",
+ notebookContents: "目次",
+ notebookUnavailable: "共有ノートブックを利用できません",
+ notebookUnavailableHint: "共有が解除されたか、ノートブックが削除された可能性があります。",
+ notebookNoteUnavailableHint: "ノートが公開範囲外に移動・削除されたか、リンクが無効です。",
+ notebookWelcome: "目次からノートを選んでください。",
+ notebookEmpty: "閲覧できるノートがまだありません。",
+ notebookManagementTitle: "ノートブックの共有",
+ notebookManagementEmpty: "共有中のノートブックはありません。",
+
managementTitle: "共有の管理",
- managementDescription: "公開リンクでアクセスできるノートを確認し、共有設定を管理します。",
+ managementDescription: "公開リンクでアクセスできるノートとノートブックを確認し、共有設定を管理します。",
managementLoading: "共有ノートを読み込み中",
managementLoadFailed: "最新の共有一覧を読み込めませんでした。接続を確認して再試行してください。",
managementEmpty: "現在共有中のノートはありません。",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 10a314bd..dade383a 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2539,8 +2539,23 @@ export const pl = {
expandOutlineHeading: "Rozwiń {{name}}",
},
sharing: {
+ notebookChoose: "Wybierz notatnik do udostępnienia",
+ notebookTitle: "Udostępnij notatnik",
+ notebookScopeHint: "Wszystkie notatki i załączniki w tym notatniku oraz jego podnotatnikach będą publiczne. Nowe i przeniesione treści są udostępniane automatycznie, a zapisane zmiany są widoczne na bieżąco. Każdy z linkiem może je przeglądać bez logowania.",
+ notebookInheritedHint: "Ten notatnik jest już publiczny przez notatnik nadrzędny. Cofnięcie jego własnego linku nie cofa udostępnienia nadrzędnego. Cofnij udostępnienie nadrzędne lub przenieś treść poza zakres publiczny.",
+ notebookRevokeHint: "Cofnięcie wyłącza ten link do całego katalogu, notatek i załączników. Inne udostępnienia notatników i pojedynczych notatek zachowują własne ustawienia.",
+ notebookPublic: "Publiczny notatnik (z podnotatnikami i przyszłą treścią)",
+ notebookContents: "Spis treści",
+ notebookUnavailable: "Ten udostępniony notatnik jest niedostępny",
+ notebookUnavailableHint: "Link mógł zostać cofnięty lub notatnik usunięty.",
+ notebookNoteUnavailableHint: "Notatka mogła zostać przeniesiona poza katalog publiczny, usunięta lub link jest nieprawidłowy.",
+ notebookWelcome: "Wybierz notatkę ze spisu treści, aby rozpocząć czytanie.",
+ notebookEmpty: "Ten notatnik nie ma jeszcze notatek do czytania.",
+ notebookManagementTitle: "Udostępnione notatniki",
+ notebookManagementEmpty: "Żadne notatniki nie są obecnie udostępniane.",
+
managementTitle: "Zarządzanie udostępnianiem",
- managementDescription: "Zobacz notatki dostępne przez publiczne linki i zarządzaj ich udostępnianiem.",
+ managementDescription: "Zobacz notatki i notatniki dostępne przez publiczne linki i zarządzaj ich udostępnianiem.",
managementLoading: "Wczytywanie udostępnionych notatek",
managementLoadFailed: "Nie udało się pobrać aktualnej listy. Sprawdź połączenie i spróbuj ponownie.",
managementEmpty: "Żadna notatka nie jest obecnie udostępniana.",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 23b58195..05a221dd 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2548,8 +2548,23 @@ export const zhCN = {
expandOutlineHeading: "展开 {{name}}",
},
sharing: {
+ notebookChoose: "选择要分享的笔记本",
+ notebookTitle: "分享笔记本",
+ notebookScopeHint: "此笔记本及所有子笔记本中的笔记和附件都会公开。新增或移入的内容自动公开,编辑后的内容实时同步。任何获得链接的人都可无需登录访问。",
+ notebookInheritedHint: "此笔记本已通过上级笔记本公开。取消此处的独立分享不会关闭上级分享;需要在上级笔记本取消分享,或将内容移出公开范围。",
+ notebookRevokeHint: "取消后,此链接下的整个目录、笔记和附件停止访问。其他笔记本分享和独立笔记分享仍按各自设置生效。",
+ notebookPublic: "公开笔记本(包含子笔记本及新增内容)",
+ notebookContents: "目录",
+ notebookUnavailable: "这个分享笔记本不可用",
+ notebookUnavailableHint: "链接可能已撤销,或笔记本已删除。",
+ notebookNoteUnavailableHint: "这篇笔记可能已移出公开目录、删除,或链接无效。",
+ notebookWelcome: "从目录选择一篇笔记开始阅读。",
+ notebookEmpty: "这个笔记本中还没有可阅读的笔记。",
+ notebookManagementTitle: "笔记本分享",
+ notebookManagementEmpty: "当前没有正在分享的笔记本。",
+
managementTitle: "分享管理",
- managementDescription: "查看当前仍可通过公开链接访问的笔记,并管理各自的分享设置。",
+ managementDescription: "查看通过公开链接访问的笔记和笔记本,并管理各自的分享设置。",
managementLoading: "正在读取分享列表",
managementLoadFailed: "无法获取最新分享列表,请检查网络后重试。",
managementEmpty: "当前没有正在分享的笔记。",
diff --git a/packages/shared/src/sharing.test.mjs b/packages/shared/src/sharing.test.mjs
index f22dc7cd..1926fcb0 100644
--- a/packages/shared/src/sharing.test.mjs
+++ b/packages/shared/src/sharing.test.mjs
@@ -54,3 +54,24 @@ describe("shared memo resources", () => {
expect(rewritten.content[0].content[1].marks[0].attrs.href).toBe("#memo=memo_private");
});
});
+
+
+test("notebook shares use their own attachment scope, link within the directory, and disable private memo links", () => {
+ const source = { type: "doc", content: [
+ { type: "image", attrs: { src: "/api/v1/resources/image/blob" } },
+ { type: "paragraph", content: [
+ { type: "text", text: "Shared", marks: [{ type: "link", attrs: { href: "#memo=inside" } }] },
+ { type: "text", text: "Private", marks: [{ type: "link", attrs: { href: "#memo=outside" } }] },
+ { type: "text", text: "External", marks: [{ type: "link", attrs: { href: "https://example.com" } }] },
+ ] },
+ ] };
+ const rewritten = rewriteMemoResourcesForShare(source, "token", {}, {
+ resourceBasePath: "/api/public/notebook-shares/token/resources",
+ memoUrls: { inside: "/share/notebook/token/inside" },
+ });
+ expect(rewritten.content[0].attrs.src).toBe("/api/public/notebook-shares/token/resources/image/blob");
+ expect(rewritten.content[1].content[0].marks[0].attrs.href).toBe("/share/notebook/token/inside");
+ expect(rewritten.content[1].content[1].marks).toEqual([]);
+ expect(rewritten.content[1].content[2].marks[0].attrs.href).toBe("https://example.com");
+ expect(source.content[1].content[1].marks).toHaveLength(1);
+});
diff --git a/packages/shared/src/sharing.ts b/packages/shared/src/sharing.ts
index e0a857fe..cb4f7b07 100644
--- a/packages/shared/src/sharing.ts
+++ b/packages/shared/src/sharing.ts
@@ -18,6 +18,26 @@ export type ManagedMemoShare = MemoShare & {
notebookName: string | null;
};
+export type NotebookShare = {
+ notebookId: string;
+ notebookName: string;
+ token: string;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type PublicNotebookShare = {
+ notebookId: string;
+ name: string;
+ notebooks: Array<{ id: string; parentId: string | null; name: string }>;
+ memos: Array<{ id: string; notebookId: string; title: string | null }>;
+};
+
+export type ShareBodyAccess = {
+ resourceBasePath: string;
+ memoUrls: Readonly<Record<string, string>>;
+};
+
export const PUBLISHED_NOTE_BODY_FONTS = [
"wenkai",
"wenkai-screen",
@@ -30,9 +50,12 @@ export const PUBLISHED_NOTE_BODY_FONTS = [
export type PublishedNoteBodyFont = (typeof PUBLISHED_NOTE_BODY_FONTS)[number];
-export const parsePublishedNoteBodyFont = (value: unknown): PublishedNoteBodyFont | null =>
- typeof value === "string" && (PUBLISHED_NOTE_BODY_FONTS as readonly string[]).includes(value)
- ? value as PublishedNoteBodyFont
+export const parsePublishedNoteBodyFont = (
+ value: unknown,
+): PublishedNoteBodyFont | null =>
+ typeof value === "string" &&
+ (PUBLISHED_NOTE_BODY_FONTS as readonly string[]).includes(value)
+ ? (value as PublishedNoteBodyFont)
: null;
export type PublicMemoShare = {
@@ -48,20 +71,23 @@ export type PublicMemoShare = {
prose: PublicNoteProse;
};
-const RESOURCE_URL_PATTERN = /^\/api\/v1\/resources\/([^/?#]+)\/blob(?:[?#].*)?$/;
+const RESOURCE_URL_PATTERN =
+ /^\/api\/v1\/resources\/([^/?#]+)\/blob(?:[?#].*)?$/;
const rewriteAttributeValue = (
value: unknown,
token: string,
memoShareTokens: Readonly<Record<string, string>>,
+ access?: ShareBodyAccess,
) => {
if (typeof value !== "string") return value;
const match = value.match(RESOURCE_URL_PATTERN);
if (match) {
- return `/api/public/shares/${encodeURIComponent(token)}/resources/${encodeURIComponent(match[1])}/blob`;
+ return `${access?.resourceBasePath ?? `/api/public/shares/${encodeURIComponent(token)}/resources`}/${encodeURIComponent(match[1])}/blob`;
}
const memoId = parseMemoLinkHref(value);
+ if (memoId && access) return access.memoUrls[memoId] ?? "#";
const shareToken = memoId ? memoShareTokens[memoId] : null;
return shareToken ? `/share/${encodeURIComponent(shareToken)}` : value;
};
@@ -71,25 +97,52 @@ export const rewriteMemoResourcesForShare = (
doc: TiptapDoc,
token: string,
memoShareTokens: Readonly<Record<string, string>> = {},
+ access?: ShareBodyAccess,
): TiptapDoc => {
- const visit = (node: TiptapNode | TiptapTextNode): TiptapNode | TiptapTextNode => {
- const attrs = "attrs" in node && node.attrs
- ? Object.fromEntries(Object.entries(node.attrs).map(([key, value]) => [key, rewriteAttributeValue(value, token, memoShareTokens)]))
- : undefined;
- const marks = "marks" in node && node.marks
- ? node.marks.map((mark) => ({
- ...mark,
- attrs: mark.attrs
- ? Object.fromEntries(Object.entries(mark.attrs).map(([key, value]) => [key, rewriteAttributeValue(value, token, memoShareTokens)]))
- : undefined,
- }))
- : undefined;
+ const visit = (
+ node: TiptapNode | TiptapTextNode,
+ ): TiptapNode | TiptapTextNode => {
+ const attrs =
+ "attrs" in node && node.attrs
+ ? Object.fromEntries(
+ Object.entries(node.attrs).map(([key, value]) => [
+ key,
+ rewriteAttributeValue(value, token, memoShareTokens, access),
+ ]),
+ )
+ : undefined;
+ const marks =
+ "marks" in node && node.marks
+ ? node.marks
+ .filter((mark) => {
+ const memoId = parseMemoLinkHref(mark.attrs?.href);
+ return !access || !memoId || Boolean(access.memoUrls[memoId]);
+ })
+ .map((mark) => ({
+ ...mark,
+ attrs: mark.attrs
+ ? Object.fromEntries(
+ Object.entries(mark.attrs).map(([key, value]) => [
+ key,
+ rewriteAttributeValue(
+ value,
+ token,
+ memoShareTokens,
+ access,
+ ),
+ ]),
+ )
+ : undefined,
+ }))
+ : undefined;
return {
...node,
...(attrs ? { attrs } : {}),
...(marks ? { marks } : {}),
- ...("content" in node && node.content ? { content: node.content.map(visit) } : {}),
+ ...("content" in node && node.content
+ ? { content: node.content.map(visit) }
+ : {}),
} as TiptapNode | TiptapTextNode;
};