Skip to content

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

feat: add revocable note sharing

tianma-if4d2ae5e27c9d
diff --git a/README.md b/README.md
index 6a0b3b1f..e5bfa172 100644
--- a/README.md
+++ b/README.md
@@ -43,6 +43,7 @@ The public demo resets every Monday at 1:00 AM (China Standard Time) and restore
- **Seamless Dual-View Editor**: Switch effortlessly between intuitive rich text editing and Markdown source code on desktop.
- **Native Mermaid Diagram Rendering**: Render clear flowcharts, sequence diagrams, and mind maps directly in notes, preserving clean, editable source code across Markdown and rich text views.
- **Revision History**: Inspect and restore previous iterations of your notes with built-in version tracking.
+- **Revocable Read-Only Sharing**: Create an unguessable public link for any note so others can view its latest saved content and attachments without signing in, then revoke access at any time.
- **Smart Local Image Compression**: Client-side WebP compression reduces file sizes by 50%-90% before uploading, saving storage and speeding up page loads without extra server costs.
- **Universal File Attachments**: Attach and preview PDFs, Office documents, zip files, audio, and video directly within notes.
- **Batch Operations & Flexible Sorting**: Easily merge or relocate multiple notes, with drag-and-drop notebook reordering.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 76a8114a..1b53c545 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -43,6 +43,7 @@ EdgeEver 是一款现代化的开源笔记工作区。它为你找回经典印
- **优雅的双视图编辑**:桌面端支持在富文本与 Markdown 源码视图之间自由切换。
- **Mermaid 架构图与流程图渲染**:原生支持 Mermaid 代码块渲染,视图切换时完整保留可编辑源码,让绘制逻辑图表更直观。
- **笔记历史版本回溯**:自动记录修改历史,随时查阅与还原过往版本。
+- **可撤销的只读分享**:为任意笔记创建难以猜测的公开链接,他人无需登录即可查看最新保存的正文与附件,并可随时取消分享。
- **智能前端图片压缩**:图片上传前在浏览器端静默完成压缩,常见截图与大图精简 50%-90% 体积,加载更迅速、存储更省心。
- **通用文件附件支持**:支持轻松上传并插入 PDF、Office 文档、压缩包及音视频等各种附件。
- **高效多选与批量操作**:支持笔记批量合并、批量移动,以及笔记本拖拽排序与层级调整。
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 07aee9a3..244e2a20 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -154,6 +154,7 @@ import {
} from "./request-auth";
import { registerTagRoutes } from "./tag-routes";
import { registerNotebookRoutes } from "./notebook-routes";
+import { registerMemoShareRoutes, registerPublicShareRoutes } from "./share-routes";
// Compatibility aliases keep the existing SQL-heavy implementation small
// while routing its dependency through the platform-neutral contract above.
@@ -465,6 +466,8 @@ app.get("/api/health", async (c) => {
app.get("/api/openapi.json", (c) => c.json(openApiSpec));
+registerPublicShareRoutes(app);
+
app.get("/api/v1/auth/session", async (c) => {
const authMode = await getInstanceAuthMode(c.env);
@@ -1112,6 +1115,7 @@ app.get("/api/v1/sync/changes", async (c) => {
});
registerTagRoutes(app);
+registerMemoShareRoutes(app);
app.get("/api/v1/templates", async (c) => {
const rows = await c.env.storage.db.prepare(
@@ -2575,6 +2579,7 @@ app.delete("/api/v1/memos/:id", async (c) => {
}
await c.env.storage.db.batch([
+ c.env.storage.db.prepare(`DELETE FROM memo_shares WHERE memo_id = ? AND workspace_id = ?`).bind(id, workspaceId),
c.env.storage.db.prepare(
`UPDATE memos
SET is_deleted = 1, deleted_at = ?, updated_at = ?
@@ -4309,6 +4314,7 @@ const deleteMemosRecord = async (
}
} else {
statements.push(
+ db.prepare(`DELETE FROM memo_shares WHERE workspace_id = ? AND memo_id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds),
db
.prepare(
`UPDATE memos
@@ -4995,6 +5001,7 @@ const mergeMemosRecord = async (
WHERE workspace_id = ? AND id IN (${placeholders})`
)
.bind(now, newMemoId, now, now, workspaceId, ...uniqueMemoIds),
+ db.prepare(`DELETE FROM memo_shares WHERE workspace_id = ? AND memo_id IN (${placeholders})`).bind(workspaceId, ...uniqueMemoIds),
db.prepare(`DELETE FROM memos_fts WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),
db
.prepare(
diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.ts
new file mode 100644
index 00000000..2d2bf628
--- /dev/null
+++ b/apps/api/src/share-routes.ts
@@ -0,0 +1,175 @@
+import type { MemoShare, PublicMemoShare, TiptapDoc } from "@edgeever/shared";
+import type { Hono } from "hono";
+import type { AppEnv } from "./api-context";
+import { audit } from "./audit";
+import { randomToken } from "./auth-crypto";
+import { createId, isoNow, parseJsonArray } from "./entity-utils";
+import { notFound } from "./http-errors";
+import { getAuditActor, getWorkspaceId, requireUser } from "./request-auth";
+
+const SHARE_TOKEN_BYTES = 32;
+const SHARE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
+
+type MemoShareRow = { memo_id: string; token: string; created_at: string; updated_at: string };
+type PublicMemoShareRow = {
+ title: string | null;
+ content_json: string;
+ content_markdown: string;
+ tags_json: string;
+ updated_at: string;
+};
+type SharedResourceRow = {
+ object_key: string;
+ kind: "image" | "attachment";
+ mime_type: string | null;
+ filename: string | null;
+};
+
+const mapMemoShare = (row: MemoShareRow): MemoShare => ({
+ memoId: row.memo_id,
+ token: row.token,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+});
+
+const normalizeFilename = (filename: string) =>
+ filename.trim().replace(/[\\/]/g, "-").replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 160);
+
+const contentDisposition = (kind: SharedResourceRow["kind"], filename: string | null) => {
+ if (!filename) return kind === "image" ? "inline" : "attachment";
+ const fallback = normalizeFilename(filename).replace(/"/g, "'");
+ const disposition = kind === "image" ? "inline" : "attachment";
+ return `${disposition}; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
+};
+
+const normalizeShareToken = (value: string) => {
+ const token = value.trim();
+ return SHARE_TOKEN_PATTERN.test(token) ? token : null;
+};
+
+export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
+ app.get("/api/public/shares/:token", async (c) => {
+ const token = normalizeShareToken(c.req.param("token"));
+ if (!token) return notFound(c, "Shared note not found");
+
+ const row = await c.env.storage.db.prepare(
+ `SELECT m.title, mc.content_json, mc.content_markdown, m.tags_json, m.updated_at
+ 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<PublicMemoShareRow>();
+ if (!row) return notFound(c, "Shared note not found");
+
+ const share: PublicMemoShare = {
+ title: row.title,
+ contentJson: JSON.parse(row.content_json) as TiptapDoc,
+ contentMarkdown: row.content_markdown,
+ tags: parseJsonArray(row.tags_json),
+ updatedAt: row.updated_at,
+ };
+ c.header("Cache-Control", "private, no-store");
+ c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
+ return c.json({ share });
+ });
+
+ app.get("/api/public/shares/:token/resources/:resourceId/blob", async (c) => {
+ const token = normalizeShareToken(c.req.param("token"));
+ if (!token) return notFound(c, "Shared resource not found");
+
+ const resource = await c.env.storage.db.prepare(
+ `SELECT r.object_key, r.kind, r.mime_type, r.filename
+ FROM memo_shares ms
+ INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
+ INNER JOIN resources r ON r.memo_id = m.id
+ WHERE ms.token = ? AND r.id = ? AND m.is_deleted = 0 AND r.is_deleted = 0
+ LIMIT 1`
+ ).bind(token, c.req.param("resourceId")).first<SharedResourceRow>();
+ if (!resource) return notFound(c, "Shared resource not found");
+
+ const object = await c.env.storage.resources.get(resource.object_key);
+ if (!object) return notFound(c, "Shared resource not found");
+
+ const headers = new Headers();
+ object.writeHttpMetadata(headers);
+ headers.set("Content-Type", resource.mime_type ?? headers.get("Content-Type") ?? "application/octet-stream");
+ headers.set("Content-Length", String(object.size));
+ headers.set("Content-Disposition", contentDisposition(resource.kind, 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 });
+ });
+};
+
+export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {
+ app.get("/api/v1/memos/:id/share", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+
+ const row = await c.env.storage.db.prepare(
+ `SELECT ms.memo_id, ms.token, ms.created_at, ms.updated_at
+ FROM memo_shares ms
+ INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
+ WHERE ms.memo_id = ? AND ms.workspace_id = ? AND m.is_deleted = 0
+ LIMIT 1`
+ ).bind(c.req.param("id"), getWorkspaceId(c)).first<MemoShareRow>();
+ return c.json({ share: row ? mapMemoShare(row) : null });
+ });
+
+ app.post("/api/v1/memos/:id/share", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+
+ const memoId = c.req.param("id");
+ const workspaceId = getWorkspaceId(c);
+ const memo = await c.env.storage.db.prepare(
+ `SELECT id FROM memos WHERE id = ? AND workspace_id = ? AND is_deleted = 0`
+ ).bind(memoId, workspaceId).first<{ id: string }>();
+ if (!memo) return notFound(c, "Memo not found");
+
+ const existing = await c.env.storage.db.prepare(
+ `SELECT memo_id, token, created_at, updated_at FROM memo_shares WHERE memo_id = ? AND workspace_id = ?`
+ ).bind(memoId, workspaceId).first<MemoShareRow>();
+ if (existing) return c.json({ share: mapMemoShare(existing) });
+
+ const now = isoNow();
+ const token = randomToken(SHARE_TOKEN_BYTES);
+ const actor = getAuditActor(c);
+ await c.env.storage.db.prepare(
+ `INSERT OR IGNORE INTO memo_shares (id, memo_id, workspace_id, token, created_by, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
+ ).bind(createId("share"), memoId, workspaceId, token, actor.actorId, now, now).run();
+ const created = await c.env.storage.db.prepare(
+ `SELECT memo_id, token, created_at, updated_at FROM memo_shares WHERE memo_id = ? AND workspace_id = ?`
+ ).bind(memoId, workspaceId).first<MemoShareRow>();
+ if (!created) {
+ throw new Error("Could not allocate a unique memo share token");
+ }
+ const isNewShare = created.token === token;
+ if (isNewShare) {
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "memo.share_create", "memo", memoId, {});
+ }
+ return c.json({ share: mapMemoShare(created) }, isNewShare ? 201 : 200);
+ });
+
+ app.delete("/api/v1/memos/:id/share", async (c) => {
+ const denied = requireUser(c);
+ if (denied) return denied;
+
+ const memoId = c.req.param("id");
+ const workspaceId = getWorkspaceId(c);
+ const existing = await c.env.storage.db.prepare(
+ `SELECT memo_id FROM memo_shares WHERE memo_id = ? AND workspace_id = ?`
+ ).bind(memoId, workspaceId).first<{ memo_id: string }>();
+ if (!existing) return notFound(c, "Active share not found");
+
+ await c.env.storage.db.prepare(
+ `DELETE FROM memo_shares WHERE memo_id = ? AND workspace_id = ?`
+ ).bind(memoId, workspaceId).run();
+ const actor = getAuditActor(c);
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "memo.share_revoke", "memo", memoId, {});
+ return c.json({ ok: true });
+ });
+};
diff --git a/apps/mobile/src/components/icons.tsx b/apps/mobile/src/components/icons.tsx
index 4ed63dd7..7b39aab8 100644
--- a/apps/mobile/src/components/icons.tsx
+++ b/apps/mobile/src/components/icons.tsx
@@ -59,6 +59,7 @@ export const Quote = createIcon("message-square");
export const RefreshCw = createIcon("refresh-cw");
export const RotateCcw = createIcon("rotate-ccw");
export const Search = createIcon("search");
+export const Share2 = createIcon("share-2");
export const ShieldCheck = createIcon("shield");
export const SlidersHorizontal = createIcon("sliders");
export const Sparkles = createIcon("star");
diff --git a/apps/mobile/src/lib/mobile-locale.tsx b/apps/mobile/src/lib/mobile-locale.tsx
index 77ee2955..bb6bf321 100644
--- a/apps/mobile/src/lib/mobile-locale.tsx
+++ b/apps/mobile/src/lib/mobile-locale.tsx
@@ -32,6 +32,9 @@ const mobileOnlyTranslations = new Map<string, string>([
["搜索本机同步缓存,结果会即时显示", "Search the local synced cache with instant results"],
["笔记操作", "Note actions"],
["版本历史", "Version history"],
+ ["分享笔记", "Share note"],
+ ["分享失败", "Could not share"],
+ ["无法创建分享链接,请检查网络后重试。", "Could not create a share link. Check your connection and try again."],
["同步冲突", "Sync conflict"],
["同步失败", "Sync failed"],
["待同步", "Pending sync"],
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
index c79cdc4f..fcda0441 100644
--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -5,7 +5,7 @@ import { Modal } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import Markdown, { type ASTNode, type RenderRules } from "react-native-markdown-display";
import { SvgXml } from "react-native-svg";
-import { ChevronDown, ChevronLeft, ChevronRight, History, MoreHorizontal, Pencil, RotateCcw, Search, Tag, Trash2, X } from "../components/icons";
+import { ChevronDown, ChevronLeft, ChevronRight, History, MoreHorizontal, Pencil, RotateCcw, Search, Share2, Tag, Trash2, X } from "../components/icons";
import { Pressable, Text, TextInput } from "../components/LocalizedText";
import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";
import { getMobileMarkdownFenceLanguage, trimMobileMarkdownFenceContent } from "../lib/mobile-mermaid";
@@ -194,6 +194,7 @@ export const MemoDetailModal = ({
isLoading,
isRestoring,
isSaving,
+ isSharing,
memo,
notebookName,
onClose,
@@ -202,6 +203,7 @@ export const MemoDetailModal = ({
onOpenRevisions,
onResolveSyncConflict,
onRestore,
+ onShare,
syncStatus,
visible,
}: {
@@ -209,6 +211,7 @@ export const MemoDetailModal = ({
isLoading: boolean;
isRestoring: boolean;
isSaving: boolean;
+ isSharing: boolean;
memo: MemoDetail | null;
notebookName: string;
onClose: () => void;
@@ -217,6 +220,7 @@ export const MemoDetailModal = ({
onOpenRevisions: (memo: MemoDetail) => void;
onResolveSyncConflict: (memo: MemoDetail) => void;
onRestore: (memo: MemoDetail) => void;
+ onShare: (memo: MemoDetail) => void;
syncStatus: MobileSyncQueueItem["status"] | null;
visible: boolean;
}) => {
@@ -403,6 +407,17 @@ export const MemoDetailModal = ({
{syncStatusLabel}
</Text>
</Pressable>
+ {memo && !memo.isDeleted ? (
+ <Pressable
+ accessibilityLabel="分享笔记"
+ accessibilityRole="button"
+ disabled={isSharing}
+ onPress={() => onShare(memo)}
+ style={[styles.detailHeaderIconButton, isSharing && styles.buttonDisabled]}
+ >
+ {isSharing ? <ActivityIndicator color="#475569" size="small" /> : <Share2 color="#475569" size={20} />}
+ </Pressable>
+ ) : null}
{memo && !memo.isDeleted ? (
<Pressable
accessibilityLabel="版本历史"
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index f581a50d..23a5b47f 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -51,6 +51,7 @@ import {
Modal,
Platform,
RefreshControl,
+ Share as NativeShare,
ScrollView,
StyleSheet,
Text as RNText,
@@ -832,6 +833,25 @@ export const WorkspaceScreen = ({
},
});
+ const shareMemoMutation = useMutation({
+ mutationFn: async (memo: MemoDetail) => {
+ if (!client || !session) {
+ throw new Error("Client is not ready");
+ }
+
+ const response = await client.createMemoShare(memo.id);
+ const shareUrl = `${session.baseUrl.replace(/\/+$/, "")}/share/${encodeURIComponent(response.share.token)}`;
+ await NativeShare.share({
+ message: `${memo.title?.trim() || DEFAULT_MEMO_TITLE}\n${shareUrl}`,
+ title: memo.title?.trim() || DEFAULT_MEMO_TITLE,
+ url: shareUrl,
+ });
+ },
+ onError: () => {
+ Alert.alert("分享失败", "无法创建分享链接,请检查网络后重试。");
+ },
+ });
+
const moveMemosMutation = useMutation({
mutationFn: async ({ memoIds, notebookId }: { memoIds: string[]; notebookId: string }) => {
if (!client) {
@@ -1036,6 +1056,7 @@ export const WorkspaceScreen = ({
isLoading={memoDetailQuery.isLoading}
isRestoring={restoreMemoMutation.isPending}
isSaving={updateMemoMutation.isPending || localUpdateMemoMutation.isPending}
+ isSharing={shareMemoMutation.isPending}
memo={selectedMemo}
notebookName={notebooks.find((notebook) => notebook.id === selectedMemo?.notebookId)?.name ?? "未分类"}
onClose={closeDetail}
@@ -1044,6 +1065,7 @@ export const WorkspaceScreen = ({
onOpenRevisions={setRevisionMemo}
onResolveSyncConflict={handleMemoSyncConflict}
onRestore={(memo) => restoreMemoMutation.mutate(memo)}
+ onShare={(memo) => shareMemoMutation.mutate(memo)}
syncStatus={selectedMemoSyncStatus}
visible={Boolean(selectedMemoId)}
/>
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index 0572093e..314453e7 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -25,6 +25,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 PublicSharePage = lazy(() => import("@/components/PublicSharePage").then((module) => ({ default: module.PublicSharePage })));
const AuthLoadingScreen = ({ title = "EdgeEver", detail }: { title?: string; detail?: string }) => (
<div className="flex h-[100dvh] items-center justify-center bg-slate-50 px-6 text-center text-slate-700">
@@ -248,6 +249,7 @@ export const App = () => {
return (
<PwaInstallProvider>
<Routes>
+ <Route path="/share/:token" element={<Suspense fallback={<AuthLoadingScreen />}><PublicSharePage /></Suspense>} />
<Route path={EVERNOTE_MIGRATION_PATH} element={<EvernoteMigrationRoute />} />
<Route path="/" element={<AuthenticatedWorkspace />} />
<Route path="/settings" element={<AuthenticatedWorkspace />} />
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 312f15e7..e3e7b59a 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -69,6 +69,7 @@ import { ThemeToggle } from "./ThemeToggle";
import { useTheme } from "./ThemeProvider";
import { sanitizeAndScopeCss } from "@/lib/css-sandbox";
import { RevisionHistoryDialog } from "./dialogs/RevisionHistoryDialog";
+import { ShareMemoDialog } from "./dialogs/ShareMemoDialog";
import { api } from "@/lib/api";
import { isDesktopResourceRuntime, stageDesktopResource, toDesktopResourceUrl } from "@/lib/desktop-resources";
import { cn, formatDateTime, parseTagsText } from "@/lib/utils";
@@ -625,6 +626,7 @@ const RichEditorPane = ({
const [editorContentVersion, setEditorContentVersion] = useState(0);
const [imageUploadState, setImageUploadState] = useState<"idle" | "compressing" | "uploading" | "error">("idle");
const [historyOpen, setHistoryOpen] = useState(false);
+ const [shareOpen, setShareOpen] = useState(false);
const [systemInfoOpen, setSystemInfoOpen] = useState(false);
const [updateAvailable, setUpdateAvailable] = useState(false);
const [mobileNotebookSheetOpen, setMobileNotebookSheetOpen] = useState(false);
@@ -2480,6 +2482,16 @@ const RichEditorPane = ({
<History className="h-4 w-4 text-slate-500" />
{t("editor.versionHistory")}
</DropdownMenuItem>
+ {!readOnly && (
+ <DropdownMenuItem
+ className="flex h-9 w-full items-center gap-2 px-3 text-left text-sm text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
+ disabled={isLocalMemoId(memo.id)}
+ onClick={() => setShareOpen(true)}
+ >
+ <Link2 className="h-4 w-4 text-slate-500" />
+ {t("sharing.action")}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-sm text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
onClick={handleExportMarkdown}
@@ -2944,6 +2956,8 @@ const RichEditorPane = ({
<SystemInfoDialog open={systemInfoOpen} onOpenChange={setSystemInfoOpen} />
+ <ShareMemoDialog memoId={memo.id} open={shareOpen} onOpenChange={setShareOpen} />
+
{mobileNotebookSheetOpen && (
<MobileNotebookSelectSheet
isUpdating={notebookUpdatePending || saveMutation.isPending}
diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsx
new file mode 100644
index 00000000..78f44be9
--- /dev/null
+++ b/apps/web/src/components/PublicSharePage.tsx
@@ -0,0 +1,159 @@
+import { Node, mergeAttributes } from "@tiptap/core";
+import Image from "@tiptap/extension-image";
+import { TableKit } from "@tiptap/extension-table";
+import { EditorContent, useEditor } from "@tiptap/react";
+import StarterKit from "@tiptap/starter-kit";
+import { useQuery } from "@tanstack/react-query";
+import { Clock3, FileText, LoaderCircle, ShieldCheck } from "lucide-react";
+import { useEffect, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { useParams } from "react-router";
+import { api } from "@/lib/api";
+import { EdgeEverCodeBlock, codeBlockLowlight } from "@/lib/code-block";
+import {
+ parseImageWidth,
+ resolveMemoContentDoc,
+ rewriteMemoResourcesForShare,
+ type PublicMemoShare,
+} from "@edgeever/shared";
+
+const SharedImage = Image.extend({
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ width: {
+ default: null,
+ parseHTML: (element) => parseImageWidth(element.getAttribute("data-width") ?? element.style.width),
+ renderHTML: (attributes) => {
+ const width = parseImageWidth(attributes.width);
+ return width ? { "data-width": String(width), style: `width: ${width}%` } : {};
+ },
+ },
+ };
+ },
+});
+
+const SharedThemeBlock = Node.create({
+ name: "edgeeverThemeBlock",
+ group: "block",
+ content: "block+",
+ defining: true,
+ isolating: true,
+ addAttributes() {
+ return {
+ kind: {
+ default: "intro",
+ parseHTML: (element: HTMLElement) => element.getAttribute("data-theme-block-kind") || "intro",
+ renderHTML: (attributes: { kind?: string }) => ({ "data-theme-block-kind": attributes.kind || "intro" }),
+ },
+ };
+ },
+ parseHTML() {
+ return [{ tag: "section[data-theme-block-kind]" }];
+ },
+ renderHTML({ HTMLAttributes }) {
+ return ["section", mergeAttributes(HTMLAttributes, { "data-edgeever-theme-block": "true" }), 0];
+ },
+});
+
+const SharedDocument = ({ share, token }: { share: PublicMemoShare; token: string }) => {
+ const content = useMemo(
+ () => rewriteMemoResourcesForShare(resolveMemoContentDoc(share.contentJson, share.contentMarkdown), token),
+ [share, token],
+ );
+ const editor = useEditor({
+ extensions: [
+ StarterKit.configure({ codeBlock: false, link: { openOnClick: true } }),
+ EdgeEverCodeBlock.configure({ lowlight: codeBlockLowlight, defaultLanguage: "plaintext" }),
+ SharedThemeBlock,
+ SharedImage.configure({ allowBase64: false, inline: false }),
+ TableKit.configure({ table: { renderWrapper: true } }),
+ ],
+ content,
+ editable: false,
+ editorProps: {
+ attributes: {
+ class: "prose prose-slate max-w-none focus:outline-none",
+ "aria-label": "Shared note content",
+ },
+ },
+ }, [content]);
+
+ return <EditorContent editor={editor} />;
+};
+
+export const PublicSharePage = () => {
+ const { t, i18n } = useTranslation();
+ const { token = "" } = useParams();
+ const shareQuery = useQuery({
+ queryKey: ["public-share", token],
+ queryFn: () => api.getPublicMemoShare(token),
+ enabled: Boolean(token),
+ retry: false,
+ });
+ const share = shareQuery.data?.share;
+
+ useEffect(() => {
+ const previousTitle = document.title;
+ const robots = document.createElement("meta");
+ robots.name = "robots";
+ robots.content = "noindex,nofollow,noarchive";
+ document.head.appendChild(robots);
+ if (share) document.title = `${share.title?.trim() || t("common.untitledMemo")} · EdgeEver`;
+ return () => {
+ document.title = previousTitle;
+ robots.remove();
+ };
+ }, [share, t]);
+
+ if (shareQuery.isLoading) {
+ return (
+ <main className="flex min-h-[100dvh] items-center justify-center bg-slate-50 text-slate-500">
+ <LoaderCircle className="h-6 w-6 animate-spin" aria-label={t("sharing.publicLoading")} />
+ </main>
+ );
+ }
+
+ if (!share) {
+ return (
+ <main className="flex min-h-[100dvh] items-center justify-center bg-slate-50 px-5">
+ <section className="max-w-md rounded-2xl border border-slate-200 bg-white p-8 text-center shadow-sm">
+ <FileText className="mx-auto h-9 w-9 text-slate-400" />
+ <h1 className="mt-4 text-xl font-semibold text-slate-900">{t("sharing.publicUnavailable")}</h1>
+ <p className="mt-2 text-sm leading-6 text-slate-500">{t("sharing.publicUnavailableHint")}</p>
+ </section>
+ </main>
+ );
+ }
+
+ return (
+ <main className="edgeever-public-share min-h-[100dvh] bg-slate-50 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-white 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-emerald-700">
+ <ShieldCheck className="h-4 w-4" /> EdgeEver · {t("sharing.readOnly")}
+ </span>
+ <span className="flex items-center gap-1.5">
+ <Clock3 className="h-4 w-4" />
+ {t("sharing.publicUpdated", {
+ time: new Intl.DateTimeFormat(i18n.resolvedLanguage || i18n.language, { dateStyle: "medium", timeStyle: "short" }).format(new Date(share.updatedAt)),
+ })}
+ </span>
+ </div>
+ <h1 className="text-3xl font-bold tracking-tight text-slate-950 sm:text-4xl">
+ {share.title?.trim() || t("common.untitledMemo")}
+ </h1>
+ {share.tags.length > 0 ? (
+ <div className="mt-4 flex flex-wrap gap-2">
+ {share.tags.map((tag) => <span key={tag} className="rounded-full bg-slate-100 px-2.5 py-1 text-xs text-slate-600">#{tag}</span>)}
+ </div>
+ ) : null}
+ </header>
+ <div className="edgeever-editor px-1 py-4 sm:px-4 sm:py-7" data-editor-theme="default">
+ <SharedDocument share={share} token={token} />
+ </div>
+ </article>
+ </main>
+ );
+};
diff --git a/apps/web/src/components/dialogs/ShareMemoDialog.tsx b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
new file mode 100644
index 00000000..1176467d
--- /dev/null
+++ b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
@@ -0,0 +1,111 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Check, Copy, ExternalLink, Link2, LoaderCircle, Trash2 } from "lucide-react";
+import { useEffect, 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";
+
+const getPublicShareUrl = (token: string) => {
+ const baseUrl = getConfiguredDesktopApiBaseUrl() || window.location.origin;
+ return `${baseUrl.replace(/\/$/, "")}/share/${encodeURIComponent(token)}`;
+};
+
+export const ShareMemoDialog = ({
+ memoId,
+ open,
+ onOpenChange,
+}: {
+ memoId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const [copyState, setCopyState] = useState<"idle" | "copied" | "error">("idle");
+ const queryKey = ["memo-share", memoId] as const;
+ const shareQuery = useQuery({
+ queryKey,
+ queryFn: () => api.getMemoShare(memoId),
+ enabled: open,
+ retry: false,
+ });
+ const createMutation = useMutation({
+ mutationFn: () => api.createMemoShare(memoId),
+ onSuccess: (data) => queryClient.setQueryData(queryKey, data),
+ });
+ const revokeMutation = useMutation({
+ mutationFn: () => api.revokeMemoShare(memoId),
+ onSuccess: () => queryClient.setQueryData(queryKey, { share: null }),
+ });
+ useEffect(() => {
+ createMutation.reset();
+ revokeMutation.reset();
+ setCopyState("idle");
+ }, [memoId]);
+
+ const share = shareQuery.data?.share ?? null;
+ const shareUrl = share ? getPublicShareUrl(share.token) : "";
+ const isWorking = shareQuery.isLoading || createMutation.isPending || revokeMutation.isPending;
+ const error = shareQuery.error || createMutation.error || revokeMutation.error;
+
+ const copyLink = async () => {
+ const copied = await copyTextToClipboard(shareUrl);
+ setCopyState(copied ? "copied" : "error");
+ window.setTimeout(() => setCopyState("idle"), 1800);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-lg gap-0 overflow-hidden p-0">
+ <DialogHeader className="border-b border-slate-200 px-5 py-5 pr-12 text-left">
+ <DialogTitle className="flex items-center gap-2 text-base">
+ <Link2 className="h-5 w-5 text-emerald-600" />
+ {t("sharing.title")}
+ </DialogTitle>
+ <DialogDescription className="pt-1 leading-5">{t("sharing.description")}</DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 px-5 py-5">
+ {shareQuery.isLoading ? (
+ <div className="flex min-h-20 items-center justify-center text-slate-500" role="status">
+ <LoaderCircle className="h-5 w-5 animate-spin" />
+ </div>
+ ) : share ? (
+ <>
+ <div className="flex gap-2">
+ <Input value={shareUrl} readOnly aria-label={t("sharing.linkLabel")} className="min-w-0 font-mono text-xs" />
+ <Button variant="outline" onClick={() => void copyLink()}>
+ {copyState === "copied" ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
+ {t(copyState === "copied" ? "sharing.copied" : copyState === "error" ? "sharing.copyFailed" : "sharing.copy")}
+ </Button>
+ </div>
+ <p className="text-xs leading-5 text-slate-500">{t("sharing.liveContentHint")}</p>
+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-between">
+ <Button variant="danger" disabled={isWorking} onClick={() => revokeMutation.mutate()}>
+ <Trash2 className="h-4 w-4" />
+ {t("sharing.revoke")}
+ </Button>
+ <Button variant="solid" onClick={() => window.open(shareUrl, "_blank", "noopener,noreferrer")}>
+ <ExternalLink className="h-4 w-4" />
+ {t("sharing.open")}
+ </Button>
+ </div>
+ </>
+ ) : (
+ <div className="space-y-4">
+ <p className="text-sm leading-6 text-slate-600">{t("sharing.inactiveHint")}</p>
+ <Button className="w-full" variant="solid" disabled={isWorking} onClick={() => createMutation.mutate()}>
+ {createMutation.isPending ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Link2 className="h-4 w-4" />}
+ {t("sharing.create")}
+ </Button>
+ </div>
+ )}
+ {error ? <p className="text-sm text-rose-600" role="alert">{t("sharing.error")}</p> : null}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 7b7b4563..3c028e5c 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -12,10 +12,12 @@ import type {
MemoEditSession,
MemoRevision,
MemoSummary,
+ MemoShare,
Notebook,
Resource,
ResourceListItem,
ResourceStorageSummary,
+ PublicMemoShare,
TagSummary,
TiptapDoc,
SyncBootstrapResponse,
@@ -201,6 +203,8 @@ type MemoResponse = {
memo: MemoDetail;
};
+export type MemoShareResponse = { share: MemoShare | null };
+
type TemplateResponse = {
template: MemoTemplate;
};
@@ -311,6 +315,9 @@ const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
export const api = {
getSession: () => request<AuthSession>("/api/v1/auth/session"),
+ getPublicMemoShare: (token: string) =>
+ request<{ share: PublicMemoShare }>(`/api/public/shares/${encodeURIComponent(token)}`),
+
listLoginDeviceSessions: () =>
request<ListLoginDeviceSessionsResponse>("/api/v1/auth/sessions"),
@@ -526,6 +533,18 @@ export const api = {
return request<MemoResponse>(`/api/v1/memos/${memoId}${suffix}`);
},
+ getMemoShare: (memoId: string) =>
+ request<MemoShareResponse>(`/api/v1/memos/${memoId}/share`),
+
+ createMemoShare: (memoId: string) =>
+ request<{ share: MemoShare }>(`/api/v1/memos/${memoId}/share`, {
+ method: "POST",
+ body: JSON.stringify({}),
+ }),
+
+ revokeMemoShare: (memoId: string) =>
+ request<{ ok: true }>(`/api/v1/memos/${memoId}/share`, { method: "DELETE" }),
+
createMemoEditSession: (memoId: string) =>
request<{ editSession: MemoEditSession }>(`/api/v1/memos/${memoId}/edit-sessions`, {
method: "POST",
diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.css
index 2674d9d7..b06b37d1 100644
--- a/apps/web/src/styles/globals.css
+++ b/apps/web/src/styles/globals.css
@@ -215,6 +215,35 @@ textarea {
padding: 8px 12px 56px;
}
+.edgeever-public-share .ProseMirror {
+ min-height: 0;
+ padding: 8px 20px 40px;
+ color: #0f172a;
+}
+
+.edgeever-public-share .ProseMirror [data-edgeever-theme-block] {
+ margin: 1.25rem 0;
+ border: 1px solid #dbeee5;
+ border-radius: 6px;
+ background: #fbfefc;
+ padding: 0.8rem 1rem;
+}
+
+.edgeever-public-share .ProseMirror [data-theme-block-kind="chapter"] {
+ border-left: 4px solid var(--brand-green);
+ background: var(--brand-green-soft);
+}
+
+:root.dark .edgeever-public-share .ProseMirror {
+ color: #0f172a;
+}
+
+@media (min-width: 640px) {
+ .edgeever-public-share .ProseMirror {
+ padding-inline: 36px;
+ }
+}
+
.ProseMirror .edgeever-search-match {
border-radius: 0.2rem;
background-color: rgb(254 240 138 / 0.8);
diff --git a/docs/openapi.json b/docs/openapi.json
index 4ec6d08d..4cd62646 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -875,6 +875,73 @@
}
}
},
+ "/api/v1/memos/{id}/share": {
+ "parameters": [
+ {
+ "$ref": "#/components/parameters/MemoId"
+ }
+ ],
+ "get": {
+ "summary": "Read the active public share for a memo",
+ "responses": {
+ "200": {
+ "description": "Current share status",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "share": {
+ "oneOf": [
+ { "$ref": "#/components/schemas/MemoShare" },
+ { "type": "null" }
+ ]
+ }
+ },
+ "required": ["share"]
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "summary": "Create or return a public read-only share link",
+ "responses": {
+ "200": {
+ "description": "Existing share",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": { "share": { "$ref": "#/components/schemas/MemoShare" } },
+ "required": ["share"]
+ }
+ }
+ }
+ },
+ "201": {
+ "description": "Share created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": { "share": { "$ref": "#/components/schemas/MemoShare" } },
+ "required": ["share"]
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "summary": "Revoke a public memo share",
+ "responses": {
+ "200": { "$ref": "#/components/responses/Ok" },
+ "404": { "$ref": "#/components/responses/Error" }
+ }
+ }
+ },
"/api/v1/memos/{id}/restore": {
"parameters": [
{
@@ -1216,6 +1283,59 @@
}
}
},
+ "/api/public/shares/{token}": {
+ "parameters": [
+ {
+ "name": "token",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string" }
+ }
+ ],
+ "get": {
+ "summary": "Read a publicly shared note",
+ "security": [],
+ "responses": {
+ "200": {
+ "description": "Public read-only note",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": { "share": { "$ref": "#/components/schemas/PublicMemoShare" } },
+ "required": ["share"]
+ }
+ }
+ }
+ },
+ "404": { "$ref": "#/components/responses/Error" }
+ }
+ }
+ },
+ "/api/public/shares/{token}/resources/{resourceId}/blob": {
+ "parameters": [
+ {
+ "name": "token",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string" }
+ },
+ {
+ "name": "resourceId",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string" }
+ }
+ ],
+ "get": {
+ "summary": "Read an attachment belonging to a publicly shared note",
+ "security": [],
+ "responses": {
+ "200": { "description": "Shared resource blob" },
+ "404": { "$ref": "#/components/responses/Error" }
+ }
+ }
+ },
"/mcp": {
"get": {
"summary": "Describe MCP endpoint",
@@ -1690,6 +1810,27 @@
}
]
},
+ "MemoShare": {
+ "type": "object",
+ "properties": {
+ "memoId": { "type": "string" },
+ "token": { "type": "string" },
+ "createdAt": { "type": "string", "format": "date-time" },
+ "updatedAt": { "type": "string", "format": "date-time" }
+ },
+ "required": ["memoId", "token", "createdAt", "updatedAt"]
+ },
+ "PublicMemoShare": {
+ "type": "object",
+ "properties": {
+ "title": { "type": ["string", "null"] },
+ "contentJson": { "$ref": "#/components/schemas/TiptapDoc" },
+ "contentMarkdown": { "type": "string" },
+ "tags": { "type": "array", "items": { "type": "string" } },
+ "updatedAt": { "type": "string", "format": "date-time" }
+ },
+ "required": ["title", "contentJson", "contentMarkdown", "tags", "updatedAt"]
+ },
"MemoCreateInput": {
"type": "object",
"properties": {
diff --git a/migrations/0022_memo_shares.sql b/migrations/0022_memo_shares.sql
new file mode 100644
index 00000000..6dd21d28
--- /dev/null
+++ b/migrations/0022_memo_shares.sql
@@ -0,0 +1,22 @@
+PRAGMA foreign_keys = ON;
+
+CREATE TABLE memo_shares (
+ id TEXT PRIMARY KEY,
+ memo_id TEXT NOT NULL,
+ workspace_id TEXT NOT NULL,
+ token TEXT NOT NULL,
+ 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')),
+ FOREIGN KEY (memo_id) REFERENCES memos(id)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE,
+ FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE,
+ UNIQUE (memo_id),
+ UNIQUE (token)
+);
+
+CREATE INDEX idx_memo_shares_workspace
+ ON memo_shares(workspace_id, updated_at DESC);
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 6d8af73b..ef40003b 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -12,10 +12,12 @@ import type {
MemoEditSession,
MemoRevision,
MemoSummary,
+ MemoShare,
Notebook,
Resource,
ResourceListItem,
ResourceStorageSummary,
+ PublicMemoShare,
TagSummary,
TiptapDoc,
} from "@edgeever/shared";
@@ -74,6 +76,14 @@ export type MemoResponse = {
memo: MemoDetail;
};
+export type MemoShareResponse = {
+ share: MemoShare | null;
+};
+
+export type PublicMemoShareResponse = {
+ share: PublicMemoShare;
+};
+
export type NotebookResponse = {
notebook: Notebook;
};
@@ -173,6 +183,9 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
return {
getSession: () => request<AuthSession>("/api/v1/auth/session"),
+ getPublicMemoShare: (token: string) =>
+ request<PublicMemoShareResponse>(`/api/public/shares/${encodeURIComponent(token)}`),
+
listLoginDeviceSessions: () =>
request<ListLoginDeviceSessionsResponse>("/api/v1/auth/sessions"),
@@ -358,6 +371,18 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
return request<MemoResponse>(`/api/v1/memos/${memoId}${suffix}`);
},
+ getMemoShare: (memoId: string) =>
+ request<MemoShareResponse>(`/api/v1/memos/${memoId}/share`),
+
+ createMemoShare: (memoId: string) =>
+ request<{ share: MemoShare }>(`/api/v1/memos/${memoId}/share`, {
+ method: "POST",
+ body: JSON.stringify({}),
+ }),
+
+ revokeMemoShare: (memoId: string) =>
+ request<{ ok: true }>(`/api/v1/memos/${memoId}/share`, { method: "DELETE" }),
+
createMemoEditSession: (memoId: string) =>
request<{ editSession: MemoEditSession }>(`/api/v1/memos/${memoId}/edit-sessions`, {
method: "POST",
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 82f5d2b0..34950290 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -663,6 +663,26 @@ export const enUS = {
showOutline: "Show outline",
hideOutline: "Hide outline",
},
+ sharing: {
+ action: "Share note",
+ title: "Share note",
+ description: "Anyone with the link can view the latest saved version of this note without signing in.",
+ linkLabel: "Public share link",
+ inactiveHint: "Create a private, unguessable link that you can revoke at any time.",
+ liveContentHint: "The link always shows the latest saved content. Revoking it disables the note and its attachments immediately.",
+ create: "Create share link",
+ copy: "Copy link",
+ copied: "Copied",
+ copyFailed: "Copy failed",
+ open: "Open shared note",
+ revoke: "Revoke sharing",
+ error: "Sharing could not be updated. Please try again.",
+ readOnly: "Read-only share",
+ publicLoading: "Loading shared note",
+ publicUpdated: "Updated {{time}}",
+ publicUnavailable: "This shared note is unavailable",
+ publicUnavailableHint: "The link may be invalid, the owner may have revoked it, or the note may have been deleted.",
+ },
editorToolbar: {
toolbar: "Editor toolbar",
paragraph: "Body",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 1a4d780f..187cf7ce 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -663,6 +663,26 @@ export const zhCN = {
showOutline: "显示文档大纲",
hideOutline: "隐藏文档大纲",
},
+ sharing: {
+ action: "分享笔记",
+ title: "分享笔记",
+ description: "任何获得链接的人无需登录,即可查看这篇笔记最新保存的内容。",
+ linkLabel: "公开分享链接",
+ inactiveHint: "创建一个难以猜测的专属链接;你可以随时撤销。",
+ liveContentHint: "链接会展示最新保存的内容。撤销后,笔记及其中的附件会立即停止公开访问。",
+ create: "创建分享链接",
+ copy: "复制链接",
+ copied: "已复制",
+ copyFailed: "复制失败",
+ open: "打开分享页",
+ revoke: "取消分享",
+ error: "分享状态更新失败,请稍后重试。",
+ readOnly: "只读分享",
+ publicLoading: "正在加载分享笔记",
+ publicUpdated: "更新于 {{time}}",
+ publicUnavailable: "这篇分享笔记不可用",
+ publicUnavailableHint: "链接可能无效、已被分享者撤销,或原笔记已经删除。",
+ },
editorToolbar: {
toolbar: "编辑器工具栏",
paragraph: "正文",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 5ebdb441..c73a8d0f 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -8,6 +8,7 @@ export * from "./note-links";
export * from "./notebooks";
export * from "./revision-diff";
export * from "./schemas";
+export * from "./sharing";
export * from "./sync";
export * from "./desktop-rpc";
export * from "./types";
diff --git a/packages/shared/src/sharing.test.mjs b/packages/shared/src/sharing.test.mjs
new file mode 100644
index 00000000..c052dd76
--- /dev/null
+++ b/packages/shared/src/sharing.test.mjs
@@ -0,0 +1,38 @@
+import { describe, expect, test } from "bun:test";
+import { rewriteMemoResourcesForShare } from "./sharing.ts";
+
+describe("shared memo resources", () => {
+ test("rewrites owned images and attachments without touching external links", () => {
+ const source = {
+ type: "doc",
+ content: [
+ { type: "image", attrs: { src: "/api/v1/resources/res_image/blob", alt: "Image" } },
+ {
+ type: "paragraph",
+ content: [{
+ type: "text",
+ text: "Attachment",
+ marks: [{ type: "link", attrs: { href: "/api/v1/resources/res_file/blob", target: "_blank" } }],
+ }],
+ },
+ {
+ type: "paragraph",
+ content: [{
+ type: "text",
+ text: "External",
+ marks: [{ type: "link", attrs: { href: "https://example.com/file" } }],
+ }],
+ },
+ ],
+ };
+
+ const rewritten = rewriteMemoResourcesForShare(source, "share_token");
+
+ expect(rewritten.content[0].attrs.src).toBe("/api/public/shares/share_token/resources/res_image/blob");
+ expect(rewritten.content[1].content[0].marks[0].attrs.href).toBe(
+ "/api/public/shares/share_token/resources/res_file/blob",
+ );
+ expect(rewritten.content[2].content[0].marks[0].attrs.href).toBe("https://example.com/file");
+ expect(source.content[0].attrs.src).toBe("/api/v1/resources/res_image/blob");
+ });
+});
diff --git a/packages/shared/src/sharing.ts b/packages/shared/src/sharing.ts
new file mode 100644
index 00000000..e37cbf88
--- /dev/null
+++ b/packages/shared/src/sharing.ts
@@ -0,0 +1,52 @@
+import type { TiptapDoc, TiptapNode, TiptapTextNode } from "./content";
+
+export type MemoShare = {
+ memoId: string;
+ token: string;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type PublicMemoShare = {
+ title: string | null;
+ contentJson: TiptapDoc;
+ contentMarkdown: string;
+ tags: string[];
+ updatedAt: string;
+};
+
+const RESOURCE_URL_PATTERN = /^\/api\/v1\/resources\/([^/?#]+)\/blob(?:[?#].*)?$/;
+
+const rewriteAttributeValue = (value: unknown, token: string) => {
+ if (typeof value !== "string") return value;
+ const match = value.match(RESOURCE_URL_PATTERN);
+ return match
+ ? `/api/public/shares/${encodeURIComponent(token)}/resources/${encodeURIComponent(match[1])}/blob`
+ : value;
+};
+
+/** Rewrites only EdgeEver-owned resource URLs so a public viewer never needs a user session. */
+export const rewriteMemoResourcesForShare = (doc: TiptapDoc, token: string): 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)]))
+ : 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)]))
+ : undefined,
+ }))
+ : undefined;
+
+ return {
+ ...node,
+ ...(attrs ? { attrs } : {}),
+ ...(marks ? { marks } : {}),
+ ...("content" in node && node.content ? { content: node.content.map(visit) } : {}),
+ } as TiptapNode | TiptapTextNode;
+ };
+
+ return visit(doc) as TiptapDoc;
+};
diff --git a/scripts/verify-deployment.mjs b/scripts/verify-deployment.mjs
index da0b3e42..a6305c68 100644
--- a/scripts/verify-deployment.mjs
+++ b/scripts/verify-deployment.mjs
@@ -9,6 +9,7 @@ export const REQUIRED_TABLES = [
"workspace_members",
"notebooks",
"memos",
+ "memo_shares",
"memo_import_sources",
"mobile_sync_changes",
];