AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(sharing): add password protection for notebook shares
tianma-ifa78586b71639
diff --git a/apps/api/src/notebook-share-routes.test.mjs b/apps/api/src/notebook-share-routes.test.mjsindex fe85a833..75975565 100644--- a/apps/api/src/notebook-share-routes.test.mjs+++ b/apps/api/src/notebook-share-routes.test.mjs@@ -28,7 +28,7 @@ const fixture = () => {// 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"),+ (file) => file < "migrations/0067_notebook_shares.sql",))db.exec(readFileSync(file, "utf8"));db.run(@@ -74,6 +74,7 @@ const fixture = () => {"INSERT INTO notebook_shares (id, notebook_id, workspace_id, token) VALUES ('shared', 'root', 'ws_test', ?)",[token],);+ db.exec(readFileSync("migrations/0068_notebook_share_passwords.sql", "utf8"));const environment = {storage: createSelfHostedStorageAdapter(db,@@ -358,3 +359,131 @@ describe("live recursive notebook sharing", () => {expect(share.memos.some((memo) => memo.id === "memo_other")).toBe(false);});});++describe("password-protected notebook shares", () => {+ const changePassword = async (fixture, enabled = true, id = "root", headers = {}) => {+ const response = await fixture.app.request(`/api/v1/notebooks/${id}/share`, {+ method: "PATCH", headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify({ passwordProtected: enabled }),+ }, fixture.environment);+ return { response, data: await response.json() };+ };+ const unlock = (fixture, password) => fixture.request("/unlock", {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password }),+ });+ const cookieFrom = (response) => response.headers.get("set-cookie").split(";")[0];+ const paths = ["", "/memos/memo_child", "/memos/memo_grand", "/resources/res_memo_grand/blob"];++ test("migrates an existing live link in place and protects directory, descendants and blobs", async () => {+ const f = fixture();+ expect((await f.request()).status).toBe(200);+ const { response, data } = await changePassword(f);+ expect(response.status).toBe(200);+ expect(data.share.token).toBe(token);+ expect(data.share.passwordProtected).toBe(true);+ expect(data.share.password.length).toBeGreaterThan(0);+ expect(f.db.query("SELECT password_hash FROM notebook_shares").get().password_hash).not.toBe(data.share.password);+ for (const path of paths) {+ const denied = await f.request(path, { headers: { Range: "bytes=2-5" } });+ expect(denied.status).toBe(403);+ expect((await denied.json()).error.code).toBe("share_password_required");+ expect(denied.headers.get("cache-control")).toBe("private, no-store");+ }+ expect(f.blobReads()).toBe(0);+ const listing = await f.app.request("/api/v1/notebook-shares", {}, f.environment);+ const shares = (await listing.json()).shares;+ expect(shares[0].passwordProtected).toBe(true);+ expect(shares[0].password).toBeUndefined();+ expect(shares[0].password_hash).toBeUndefined();+ const wrong = await unlock(f, "wrong");+ expect((await wrong.json()).error.code).toBe("share_password_invalid");+ const ok = await unlock(f, data.share.password);+ expect(ok.status).toBe(200);+ expect(ok.headers.get("set-cookie")).toContain(`Path=/api/public/notebook-shares/${token}`);+ expect(ok.headers.get("set-cookie")).toContain("HttpOnly");+ const headers = { Cookie: cookieFrom(ok) };+ for (const path of paths) expect((await f.request(path, { headers })).status).toBe(200);+ const range = await f.request(paths[3], { headers: { ...headers, Range: "bytes=2-5" } });+ expect(range.status).toBe(206);+ expect(await range.text()).toBe("2345");+ });++ test("rotating rejects previous passwords and cookies; clearing restores the same public link", async () => {+ const f = fixture();+ const first = (await changePassword(f)).data.share;+ const cookie = cookieFrom(await unlock(f, first.password));+ const second = (await changePassword(f)).data.share;+ expect(second.token).toBe(first.token);+ expect(second.password).not.toBe(first.password);+ expect((await unlock(f, first.password)).status).toBe(403);+ for (const path of paths) expect((await f.request(path, { headers: { Cookie: cookie } })).status).toBe(403);+ expect((await unlock(f, second.password)).status).toBe(200);+ const cleared = (await changePassword(f, false)).data.share;+ expect(cleared.token).toBe(token);+ expect(cleared.passwordProtected).toBe(false);+ expect(cleared.password).toBeUndefined();+ for (const path of paths) expect((await f.request(path)).status).toBe(200);+ expect((await unlock(f, second.password)).status).toBe(400);+ });++ test("limits wrong attempts and resets attempt state when regenerating", async () => {+ const f = fixture();+ const share = (await changePassword(f)).data.share;+ for (let i = 0; i < 7; i++) expect((await unlock(f, "wrong")).status).toBe(403);+ expect((await unlock(f, "wrong")).status).toBe(429);+ expect((await unlock(f, share.password)).status).toBe(429);+ const regenerated = (await changePassword(f)).data.share;+ expect((await unlock(f, regenerated.password)).status).toBe(200);+ expect(f.db.query("SELECT unlock_failed_count FROM notebook_shares").get().unlock_failed_count).toBe(0);+ });++ test("management requires a live share in the interactive user's workspace", async () => {+ const f = fixture();+ for (const [kind, status] of [["none", 403], ["agent", 403]]) expect((await changePassword(f, true, "root", { "test-auth": kind })).response.status).toBe(status);+ expect((await changePassword(f, true, "foreign")).response.status).toBe(404);+ expect((await changePassword(f, true, "private")).response.status).toBe(404);+ f.db.run("UPDATE notebooks SET is_deleted = 1 WHERE id = 'root'");+ expect((await changePassword(f)).response.status).toBe(404);+ expect((await unlock(f, "wrong")).status).toBe(404);+ });++ test("other share links have independent passwords and grants; revocation invalidates all reads", async () => {+ const f = fixture();+ const parent = (await changePassword(f)).data.share;+ const parentCookie = cookieFrom(await unlock(f, parent.password));+ const created = await f.app.request("/api/v1/notebooks/child/share", { method: "POST" }, f.environment);+ const child = (await created.json()).share;+ // Another public link still grants access independently.+ expect((await f.app.request(`/api/public/notebook-shares/${child.token}`, {}, f.environment)).status).toBe(200);+ expect((await f.app.request(`/api/public/shares/${individualToken}`, {}, f.environment)).status).toBe(200);+ const protectedChild = (await changePassword(f, true, "child")).data.share;+ const childBase = `/api/public/notebook-shares/${child.token}`;+ expect((await f.app.request(childBase, { headers: { Cookie: parentCookie } }, f.environment)).status).toBe(403);+ const childUnlock = await f.app.request(`${childBase}/unlock`, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password: protectedChild.password }),+ }, f.environment);+ expect(childUnlock.status).toBe(200);+ expect((await f.request("", { headers: { Cookie: cookieFrom(childUnlock) } })).status).toBe(403);+ await f.app.request("/api/v1/notebooks/root/share", { method: "DELETE" }, f.environment);+ for (const path of [...paths, "/unlock"]) expect((await f.request(path, { headers: { Cookie: parentCookie } })).status).toBe(404);+ expect((await f.app.request(childBase, { headers: { Cookie: cookieFrom(childUnlock) } }, f.environment)).status).toBe(200);+ });+});++test("only an authenticated session in the shared workspace can preview without the share password", async () => {+ const { createHash } = await import("node:crypto");+ const f = fixture();+ await f.app.request("/api/v1/notebooks/root/share", {+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ passwordProtected: true }),+ }, f.environment);+ for (const [user, workspace] of [["owner", "ws_test"], ["other", "ws_other"]]) {+ f.db.run("INSERT INTO users (id, username, password_hash) VALUES (?, ?, 'unused')", [user, user]);+ f.db.run("INSERT INTO workspace_members (workspace_id, user_id, role) VALUES (?, ?, 'owner')", [workspace, user]);+ f.db.run("INSERT INTO sessions (id, user_id, token_hash, expires_at) VALUES (?, ?, ?, ?)",+ [user, user, createHash("sha256").update(user).digest("hex"), new Date(Date.now()+3600000).toISOString()]);+ }+ for (const path of ["", "/memos/memo_child", "/resources/res_memo_child/blob"]) {+ expect((await f.request(path, { headers: { Cookie: "edgeever_session=owner" } })).status).toBe(200);+ expect((await f.request(path, { headers: { Cookie: "edgeever_session=other" } })).status).toBe(403);+ }+});diff --git a/apps/api/src/notebook-share-routes.ts b/apps/api/src/notebook-share-routes.tsindex fdd3f862..d9533f38 100644--- a/apps/api/src/notebook-share-routes.ts+++ b/apps/api/src/notebook-share-routes.ts@@ -1,4 +1,6 @@import {+ NotebookShareUpdateSchema,+ PublicShareUnlockSchema,collectMemoLinkIds,accountNoteProseFromRow,publicNoteProseFromAccount,@@ -11,14 +13,18 @@ import {type NoteProseAccountRow,type TiptapDoc,} from "@edgeever/shared";+import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";import type { AppEnv } from "./api-context";-import { randomToken } from "./auth-crypto";+import { hashPassword, verifyPassword, randomToken } from "./auth-crypto";import { audit } from "./audit";import { createId, isoNow, parseJsonArray } from "./entity-utils";-import { notFound } from "./http-errors";+import { apiError, notFound } from "./http-errors";import { getAuditActor, getWorkspaceId, requireUser } from "./request-auth";import { serveSharedResource } from "./share-routes";+import { allowPasswordProtectedShare, setShareAccessCookie } from "./share-http-access";+import { isShareUnlockBlocked, nextShareUnlockFailure, type ShareUnlockState } from "./share-access";+import { generateSharePassword } from "./share-password";// Every public query starts at the live share, and constrains every level to// its workspace. Deleted ancestors stop traversal; UNION also tolerates cycles.@@ -32,20 +38,23 @@ const publicTreeSql = `WITH RECURSIVE tree(id, workspace_id) AS ()`;type ShareRow = {+ password_hash: string | null;notebook_id: string;notebook_name: string;token: string;created_at: string;updated_at: string;};-const mapShare = (row: ShareRow): NotebookShare => ({+const mapShare = (row: ShareRow, password?: string): NotebookShare => ({+ passwordProtected: Boolean(row.password_hash),+ ...(password ? { password } : {}),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+const selectShareSql = `SELECT ns.notebook_id, n.name AS notebook_name, ns.password_hash, ns.token, ns.created_at, ns.updated_atFROM notebook_shares ns JOIN notebooks n ON n.id = ns.notebook_id AND n.workspace_id = ns.workspace_idWHERE ns.workspace_id = ? AND n.is_deleted = 0`;const validToken = (token: string) => /^[A-Za-z0-9_-]{43}$/.test(token);@@ -59,7 +68,7 @@ export const registerNotebookShareRoutes = (app: Hono<AppEnv>) => {.bind(getWorkspaceId(c)).all<ShareRow>();c.header("Cache-Control", "private, no-store");- return c.json({ shares: rows.results.map(mapShare) });+ return c.json({ shares: rows.results.map((row) => mapShare(row)) });});app.get("/api/v1/notebooks/:id/share", async (c) => {const denied = requireUser(c);@@ -118,6 +127,27 @@ export const registerNotebookShareRoutes = (app: Hono<AppEnv>) => {c.header("Cache-Control", "private, no-store");return c.json({ share: mapShare(row) });});+ app.patch("/api/v1/notebooks/:id/share", zValidator("json", NotebookShareUpdateSchema), async (c) => {+ const denied = requireUser(c);+ if (denied) return denied;+ const workspaceId = getWorkspaceId(c);+ const notebookId = c.req.param("id");+ const existing = await c.env.storage.db.prepare(`${selectShareSql} AND ns.notebook_id = ?`)+ .bind(workspaceId, notebookId).first<ShareRow>();+ if (!existing) return notFound(c, "Active share not found");+ const password = c.req.valid("json").passwordProtected ? generateSharePassword() : undefined;+ const passwordHash = password ? await hashPassword(password) : null;+ const now = isoNow();+ await c.env.storage.db.prepare(`UPDATE notebook_shares SET password_hash = ?, unlock_failed_count = 0,+ unlock_window_started_at = NULL, unlock_blocked_until = NULL, updated_at = ?+ WHERE notebook_id = ? AND workspace_id = ?`).bind(passwordHash, now, notebookId, workspaceId).run();+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId,+ password ? (existing.password_hash ? "notebook.share_password_rotate" : "notebook.share_password_set") : "notebook.share_password_clear",+ "notebook", notebookId, {});+ c.header("Cache-Control", "private, no-store");+ return c.json({ share: mapShare({ ...existing, password_hash: passwordHash, updated_at: now }, password) });+ });app.delete("/api/v1/notebooks/:id/share", async (c) => {const denied = requireUser(c);if (denied) return denied;@@ -145,8 +175,39 @@ 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");+ const token = c.req.path.split("/")[4] ?? "";+ if (!validToken(token)) return notFound(c, "Shared notebook not found");+ const gate = await c.env.storage.db.prepare(`SELECT ns.workspace_id, ns.password_hash 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<{ workspace_id: string; password_hash: string | null }>();+ if (!gate) return notFound(c, "Shared notebook not found");+ // Only the password submission bypasses the gate; all reads, including blobs, share it.+ const unlocking = c.req.method === "POST" && c.req.path === `/api/public/notebook-shares/${token}/unlock`;+ if (!unlocking && gate.password_hash && !(await allowPasswordProtectedShare(c, token, gate.workspace_id, gate.password_hash))) {+ return apiError(c, "share_password_required", "Password required to view this shared notebook", 403);+ }await next();});+ app.post("/api/public/notebook-shares/:token/unlock", zValidator("json", PublicShareUnlockSchema), async (c) => {+ const token = c.req.param("token");+ const gate = await c.env.storage.db.prepare(`SELECT password_hash, unlock_failed_count, unlock_window_started_at, unlock_blocked_until+ FROM notebook_shares WHERE token = ?`).bind(token).first<ShareUnlockState & { password_hash: string | null }>();+ if (!gate) return notFound(c, "Shared notebook not found");+ if (!gate.password_hash) return apiError(c, "share_password_not_required", "This shared notebook does not require a password", 400);+ const rateLimited = () => apiError(c, "share_unlock_rate_limited", "Too many share password attempts. Try again later.", 429);+ if (isShareUnlockBlocked(gate.unlock_blocked_until)) return rateLimited();+ if (!(await verifyPassword(c.req.valid("json").password, gate.password_hash))) {+ const failure = nextShareUnlockFailure(gate);+ await c.env.storage.db.prepare(`UPDATE notebook_shares SET unlock_failed_count = ?, unlock_window_started_at = ?, unlock_blocked_until = ?+ WHERE token = ?`).bind(failure.failureCount, failure.windowStartedAt, failure.blockedUntil, token).run();+ return failure.blockedUntil ? rateLimited() : apiError(c, "share_password_invalid", "Incorrect share password", 403);+ }+ await c.env.storage.db.prepare(`UPDATE notebook_shares SET unlock_failed_count = 0, unlock_window_started_at = NULL, unlock_blocked_until = NULL+ WHERE token = ?`).bind(token).run();+ await setShareAccessCookie(c, token, gate.password_hash, `/api/public/notebook-shares/${token}`);+ return c.json({ ok: true });+ });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");diff --git a/apps/api/src/share-http-access.ts b/apps/api/src/share-http-access.tsnew file mode 100644index 00000000..29303851--- /dev/null+++ b/apps/api/src/share-http-access.ts@@ -0,0 +1,33 @@+import { getCookie, setCookie } from "hono/cookie";+import type { AppContext } from "./api-context";+import { authenticateRequest } from "./auth-service";+import { createShareAccessCookieValue, isValidShareAccessCookieValue, SHARE_ACCESS_COOKIE, SHARE_ACCESS_MAX_AGE_SECONDS } from "./share-access";++const shareAccessCookiePath = (token: string) => `/api/public/shares/${encodeURIComponent(token)}`;++export const setShareAccessCookie = async (c: AppContext, token: string, passwordHash: string, path = shareAccessCookiePath(token)) => {+ const value = await createShareAccessCookieValue(passwordHash, token);+ setCookie(c, SHARE_ACCESS_COOKIE, value, {+ httpOnly: true,+ secure: new URL(c.req.url).protocol === "https:",+ sameSite: "Lax",+ path,+ maxAge: SHARE_ACCESS_MAX_AGE_SECONDS,+ });+};++const hasShareAccessCookie = async (c: AppContext, token: string, passwordHash: string) =>+ isValidShareAccessCookieValue(getCookie(c, SHARE_ACCESS_COOKIE), passwordHash, token);++const isShareOwner = async (c: AppContext, workspaceId: string) => {+ const auth = await authenticateRequest(c, false);+ return auth?.workspaceId === workspaceId;+};++export const allowPasswordProtectedShare = async (+ c: AppContext,+ token: string,+ workspaceId: string,+ passwordHash: string,+) => (await hasShareAccessCookie(c, token, passwordHash)) || isShareOwner(c, workspaceId);+diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.tsindex 7418b1df..a15dac8b 100644--- a/apps/api/src/share-routes.ts+++ b/apps/api/src/share-routes.ts@@ -1,10 +1,8 @@import { accountNoteProseFromRow, collectMemoLinkIds, isPdfAttachment, MemoShareUpdateSchema, NoteBodyFontUpdateSchema, NoteProseUpdateSchema, parsePublishedNoteBodyFont, publicNoteProseFromAccount, PublicShareUnlockSchema, resolveMemoContentDoc, resolvePlayableMediaMimeType, sanitizeNoteProseCss, type AccountNoteProse, type ManagedMemoShare, type MemoShare, type NoteProseAccountRow, type PublicMemoShare, type TiptapDoc } from "@edgeever/shared";import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";-import { getCookie, setCookie } from "hono/cookie";import type { AppContext, AppEnv } from "./api-context";import { audit } from "./audit";-import { authenticateRequest } from "./auth-service";import { hashPassword, randomToken, verifyPassword } from "./auth-crypto";import { parseByteRange, rangeNotSatisfiable } from "./byte-range";import { createId, isoNow, parseJsonArray } from "./entity-utils";@@ -13,13 +11,10 @@ import { resolveObjectStorage } from "./object-storage";import { getAuditActor, getWorkspaceId, requireUser } from "./request-auth";import { contentDispositionAttachment, contentDispositionInline } from "./resource-service";import {- createShareAccessCookieValue,isShareUnlockBlocked,- isValidShareAccessCookieValue,nextShareUnlockFailure,- SHARE_ACCESS_COOKIE,- SHARE_ACCESS_MAX_AGE_SECONDS,} from "./share-access";+import { allowPasswordProtectedShare, setShareAccessCookie } from "./share-http-access";import { generateSharePassword } from "./share-password";const SHARE_TOKEN_BYTES = 32;@@ -94,34 +89,6 @@ const sharePasswordInvalid = (c: AppContext) =>const shareUnlockRateLimited = (c: AppContext) =>apiError(c, "share_unlock_rate_limited", "Too many share password attempts. Try again later.", 429);-const shareAccessCookiePath = (token: string) => `/api/public/shares/${encodeURIComponent(token)}`;--const setShareAccessCookie = async (c: AppContext, token: string, passwordHash: string) => {- const value = await createShareAccessCookieValue(passwordHash, token);- setCookie(c, SHARE_ACCESS_COOKIE, value, {- httpOnly: true,- secure: new URL(c.req.url).protocol === "https:",- sameSite: "Lax",- path: shareAccessCookiePath(token),- maxAge: SHARE_ACCESS_MAX_AGE_SECONDS,- });-};--const hasShareAccessCookie = async (c: AppContext, token: string, passwordHash: string) =>- isValidShareAccessCookieValue(getCookie(c, SHARE_ACCESS_COOKIE), passwordHash, token);--const isShareOwner = async (c: AppContext, workspaceId: string) => {- const auth = await authenticateRequest(c, false);- return auth?.workspaceId === workspaceId;-};--const allowPasswordProtectedShare = async (- c: AppContext,- token: string,- workspaceId: string,- passwordHash: string,-) => hasShareAccessCookie(c, token, passwordHash) || isShareOwner(c, workspaceId);-const loadShareGate = async (c: AppContext, token: string) =>c.env.storage.db.prepare(`SELECT ms.workspace_id, ms.password_hash, ms.unlock_failed_count, ms.unlock_window_started_at, ms.unlock_blocked_untildiff --git a/apps/web/src/components/PublicNotebookSharePage.tsx b/apps/web/src/components/PublicNotebookSharePage.tsxindex 39acf1f4..db0650e8 100644--- a/apps/web/src/components/PublicNotebookSharePage.tsx+++ b/apps/web/src/components/PublicNotebookSharePage.tsx@@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";import { useParams } from "react-router";import { api } from "@/lib/api";import { Button } from "@/components/ui/button";-import { PublicShareArticle } from "./PublicSharePage";+import { isSharePasswordError, PublicSharePasswordForm, PublicShareArticle } from "./PublicSharePage";import { PublicNotebookSite } from "./PublicNotebookSite";import { withEnvironmentTitlePrefix } from "@/lib/environment-title";@@ -23,7 +23,7 @@ export const PublicNotebookSharePage = () => {const memo = useQuery({queryKey: ["public-notebook-memo", token, memoId],queryFn: () => api.getPublicNotebookMemo(token, memoId!),- enabled: Boolean(memoId),+ enabled: Boolean(memoId) && directory.isSuccess,retry: false,staleTime: 0,refetchOnMount: "always",@@ -65,6 +65,17 @@ export const PublicNotebookSharePage = () => {/></main>);+ if (isSharePasswordError(directory.error, "share_password_required") || isSharePasswordError(memo.error, "share_password_required"))+ return <PublicSharePasswordForm+ key={token}+ token={token}+ hintKey="sharing.notebookPasswordRequiredHint"+ unlock={(password) => api.unlockPublicNotebookShare(token, password)}+ onUnlocked={async () => {+ await directory.refetch();+ if (memoId) await memo.refetch();+ }}+ />;if (!share)return (<main className="flex min-h-[100dvh] flex-col items-center justify-center gap-4 p-6">diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsxindex 6aff3943..e5f384f1 100644--- a/apps/web/src/components/PublicSharePage.tsx+++ b/apps/web/src/components/PublicSharePage.tsx@@ -165,20 +165,24 @@ const SharedDocument = ({return <SharedRichText content={body.content} />;};-const isSharePasswordError = (error: unknown, code: string) =>+export const isSharePasswordError = (error: unknown, code: string) =>error instanceof ApiRequestError && error.code === code;-const PublicSharePasswordForm = ({+export const PublicSharePasswordForm = ({token,onUnlocked,+ unlock,+ hintKey = "sharing.passwordRequiredHint",}: {token: string;+ unlock?: (password: string) => Promise<unknown>;+ hintKey?: string;onUnlocked: () => Promise<unknown>;}) => {const { t } = useTranslation();const [password, setPassword] = useState("");const unlockMutation = useMutation({- mutationFn: () => api.unlockPublicMemoShare(token, password),+ mutationFn: () => unlock ? unlock(password) : api.unlockPublicMemoShare(token, password),onSuccess: () => onUnlocked(),});const submit = (event: FormEvent) => {@@ -197,7 +201,7 @@ const PublicSharePasswordForm = ({<section className="w-full max-w-md rounded-2xl border border-slate-200 bg-card p-8 shadow-sm"><LockKeyhole className="mx-auto h-9 w-9 text-slate-700" /><h1 className="mt-4 text-center text-xl font-semibold text-slate-900">{t("sharing.passwordRequiredTitle")}</h1>- <p className="mt-2 text-center text-sm leading-6 text-slate-500">{t("sharing.passwordRequiredHint")}</p>+ <p className="mt-2 text-center text-sm leading-6 text-slate-500">{t(hintKey)}</p><form className="mt-6 space-y-3" onSubmit={submit}><Inputtype="password"diff --git a/apps/web/src/components/dialogs/ShareMemoDialog.tsx b/apps/web/src/components/dialogs/ShareMemoDialog.tsxindex 41ac552e..1510a2ac 100644--- a/apps/web/src/components/dialogs/ShareMemoDialog.tsx+++ b/apps/web/src/components/dialogs/ShareMemoDialog.tsx@@ -1,12 +1,12 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { Check, Copy, ExternalLink, Link2, LoaderCircle, RefreshCw, Share2, Trash2 } from "lucide-react";+import { Check, Copy, ExternalLink, Link2, LoaderCircle, Share2, Trash2 } from "lucide-react";import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Link, useLocation } from "react-router";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";-import { Switch } from "@/components/ui/switch";+import { SharePasswordControls } from "./SharePasswordControls";import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";import { copyTextToClipboard } from "@/lib/clipboard";@@ -178,60 +178,8 @@ export const ShareMemoDialog = ({</Button></div>- <div className="space-y-3 rounded-lg border border-slate-200 px-3 py-3">- <div className="flex items-center justify-between gap-3">- <div className="text-xs font-normal leading-5 text-slate-900">{t("sharing.passwordToggle")}</div>- <Switch- checked={share.passwordProtected}- disabled={isWorking}- onCheckedChange={(enabled) => passwordMutation.mutate(enabled)}- aria-label={t("sharing.passwordToggle")}- />- </div>- {share.passwordProtected ? (- <div className="space-y-2">- <div className="flex gap-2">- <Input- value={revealedPassword}- readOnly- placeholder={t("sharing.passwordSet")}- aria-label={t("sharing.passwordLabel")}- className="min-w-0 font-mono text-xs tracking-wide"- />- <Button- variant={copyState === "copied" && copyTarget === "password" ? "solid" : copyState === "error" && copyTarget === "password" ? "danger" : "outline"}- className="min-w-28"- disabled={!revealedPassword}- aria-live="polite"- onClick={() => void copyValue("password", revealedPassword)}- >- {copyState === "copied" && copyTarget === "password" ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}- {t(copiedLabel("password", "sharing.passwordCopy"))}- </Button>- <Button- variant="outline"- size="icon"- disabled={isWorking}- title={t("sharing.regeneratePassword")}- aria-label={t("sharing.regeneratePassword")}- onClick={() => passwordMutation.mutate(true)}- >- {passwordMutation.isPending ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}- </Button>- </div>- {revealedPassword ? (- <Button- variant="ghost"- className="h-8 px-0 text-xs text-slate-600 hover:bg-transparent hover:text-slate-900"- onClick={() => void copyValue("both", `${shareUrl}\n${t("sharing.passwordPrefix")}${revealedPassword}`)}- >- {copyState === "copied" && copyTarget === "both" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}- {t(copiedLabel("both", "sharing.copyLinkAndPassword"))}- </Button>- ) : null}- </div>- ) : null}- </div>+ <SharePasswordControls passwordProtected={share.passwordProtected} password={revealedPassword}+ busy={isWorking} shareUrl={shareUrl} onChange={(enabled) => passwordMutation.mutate(enabled)} /><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">diff --git a/apps/web/src/components/dialogs/ShareNotebookDialog.tsx b/apps/web/src/components/dialogs/ShareNotebookDialog.tsxindex 521c66c3..cf7e5b63 100644--- a/apps/web/src/components/dialogs/ShareNotebookDialog.tsx+++ b/apps/web/src/components/dialogs/ShareNotebookDialog.tsx@@ -10,6 +10,7 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import { SharePasswordControls } from "./SharePasswordControls";import { Input } from "@/components/ui/input";import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";import { copyTextToClipboard } from "@/lib/clipboard";@@ -32,6 +33,7 @@ export const ShareNotebookDialog = ({}) => {const { t } = useTranslation();const queryClient = useQueryClient();+ const [secret, setSecret] = useState<{ token: string; updatedAt: string; password: string } | null>(null);const [copyResult, setCopyResult] = useState<boolean | null>(null);const queryKey = ["notebook-share",@@ -54,17 +56,26 @@ export const ShareNotebookDialog = ({void invalidate();},});+ const passwordMutation = useMutation({+ mutationFn: (passwordProtected: boolean) => api.updateNotebookShare(notebookId, { passwordProtected }),+ onSuccess: (data) => {+ queryClient.setQueryData(queryKey, { share: { ...data.share, password: undefined } });+ setSecret(data.share.password ? { token: data.share.token, updatedAt: data.share.updatedAt, password: data.share.password } : null);+ void invalidate();+ },+ });const revoke = useMutation({mutationFn: () => api.revokeNotebookShare(notebookId),onSuccess: () => {queryClient.setQueryData(queryKey, { share: null });+ setSecret(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;+ const busy = query.isFetching || create.isPending || revoke.isPending || passwordMutation.isPending;+ const failed = query.isError || create.isError || revoke.isError || passwordMutation.isError;return (<Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="max-w-lg">@@ -75,8 +86,8 @@ export const ShareNotebookDialog = ({</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 className="rounded-lg bg-muted p-3 text-sm leading-6 text-muted-foreground">+ {t(share?.passwordProtected ? "sharing.notebookProtectedScopeHint" : "sharing.notebookScopeHint")}</p>{inherited ? (<p className="text-sm leading-6 text-slate-600">@@ -95,6 +106,15 @@ export const ShareNotebookDialog = ({readOnlyaria-label={t("sharing.linkLabel")}/>+ <SharePasswordControls+ key={share.token}+ passwordProtected={share.passwordProtected}+ password={secret?.token === share.token && secret.updatedAt === share.updatedAt ? secret.password : ""}+ busy={busy}+ shareUrl={getPublicNotebookShareUrl(share.token)}+ onChange={(enabled) => passwordMutation.mutate(enabled)}+ />+ <p className="text-xs leading-5 text-slate-500">{t("sharing.notebookPasswordScopeHint")}</p><div className="flex flex-wrap gap-2"><Buttonvariant="outline"diff --git a/apps/web/src/components/dialogs/SharePasswordControls.tsx b/apps/web/src/components/dialogs/SharePasswordControls.tsxnew file mode 100644index 00000000..c01e8372--- /dev/null+++ b/apps/web/src/components/dialogs/SharePasswordControls.tsx@@ -0,0 +1,87 @@+import { Check, Copy, LoaderCircle, RefreshCw } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { copyTextToClipboard } from "@/lib/clipboard";++export const SharePasswordControls = ({ passwordProtected, password, busy, shareUrl, onChange }: {+ passwordProtected: boolean;+ password: string;+ busy: boolean;+ shareUrl: string;+ onChange: (enabled: boolean) => void;+}) => {+ const { t } = useTranslation();+ const [copyState, setCopyState] = useState<"idle" | "copied" | "error">("idle");+ const [copyTarget, setCopyTarget] = useState<"password" | "both">("password");+ const resetTimer = useRef<number | null>(null);+ useEffect(() => () => { if (resetTimer.current !== null) window.clearTimeout(resetTimer.current); }, []);+ const copyValue = async (target: "password" | "both", value: string) => {+ const copied = await copyTextToClipboard(value);+ setCopyTarget(target);+ setCopyState(copied ? "copied" : "error");+ if (resetTimer.current !== null) window.clearTimeout(resetTimer.current);+ resetTimer.current = window.setTimeout(() => setCopyState("idle"), 3000);+ };+ const copiedLabel = (target: "password" | "both", idleKey: string) =>+ copyTarget === target && copyState === "copied" ? "sharing.copied" : copyTarget === target && copyState === "error" ? "sharing.copyFailed" : idleKey;+ return (+ <div className="space-y-3 rounded-lg border border-slate-200 px-3 py-3">+ <div className="flex items-center justify-between gap-3">+ <div className="text-xs font-normal leading-5 text-slate-900">{t("sharing.passwordToggle")}</div>+ <Switch+ checked={passwordProtected}+ disabled={busy}+ onCheckedChange={(enabled) => onChange(enabled)}+ aria-label={t("sharing.passwordToggle")}+ />+ </div>+ {passwordProtected ? (+ <div className="space-y-2">+ <div className="flex gap-2">+ <Input+ value={password}+ readOnly+ placeholder={t("sharing.passwordSet")}+ aria-label={t("sharing.passwordLabel")}+ className="min-w-0 font-mono text-xs tracking-wide"+ />+ <Button+ variant={copyState === "copied" && copyTarget === "password" ? "solid" : copyState === "error" && copyTarget === "password" ? "danger" : "outline"}+ className="min-w-28"+ disabled={!password}+ aria-live="polite"+ onClick={() => void copyValue("password", password)}+ >+ {copyState === "copied" && copyTarget === "password" ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}+ {t(copiedLabel("password", "sharing.passwordCopy"))}+ </Button>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="outline" size="icon" disabled={busy}+ aria-label={t("sharing.regeneratePassword")} onClick={() => onChange(true)}>+ {busy ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}+ </Button>+ </TooltipTrigger>+ <TooltipContent>{t("sharing.regeneratePassword")}</TooltipContent>+ </Tooltip>+ </div>+ {password ? (+ <Button+ variant="ghost"+ className="h-8 px-0 text-xs text-slate-600 hover:bg-transparent hover:text-slate-900"+ onClick={() => void copyValue("both", `${shareUrl}\n${t("sharing.passwordPrefix")}${password}`)}+ >+ {copyState === "copied" && copyTarget === "both" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ {t(copiedLabel("both", "sharing.copyLinkAndPassword"))}+ </Button>+ ) : null}+ </div>+ ) : null}+ </div>++ );+};diff --git a/migrations/0068_notebook_share_passwords.sql b/migrations/0068_notebook_share_passwords.sqlnew file mode 100644index 00000000..02a30197--- /dev/null+++ b/migrations/0068_notebook_share_passwords.sql@@ -0,0 +1,4 @@+ALTER TABLE notebook_shares ADD COLUMN password_hash TEXT;+ALTER TABLE notebook_shares ADD COLUMN unlock_failed_count INTEGER NOT NULL DEFAULT 0;+ALTER TABLE notebook_shares ADD COLUMN unlock_window_started_at TEXT;+ALTER TABLE notebook_shares ADD COLUMN unlock_blocked_until TEXT;diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex eec67483..57610198 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -843,6 +843,10 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {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)}`),+ unlockPublicNotebookShare: (token: string, password: string) =>+ request<{ ok: true }>(`/api/public/notebook-shares/${encodeURIComponent(token)}/unlock`, { method: "POST", body: JSON.stringify({ password }) }),+ updateNotebookShare: (id: string, input: { passwordProtected: boolean }) =>+ request<{ share: NotebookShare }>(`/api/v1/notebooks/${encodeURIComponent(id)}/share`, { method: "PATCH", body: JSON.stringify(input) }),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" }),diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 22776f81..0f86d26d 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -2568,9 +2568,12 @@ export const enUS = {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.",+ notebookProtectedScopeHint: "A password is required to view this notebook, including sub-notebooks and attachments. Content updates automatically.",+ notebookPasswordScopeHint: "The password protects only this link. Other shares are independent.",+ notebookPasswordRequiredHint: "This shared notebook is password-protected. Enter the password to view its directory, notes, and attachments.",+ notebookScopeHint: "Anyone with the link can view this notebook, including sub-notebooks and attachments. Content updates automatically.",+ notebookInheritedHint: "This notebook is also shared through a parent. These settings do not affect the parent link.",+ notebookRevokeHint: "Revoking disables this link. Other shares remain active.",notebookPublic: "Public notebook (including sub-notebooks and future content)",notebookContents: "Contents",notebookUnavailable: "This shared notebook is unavailable",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 77bd2bf2..66dc0bc0 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2557,9 +2557,12 @@ export const ja = {notebookChoose: "共有するノートブックを選択",notebookTitle: "ノートブックを共有",- notebookScopeHint: "このノートブックとすべての子ノートブックのノートや添付ファイルが公開されます。新規・移動した内容は自動で公開され、保存した編集も反映されます。リンクがあればログインせずに閲覧できます。",- notebookInheritedHint: "このノートブックは親ノートブックから公開されています。独自の共有を解除しても親の共有は継続します。親の共有を解除するか、公開範囲外に移動してください。",- notebookRevokeHint: "解除すると、このリンクからディレクトリ全体・ノート・添付ファイルにアクセスできなくなります。他のノートブックや単独のノート共有は継続します。",+ notebookProtectedScopeHint: "子ノートブックや添付ファイルを含めて閲覧するにはパスワードが必要です。内容は自動更新されます。",+ notebookPasswordScopeHint: "パスワードはこのリンクのみを保護します。他の共有には影響しません。",+ notebookPasswordRequiredHint: "この共有ノートブックはパスワードで保護されています。パスワードを入力すると、目次、ノート、添付ファイルを閲覧できます。",+ notebookScopeHint: "リンクがあれば、子ノートブックや添付ファイルを含めて閲覧できます。内容は自動更新されます。",+ notebookInheritedHint: "親ノートブックからも共有されています。ここでの設定は親のリンクには影響しません。",+ notebookRevokeHint: "解除するとこのリンクは無効になります。他の共有は継続します。",notebookPublic: "公開ノートブック(子ノートブックと今後の内容を含む)",notebookContents: "目次",notebookUnavailable: "共有ノートブックを利用できません",diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex d08ad466..3f4c93b9 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -2557,9 +2557,12 @@ export const pl = {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.",+ notebookProtectedScopeHint: "Przeglądanie notatnika, podnotatników i załączników wymaga hasła. Treść aktualizuje się automatycznie.",+ notebookPasswordScopeHint: "Hasło chroni tylko ten link. Inne udostępnienia są niezależne.",+ notebookPasswordRequiredHint: "Ten udostępniony notatnik jest chroniony hasłem. Wpisz hasło, aby zobaczyć spis treści, notatki i załączniki.",+ notebookScopeHint: "Każdy z linkiem może przeglądać notatnik, podnotatniki i załączniki. Treść aktualizuje się automatycznie.",+ notebookInheritedHint: "Notatnik jest też udostępniony przez notatnik nadrzędny. Te ustawienia nie wpływają na link nadrzędny.",+ notebookRevokeHint: "Cofnięcie wyłącza ten link. Inne udostępnienia pozostają aktywne.",notebookPublic: "Publiczny notatnik (z podnotatnikami i przyszłą treścią)",notebookContents: "Spis treści",notebookUnavailable: "Ten udostępniony notatnik jest niedostępny",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex eb7f9e35..68ec3684 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -2566,9 +2566,12 @@ export const zhCN = {notebookChoose: "选择要分享的笔记本",notebookTitle: "分享笔记本",- notebookScopeHint: "此笔记本及所有子笔记本中的笔记和附件都会公开。新增或移入的内容自动公开,编辑后的内容实时同步。任何获得链接的人都可无需登录访问。",- notebookInheritedHint: "此笔记本已通过上级笔记本公开。取消此处的独立分享不会关闭上级分享;需要在上级笔记本取消分享,或将内容移出公开范围。",- notebookRevokeHint: "取消后,此链接下的整个目录、笔记和附件停止访问。其他笔记本分享和独立笔记分享仍按各自设置生效。",+ notebookProtectedScopeHint: "输入密码即可查看整个笔记本(含子笔记本和附件),内容变更自动同步。",+ notebookPasswordScopeHint: "密码仅保护此链接,不影响其他分享。",+ notebookPasswordRequiredHint: "这个分享笔记本受密码保护。输入密码后即可查看目录、笔记和附件。",+ notebookScopeHint: "持有链接即可查看整个笔记本(含子笔记本和附件),内容变更自动同步。",+ notebookInheritedHint: "此笔记本也通过上级分享,此处的设置不影响上级链接。",+ notebookRevokeHint: "取消后此链接失效,其他分享不受影响。",notebookPublic: "公开笔记本(包含子笔记本及新增内容)",notebookContents: "目录",notebookUnavailable: "这个分享笔记本不可用",diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.tsindex e8517a61..7b4216fb 100644--- a/packages/shared/src/schemas.ts+++ b/packages/shared/src/schemas.ts@@ -421,10 +421,13 @@ export const AiPromptTemplateUpdateSchema = z.object({message: "At least one field is required.",});-export const MemoShareUpdateSchema = z.object({+export const SharePasswordUpdateSchema = z.object({passwordProtected: z.boolean(),});+export const MemoShareUpdateSchema = SharePasswordUpdateSchema;+export const NotebookShareUpdateSchema = SharePasswordUpdateSchema;+export const NoteBodyFontUpdateSchema = z.object({bodyFont: z.enum(["wenkai", "wenkai-screen", "zhuque", "source-han-serif", "neo-zhi-song", "source-han-sans", "source-serif"]).nullable(),});diff --git a/packages/shared/src/sharing.ts b/packages/shared/src/sharing.tsindex cb4f7b07..ea3fa00c 100644--- a/packages/shared/src/sharing.ts+++ b/packages/shared/src/sharing.ts@@ -24,6 +24,9 @@ export type NotebookShare = {token: string;createdAt: string;updatedAt: string;+ passwordProtected: boolean;+ /** Returned only when enabling or regenerating the password. */+ password?: string;};export type PublicNotebookShare = {