Skip to content

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

feat(sharing): include note text in public share responses

tianma-if37740cff06ca
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index da866dbc..56eba210 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -121,6 +121,7 @@ import {
import { registerNotebookRoutes } from "./notebook-routes";
import { registerNotebookShareRoutes, registerPublicNotebookShareRoutes } from "./notebook-share-routes";
import { isNotebookSitePagePath, renderNotebookSitePage } from "./notebook-site-page";
+import { isPublicMemoSharePagePath, renderPublicMemoSharePage } from "./share-page";
import { registerMemoShareRoutes, registerPublicShareRoutes } from "./share-routes";
import { registerPublicTableFormRoutes, registerTableFormRoutes } from "./table-form-routes";
import {
@@ -459,9 +460,19 @@ export const fetchEdgeEverApp = async (
const worker = {
async fetch(request: Request, env: WorkerBindings, ctx: ExecutionContext) {
- if (isNotebookSitePagePath(new URL(request.url).pathname)) {
- return (await renderNotebookSitePage(request, createCloudflareStorageAdapter(env).db,
- () => env.ASSETS.fetch(new Request(new URL("/", request.url), { method: "GET" }))))!;
+ const { pathname } = new URL(request.url);
+ const loadAppShell = () => env.ASSETS.fetch(new Request(new URL("/", request.url), { method: "GET" }));
+ if (isNotebookSitePagePath(pathname)) {
+ return (await renderNotebookSitePage(request, createCloudflareStorageAdapter(env).db, loadAppShell))!;
+ }
+ // `/share/*` runs the worker first. Unknown share paths still fall through
+ // to the asset shell so a typo does not become a JSON 404.
+ if (pathname.startsWith("/share/")) {
+ if (isPublicMemoSharePagePath(pathname)) {
+ const page = await renderPublicMemoSharePage(request, createCloudflareStorageAdapter(env).db, loadAppShell);
+ if (page) return page;
+ }
+ return env.ASSETS.fetch(request);
}
return fetchEdgeEverApp(request, {
...env,
diff --git a/apps/api/src/share-page.test.mjs b/apps/api/src/share-page.test.mjs
new file mode 100644
index 00000000..e60d50f4
--- /dev/null
+++ b/apps/api/src/share-page.test.mjs
@@ -0,0 +1,170 @@
+import { PUBLIC_PAGE_ROBOTS } from "@edgeever/shared/public-page-headers";
+import { describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+import { globSync, readFileSync } from "node:fs";
+import { isPublicMemoSharePagePath, parsePublicMemoSharePagePath, renderPublicMemoSharePage } from "./share-page.ts";
+
+class SqliteD1PreparedStatement {
+ constructor(db, sql, bindings = []) {
+ this.db = db;
+ this.sql = sql;
+ this.bindings = bindings;
+ }
+
+ bind(...bindings) {
+ return new SqliteD1PreparedStatement(this.db, this.sql, bindings);
+ }
+
+ async all() {
+ return { results: this.db.query(this.sql).all(...this.bindings), success: true, meta: {} };
+ }
+
+ async first() {
+ return this.db.query(this.sql).get(...this.bindings) ?? null;
+ }
+
+ async run() {
+ this.db.query(this.sql).run(...this.bindings);
+ return { success: true, meta: {} };
+ }
+}
+
+const token = "s".repeat(43);
+const shell = `<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="description" content="old description" />
+ <title>EdgeEver</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ </body>
+</html>`;
+
+const createDatabase = () => {
+ const sqlite = new Database(":memory:");
+ for (const migration of globSync("migrations/*.sql").sort()) {
+ sqlite.exec(readFileSync(migration, "utf8"));
+ }
+ sqlite.query("INSERT INTO workspaces (id, name, is_personal) VALUES (?, ?, 1)").run("ws_member", "Member workspace");
+ sqlite.query("INSERT INTO notebooks (id, workspace_id, name) VALUES (?, ?, ?)").run("nb_member", "ws_member", "Inbox");
+ sqlite.query("INSERT INTO memos (id, workspace_id, notebook_id, title) VALUES (?, ?, ?, ?)")
+ .run("memo_source", "ws_member", "nb_member", "A $& $' $$ <script>");
+ sqlite.query("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_hash) VALUES (?, ?, ?, ?)")
+ .run("memo_source", "{}", "# A $& $' $$ <script>\n\nHello <script>secret()</script>\n", "hash");
+ sqlite.query("INSERT INTO memo_shares (id, memo_id, workspace_id, token) VALUES (?, ?, ?, ?)")
+ .run("share_source", "memo_source", "ws_member", token);
+ return sqlite;
+};
+
+const dbOf = (sqlite) => ({ prepare: (sql) => new SqliteD1PreparedStatement(sqlite, sql) });
+
+const render = (sqlite, path, accept) => renderPublicMemoSharePage(
+ new Request(`https://note.example${path}`, accept ? { headers: { accept } } : undefined),
+ dbOf(sqlite),
+ async () => new Response(shell, { headers: { "content-type": "text/html", etag: "shell" } }),
+);
+
+describe("public memo share pages", () => {
+ test("recognizes only a single-note share path", () => {
+ expect(parsePublicMemoSharePagePath(`/share/${token}`)).toEqual({ token, markdown: false });
+ expect(parsePublicMemoSharePagePath(`/share/${token}.md`)).toEqual({ token, markdown: true });
+ expect(parsePublicMemoSharePagePath(`/share/${token}/`)).toEqual({ token, markdown: false });
+ expect(isPublicMemoSharePagePath(`/share/notebook/${token}`)).toBe(false);
+ expect(isPublicMemoSharePagePath("/share/not-a-token")).toBe(false);
+ expect(parsePublicMemoSharePagePath("/share/%2e%2e/secret")).toBeNull();
+ });
+
+ test("puts the note in the first HTML response and keeps the app shell", async () => {
+ const response = await render(createDatabase(), `/share/${token}`);
+ expect(response.status).toBe(200);
+ expect(response.headers.get("content-type")).toContain("text/html");
+ expect(response.headers.get("x-robots-tag")).toBe(PUBLIC_PAGE_ROBOTS);
+ expect(response.headers.get("cache-control")).toBe("private, no-store");
+ expect(response.headers.get("link")).toBe(`<https://note.example/share/${token}.md>; rel="alternate"; type="text/markdown"`);
+ expect(response.headers.get("etag")).toBeNull();
+ const html = await response.text();
+ expect(html).toContain(`<title>A $&amp; $&#39; $$ &lt;script&gt; · EdgeEver</title>`);
+ expect(html).toContain(`<meta name="robots" content="${PUBLIC_PAGE_ROBOTS}">`);
+ expect(html).toContain(`rel="canonical" href="https://note.example/share/${token}"`);
+ expect(html).toContain(`rel="alternate" type="text/markdown" href="https://note.example/share/${token}.md"`);
+ expect(html).toContain("Hello &lt;script&gt;secret()&lt;/script&gt;");
+ expect(html).not.toContain("<script>secret()");
+ expect(html).toContain('<div id="root"><article id="edgeever-shared-note"');
+ expect(html).toContain('<script type="module" src="/src/main.tsx"></script>');
+ expect(html).not.toContain("old description");
+ });
+
+ test("returns markdown for the direct link and for an explicit markdown accept", async () => {
+ const sqlite = createDatabase();
+ const direct = await render(sqlite, `/share/${token}.md`, "text/html");
+ expect(direct.status).toBe(200);
+ expect(direct.headers.get("content-type")).toContain("text/markdown");
+ expect(direct.headers.get("x-content-type-options")).toBe("nosniff");
+ expect(await direct.text()).toBe("# A $& $' $$ <script>\n\nHello <script>secret()</script>\n");
+
+ const negotiated = await render(sqlite, `/share/${token}`, "text/markdown, */*");
+ expect(negotiated.headers.get("content-type")).toContain("text/markdown");
+ expect(await negotiated.text()).toContain("Hello <script>secret()</script>");
+
+ const browser = await render(sqlite, `/share/${token}`, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
+ expect(browser.headers.get("content-type")).toContain("text/html");
+ expect(await browser.text()).toContain("edgeever-shared-note");
+ });
+
+ test("omits the body when the share is missing, deleted, or password protected", async () => {
+ const sqlite = createDatabase();
+ const missing = await render(sqlite, `/share/${"m".repeat(43)}`);
+ expect(missing.status).toBe(200);
+ const missingHtml = await missing.text();
+ expect(missingHtml).not.toContain("edgeever-shared-note");
+ expect(missingHtml).not.toContain("secret()");
+ expect(missingHtml).toContain('<script type="module" src="/src/main.tsx"></script>');
+
+ const missingMarkdown = await render(sqlite, `/share/${"m".repeat(43)}.md`);
+ expect(missingMarkdown.status).toBe(404);
+ expect(await missingMarkdown.text()).not.toContain("secret()");
+
+ sqlite.query("UPDATE memos SET is_deleted = 1 WHERE id = 'memo_source'").run();
+ expect(await (await render(sqlite, `/share/${token}`)).text()).not.toContain("secret()");
+ sqlite.query("UPDATE memos SET is_deleted = 0 WHERE id = 'memo_source'").run();
+
+ sqlite.query("UPDATE memo_shares SET password_hash = ? WHERE token = ?").run("hash", token);
+ const locked = await render(sqlite, `/share/${token}`);
+ const lockedHtml = await locked.text();
+ expect(lockedHtml).not.toContain("secret()");
+ expect(lockedHtml).not.toContain("Hello");
+ expect(lockedHtml).not.toContain("$&");
+ expect(lockedHtml).not.toContain("rel=\"alternate\"");
+ expect(lockedHtml).toContain("This shared note requires a password.");
+ expect(locked.headers.get("link")).toBeNull();
+
+ const lockedMarkdown = await render(sqlite, `/share/${token}.md`);
+ expect(lockedMarkdown.status).toBe(403);
+ expect(await lockedMarkdown.text()).toBe("This shared note requires a password.\n");
+ });
+
+ test("HEAD keeps the headers and omits the body", async () => {
+ const response = await renderPublicMemoSharePage(
+ new Request(`https://note.example/share/${token}.md`, { method: "HEAD" }),
+ dbOf(createDatabase()),
+ async () => new Response(shell),
+ );
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe("");
+ });
+
+ test("production entrypoints serve the share page from the worker", () => {
+ const worker = readFileSync("apps/api/src/index.ts", "utf8");
+ const selfHosted = readFileSync("scripts/self-hosted-server.mjs", "utf8");
+ const wrangler = readFileSync("wrangler.toml", "utf8");
+ const webConfig = readFileSync("apps/web/vite.config.ts", "utf8");
+ expect(worker).toContain("renderPublicMemoSharePage");
+ expect(worker).toContain('pathname.startsWith("/share/")');
+ expect(selfHosted).toContain("renderPublicMemoSharePage");
+ expect(wrangler).toContain('"/share/*"');
+ expect(webConfig).toContain("!/^\\/(?:share|s)\\//.test(url.pathname)");
+ });
+});
diff --git a/apps/api/src/share-page.ts b/apps/api/src/share-page.ts
new file mode 100644
index 00000000..c01f70ee
--- /dev/null
+++ b/apps/api/src/share-page.ts
@@ -0,0 +1,174 @@
+import { PUBLIC_PAGE_HEADERS, PUBLIC_PAGE_ROBOTS } from "@edgeever/shared/public-page-headers";
+import type { DatabaseAdapter } from "./storage-contract";
+
+const SHARE_PAGE_PATH = /^\/share\/([A-Za-z0-9_-]{43})(\.md)?\/?$/;
+
+type SharePageRow = {
+ title: string | null;
+ content_markdown: string | null;
+ password_hash: string | null;
+};
+
+export type PublicMemoSharePageTarget = {
+ token: string;
+ markdown: boolean;
+};
+
+const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (char) => ({
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ "\"": "&quot;",
+ "'": "&#39;",
+})[char]!);
+
+/** Single-note public links. Notebook sites stay on their own renderer. */
+export const parsePublicMemoSharePagePath = (pathname: string): PublicMemoSharePageTarget | null => {
+ let path = pathname;
+ try {
+ path = decodeURIComponent(pathname);
+ } catch {
+ return null;
+ }
+ const match = SHARE_PAGE_PATH.exec(path);
+ if (!match?.[1]) return null;
+ return { token: match[1], markdown: match[2] === ".md" };
+};
+
+export const isPublicMemoSharePagePath = (pathname: string) => parsePublicMemoSharePagePath(pathname) !== null;
+
+const prefersMarkdown = (accept: string | null, markdownPath: boolean) => {
+ if (markdownPath) return true;
+ if (!accept || !/text\/markdown/i.test(accept)) return false;
+ return !/text\/html/i.test(accept);
+};
+
+const describeNote = (markdown: string) => {
+ const normalized = markdown.replace(/\s+/g, " ").trim();
+ if (!normalized) return "Read a shared note on EdgeEver.";
+ return normalized.length > 160 ? `${normalized.slice(0, 160)}…` : normalized;
+};
+
+export const PUBLIC_SHARE_MARKDOWN_NOT_FOUND = "Shared note not found\n";
+export const PUBLIC_SHARE_MARKDOWN_PASSWORD = "This shared note requires a password.\n";
+
+/** Markdown body for a public note. A title already used as the first heading is kept once. */
+export const publicShareMarkdown = (title: string | null, body: string) => {
+ const heading = (title ?? "").replace(/[\r\n]+/g, " ").trim();
+ if (!heading) return body;
+ const firstLine = body.split(/\r?\n/, 1)[0] ?? "";
+ if (firstLine.replace(/^#\s+/, "").trim() === heading) return body;
+ return body ? `# ${heading}\n\n${body}` : `# ${heading}\n`;
+};
+
+const loadShare = (db: DatabaseAdapter, token: string) => db.prepare(
+ `SELECT m.title, mc.content_markdown, ms.password_hash
+ FROM memo_shares ms
+ INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
+ INNER JOIN memo_contents mc ON mc.memo_id = m.id
+ WHERE ms.token = ? AND m.is_deleted = 0
+ LIMIT 1`,
+).bind(token).first<SharePageRow>();
+
+const pageHeaders = (contentType: string) => {
+ const headers = new Headers();
+ for (const [key, value] of Object.entries(PUBLIC_PAGE_HEADERS)) headers.set(key, value);
+ headers.set("Content-Type", contentType);
+ headers.set("Vary", "Accept");
+ headers.set("X-Content-Type-Options", "nosniff");
+ return headers;
+};
+
+const injectArticle = (html: string, article: string) => {
+ if (!article) return html;
+ let injected = false;
+ const withRoot = html.replace(/<div\b([^>]*\bid=["']root["'][^>]*)>\s*<\/div>/i, (_match, attrs: string) => {
+ injected = true;
+ return `<div${attrs}>${article}</div>`;
+ });
+ if (injected) return withRoot;
+ if (/<\/body>/i.test(html)) return html.replace(/<\/body>/i, () => `${article}</body>`);
+ return `${html}${article}`;
+};
+
+/**
+ * The share URL is what people paste to an assistant. Browsers still receive
+ * the app shell and replace `#root`. A fetch that does not run JavaScript
+ * reads the note from this first response, or from the `.md` alternate.
+ * Password-protected notes stay out of both representations.
+ */
+export const renderPublicMemoSharePage = async (
+ request: Request,
+ db: DatabaseAdapter,
+ loadTemplate: () => Promise<Response>,
+): Promise<Response | null> => {
+ if (request.method !== "GET" && request.method !== "HEAD") return null;
+ const url = new URL(request.url);
+ const target = parsePublicMemoSharePagePath(url.pathname);
+ if (!target) return null;
+
+ const row = await loadShare(db, target.token);
+ const locked = Boolean(row?.password_hash);
+ const readable = Boolean(row) && !locked;
+ const body = row?.content_markdown ?? "";
+ const markdownUrl = `${url.origin}/share/${encodeURIComponent(target.token)}.md`;
+ const canonical = `${url.origin}/share/${encodeURIComponent(target.token)}`;
+
+ if (prefersMarkdown(request.headers.get("accept"), target.markdown)) {
+ const headers = pageHeaders("text/markdown; charset=utf-8");
+ if (!row) {
+ return new Response(request.method === "HEAD" ? null : PUBLIC_SHARE_MARKDOWN_NOT_FOUND, { status: 404, headers });
+ }
+ if (locked) {
+ return new Response(request.method === "HEAD" ? null : PUBLIC_SHARE_MARKDOWN_PASSWORD, { status: 403, headers });
+ }
+ headers.set("Content-Disposition", "inline");
+ return new Response(request.method === "HEAD" ? null : publicShareMarkdown(row.title, body), { status: 200, headers });
+ }
+
+ const title = readable ? (row?.title?.replace(/[\r\n]+/g, " ").trim() || "Shared note") : "Shared note";
+ const description = readable
+ ? describeNote(body)
+ : locked
+ ? "This shared note requires a password."
+ : "Read a shared note on EdgeEver.";
+ const article = readable
+ ? `<article id="edgeever-shared-note" style="max-width:44rem;margin:1.5rem auto;padding:0 1rem"><h1>${escapeHtml(title)}</h1><pre style="white-space:pre-wrap;font:inherit">${escapeHtml(body)}</pre></article>`
+ : "";
+ const metadata = `<title>${escapeHtml(`${title} · EdgeEver`)}</title>
+<meta name="description" content="${escapeHtml(description)}">
+<meta name="robots" content="${PUBLIC_PAGE_ROBOTS}">
+<link rel="canonical" href="${escapeHtml(canonical)}">
+${readable ? `<link rel="alternate" type="text/markdown" href="${escapeHtml(markdownUrl)}">` : ""}
+<meta property="og:type" content="article">
+<meta property="og:title" content="${escapeHtml(title)}">
+<meta property="og:description" content="${escapeHtml(description)}">
+<meta property="og:url" content="${escapeHtml(canonical)}">
+<meta name="twitter:card" content="summary">
+<meta name="twitter:title" content="${escapeHtml(title)}">
+<meta name="twitter:description" content="${escapeHtml(description)}">`;
+
+ const template = await loadTemplate();
+ if (!template.ok) return template;
+ const html = injectArticle(
+ (await template.text())
+ .replace(/<title\b[^>]*>[\s\S]*?<\/title>/gi, "")
+ .replace(/<meta\b[^>]*(?:name|property)=["'](?:description|robots|og:[^"']+|twitter:[^"']+)["'][^>]*>/gi, "")
+ .replace(/<link\b[^>]*rel=["'](?:canonical|alternate)["'][^>]*>/gi, "")
+ .replace(/<\/head>/i, () => `${metadata}</head>`),
+ article,
+ );
+ const headers = new Headers(template.headers);
+ headers.delete("Content-Length");
+ headers.delete("ETag");
+ headers.delete("Content-Encoding");
+ headers.delete("Last-Modified");
+ headers.delete("Age");
+ headers.delete("CF-Cache-Status");
+ for (const [key, value] of Object.entries(PUBLIC_PAGE_HEADERS)) headers.set(key, value);
+ headers.set("Content-Type", "text/html; charset=utf-8");
+ headers.set("Vary", "Accept");
+ headers.set("X-Content-Type-Options", "nosniff");
+ if (readable) headers.set("Link", `<${markdownUrl}>; rel="alternate"; type="text/markdown"`);
+ return new Response(request.method === "HEAD" ? null : html, { status: 200, headers });
+};
diff --git a/apps/web/share-markdown-dev.test.mjs b/apps/web/share-markdown-dev.test.mjs
new file mode 100644
index 00000000..ebe82928
--- /dev/null
+++ b/apps/web/share-markdown-dev.test.mjs
@@ -0,0 +1,53 @@
+import { describe, expect, test } from "bun:test";
+import { devShareMarkdownToken, loadDevShareMarkdown } from "./share-markdown-dev.ts";
+
+const token = "9tjFn0ZR0iawPf-8EaZtpRw3i-vawo7E0yTnqMMCBgk";
+
+const jsonResponse = (status, body, contentType = "application/json") => new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": contentType },
+});
+
+describe("local share markdown", () => {
+ test("recognizes the markdown suffix on a real share token", () => {
+ expect(devShareMarkdownToken(`/share/${token}.md`)).toBe(token);
+ expect(devShareMarkdownToken(`/share/${token}`)).toBeNull();
+ expect(devShareMarkdownToken(`/share/${token}.md/extra`)).toBeNull();
+ });
+
+ test("uses the worker markdown response when it is already markdown", async () => {
+ const fetchImpl = async (url) => {
+ expect(url).toBe(`http://api.test/share/${token}.md`);
+ return new Response("# Title\n\nBody\n", { status: 200, headers: { "content-type": "text/markdown; charset=utf-8" } });
+ };
+ const result = await loadDevShareMarkdown(token, fetchImpl, "http://api.test");
+ expect(result).toEqual({ status: 200, body: "# Title\n\nBody\n" });
+ });
+
+ test("reads the public share API when the worker still returns the app shell", async () => {
+ const fetchImpl = async (url) => {
+ if (String(url).endsWith(".md")) return new Response("<html></html>", { status: 200, headers: { "content-type": "text/html" } });
+ expect(url).toBe(`http://api.test/api/public/shares/${token}`);
+ return jsonResponse(200, { share: { title: "布局按钮", contentMarkdown: "按钮在右上角。\n" } });
+ };
+ const result = await loadDevShareMarkdown(token, fetchImpl, "http://api.test");
+ expect(result).toEqual({ status: 200, body: "# 布局按钮\n\n按钮在右上角。\n" });
+ });
+
+ test("keeps a missing or locked note out of the body", async () => {
+ const missing = await loadDevShareMarkdown(token, async (url) => (
+ String(url).endsWith(".md")
+ ? jsonResponse(404, { error: { code: "not_found" } }, "text/html")
+ : jsonResponse(404, { error: { code: "not_found" } })
+ ), "http://api.test");
+ expect(missing.status).toBe(404);
+ expect(missing.body).not.toContain("secret");
+
+ const locked = await loadDevShareMarkdown(token, async (url) => (
+ String(url).endsWith(".md")
+ ? new Response("no", { status: 200, headers: { "content-type": "text/html" } })
+ : jsonResponse(403, { error: { code: "share_password_required" } })
+ ), "http://api.test");
+ expect(locked).toEqual({ status: 403, body: "This shared note requires a password.\n" });
+ });
+});
diff --git a/apps/web/share-markdown-dev.ts b/apps/web/share-markdown-dev.ts
new file mode 100644
index 00000000..446fc44d
--- /dev/null
+++ b/apps/web/share-markdown-dev.ts
@@ -0,0 +1,83 @@
+import {
+ PUBLIC_SHARE_MARKDOWN_NOT_FOUND,
+ PUBLIC_SHARE_MARKDOWN_PASSWORD,
+ publicShareMarkdown,
+} from "../api/src/share-page.ts";
+import { PUBLIC_PAGE_HEADERS } from "@edgeever/shared/public-page-headers";
+import type { Plugin } from "vite";
+
+const SHARE_MARKDOWN_PATH = /^\/share\/([A-Za-z0-9_-]{43})\.md\/?$/;
+
+export const devShareMarkdownToken = (pathname: string) => SHARE_MARKDOWN_PATH.exec(pathname)?.[1] ?? null;
+const LOCAL_API_ORIGIN = "http://127.0.0.1:8787";
+
+type ShareMarkdownResult = { status: number; body: string };
+
+const isMarkdownResponse = (response: Response) =>
+ (response.headers.get("content-type") ?? "").toLowerCase().includes("text/markdown");
+
+/**
+ * Local Vite serves the app shell for every `/share/` path, so `/share/<token>.md`
+ * used to reach the page with `.md` glued onto the token. Ask the API for the
+ * note and answer with the Markdown body instead.
+ */
+export const loadDevShareMarkdown = async (
+ token: string,
+ fetchImpl: typeof fetch,
+ origin = LOCAL_API_ORIGIN,
+ cookie?: string,
+): Promise<ShareMarkdownResult> => {
+ const headers = new Headers();
+ if (cookie) headers.set("cookie", cookie);
+ try {
+ const direct = await fetchImpl(`${origin}/share/${token}.md`, {
+ headers,
+ signal: AbortSignal.timeout(8000),
+ });
+ if (isMarkdownResponse(direct)) return { status: direct.status, body: await direct.text() };
+ } catch {
+ // The local worker may still be serving the app shell for this path.
+ }
+
+ const api = await fetchImpl(`${origin}/api/public/shares/${encodeURIComponent(token)}`, {
+ headers,
+ signal: AbortSignal.timeout(8000),
+ });
+ if (api.status === 403) return { status: 403, body: PUBLIC_SHARE_MARKDOWN_PASSWORD };
+ if (!api.ok) return { status: api.status === 404 ? 404 : api.status, body: PUBLIC_SHARE_MARKDOWN_NOT_FOUND };
+ const payload = await api.json() as { share?: { title?: string | null; contentMarkdown?: string } };
+ if (!payload.share) return { status: 404, body: PUBLIC_SHARE_MARKDOWN_NOT_FOUND };
+ return {
+ status: 200,
+ body: publicShareMarkdown(payload.share.title ?? null, payload.share.contentMarkdown ?? ""),
+ };
+};
+
+export const publicShareMarkdownDev = (origin = LOCAL_API_ORIGIN): Plugin => ({
+ name: "edgeever-public-share-markdown",
+ apply: "serve",
+ configureServer(server) {
+ server.middlewares.use(async (request, response, next) => {
+ if (request.method !== "GET" && request.method !== "HEAD") return next();
+ const pathname = request.url?.split("?")[0] ?? "";
+ const token = devShareMarkdownToken(pathname);
+ if (!token) return next();
+ try {
+ const result = await loadDevShareMarkdown(
+ token,
+ fetch,
+ origin,
+ request.headers.cookie,
+ );
+ response.statusCode = result.status;
+ for (const [key, value] of Object.entries(PUBLIC_PAGE_HEADERS)) response.setHeader(key, value);
+ response.setHeader("Content-Type", "text/markdown; charset=utf-8");
+ response.setHeader("X-Content-Type-Options", "nosniff");
+ response.setHeader("Content-Disposition", "inline");
+ response.end(request.method === "HEAD" ? undefined : result.body);
+ } catch (error) {
+ next(error);
+ }
+ });
+ },
+});
diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsx
index 354223ea..0f2c82aa 100644
--- a/apps/web/src/components/PublicSharePage.tsx
+++ b/apps/web/src/components/PublicSharePage.tsx
@@ -248,7 +248,10 @@ export const PublicSharePasswordForm = ({
export const PublicSharePage = () => {
const { t } = useTranslation();
- const { token = "" } = useParams();
+ const { token: routeToken = "" } = useParams();
+ // The dev server answers `/share/<token>.md` itself. If the app shell still
+ // loads that address, the suffix is not part of the share token.
+ const token = routeToken.endsWith(".md") ? routeToken.slice(0, -3) : routeToken;
const shareQuery = useQuery({
queryKey: ["public-share", token],
queryFn: () => api.getPublicMemoShare(token),
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 9bb9188e..0f3d8750 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -8,6 +8,7 @@ import { fileURLToPath, URL } from "node:url";
import { defineConfig, type Plugin } from "vite";
import { VitePWA } from "vite-plugin-pwa";
import { localDevelopmentAuth } from "./local-dev-auth";
+import { publicShareMarkdownDev } from "./share-markdown-dev";
import { resolveAppVersion, resolveReleaseTimestamp } from "./build-metadata";
const readPackageVersion = () => {
@@ -148,6 +149,7 @@ export default defineConfig({
automaticPosterThumbnails(),
tailwindcss(),
localDevelopmentAuth(),
+ publicShareMarkdownDev(),
developmentServiceWorkerReset,
react(),
VitePWA({
@@ -197,7 +199,8 @@ export default defineConfig({
{
urlPattern: ({ request, url }) =>
request.mode === "navigate" &&
- !/^\/(?:share\/notebook|s)\//.test(url.pathname) &&
+ // Share HTML includes the note. Leave it out of the shared navigation cache.
+ !/^\/(?:share|s)\//.test(url.pathname) &&
!["/mobile-edit.html", "/note-print.html", "/tiptap-ime-test.html"].includes(url.pathname),
handler: "NetworkFirst",
options: {
diff --git a/scripts/self-hosted-server.mjs b/scripts/self-hosted-server.mjs
index e8adc1f7..fd66e02a 100644
--- a/scripts/self-hosted-server.mjs
+++ b/scripts/self-hosted-server.mjs
@@ -6,6 +6,7 @@ import { hasBootstrapCredential } from "../apps/api/src/auth-bootstrap.ts";
import { isUnauthenticatedAccessEnabled } from "../apps/api/src/auth-state.ts";
import { fetchEdgeEverApp } from "../apps/api/src/index.ts";
import { isNotebookSitePagePath, renderNotebookSitePage } from "../apps/api/src/notebook-site-page.ts";
+import { isPublicMemoSharePagePath, renderPublicMemoSharePage } from "../apps/api/src/share-page.ts";
import { isPublicPagePath, PUBLIC_PAGE_HEADERS } from "../packages/shared/src/public-page-headers.ts";
import { nodePublicFetch } from "../apps/api/src/node-public-network.ts";
import { createSelfHostedStorageAdapter } from "../apps/api/src/self-hosted-storage-adapter.ts";
@@ -163,9 +164,13 @@ const server = Bun.serve({
idleTimeout: config.idleTimeout,
async fetch(request) {
const pathname = new URL(request.url).pathname;
+ const loadAppShell = () => serveStatic(new Request(new URL("/index.html", request.url)));
if (isNotebookSitePagePath(pathname)) {
- return renderNotebookSitePage(request, storage.db,
- () => serveStatic(new Request(new URL("/index.html", request.url))));
+ return renderNotebookSitePage(request, storage.db, loadAppShell);
+ }
+ if (isPublicMemoSharePagePath(pathname)) {
+ const page = await renderPublicMemoSharePage(request, storage.db, loadAppShell);
+ if (page) return page;
}
if (pathname.startsWith("/api/") || pathname === "/mcp" || pathname.startsWith("/mcp/")) {
return fetchEdgeEverApp(request, env, executionContext);
diff --git a/scripts/wrangler-runner.mjs b/scripts/wrangler-runner.mjs
index 53b9694d..4a7c92c6 100644
--- a/scripts/wrangler-runner.mjs
+++ b/scripts/wrangler-runner.mjs
@@ -13,7 +13,7 @@ const REPOSITORY_WRANGLER_VALUES = {
bucket_name: "edgeever-resources",
preview_bucket_name: "edgeever-resources-preview",
};
-const REPOSITORY_WRANGLER_SHA256 = "55b5f99e86f4d752c44560a6e392d8b52d782c8cdb0311faec9544e6cb883af7";
+const REPOSITORY_WRANGLER_SHA256 = "1da7f15efc45e2efbac1f5c04609e1ff69f3b4451b81871719ab1fde2276ac17";
const configValue = (config, key) => {
const match = config.match(new RegExp(`^${key}\\s*=\\s*(?:"([^"]*)"|(true|false))`, "m"));
diff --git a/wrangler.toml b/wrangler.toml
index 963876a1..52a3e18f 100644
--- a/wrangler.toml
+++ b/wrangler.toml
@@ -19,7 +19,7 @@ watch_dir = ["apps/api/src", "packages/shared/src"]
directory = "apps/web/dist"
binding = "ASSETS"
not_found_handling = "single-page-application"
-run_worker_first = ["/api/*", "/mcp", "/__scheduled", "/share/notebook/*", "/s/*"]
+run_worker_first = ["/api/*", "/mcp", "/__scheduled", "/s/*", "/share/*"]
[[d1_databases]]
binding = "DB"