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): custom passwords and independent page controls (#735)
LuoQianhong4ad4f6db5139
diff --git a/apps/api/src/share-page.test.mjs b/apps/api/src/share-page.test.mjsindex bd6dfef0..c704d4ba 100644--- a/apps/api/src/share-page.test.mjs+++ b/apps/api/src/share-page.test.mjs@@ -99,6 +99,31 @@ describe("public memo share pages", () => {expect(html).not.toContain("old description");});+ test.each([[true, true], [true, false], [false, true], [false, false]])(+ "independently renders update time (%s) and footer branding (%s) in the first HTML response",+ async (showUpdatedAt, showBranding) => {+ const sqlite = createDatabase();+ try {+ sqlite.query("UPDATE memo_shares SET show_updated_at = ?, show_branding = ? WHERE token = ?")+ .run(Number(showUpdatedAt), Number(showBranding), token);+ const html = await (await render(sqlite, `/share/${token}`)).text();+ expect(html.includes("<time ")).toBe(showUpdatedAt);+ expect(html.includes("Published with EdgeEver</a>")).toBe(showBranding);+ if (showBranding) {+ expect(html).toContain('<footer style="');+ expect(html).toContain('href="https://edgeever.org/"');+ expect(html.indexOf("<footer ")).toBeGreaterThan(html.indexOf("</pre>"));+ }+ expect(html).not.toContain("Read-only share");+ expect(html).toContain("Hello <script>secret()</script>");+ const markdown = await (await render(sqlite, `/share/${token}.md`)).text();+ expect(markdown).toBe("# A $& $' $$ <script>\n\nHello <script>secret()</script>\n");+ } finally {+ sqlite.close();+ }+ },+ );+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");diff --git a/apps/api/src/share-page.ts b/apps/api/src/share-page.tsindex 68ddfa40..6c662b94 100644--- a/apps/api/src/share-page.ts+++ b/apps/api/src/share-page.ts@@ -10,6 +10,9 @@ type SharePageRow = {title: string | null;content_markdown: string | null;password_hash: string | null;+ updated_at: string;+ show_updated_at: number;+ show_branding: number;};export type PublicMemoSharePageTarget = {@@ -90,7 +93,7 @@ export const publicShareMarkdown = (title: string | null, body: string) => {};const loadShare = (db: DatabaseAdapter, token: string) => db.prepare(- `SELECT m.title, mc.content_markdown, ms.password_hash+ `SELECT m.title, mc.content_markdown, ms.password_hash, m.updated_at, ms.show_updated_at, ms.show_brandingFROM memo_shares msINNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_idINNER JOIN memo_contents mc ON mc.memo_id = m.id@@ -161,8 +164,14 @@ export const renderPublicMemoSharePage = async (: locked? "This shared note requires a password.": "Read a shared note on EdgeEver.";+ const updatedTime = readable && row && row.show_updated_at !== 0+ ? `<p style="font-size:.75rem;color:#64748b">Updated <time datetime="${escapeHtml(row.updated_at)}">${escapeHtml(new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" }).format(new Date(row.updated_at)))} UTC</time></p>`+ : "";+ const branding = readable && row && row.show_branding !== 0+ ? `<footer style="margin-top:2rem;font-size:.75rem;text-align:center;color:#64748b"><a href="https://edgeever.org/" style="color:inherit">Published with EdgeEver</a></footer>`+ : "";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>`+ ? `<article id="edgeever-shared-note" style="max-width:44rem;margin:1.5rem auto;padding:0 1rem"><h1>${escapeHtml(title)}</h1>${updatedTime}<pre style="white-space:pre-wrap;font:inherit">${escapeHtml(body)}</pre>${branding}</article>`: "";const metadata = `<title>${escapeHtml(`${title} · EdgeEver`)}</title><meta name="description" content="${escapeHtml(description)}">diff --git a/apps/api/src/share-routes.test.mjs b/apps/api/src/share-routes.test.mjsindex 4f9a6641..6ba3f6dc 100644--- a/apps/api/src/share-routes.test.mjs+++ b/apps/api/src/share-routes.test.mjs@@ -49,9 +49,10 @@ class SqliteD1Database {const sourceToken = "s".repeat(43);const targetToken = "t".repeat(43);-const createDatabaseEnvironment = () => {+const createDatabaseEnvironment = ({ presentationMigration = true } = {}) => {const sqlite = new Database(":memory:");for (const migration of globSync("migrations/*.sql").sort()) {+ if (!presentationMigration && migration.endsWith("0083_memo_share_presentation.sql")) continue;sqlite.exec(readFileSync(migration, "utf8"));}sqlite.query("INSERT INTO workspaces (id, name, is_personal) VALUES (?, ?, 1)")@@ -105,6 +106,69 @@ describe("public memo shares", () => {sqlite.close();});+ test("defaults both presentation settings on for migrated shares and new shares", async () => {+ const { sqlite, environment } = createDatabaseEnvironment({ presentationMigration: false });+ try {+ sqlite.exec("UPDATE memo_shares SET show_details = 0");+ const before = sqlite.query("SELECT * FROM memo_shares ORDER BY id").all();+ sqlite.exec(readFileSync("migrations/0083_memo_share_presentation.sql", "utf8"));+ expect(sqlite.prepare("SELECT * FROM memo_shares ORDER BY id").all()).toEqual(+ before.map((row) => ({ ...row, show_updated_at: 1, show_branding: 1 })),+ );+ const app = createShareApp(environment);+ for (const path of ["/api/v1/memos/memo_source/share", `/api/public/shares/${sourceToken}`]) {+ const share = (await (await app.request(path, {}, environment)).json()).share;+ expect(share).toMatchObject({ showUpdatedAt: true, showBranding: true });+ expect(share).not.toHaveProperty("showDetails");+ }+ const created = await app.request("/api/v1/memos/memo_private/share", { method: "POST" }, environment);+ expect(created.status).toBe(201);+ expect((await created.json()).share).toMatchObject({ showUpdatedAt: true, showBranding: true });+ } finally {+ sqlite.close();+ }+ });++ test("persists all four time/branding combinations independently without changing passwords", async () => {+ const { sqlite, environment } = createDatabaseEnvironment();+ const app = createShareApp(environment);+ const path = "/api/v1/memos/memo_source/share";+ const patch = (body) => app.request(path, {+ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),+ }, environment);+ try {+ const protectedShare = (await (await patch({ password: "custom-password-714" })).json()).share;+ const unlocked = await app.request(`/api/public/shares/${sourceToken}/unlock`, {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password: protectedShare.password }),+ }, environment);+ const headers = { Cookie: unlocked.headers.get("Set-Cookie").split(";")[0] };+ const passwordBefore = sqlite.query("SELECT password_hash, password_encrypted FROM memo_shares WHERE token = ?").get(sourceToken);+ for (const [payload, expected] of [+ [{ showUpdatedAt: true, showBranding: true }, { showUpdatedAt: true, showBranding: true }],+ [{ showUpdatedAt: false }, { showUpdatedAt: false, showBranding: true }],+ [{ showBranding: false }, { showUpdatedAt: false, showBranding: false }],+ [{ showUpdatedAt: true }, { showUpdatedAt: true, showBranding: false }],+ ]) {+ const response = await patch(payload);+ expect(response.status).toBe(200);+ expect((await response.json()).share).toMatchObject({ ...expected, password: protectedShare.password });+ expect((await (await app.request(path, {}, environment)).json()).share).toMatchObject(expected);+ const listed = (await (await app.request("/api/v1/memo-shares", {}, environment)).json()).shares;+ expect(listed.find((share) => share.memoId === "memo_source")).toMatchObject(expected);+ const publicResponse = await app.request(`/api/public/shares/${sourceToken}`, { headers }, environment);+ expect(publicResponse.status).toBe(200);+ expect((await publicResponse.json()).share).toMatchObject(expected);+ expect(sqlite.query("SELECT show_updated_at, show_branding FROM memo_shares WHERE token = ?").get(sourceToken))+ .toEqual({ show_updated_at: Number(expected.showUpdatedAt), show_branding: Number(expected.showBranding) });+ expect(sqlite.query("SELECT password_hash, password_encrypted FROM memo_shares WHERE token = ?").get(sourceToken))+ .toEqual(passwordBefore);+ }+ } finally {+ sqlite.close();+ }+ });+test("reads existing fonts and new catalog choices through the same stored preference", async () => {const { sqlite, environment } = createDatabaseEnvironment();sqlite.query("INSERT INTO users (id, username, password_hash, note_body_font) VALUES (?, ?, ?, ?)")@@ -429,6 +493,55 @@ describe("memo share management", () => {});describe("password-protected memo shares", () => {+ test("accepts an owner-chosen password, trims it, and keeps the password gate", async () => {+ const { sqlite, environment } = createDatabaseEnvironment();+ const app = createShareApp(environment);+ const path = "/api/v1/memos/memo_source/share";++ const enabled = await app.request(path, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password: " custom-pass " }),+ }, environment);+ expect(enabled.status).toBe(200);+ expect((await enabled.json()).share).toMatchObject({ passwordProtected: true, password: "custom-pass" });+ const stored = sqlite.query("SELECT password_hash, password_encrypted FROM memo_shares WHERE memo_id = ?").get("memo_source");+ expect(stored.password_hash).not.toContain("custom-pass");+ expect(stored.password_encrypted).not.toContain("custom-pass");++ expect((await app.request(`/api/public/shares/${sourceToken}`, {}, environment)).status).toBe(403);+ const unlocked = await app.request(`/api/public/shares/${sourceToken}/unlock`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password: "custom-pass" }),+ }, environment);+ expect(unlocked.status).toBe(200);++ const rotated = await app.request(path, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ passwordProtected: true, password: "new-pass" }),+ }, environment);+ expect((await rotated.json()).share.password).toBe("new-pass");+ sqlite.close();+ });++ test("rejects custom passwords outside the supported length", async () => {+ const { sqlite, environment } = createDatabaseEnvironment();+ const app = createShareApp(environment);+ const path = "/api/v1/memos/memo_source/share";+ for (const password of [" ", "abc", "x".repeat(65)]) {+ const response = await app.request(path, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ }, environment);+ expect(response.status).toBe(400);+ }+ expect((await (await app.request(path, {}, environment)).json()).share.passwordProtected).toBe(false);+ sqlite.close();+ });+test("keeps existing shares public until a password is enabled", async () => {const { sqlite, environment } = createDatabaseEnvironment();const app = createShareApp(environment);@@ -512,7 +625,7 @@ describe("password-protected memo shares", () => {sqlite.close();});- test("clearing the password makes the existing link public again", async () => {+ test("clearing the password ignores a supplied value and makes the existing link public again", async () => {const { sqlite, environment } = createDatabaseEnvironment();sqlite.query("UPDATE memo_shares SET password_hash = ? WHERE token = ?").run(await hashPassword("secretPwd"), sourceToken);@@ -521,7 +634,7 @@ describe("password-protected memo shares", () => {const cleared = await app.request(`/api/v1/memos/memo_source/share`, {method: "PATCH",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ passwordProtected: false }),+ body: JSON.stringify({ passwordProtected: false, password: "ignored-value" }),}, environment);expect(cleared.status).toBe(200);const clearedBody = await cleared.json();diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.tsindex 0d74aca4..cf6f54bb 100644--- a/apps/api/src/share-routes.ts+++ b/apps/api/src/share-routes.ts@@ -29,6 +29,8 @@ type MemoShareRow = {created_at: string;updated_at: string;password_hash: string | null;+ show_updated_at?: number | null;+ show_branding?: number | null;};type ManagedMemoShareRow = MemoShareRow & {title: string | null;@@ -43,6 +45,8 @@ type PublicMemoShareRow = {tags_json: string;updated_at: string;password_hash: string | null;+ show_updated_at?: number | null;+ show_branding?: number | null;note_body_font: string | null;} & NoteProseAccountRow;type ShareGateRow = {@@ -71,6 +75,8 @@ const mapMemoShare = (row: MemoShareRow, password?: string): MemoShare => ({createdAt: row.created_at,updatedAt: row.updated_at,passwordProtected: Boolean(row.password_hash),+ showUpdatedAt: row.show_updated_at !== 0,+ showBranding: row.show_branding !== 0,...(password ? { password } : {}),});@@ -97,7 +103,7 @@ const loadShareGate = async (c: AppContext, token: string) =>LIMIT 1`).bind(token).first<ShareGateRow>();-const selectMemoShareSql = `SELECT memo_id, token, slug, created_at, updated_at, password_hash, password_encrypted+const selectMemoShareSql = `SELECT memo_id, token, slug, created_at, updated_at, password_hash, password_encrypted, show_updated_at, show_brandingFROM memo_shares WHERE memo_id = ? AND workspace_id = ?`;const NOTE_PROSE_COLUMNS = `note_prose_font_size, note_prose_line_height, note_prose_palette, note_prose_custom_css, note_prose_custom_colors`;@@ -159,7 +165,7 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {if (!token) return notFound(c, "Shared note not found");const row = await c.env.storage.db.prepare(- `SELECT ms.workspace_id, m.title, mc.content_json, mc.content_markdown, m.tags_json, m.updated_at, ms.password_hash,+ `SELECT ms.workspace_id, m.title, mc.content_json, mc.content_markdown, m.tags_json, m.updated_at, ms.password_hash, ms.show_updated_at, ms.show_branding,u.note_body_font, u.note_prose_font_size, u.note_prose_line_height, u.note_prose_palette,u.note_prose_custom_css, u.note_prose_custom_colorsFROM memo_shares ms@@ -200,6 +206,8 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {memoShareTokens,bodyFont: parsePublishedNoteBodyFont(row.note_body_font),prose: publicNoteProseFromAccount(presentAccountNoteProse(row)),+ showUpdatedAt: row.show_updated_at !== 0,+ showBranding: row.show_branding !== 0,};c.header("Cache-Control", "private, no-store");c.header("X-Robots-Tag", "noindex, nofollow, noarchive");@@ -274,7 +282,7 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {const limit = Number.isSafeInteger(parsedLimit) ? Math.min(100, Math.max(1, parsedLimit)) : 50;const offset = Number.isSafeInteger(parsedOffset) ? Math.min(1_000_000, Math.max(0, parsedOffset)) : 0;const rows = await c.env.storage.db.prepare(- `SELECT ms.memo_id, ms.token, ms.slug, ms.created_at, ms.updated_at, ms.password_hash,+ `SELECT ms.memo_id, ms.token, ms.slug, ms.created_at, ms.updated_at, ms.password_hash, ms.show_updated_at, ms.show_branding,m.title, m.notebook_id, n.name AS notebook_nameFROM memo_shares msINNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id@@ -359,7 +367,7 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {c.header("Cache-Control", "private, no-store");const row = await c.env.storage.db.prepare(- `SELECT ms.memo_id, ms.token, ms.slug, ms.created_at, ms.updated_at, ms.password_hash, ms.password_encrypted+ `SELECT ms.memo_id, ms.token, ms.slug, ms.created_at, ms.updated_at, ms.password_hash, ms.password_encrypted, ms.show_updated_at, ms.show_brandingFROM memo_shares msINNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_idWHERE ms.memo_id = ? AND ms.workspace_id = ? AND m.is_deleted = 0@@ -419,7 +427,7 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {const now = isoNow();const actor = getAuditActor(c);- const { passwordProtected, slug } = c.req.valid("json");+ const { passwordProtected, password, slug, showUpdatedAt, showBranding } = c.req.valid("json");if (slug !== undefined && slug !== (existing.slug ?? null)) {if (slug !== null) {await c.env.storage.db.prepare(@@ -445,12 +453,33 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {}await audit(c.env.storage.db, actor.actorType, actor.actorId, slug ? "memo.share_slug_set" : "memo.share_slug_clear", "memo", memoId, {});}- if (passwordProtected === undefined) {+ if ((showUpdatedAt !== undefined && showUpdatedAt !== (existing.show_updated_at !== 0)) ||+ (showBranding !== undefined && showBranding !== (existing.show_branding !== 0))) {+ await c.env.storage.db.prepare(+ `UPDATE memo_shares+ SET show_updated_at = COALESCE(?, show_updated_at), show_branding = COALESCE(?, show_branding), updated_at = ?+ WHERE memo_id = ? AND workspace_id = ?`+ ).bind(+ showUpdatedAt === undefined ? null : Number(showUpdatedAt),+ showBranding === undefined ? null : Number(showBranding),+ now, memoId, workspaceId,+ ).run();+ await audit(+ c.env.storage.db,+ actor.actorType,+ actor.actorId,+ "memo.share_presentation_update",+ "memo",+ memoId,+ { showUpdatedAt, showBranding },+ );+ }+ if (passwordProtected === undefined && password === undefined) {const current = await c.env.storage.db.prepare(selectMemoShareSql).bind(memoId, workspaceId).first<MemoShareRow>() ?? existing;return c.json({ share: mapMemoShare(current, current.password_hash ? await readSharePassword(current.password_encrypted, current.token, c.env, current.password_hash) : undefined) });}- if (!passwordProtected) {+ if (passwordProtected === false) {await c.env.storage.db.prepare(`UPDATE memo_sharesSET password_hash = NULL, password_encrypted = NULL, unlock_failed_count = 0, unlock_window_started_at = NULL,@@ -463,9 +492,9 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {return c.json({ share: mapMemoShare(cleared ?? { ...existing, password_hash: null, updated_at: now }) });}- const password = generateSharePassword();- const passwordHash = await hashPassword(password);- const encrypted = await encryptSharePassword(password, existing.token, c.env);+ const nextPassword = password ?? generateSharePassword();+ const passwordHash = await hashPassword(nextPassword);+ const encrypted = await encryptSharePassword(nextPassword, existing.token, c.env);await c.env.storage.db.prepare(`UPDATE memo_sharesSET password_hash = ?, password_encrypted = ?, unlock_failed_count = 0, unlock_window_started_at = NULL,@@ -479,11 +508,11 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {existing.password_hash ? "memo.share_password_rotate" : "memo.share_password_set","memo",memoId,- {},+ { custom: Boolean(password) },);const updated = await c.env.storage.db.prepare(selectMemoShareSql).bind(memoId, workspaceId).first<MemoShareRow>();- return c.json({ share: mapMemoShare(updated ?? { ...existing, password_hash: passwordHash, updated_at: now }, password) });+ return c.json({ share: mapMemoShare(updated ?? { ...existing, password_hash: passwordHash, updated_at: now }, nextPassword) });});app.delete("/api/v1/memos/:id/share", async (c) => {diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsxindex 4c3b1049..130c7dcb 100644--- a/apps/web/src/components/PublicSharePage.tsx+++ b/apps/web/src/components/PublicSharePage.tsx@@ -3,7 +3,7 @@ import { Node, mergeAttributes } from "@tiptap/core";import Image from "@tiptap/extension-image";import { EditorContent, useEditor, ReactNodeViewRenderer } from "@tiptap/react";import { useMutation, useQuery } from "@tanstack/react-query";-import { Clock3, FileText, LoaderCircle, LockKeyhole, ShieldCheck } from "lucide-react";+import { Clock3, FileText, LoaderCircle, LockKeyhole } from "lucide-react";import { lazy, Suspense, useContext, useEffect, useMemo, useRef, useState, type CSSProperties, type FormEvent, type MouseEvent } from "react";import { useTranslation } from "react-i18next";import { useParams } from "react-router";@@ -326,6 +326,8 @@ export const PublicShareArticle = ({const containerRef = useRef<HTMLDivElement>(null);const openSearch = useContext(NotebookSiteSearchContext);const publishedBodyFont = parsePublishedNoteBodyFont(share.bodyFont);+ const showUpdatedAt = layout === "site" || share.showUpdatedAt !== false;+ const showBranding = layout === "standalone" && share.showBranding !== false;useEffect(() => {if (publishedBodyFont === undefined) return undefined;@@ -366,28 +368,6 @@ export const PublicShareArticle = ({: "border-b border-slate-200 py-6 sm:py-8",)}>- <div- className={cn(- "flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-slate-500",- layout === "site" ? "order-2 mt-4" : "mb-5",- )}- >- {layout === "standalone" && (- <span className="flex shrink-0 items-center gap-1.5 font-semibold text-slate-700">- <ShieldCheck className="h-4 w-4" /> EdgeEver ·{" "}- {t("sharing.readOnly")}- </span>- )}- <span className="flex items-center gap-1.5">- <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><h1className={cn("break-words text-3xl font-bold tracking-tight text-slate-950 sm:text-4xl",@@ -396,6 +376,24 @@ export const PublicShareArticle = ({>{getMemoDisplayTitle(share.title, t("common.untitledMemo"))}</h1>+ {showUpdatedAt ? (+ <div+ className={cn(+ "mt-4 flex items-center gap-1.5 text-xs text-slate-500",+ layout === "site" && "order-2",+ )}+ >+ <Clock3 className="h-4 w-4" />+ <time dateTime={share.updatedAt}>+ {t("sharing.publicUpdated", {+ time: new Intl.DateTimeFormat(+ i18n.resolvedLanguage || i18n.language,+ { dateStyle: "medium", timeStyle: "short" },+ ).format(new Date(share.updatedAt)),+ })}+ </time>+ </div>+ ) : null}{share.tags.length > 0 ? (<divclassName={cn(@@ -439,6 +437,18 @@ export const PublicShareArticle = ({site={layout === "site"}/></div>+ {showBranding ? (+ <footer className="px-5 pb-6 pt-2 text-center text-xs text-slate-500 sm:px-10 sm:pb-8">+ <a+ href="https://edgeever.org/"+ target="_blank"+ rel="noopener noreferrer"+ className="rounded-sm transition-colors hover:text-slate-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400"+ >+ {t("sharing.publishedWith")}+ </a>+ </footer>+ ) : null}</article>{layout === "site" && <NotebookSiteArticleTools containerRef={containerRef} token={token} memoUrls={access?.memoUrls ?? {}} />}</div>diff --git a/apps/web/src/components/dialogs/ShareMemoDialog.tsx b/apps/web/src/components/dialogs/ShareMemoDialog.tsxindex c35e68d6..ba506abe 100644--- a/apps/web/src/components/dialogs/ShareMemoDialog.tsx+++ b/apps/web/src/components/dialogs/ShareMemoDialog.tsx@@ -6,6 +6,7 @@ import { Link, useLocation } from "react-router";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";import { memoSharePathSegment } from "@edgeever/shared";import { SharePasswordControls } from "./SharePasswordControls";import { ShareSlugControls } from "./ShareSlugControls";@@ -55,7 +56,15 @@ export const ShareMemoDialog = ({},});const passwordMutation = useMutation({- mutationFn: (passwordProtected: boolean) => api.updateMemoShare(memoId, { passwordProtected }),+ mutationFn: ({ passwordProtected, password }: { passwordProtected: boolean; password?: string }) =>+ api.updateMemoShare(memoId, { passwordProtected, ...(password ? { password } : {}) }),+ onSuccess: (data) => {+ queryClient.setQueryData(queryKey, data);+ void queryClient.invalidateQueries({ queryKey: ["memo-shares"] });+ },+ });+ const presentationMutation = useMutation({+ mutationFn: (settings: { showUpdatedAt?: boolean; showBranding?: boolean }) => api.updateMemoShare(memoId, settings),onSuccess: (data) => {queryClient.setQueryData(queryKey, data);void queryClient.invalidateQueries({ queryKey: ["memo-shares"] });@@ -78,6 +87,7 @@ export const ShareMemoDialog = ({useEffect(() => {createMutation.reset();passwordMutation.reset();+ presentationMutation.reset();slugMutation.reset();revokeMutation.reset();setCopyState("idle");@@ -92,9 +102,9 @@ export const ShareMemoDialog = ({const shareUrl = share ? getPublicShareUrl(memoSharePathSegment(share)) : "";const markdownUrl = shareUrl ? `${shareUrl}.md` : "";- const isWorking = shareQuery.isLoading || createMutation.isPending || passwordMutation.isPending || slugMutation.isPending || revokeMutation.isPending;+ const isWorking = shareQuery.isLoading || createMutation.isPending || passwordMutation.isPending || presentationMutation.isPending || slugMutation.isPending || revokeMutation.isPending;const slugTaken = slugMutation.error instanceof ApiRequestError && slugMutation.error.code === "share_slug_taken";- const error = shareQuery.error || createMutation.error || passwordMutation.error || (slugTaken ? null : slugMutation.error) || revokeMutation.error;+ const error = shareQuery.error || createMutation.error || passwordMutation.error || presentationMutation.error || (slugTaken ? null : slugMutation.error) || revokeMutation.error;const markCopied = (target: "link" | "password" | "both" | "markdown", copied: boolean) => {setCopyTarget(target);@@ -207,9 +217,39 @@ export const ShareMemoDialog = ({busy={isWorking}shareUrl={shareUrl}hideCopyBoth={true}- onChange={(enabled) => passwordMutation.mutate(enabled)}+ allowCustomPassword={true}+ onChange={(enabled, password) => {+ const payload = { passwordProtected: enabled, password };+ if (password !== undefined) {+ return passwordMutation.mutateAsync(payload).then(() => undefined);+ }+ passwordMutation.mutate(payload);+ }}/>+ <div className="space-y-3 border-t border-slate-100 pt-3">+ <div className="flex items-center justify-between gap-3">+ <label htmlFor="share-show-updated-at" className="text-sm font-medium text-slate-800">{t("sharing.showUpdatedAt")}</label>+ <Switch+ id="share-show-updated-at"+ aria-label={t("sharing.showUpdatedAt")}+ checked={share.showUpdatedAt !== false}+ disabled={isWorking}+ onCheckedChange={(enabled) => presentationMutation.mutate({ showUpdatedAt: enabled })}+ />+ </div>+ <div className="flex items-center justify-between gap-3">+ <label htmlFor="share-show-branding" className="text-sm font-medium text-slate-800">{t("sharing.showBranding")}</label>+ <Switch+ id="share-show-branding"+ aria-label={t("sharing.showBranding")}+ checked={share.showBranding !== false}+ disabled={isWorking}+ onCheckedChange={(enabled) => presentationMutation.mutate({ showBranding: enabled })}+ />+ </div>+ </div>+{share.passwordProtected ? null : (<ShareQrCode key={`qr-${share.token}`} url={shareUrl} hint={t("sharing.qrCodeHint")} />)}diff --git a/apps/web/src/components/dialogs/SharePasswordControls.tsx b/apps/web/src/components/dialogs/SharePasswordControls.tsxindex 65818ebd..c256b3f5 100644--- a/apps/web/src/components/dialogs/SharePasswordControls.tsx+++ b/apps/web/src/components/dialogs/SharePasswordControls.tsx@@ -15,17 +15,22 @@ export const SharePasswordControls = ({shareUrl,onChange,hideCopyBoth = false,+ allowCustomPassword = false,}: {passwordProtected: boolean;password: string;busy: boolean;shareUrl: string;- onChange: (enabled: boolean) => void;+ onChange: (enabled: boolean, password?: string) => Promise<void> | void;hideCopyBoth?: boolean;+ allowCustomPassword?: boolean;}) => {const { t } = useTranslation();const [copyState, setCopyState] = useState<"idle" | "copied" | "error">("idle");const [copyTarget, setCopyTarget] = useState<"password" | "both">("password");+ const [customMode, setCustomMode] = useState(false);+ const [customPassword, setCustomPassword] = useState("");+ const [customError, setCustomError] = useState(false);const resetTimer = useRef<number | null>(null);useEffect(() => () => { if (resetTimer.current !== null) window.clearTimeout(resetTimer.current); }, []);const copyValue = async (target: "password" | "both", value: string) => {@@ -37,6 +42,24 @@ export const SharePasswordControls = ({};const copiedLabel = (target: "password" | "both", idleKey: string) =>copyTarget === target && copyState === "copied" ? "sharing.copied" : copyTarget === target && copyState === "error" ? "sharing.copyFailed" : idleKey;+ const closeCustomMode = () => {+ setCustomMode(false);+ setCustomPassword("");+ setCustomError(false);+ };+ const submitCustomPassword = async () => {+ const value = customPassword.trim();+ if (value.length < 4 || value.length > 64) {+ setCustomError(true);+ return;+ }+ try {+ await onChange(true, value);+ closeCustomMode();+ } catch {+ // The parent mutation renders the shared error message.+ }+ };return (<div className="space-y-2 pt-1"><div className="flex items-center justify-between gap-3">@@ -44,7 +67,10 @@ export const SharePasswordControls = ({<Switchchecked={passwordProtected}disabled={busy}- onCheckedChange={(enabled) => onChange(enabled)}+ onCheckedChange={(enabled) => {+ if (allowCustomPassword) closeCustomMode();+ onChange(enabled);+ }}aria-label={t("sharing.passwordToggle")}/></div>@@ -108,6 +134,51 @@ export const SharePasswordControls = ({) : null}</div>) : null}+ {allowCustomPassword && customMode ? (+ <div className="space-y-2 rounded-lg border border-slate-200 bg-slate-50 p-3">+ <Input+ type="password"+ value={customPassword}+ disabled={busy}+ minLength={4}+ maxLength={64}+ autoComplete="new-password"+ autoFocus+ aria-label={t("sharing.passwordCustomLabel")}+ aria-invalid={customError}+ placeholder={t("sharing.passwordCustomPlaceholder")}+ onChange={(event) => {+ setCustomPassword(event.target.value);+ setCustomError(false);+ }}+ />+ <p className={`text-xs leading-5 ${customError ? "text-rose-600" : "text-slate-500"}`} role={customError ? "alert" : undefined}>+ {t(customError ? "sharing.passwordCustomInvalid" : "sharing.passwordCustomHint")}+ </p>+ <div className="flex items-center gap-2">+ <Button type="button" size="sm" variant="solid" disabled={busy} onClick={() => void submitCustomPassword()}>+ {busy ? <LoaderCircle className="h-3.5 w-3.5 animate-spin" /> : null}+ {t("sharing.passwordCustomSave")}+ </Button>+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={closeCustomMode}>+ {t("sharing.passwordCustomCancel")}+ </Button>+ </div>+ </div>+ ) : allowCustomPassword ? (+ <Button+ type="button"+ variant="ghost"+ className="h-7 px-0 text-xs text-slate-600 hover:bg-transparent hover:text-slate-900"+ disabled={busy}+ onClick={() => {+ setCustomMode(true);+ setCustomError(false);+ }}+ >+ {t("sharing.passwordCustomAction")}+ </Button>+ ) : null}</div>);};diff --git a/docs/changes/2026-10-30-share-options.md b/docs/changes/2026-10-30-share-options.mdnew file mode 100644index 00000000..4c897398--- /dev/null+++ b/docs/changes/2026-10-30-share-options.md@@ -0,0 +1,33 @@+# Share options: custom password, update time and branding++[简体中文](2026-10-30-share-options.zh-CN.md) · [Issue #714](https://github.com/tianma-if/edgeever/issues/714)++## Problem and outcome++Complete the remaining sharing options from #714 and the [presentation requirements in PR #735](https://github.com/tianma-if/edgeever/pull/735#issuecomment-6521859852). Share owners can choose a password and independently control the public page's last-updated time and EdgeEver branding. Both presentation settings default to on, including for existing shares. QR PNG/SVG download is already released and is outside this change.++## Allowed changes and acceptance++1. **Custom password.** Extend the existing single-note share PATCH contract so a password-protected share can accept an explicit password in addition to the existing generated-password flow. Preserve `passwordProtected`-only clients, hashing/encryption-at-rest, unlock rate limiting, cookie invalidation, and password return behavior. Explicit passwords must be trimmed and contain 4–64 characters; reject empty, shorter, longer, or whitespace-only values without changing the share. The dialog offers generated-password and custom-password modes, shows the custom input while the owner is editing/creating it, and keeps existing authenticated password readback, regenerate, and copy behavior. Preserve `passwordProtected: false` disabling semantics without adding a combined-field rejection for an accompanying valid password. Disable custom input while saving; on failure retain the draft and original share state, display the existing error, and avoid unhandled promises. Test API compatibility, validation, hashing, replacement, old clients, and failed/pending saves.+2. **Independent presentation settings.** Replace the single `showDetails` API/UI field with `showUpdatedAt` and `showBranding`, stored as two independent columns. Both default to true for new and existing shares; clients also treat omitted fields as true. The owner can change either without changing the other or the password. Remove the EdgeEver/read-only header label. Keep the optional last-updated time near the title, and render optional branding as a small, muted, normal-flow footer linking “Published with EdgeEver” to `https://edgeever.org/`. No floating or sticky badge. Apply the settings to the standalone public HTML fallback and client renderer; notebook-sharing presentation, note content, title/meta behavior, Markdown endpoint, resources, password gate and slug/token stay unchanged. Cover all four combinations, persisted readback and defaults for old rows.+3. Update shared schemas/types, API rows/mappers, the client, Web/desktop share dialog and all existing locale catalogs needed by the touched UI. Use established share components and API error patterns without redundant switch descriptions. Add migration `0083_memo_share_presentation.sql` with two `NOT NULL DEFAULT 1` columns. Preserve migration 0082 and its now-unused `show_details` column so previously migrated databases and application rollback remain supported.+4. Sync the PR branch with upstream main, including its existing font-regression test correction, without independently changing font behavior. Verify the merged PR through its Ubuntu Test and container-build workflows.++Acceptance: write focused presentation tests before implementation and exercise the actual dialog and public page in an isolated local instance. Cover the four settings combinations, persistence after reopening, old-share migration/defaults, password-protected rendering, and unchanged notebook presentation. Reuse valid password checks and rerun changed API/shared/Web paths, `bun run typecheck`, `bun run typecheck:mobile`, and `bun run build:web`. Verify old routes/schema → migrations 0082/0083 → new routes → old-route rollback using SQLite. Record real failures and unverified native/production paths.++## Boundaries and risk++No QR download changes, notebook-share behavior, authentication redesign, backup/sync changes, unrelated sharing refactors, release/version/deployment changes, or destructive data operations.++Worst outcomes are locking out a share through an incompatible password update or hiding metadata/content incorrectly on a public page. Rollback is reverting application changes and retaining the additive columns. The migration and old-client behavior require explicit verification. Real production Cloudflare/Docker and installed desktop acceptance are outside this local change unless separately requested.++## Completion check++Custom passwords and both independent presentation settings are implemented. The active contract uses `showUpdatedAt` and `showBranding`; migration 0083 defaults both to on. The old header label is removed and optional branding is a normal-flow footer. Notebook-sharing behavior, QR downloads and deployment configuration are unchanged.++- 81 focused API, public-HTML, notebook, shared, dialog and menu tests passed, including all four combinations and old-row defaults. Locale tests (5) and the corrected upstream font tests (6) passed. Type checks, Web build, lint and diff checks passed; see [validation results](evidence/2026-10-30-share-options/validation.json) and [focused tests](evidence/2026-10-30-share-options/share-tests.txt).+- [Browser acceptance](evidence/2026-10-30-share-options/presentation-browser.json) covers the two switches, all four actual page combinations, persistence after reopening and password-protected rendering. Captures: [controls](evidence/2026-10-30-share-options/presentation-controls.png), [both enabled](evidence/2026-10-30-share-options/presentation-both.png), [time only](evidence/2026-10-30-share-options/presentation-time.png), [branding only](evidence/2026-10-30-share-options/presentation-branding.png), and [both hidden](evidence/2026-10-30-share-options/presentation-hidden.png). Earlier [password failure/pending checks](evidence/2026-10-30-share-options/password-controls-regression.json) remain applicable to the unchanged password controls.+- [Cross-version acceptance](evidence/2026-10-30-share-options/cross-version.mjs) covers baseline `e052ac3b` share routes/schema → SQLite migrations 0082/0083 → new routes → baseline route read/update. It verifies preserved old rows, pre-upgrade unlock continuity, and password/cookie invalidation for body and attachments after replacement. It uses test object storage and validates API/database compatibility, not installed-application upgrades.+- Upstream main, including its font-test correction, is merged. Full Ubuntu Test and container-build results are available in [PR #735 checks](https://github.com/tianma-if/edgeever/pull/735/checks).++Installed native desktop apps and production Cloudflare/Docker deployments are unverified; no mobile feature changes are included. Apply migrations 0082 and 0083 before deploying the application. Rollback can retain the added columns and revert application code; baseline share-route read/update compatibility was verified. No out-of-scope behavior changes were introduced.diff --git a/docs/changes/2026-10-30-share-options.zh-CN.md b/docs/changes/2026-10-30-share-options.zh-CN.mdnew file mode 100644index 00000000..da7023d7--- /dev/null+++ b/docs/changes/2026-10-30-share-options.zh-CN.md@@ -0,0 +1,33 @@+# 分享选项:自定义密码、更新时间与品牌++[English](2026-10-30-share-options.md) · [Issue #714](https://github.com/tianma-if/edgeever/issues/714)++## 问题与目标++完成 #714 剩余分享选项及 [PR #735 的展示要求](https://github.com/tianma-if/edgeever/pull/735#issuecomment-6521859852):分享者可以自行设置访问密码,并独立控制公开页的最后更新时间和 EdgeEver 品牌。两个展示设置均默认开启,包括已有分享。二维码 PNG/SVG 下载已经发布,不属于本次改动。++## 允许变更与验收++1. **自定义密码。** 扩展现有单笔记分享 PATCH 契约,在保留自动生成密码流程的同时允许密码保护分享接收显式密码。保留只发送 `passwordProtected` 的旧客户端、哈希/静态加密、解锁限流、Cookie 失效和密码返回行为。显式密码先去除首尾空白,长度必须为4–64个字符;空值、过短、过长或只含空白的输入拒绝且不修改分享。对话框提供自动生成/自定义两种模式,自定义输入只在编辑/创建期间显示,并保留现有管理端密码读取、重新生成和复制行为。保留 `passwordProtected: false` 的关闭语义,不因随附有效密码增加组合拒绝条件。保存期间禁用自定义密码输入,失败时保留输入和原分享状态、显示现有错误,不产生未处理的 Promise。测试 API 兼容、校验、哈希、替换、旧客户端以及保存失败/处理中状态。+2. **独立展示设置。** 将 API/UI 的单一 `showDetails` 字段替换为 `showUpdatedAt` 和 `showBranding`,分别持久化。新分享和已有分享均默认开启;客户端将缺省字段视为开启。修改其中一个不改变另一个或密码。移除 EdgeEver/只读分享页头标识;启用时在标题附近显示最后更新时间,品牌以小号、弱化、普通文档流中的页脚链接展示“使用 EdgeEver 发布”,指向 `https://edgeever.org/`,不使用悬浮或吸附徽章。独立公开页的 HTML 后备展示与客户端均遵守设置;笔记本分享展示、正文、标题/元数据、Markdown 接口、资源、密码门禁和 slug/token 不变。覆盖四种组合、持久化读回和旧行默认值。+3. 更新共享 schema/类型、API 行映射、客户端、Web/桌面分享对话框和涉及的全部语言目录。复用现有分享组件和 API 错误模式,不增加重复开关说明。新增 `0083_memo_share_presentation.sql`,增加两个 `NOT NULL DEFAULT 1` 字段。保留 migration 0082 及不再使用的 `show_details` 字段,支持已迁移数据库和应用代码回退。+4. 将上游 main 合入 PR 分支,包含其已有字体回归测试修正,不另改字体行为。通过 PR 的 Ubuntu Test 和容器构建工作流验证合并结果。++验收:先编写针对性展示测试,再实现;在隔离本地实例实际操作对话框和公开页。覆盖四种开关组合、重新打开后的持久化、旧分享迁移/默认值、密码保护展示及笔记本原展示。复用仍有效的密码验收,重跑变化的 API/shared/Web 路径,以及 `bun run typecheck`、`bun run typecheck:mobile`、`bun run build:web`。使用 SQLite 验证旧路由/schema → migration 0082/0083 → 新路由 → 旧路由回退。记录真实失败及未验证的原生/生产路径。++## 边界与风险++不改二维码下载、笔记本分享、认证设计、备份/同步、无关分享重构、发版/版本号/部署,也不删除用户数据。++最坏后果是密码更新导致分享无法解锁,或公开页错误隐藏元数据/内容。回退是撤回应用代码并保留追加字段。migration 和旧客户端行为需要明确验证。真实 Cloudflare/Docker 生产及已安装桌面端验收不在本地变更范围,除非另行要求。++## 完成核对++自定义密码和两个独立展示设置均已实现。当前契约使用 `showUpdatedAt` 和 `showBranding`;migration 0083 将两项默认设为开启。旧页头标识已移除,可选品牌以普通文档流页脚展示。笔记本分享行为、二维码下载和部署配置保持不变。++- 81 项针对性 API、公开 HTML、笔记本、shared、对话框和菜单测试通过,覆盖四种组合和旧行默认值。语言目录测试 5 项、上游已修正的字体测试 6 项通过。类型检查、Web 构建、lint 和 diff 检查通过,见[验证结果](evidence/2026-10-30-share-options/validation.json)和[针对性测试](evidence/2026-10-30-share-options/share-tests.txt)。+- [浏览器验收](evidence/2026-10-30-share-options/presentation-browser.json)覆盖两个开关、四种实际页面组合、重新打开后的持久化和密码保护展示。截图:[开关](evidence/2026-10-30-share-options/presentation-controls.png)、[全部显示](evidence/2026-10-30-share-options/presentation-both.png)、[仅时间](evidence/2026-10-30-share-options/presentation-time.png)、[仅品牌](evidence/2026-10-30-share-options/presentation-branding.png)、[全部隐藏](evidence/2026-10-30-share-options/presentation-hidden.png)。此前[密码失败/处理中检查](evidence/2026-10-30-share-options/password-controls-regression.json)仍适用于未改动的密码控件。+- [跨版本验收](evidence/2026-10-30-share-options/cross-version.mjs)覆盖基线 `e052ac3b` 分享路由/schema → SQLite migration 0082/0083 → 新路由 → 旧路由读取和更新。结果验证旧行保留、升级后旧解锁有效、换密码使旧密码/Cookie 对正文和附件失效。使用测试对象存储,属于 API/数据库兼容验证,不是已安装应用升级测试。+- 已合入上游 main 及其字体测试修正。完整 Ubuntu Test 和容器构建结果见 [PR #735 检查](https://github.com/tianma-if/edgeever/pull/735/checks)。++未验证已安装原生桌面端及真实 Cloudflare/Docker 生产环境;没有移动端功能变更。部署时先应用 migration 0082 和 0083,再部署应用。回退可保留新增字段并撤回应用代码;旧分享路由读取和更新已验证。没有引入清单外行为变化。diff --git a/docs/changes/evidence/2026-10-30-share-options/browser.json b/docs/changes/evidence/2026-10-30-share-options/browser.jsonnew file mode 100644index 00000000..f2f74dc9--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/browser.json@@ -0,0 +1,26 @@+{+ "runtime": "Local workerd with the production Web bundle in Chromium",+ "data": "Isolated demo/test fixtures",+ "status": "passed",+ "checks": [+ "Create an unprotected share and see details by default",+ "Hide details: header label and timestamp disappear; note title, tags and body remain",+ "Three-character custom password shows validation and leaves protection disabled",+ "Trimmed Chinese custom password saves; incorrect password rejected; correct password unlocks",+ "Replace custom password; prior browser unlock no longer grants access; new password unlocks",+ "Restore details while protected without invalidating the current unlock",+ "Generated eight-character password unlocks",+ "Protected raw Markdown returns 403 even after browser unlock; disabling protection restores 200",+ "Close and reopen management dialog: password protection false and details true persisted"+ ],+ "screenshots": [+ "custom-invalid.png",+ "details-hidden.png",+ "details-visible.png",+ "reopened.png"+ ],+ "limits": [+ "No installed native desktop or production deployment tested"+ ],+ "failureAndPendingRegression": "password-controls-regression.json"+}diff --git a/docs/changes/evidence/2026-10-30-share-options/cross-version.json b/docs/changes/evidence/2026-10-30-share-options/cross-version.jsonnew file mode 100644index 00000000..d23c4d95--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/cross-version.json@@ -0,0 +1,13 @@+{+ "baseline": "e052ac3b54bdcba4b2c452e6b06c091b1e2c70f4",+ "checks": [+ "Baseline routes and schema create and unlock a generated-password share before migration 0082",+ "Migrations 0082/0083 preserve every old row value; new routes accept the pre-upgrade unlock and enable both presentation settings by default",+ "Changing only presentation preserves password and existing unlock",+ "Invalid lengths leave the entire share unchanged; lengths 4/64 and trimmed Chinese passwords unlock",+ "Custom password replacement invalidates the old password and cookie for both body and attachment; new unlock works",+ "Password-protected raw Markdown remains blocked and password storage is not plaintext",+ "Baseline application reads new custom passwords and regenerates after migration; old-style disable restores public Markdown without changing presentation"+ ],+ "status": "passed"+}diff --git a/docs/changes/evidence/2026-10-30-share-options/cross-version.mjs b/docs/changes/evidence/2026-10-30-share-options/cross-version.mjsnew file mode 100644index 00000000..bdd545d4--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/cross-version.mjs@@ -0,0 +1,121 @@+// Run from the repository root: bun docs/changes/evidence/2026-10-30-share-options/cross-version.mjs+import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { readFileSync, writeFileSync, unlinkSync, globSync } from 'node:fs';+import { resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { Database } from 'bun:sqlite';+import { Hono } from 'hono';+import * as current from '../../../../apps/api/src/share-routes.ts';+import { renderPublicMemoSharePage } from '../../../../apps/api/src/share-page.ts';+const baseline = 'e052ac3b54bdcba4b2c452e6b06c091b1e2c70f4';+const oldRoute = resolve(`apps/api/src/.714-baseline-${process.pid}.ts`);+const oldSchema = resolve(`packages/shared/src/.714-baseline-${process.pid}.ts`);+const sql = new Database(':memory:');+class Statement {+ constructor(query, args = []) { this.query = query; this.args = args; }+ bind(...args) { return new Statement(this.query, args); }+ async first() { return sql.prepare(this.query).get(...this.args); }+ async all() { return { results: sql.prepare(this.query).all(...this.args), success: true }; }+ async run() { sql.prepare(this.query).run(...this.args); return { success: true }; }+}+const db = { prepare: (query) => new Statement(query), batch: async (statements) => {+ return sql.transaction(() => statements.map(s => sql.prepare(s.query).run(...s.args)))();+} };+const env = { EDGE_EVER_CREDENTIALS_ENCRYPTION_KEY: 'isolated-714-test-key', storage: { db, resources: {+ get: async () => ({body: new Blob(['attachment-714']).stream(), size: 14, writeHttpMetadata() {}}),+} } };+const appFor = (routes) => {+ const app = new Hono();+ app.use('/api/v1/*', async (c, next) => {+ c.set('auth', { kind: 'user', actorType: 'user', actorId: null, scopes: [], workspaceId: 'ws_714', role: 'member' });+ await next();+ });+ routes.registerMemoShareRoutes(app); routes.registerPublicShareRoutes(app); return app;+};+const request = (app, path, method = 'GET', body, cookie) => app.request(path, {+ method, headers: { 'Content-Type': 'application/json', ...(cookie ? {Cookie: cookie} : {}) },+ ...(body ? {body: JSON.stringify(body)} : {}),+}, env);+const sharePath = '/api/v1/memos/memo_714/share';+const results = { baseline, checks: [] };+const check = (name) => results.checks.push(name);+try {+ writeFileSync(oldSchema, execFileSync('git', ['show', `${baseline}:packages/shared/src/schemas.ts`]));+ const oldSource = execFileSync('git', ['show', `${baseline}:apps/api/src/share-routes.ts`], {encoding:'utf8'});+ writeFileSync(oldRoute, oldSource.replace('MemoShareUpdateSchema, ', '') + `\nimport { MemoShareUpdateSchema } from ${JSON.stringify(oldSchema)};\n`);+ const old = appFor(await import(pathToFileURL(oldRoute).href));+ for (const file of globSync('migrations/*.sql').sort()) {+ if (file < 'migrations/0082_') sql.exec(readFileSync(file,'utf8'));+ }+ sql.exec(`INSERT INTO workspaces(id,name,is_personal) VALUES('ws_714','Isolated acceptance',1);+ INSERT INTO notebooks(id,workspace_id,name) VALUES('nb_714','ws_714','Inbox');+ INSERT INTO memos(id,workspace_id,notebook_id,title) VALUES('memo_714','ws_714','nb_714','Migration acceptance');+ INSERT INTO memo_contents(memo_id,content_json,content_markdown,content_hash) VALUES('memo_714','{"type":"doc","content":[]}','Unchanged body','test');+ INSERT INTO resources(id,memo_id,object_key,kind,mime_type,filename,byte_size) VALUES('res_714','memo_714','714','attachment','text/plain','test.txt',14);`);+ assert.equal((await request(old,sharePath,'POST',{})).status,201);+ const protectedShare = (await (await request(old,sharePath,'PATCH',{passwordProtected:true})).json()).share;+ assert.equal(protectedShare.password.length,8);+ const base = `/api/public/shares/${protectedShare.token}`;+ const unlock = async (app,password) => request(app,`${base}/unlock`,'POST',{password});+ const oldUnlocked = await unlock(old,protectedShare.password);+ assert.equal(oldUnlocked.status,200);+ const cookie = oldUnlocked.headers.get('set-cookie').split(';')[0];+ check('Baseline routes and schema create and unlock a generated-password share before migration 0082');+ const before = sql.prepare('SELECT * FROM memo_shares').get();+ sql.exec(readFileSync('migrations/0082_memo_share_options.sql','utf8'));+ sql.exec(readFileSync('migrations/0083_memo_share_presentation.sql','utf8'));+ const after = sql.prepare('SELECT * FROM memo_shares').get();+ assert.deepEqual(after,{...before,show_details:1,show_updated_at:1,show_branding:1});+ const next = appFor(current);+ assert.equal((await request(next,base,'GET',null,cookie)).status,200);+ const migratedShare=(await (await request(next,sharePath)).json()).share;+ assert.equal(migratedShare.showUpdatedAt,true);+ assert.equal(migratedShare.showBranding,true);+ check('Migrations 0082/0083 preserve every old row value; new routes accept the pre-upgrade unlock and enable both presentation settings by default');+ const hidden = await request(next,sharePath,'PATCH',{showUpdatedAt:false,showBranding:true});+ assert.equal((await hidden.json()).share.password,protectedShare.password);+ assert.equal((await request(next,base,'GET',null,cookie)).status,200);+ check('Changing only presentation preserves password and existing unlock');+ for (const password of ['', ' ', 'abc', 'x'.repeat(65)]) {+ const beforeInvalid = sql.prepare('SELECT * FROM memo_shares').get();+ assert.equal((await request(next,sharePath,'PATCH',{password,showBranding:false})).status,400);+ assert.deepEqual(sql.prepare('SELECT * FROM memo_shares').get(),beforeInvalid);+ }+ for (const password of ['abcd','x'.repeat(64),' 分享验收714 ']) {+ const response=await request(next,sharePath,'PATCH',{passwordProtected:true,password});+ assert.equal(response.status,200);+ assert.equal((await response.json()).share.password,password.trim());+ assert.equal((await unlock(next,password.trim())).status,200);+ }+ check('Invalid lengths leave the entire share unchanged; lengths 4/64 and trimmed Chinese passwords unlock');+ assert.equal((await unlock(next,protectedShare.password)).status,403);+ assert.equal((await request(next,base,'GET',null,cookie)).status,403);+ assert.equal((await request(next,`${base}/resources/res_714/blob`,'GET',null,cookie)).status,403);+ const fresh = (await unlock(next,'分享验收714')).headers.get('set-cookie').split(';')[0];+ assert.equal((await request(next,`${base}/resources/res_714/blob`,'GET',null,fresh)).status,200);+ check('Custom password replacement invalidates the old password and cookie for both body and attachment; new unlock works');+ const lockedMd=await renderPublicMemoSharePage(new Request(`http://localhost/share/${protectedShare.token}.md`),db,async()=>new Response('<div id="root"></div>'));+ assert.equal(lockedMd.status,403);+ const stored=sql.prepare('SELECT password_hash,password_encrypted FROM memo_shares').get();+ assert(!stored.password_hash.includes('分享验收714')); assert(!stored.password_encrypted.includes('分享验收714'));+ check('Password-protected raw Markdown remains blocked and password storage is not plaintext');+ // Old clients and an application rollback continue using their original contract.+ const oldRead=(await (await request(old,sharePath)).json()).share;+ assert.equal(oldRead.password,'分享验收714');+ assert.equal((await request(old,base,'GET',null,fresh)).status,200);+ const regenerated=(await (await request(old,sharePath,'PATCH',{passwordProtected:true})).json()).share;+ assert.equal(regenerated.password.length,8);+ assert.deepEqual(sql.prepare('SELECT show_updated_at,show_branding FROM memo_shares').get(),{show_updated_at:0,show_branding:1});+ assert.equal((await request(next,sharePath,'PATCH',{passwordProtected:false})).status,200);+ assert.equal((await request(next,base)).status,200);+ const markdown=await renderPublicMemoSharePage(new Request(`http://localhost/share/${protectedShare.token}.md`),db,async()=>new Response('<div id="root"></div>'));+ assert.equal(markdown.status,200); assert.equal(await markdown.text(),'# Migration acceptance\n\nUnchanged body');+ check('Baseline application reads new custom passwords and regenerates after migration; old-style disable restores public Markdown without changing presentation');+ results.status='passed';+ writeFileSync(new URL('./cross-version.json',import.meta.url),JSON.stringify(results,null,2)+'\n');+ console.log(JSON.stringify(results,null,2));+} finally {+ sql.close();+ for (const path of [oldRoute,oldSchema]) { try { unlinkSync(path); } catch {} }+}diff --git a/docs/changes/evidence/2026-10-30-share-options/custom-invalid.png b/docs/changes/evidence/2026-10-30-share-options/custom-invalid.pngnew file mode 100644index 00000000..2ec531fdBinary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/custom-invalid.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/details-hidden.png b/docs/changes/evidence/2026-10-30-share-options/details-hidden.pngnew file mode 100644index 00000000..a04d0368Binary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/details-hidden.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/details-visible.png b/docs/changes/evidence/2026-10-30-share-options/details-visible.pngnew file mode 100644index 00000000..bdc3ad77Binary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/details-visible.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/menu-tests.txt b/docs/changes/evidence/2026-10-30-share-options/menu-tests.txtnew file mode 100644index 00000000..ecf99fdf--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/menu-tests.txt@@ -0,0 +1,2 @@+Command: bun test tests/note-sharing-menu.test.ts+Result: 4 pass, 0 fail; 24 assertions.diff --git a/docs/changes/evidence/2026-10-30-share-options/password-controls-regression.json b/docs/changes/evidence/2026-10-30-share-options/password-controls-regression.jsonnew file mode 100644index 00000000..99fc8263--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/password-controls-regression.json@@ -0,0 +1,26 @@+{+ "status": "passed",+ "failure": {+ "rejections": [],+ "requests": [+ {+ "passwordProtected": true+ },+ {+ "passwordProtected": false+ },+ {+ "passwordProtected": true,+ "password": "retain-draft-714"+ }+ ],+ "alert": "分享状态更新失败,请稍后重试。",+ "checked": "true",+ "password": "review-password-714",+ "draft": "retain-draft-714"+ },+ "pending": {+ "inputDisabled": true,+ "savedPassword": "review-password-714"+ }+}diff --git a/docs/changes/evidence/2026-10-30-share-options/password-controls-regression.mjs b/docs/changes/evidence/2026-10-30-share-options/password-controls-regression.mjsnew file mode 100644index 00000000..d2b70477--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/password-controls-regression.mjs@@ -0,0 +1,100 @@+// Import these checks from ego-browser nodejs and pass a Page on the isolated demo instance.+import assert from 'node:assert/strict';++const openManagement = async (page) => {+ await page.goto('http://127.0.0.1:8788/');+ await page.waitForSelector('button[aria-label="管理分享"]');+ await page.click('button[aria-label="管理分享"]');+ await page.waitForSelector('button[aria-label="访问密码"]');+};++export const checkPasswordMutationFailure = async (page) => {+ await openManagement(page);+ const before = await page.evaluate(() => ({+ checked: document.querySelector('button[aria-label="访问密码"]').getAttribute('aria-checked'),+ password: document.querySelector('input[aria-label="访问密码"]')?.value,+ }));+ assert.equal(before.checked, 'true', 'Use an existing protected share in the isolated demo');+ await page.evaluate(() => {+ const state = window.__shareReview = {originalFetch: window.fetch, requests: [], rejections: []};+ state.onRejection = (event) => state.rejections.push(String(event.reason));+ window.addEventListener('unhandledrejection', state.onRejection);+ window.fetch = async function(input, init) {+ const url = String(typeof input === 'string' ? input : input.url);+ if (init?.method === 'PATCH' && /\/memos\/[^/]+\/share$/.test(url)) {+ state.requests.push(JSON.parse(init.body));+ return new Response(JSON.stringify({error:{code:'test_failure',message:'Injected failure'}}),+ {status:503,headers:{'content-type':'application/json'}});+ }+ return state.originalFetch.apply(this, arguments);+ };+ });+ let result;+ try {+ await page.click('button[aria-label="重新生成"]');+ await page.waitForSelector('[role="alert"]');+ await page.waitForFunction(() => !document.querySelector('button[aria-label="访问密码"]').disabled);+ await page.click('button[aria-label="访问密码"]');+ await page.waitForFunction(() => window.__shareReview.requests.length === 2 && !document.querySelector('button[aria-label="访问密码"]').disabled);+ await page.click('text="自定义密码"');+ await page.fill('input[aria-label="自定义分享密码"]', 'retain-draft-714');+ await page.click('text="保存密码"');+ await page.waitForFunction(() => window.__shareReview.requests.length === 3 && !document.querySelector('button[aria-label="访问密码"]').disabled);+ // Let the browser dispatch any unhandled-rejection event queued after the React update.+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));+ result = await page.evaluate(() => ({+ rejections: window.__shareReview.rejections,+ requests: window.__shareReview.requests,+ alert: document.querySelector('[role="alert"]')?.textContent,+ checked: document.querySelector('button[aria-label="访问密码"]').getAttribute('aria-checked'),+ password: document.querySelector('input[aria-label="访问密码"]')?.value,+ draft: document.querySelector('input[aria-label="自定义分享密码"]')?.value,+ }));+ } finally {+ await page.evaluate(() => {+ window.fetch = window.__shareReview.originalFetch;+ window.removeEventListener('unhandledrejection', window.__shareReview.onRejection);+ delete window.__shareReview;+ });+ }+ assert.deepEqual(result.rejections, [], 'Generated-password failures must not leak rejected promises');+ assert.equal(result.requests.length, 3);+ assert.equal(result.checked, before.checked);+ assert.equal(result.password, before.password);+ assert.equal(result.draft, 'retain-draft-714');+ assert.ok(result.alert?.includes('分享状态更新失败'));+ return result;+};++export const checkPendingCustomSave = async (page) => {+ await openManagement(page);+ await page.click('text="自定义密码"');+ await page.fill('input[aria-label="自定义分享密码"]', ' review-password-714 ');+ await page.evaluate(() => {+ const state = window.__shareReview = { originalFetch: window.fetch, pending: false };+ window.fetch = async function(input, init) {+ const url = String(typeof input === 'string' ? input : input.url);+ if (init?.method === 'PATCH' && /\/memos\/[^/]+\/share$/.test(url)) {+ state.pending = true;+ await new Promise(resolve => { state.release = resolve; });+ }+ return state.originalFetch.apply(this, arguments);+ };+ });+ let inputDisabled;+ try {+ await page.click('text="保存密码"');+ await page.waitForFunction(() => window.__shareReview.pending && document.querySelector('button[aria-label="访问密码"]').disabled);+ inputDisabled = await page.evaluate(() => document.querySelector('input[aria-label="自定义分享密码"]').disabled);+ } finally {+ await page.evaluate(() => {+ const state = window.__shareReview;+ state.release?.(); window.fetch = state.originalFetch; delete window.__shareReview;+ });+ }+ await page.waitForFunction(() => !document.querySelector('input[aria-label="自定义分享密码"]'));+ const password = await page.evaluate(() => document.querySelector('input[aria-label="访问密码"]').value);+ assert.equal(inputDisabled, true, 'Pending saves must lock the custom input to avoid losing later edits');+ assert.equal(password, 'review-password-714');+ return { inputDisabled, savedPassword: password };+};diff --git a/docs/changes/evidence/2026-10-30-share-options/presentation-both.png b/docs/changes/evidence/2026-10-30-share-options/presentation-both.pngnew file mode 100644index 00000000..b2940ffdBinary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/presentation-both.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/presentation-branding.png b/docs/changes/evidence/2026-10-30-share-options/presentation-branding.pngnew file mode 100644index 00000000..1548dae6Binary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/presentation-branding.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/presentation-browser.json b/docs/changes/evidence/2026-10-30-share-options/presentation-browser.jsonnew file mode 100644index 00000000..aca52853--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/presentation-browser.json@@ -0,0 +1,75 @@+{+ "runtime": "Local workerd and Vite Web/desktop renderer in Chromium",+ "data": "Isolated demo fixture",+ "combinations": [+ {+ "showUpdatedAt": true,+ "showBranding": true,+ "titleAndBodyPreserved": true,+ "headerBrandingRemoved": true,+ "footer": {+ "href": "https://edgeever.org/",+ "position": "static",+ "fontSize": "12px",+ "afterBody": true+ },+ "screenshot": "presentation-both.png"+ },+ {+ "showUpdatedAt": false,+ "showBranding": true,+ "titleAndBodyPreserved": true,+ "headerBrandingRemoved": true,+ "footer": {+ "href": "https://edgeever.org/",+ "position": "static",+ "fontSize": "12px",+ "afterBody": true+ },+ "screenshot": "presentation-branding.png"+ },+ {+ "showUpdatedAt": false,+ "showBranding": false,+ "titleAndBodyPreserved": true,+ "headerBrandingRemoved": true,+ "footer": null,+ "screenshot": "presentation-hidden.png"+ },+ {+ "showUpdatedAt": true,+ "showBranding": false,+ "titleAndBodyPreserved": true,+ "headerBrandingRemoved": true,+ "footer": null,+ "screenshot": "presentation-time.png"+ }+ ],+ "persistenceAfterReopening": {+ "showUpdatedAt": true,+ "showBranding": false,+ "passed": true+ },+ "passwordProtected": {+ "wrongPasswordRejected": true,+ "customPasswordUnlocks": true,+ "presentationChangesPreserveUnlock": true,+ "rawMarkdownBlocked": true+ },+ "saveFailure": {+ "settingsAndPasswordPreserved": true,+ "unhandledRejections": 0+ },+ "pendingSave": {+ "bothSwitchesAndPasswordDisabled": true+ },+ "notebookSharing": {+ "standaloneSettingsIgnored": true,+ "timeRemainsVisible": true,+ "noNewArticleFooter": true+ },+ "status": "passed",+ "limits": [+ "Installed native desktop apps and production Cloudflare/Docker deployments were not exercised"+ ]+}diff --git a/docs/changes/evidence/2026-10-30-share-options/presentation-controls.png b/docs/changes/evidence/2026-10-30-share-options/presentation-controls.pngnew file mode 100644index 00000000..31a500beBinary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/presentation-controls.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/presentation-hidden.png b/docs/changes/evidence/2026-10-30-share-options/presentation-hidden.pngnew file mode 100644index 00000000..c2257afbBinary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/presentation-hidden.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/presentation-time.png b/docs/changes/evidence/2026-10-30-share-options/presentation-time.pngnew file mode 100644index 00000000..907991c6Binary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/presentation-time.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/related-tests.txt b/docs/changes/evidence/2026-10-30-share-options/related-tests.txtnew file mode 100644index 00000000..083df7a8--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/related-tests.txt@@ -0,0 +1,53 @@+bun test v1.3.14 (0d9b296a)++apps/api/src/notebook-share-routes.test.mjs:+(pass) public notebook site controls > old share upgrade preserves scope, token, and password while settings patch is independent [76.90ms]+(pass) public notebook site controls > exclusion gates every read path, keeps independent shares, and restores idempotently [45.93ms]+(pass) public notebook site controls > original-note controls list live ancestor sites with independent exclusions and no new shares [37.03ms]+(pass) public notebook site controls > owner content management filters before paging and reports exclusions beyond the first page [48.21ms]+(pass) public notebook site controls > body and Chinese search filter before paging and combine with exact tags [33.06ms]+(pass) public notebook site controls > rejects invalid targets, unknown settings, non-HTTPS URLs and oversized merged settings [35.46ms]+(pass) public notebook site controls > homepages fall back on exclusion and aliases disclose identity only [42.49ms]+(pass) public notebook site controls > enabling or rotating passwords disables indexing and clearing does not re-enable it [52.65ms]+(pass) public notebook site controls > server HTML escapes metadata, preserves protected privacy, and denies excluded aliases [49.25ms]+(pass) public notebook site controls > Token pages without an alias remain noindex after opting in [39.22ms]+(pass) live recursive notebook sharing > upgrades existing data without creating individual shares; exposes only the live workspace subtree [36.21ms]+(pass) live recursive notebook sharing > publishes new and moved-in notes, edits, and moved-in subtrees without changing the token [33.74ms]+(pass) live recursive notebook sharing > moving a note or subtree out immediately denies its note and resource endpoints [33.48ms]+(pass) live recursive notebook sharing > deleted notes, resources, ancestors, and roots cannot be read [33.54ms]+(pass) live recursive notebook sharing > revocation closes every endpoint, keeps independent shares, and recreation gets a fresh token [33.62ms]+(pass) live recursive notebook sharing > interactive management is workspace scoped and rejects anonymous and API-token callers [33.77ms]+(pass) live recursive notebook sharing > internal links resolve only within the shared tree, even if an outside note has an independent share [35.19ms]+(pass) live recursive notebook sharing > resource streaming keeps range, MIME, and no-store behavior [31.33ms]+(pass) live recursive notebook sharing > independent child notebook shares survive parent revocation [32.94ms]+(pass) live recursive notebook sharing > even inconsistent cross-workspace notebook references do not grant access [33.46ms]+(pass) password-protected notebook shares > migrates an existing live link in place and protects directory, descendants and blobs [55.45ms]+(pass) password-protected notebook shares > rotating rejects previous passwords and cookies; clearing restores the same public link [75.31ms]+(pass) password-protected notebook shares > limits wrong attempts and resets attempt state when regenerating [114.80ms]+(pass) password-protected notebook shares > management requires a live share in the interactive user's workspace [44.36ms]+(pass) password-protected notebook shares > other share links have independent passwords and grants; revocation invalidates all reads [73.21ms]+(pass) workspace login cannot bypass the notebook password; an unlock grant is still required [55.08ms]+(pass) notebook share password recovery > upgrades a hash-only share in place without invalidating the old password [62.71ms]+(pass) notebook share password recovery > recovers on a fresh read, hides from other workspaces/agents, and clears ciphertext [56.37ms]+(pass) an older server rotating only the hash cannot display stale ciphertext [60.24ms]+(pass) missing deployment keys reject regeneration without changing the existing password [49.31ms]++apps/api/src/share-page.test.mjs:+(pass) public memo share pages > recognizes only a single-note share path [0.13ms]+(pass) public memo share pages > puts the note in the first HTML response and keeps the app shell [32.23ms]+(pass) public memo share pages > returns markdown for the direct link and for an explicit markdown accept [31.36ms]+(pass) public memo share pages > omits the body when the share is missing, deleted, or password protected [31.05ms]+(pass) public memo share pages > serves a custom address like the token and keeps password-protected notes out [29.62ms]+(pass) public memo share pages > treats the stored default title as untitled in metadata and markdown [38.59ms]+(pass) public memo share pages > HEAD keeps the headers and omits the body [45.46ms]+(pass) public memo share pages > production entrypoints serve the share page from the worker [0.45ms]++packages/shared/src/sharing.test.mjs:+(pass) shared memo resources > rewrites owned images and attachments without touching external links [0.27ms]+(pass) shared memo resources > rewrites references to publicly shared notes without exposing private targets [0.03ms]+(pass) notebook shares use their own attachment scope, link within the directory, and disable private memo links [0.04ms]++ 41 pass+ 0 fail+ 378 expect() calls+Ran 41 tests across 3 files. [1.86s]diff --git a/docs/changes/evidence/2026-10-30-share-options/reopened.png b/docs/changes/evidence/2026-10-30-share-options/reopened.pngnew file mode 100644index 00000000..c984682dBinary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/reopened.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/review-pending.png b/docs/changes/evidence/2026-10-30-share-options/review-pending.pngnew file mode 100644index 00000000..2d4742e6Binary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/review-pending.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/review-saved.png b/docs/changes/evidence/2026-10-30-share-options/review-saved.pngnew file mode 100644index 00000000..17d33bf3Binary files /dev/null and b/docs/changes/evidence/2026-10-30-share-options/review-saved.png differdiff --git a/docs/changes/evidence/2026-10-30-share-options/share-tests.txt b/docs/changes/evidence/2026-10-30-share-options/share-tests.txtnew file mode 100644index 00000000..be78b005--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/share-tests.txt@@ -0,0 +1,99 @@+bun test v1.3.14 (0d9b296a)++tests/note-sharing-menu.test.ts:+(pass) note sharing menu > keeps sharing available while reading is locked and on the phone [0.32ms]+(pass) note sharing menu > shows a toast after copying the note for other platforms [0.14ms]+(pass) note sharing menu > explains why sharing a newly created local note is disabled [0.11ms]+(pass) note sharing menu > share dialog can enable an auto-generated access password [0.03ms]++apps/api/src/notebook-share-routes.test.mjs:+(pass) public notebook site controls > old share upgrade preserves scope, token, and password while settings patch is independent [58.38ms]+(pass) public notebook site controls > exclusion gates every read path, keeps independent shares, and restores idempotently [39.99ms]+(pass) public notebook site controls > original-note controls list live ancestor sites with independent exclusions and no new shares [34.27ms]+(pass) public notebook site controls > owner content management filters before paging and reports exclusions beyond the first page [43.67ms]+(pass) public notebook site controls > body and Chinese search filter before paging and combine with exact tags [34.91ms]+(pass) public notebook site controls > rejects invalid targets, unknown settings, non-HTTPS URLs and oversized merged settings [34.36ms]+(pass) public notebook site controls > homepages fall back on exclusion and aliases disclose identity only [33.97ms]+(pass) public notebook site controls > enabling or rotating passwords disables indexing and clearing does not re-enable it [40.68ms]+(pass) public notebook site controls > server HTML escapes metadata, preserves protected privacy, and denies excluded aliases [40.46ms]+(pass) public notebook site controls > Token pages without an alias remain noindex after opting in [31.99ms]+(pass) live recursive notebook sharing > upgrades existing data without creating individual shares; exposes only the live workspace subtree [33.40ms]+(pass) live recursive notebook sharing > publishes new and moved-in notes, edits, and moved-in subtrees without changing the token [33.76ms]+(pass) live recursive notebook sharing > moving a note or subtree out immediately denies its note and resource endpoints [33.05ms]+(pass) live recursive notebook sharing > deleted notes, resources, ancestors, and roots cannot be read [32.68ms]+(pass) live recursive notebook sharing > revocation closes every endpoint, keeps independent shares, and recreation gets a fresh token [33.56ms]+(pass) live recursive notebook sharing > interactive management is workspace scoped and rejects anonymous and API-token callers [32.11ms]+(pass) live recursive notebook sharing > internal links resolve only within the shared tree, even if an outside note has an independent share [32.26ms]+(pass) live recursive notebook sharing > resource streaming keeps range, MIME, and no-store behavior [31.47ms]+(pass) live recursive notebook sharing > independent child notebook shares survive parent revocation [34.66ms]+(pass) live recursive notebook sharing > even inconsistent cross-workspace notebook references do not grant access [32.84ms]+(pass) password-protected notebook shares > migrates an existing live link in place and protects directory, descendants and blobs [52.69ms]+(pass) password-protected notebook shares > rotating rejects previous passwords and cookies; clearing restores the same public link [64.14ms]+(pass) password-protected notebook shares > limits wrong attempts and resets attempt state when regenerating [97.73ms]+(pass) password-protected notebook shares > management requires a live share in the interactive user's workspace [33.10ms]+(pass) password-protected notebook shares > other share links have independent passwords and grants; revocation invalidates all reads [57.55ms]+(pass) workspace login cannot bypass the notebook password; an unlock grant is still required [49.36ms]+(pass) notebook share password recovery > upgrades a hash-only share in place without invalidating the old password [60.04ms]+(pass) notebook share password recovery > recovers on a fresh read, hides from other workspaces/agents, and clears ciphertext [59.94ms]+(pass) an older server rotating only the hash cannot display stale ciphertext [57.36ms]+(pass) missing deployment keys reject regeneration without changing the existing password [50.74ms]++apps/api/src/share-page.test.mjs:+(pass) public memo share pages > recognizes only a single-note share path [0.13ms]+(pass) public memo share pages > puts the note in the first HTML response and keeps the app shell [32.96ms]+(pass) public memo share pages > independently renders update time (%s) and footer branding (%s) in the first HTML response [31.36ms]+(pass) public memo share pages > independently renders update time (%s) and footer branding (%s) in the first HTML response [31.96ms]+(pass) public memo share pages > independently renders update time (%s) and footer branding (%s) in the first HTML response [31.29ms]+(pass) public memo share pages > independently renders update time (%s) and footer branding (%s) in the first HTML response [30.43ms]+(pass) public memo share pages > returns markdown for the direct link and for an explicit markdown accept [31.06ms]+(pass) public memo share pages > omits the body when the share is missing, deleted, or password protected [33.63ms]+(pass) public memo share pages > serves a custom address like the token and keeps password-protected notes out [32.40ms]+(pass) public memo share pages > treats the stored default title as untitled in metadata and markdown [31.74ms]+(pass) public memo share pages > HEAD keeps the headers and omits the body [36.00ms]+(pass) public memo share pages > production entrypoints serve the share page from the worker [0.41ms]++apps/api/src/share-routes.test.mjs:+(pass) public memo shares > returns share tokens only for referenced notes that are also public [40.41ms]+(pass) public memo shares > defaults both presentation settings on for migrated shares and new shares [35.58ms]+(pass) public memo shares > persists all four time/branding combinations independently without changing passwords [98.50ms]+(pass) public memo shares > reads existing fonts and new catalog choices through the same stored preference [34.16ms]+(pass) public memo shares > publishes the author's built-in note font and ignores anything else [32.77ms]+(pass) public memo shares > publishes account prose with the public share [32.99ms]+(pass) public memo shares > saves a signed-in user's published note font [32.35ms]+(pass) public memo shares > serves shared PDF byte ranges with public-share cache controls [42.53ms]+(pass) public memo shares > serves filename-detected shared audio inline [32.53ms]+(pass) public memo shares > serves filename-detected shared video inline [31.36ms]+(pass) memo share management > revocation retries succeed and keep the old link inaccessible [31.48ms]+(pass) memo share management > lists only live shares from the signed-in workspace without exposing passwords [31.36ms]+(pass) memo share management > paginates shares and requires an interactive user session [31.85ms]+(pass) password-protected memo shares > accepts an owner-chosen password, trims it, and keeps the password gate [49.70ms]+(pass) password-protected memo shares > rejects custom passwords outside the supported length [31.86ms]+(pass) password-protected memo shares > keeps existing shares public until a password is enabled [37.36ms]+(pass) password-protected memo shares > unlocks with the generated password and then serves the note and attachments [57.20ms]+(pass) password-protected memo shares > clearing the password ignores a supplied value and makes the existing link public again [39.45ms]+(pass) workspace login cannot bypass a memo's password or attachment gate [47.14ms]+(pass) memo share password recovery > returns encrypted-at-rest passwords only through authenticated single-share reads [48.39ms]+(pass) one-step memo sharing > concurrent creation and retries reuse one link; reopening preserves its password [44.38ms]+(pass) public SVG previews use the same sandbox and preserve the original [30.40ms]+(pass) custom memo share addresses > serves the note at the custom address while the token link keeps working [30.93ms]+(pass) custom memo share addresses > links between public notes prefer the custom address [29.86ms]+(pass) custom memo share addresses > rejects invalid, reserved and already used addresses [30.21ms]+(pass) custom memo share addresses > clearing or changing the address retires the old one immediately [31.06ms]+(pass) custom memo share addresses > keeps a released address bound to its workspace so other tenants cannot take over old links [32.77ms]+(pass) custom memo share addresses > keeps the password gate and scopes the unlock grant to the custom address [53.01ms]++packages/shared/src/sharing.test.mjs:+(pass) shared memo resources > rewrites owned images and attachments without touching external links [0.24ms]+(pass) shared memo resources > rewrites references to publicly shared notes without exposing private targets [0.03ms]+(pass) notebook shares use their own attachment scope, link within the directory, and disable private memo links [0.03ms]++apps/web/src/components/dialogs/ShareMemoDialog.test.mjs:+(pass) ShareMemoDialog raw markdown link support > generates public share URLs and .md alternates [0.09ms]+(pass) ShareMemoDialog raw markdown link support > renders compact raw markdown strip with copy button and i18n labels [0.03ms]+(pass) ShareMemoDialog raw markdown link support > renders open markdown button in actions footer when not password protected [0.02ms]+(pass) ShareMemoDialog raw markdown link support > switches compact hint text when password protection is active [0.02ms]++ 81 pass+ 0 fail+ 746 expect() calls+Ran 81 tests across 6 files. [3.01s]diff --git a/docs/changes/evidence/2026-10-30-share-options/validation.json b/docs/changes/evidence/2026-10-30-share-options/validation.jsonnew file mode 100644index 00000000..2d1ffc16--- /dev/null+++ b/docs/changes/evidence/2026-10-30-share-options/validation.json@@ -0,0 +1,51 @@+{+ "status": "passed",+ "commands": [+ {+ "command": "bun test apps/api/src/share-routes.test.mjs apps/api/src/share-page.test.mjs apps/api/src/notebook-share-routes.test.mjs packages/shared/src/sharing.test.mjs apps/web/src/components/dialogs/ShareMemoDialog.test.mjs tests/note-sharing-menu.test.ts",+ "exitCode": 0,+ "result": "81 pass, 0 fail",+ "output": "share-tests.txt"+ },+ {+ "command": "bun test packages/shared/src/i18n/catalog.test.mjs packages/shared/src/i18n/locales.test.mjs",+ "exitCode": 0,+ "result": "5 pass, 0 fail"+ },+ {+ "command": "bun test apps/web/src/components/settings/PreferenceCard.test.mjs",+ "exitCode": 0,+ "result": "6 pass, 0 fail; upstream font-regression correction included"+ },+ {+ "command": "bun run typecheck",+ "exitCode": 0+ },+ {+ "command": "bun run typecheck:mobile",+ "exitCode": 0+ },+ {+ "command": "bun run build:web",+ "exitCode": 0+ },+ {+ "command": "bun run lint",+ "exitCode": 0+ },+ {+ "command": "git diff --check upstream/main",+ "exitCode": 0+ },+ {+ "command": "bun docs/changes/evidence/2026-10-30-share-options/cross-version.mjs",+ "exitCode": 0,+ "output": "cross-version.json"+ }+ ],+ "presentationBrowser": "presentation-browser.json",+ "reusedChecks": [+ "Custom-password failure/pending-save behavior: password-controls-regression.json; SharePasswordControls and its calling password mutation are unchanged"+ ],+ "ubuntuCI": "https://github.com/tianma-if/edgeever/pull/735/checks"+}diff --git a/migrations/0082_memo_share_options.sql b/migrations/0082_memo_share_options.sqlnew file mode 100644index 00000000..8340ec50--- /dev/null+++ b/migrations/0082_memo_share_options.sql@@ -0,0 +1,3 @@+-- Owner-selected password support and per-share public-page details visibility.+-- Existing rows keep the current behavior: details remain visible.+ALTER TABLE memo_shares ADD COLUMN show_details INTEGER NOT NULL DEFAULT 1;diff --git a/migrations/0083_memo_share_presentation.sql b/migrations/0083_memo_share_presentation.sqlnew file mode 100644index 00000000..6bf6cb8d--- /dev/null+++ b/migrations/0083_memo_share_presentation.sql@@ -0,0 +1,4 @@+-- Independent presentation controls default on for every existing and new share.+-- Keep the legacy show_details column for databases that already applied 0082.+ALTER TABLE memo_shares ADD COLUMN show_updated_at INTEGER NOT NULL DEFAULT 1;+ALTER TABLE memo_shares ADD COLUMN show_branding INTEGER NOT NULL DEFAULT 1;diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex ec854bbf..d95bc9f0 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -1460,7 +1460,7 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {body: JSON.stringify({}),}),- updateMemoShare: (memoId: string, payload: { passwordProtected?: boolean; slug?: string | null }) =>+ updateMemoShare: (memoId: string, payload: { passwordProtected?: boolean; password?: string; slug?: string | null; showUpdatedAt?: boolean; showBranding?: boolean }) =>request<{ share: MemoShare }>(`/api/v1/memos/${memoId}/share`, {method: "PATCH",body: JSON.stringify(payload),diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex d867eee2..36bfab28 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -3002,6 +3002,13 @@ export const enUS = {copyLinkAndPassword: "Copy link and password",regeneratePassword: "Regenerate",passwordUnavailableHint: "This password cannot be displayed. Regenerate it to view it across devices; the previous password will stop working.",+ passwordCustomAction: "Set a custom password",+ passwordCustomLabel: "Custom share password",+ passwordCustomPlaceholder: "Enter 4–64 characters",+ passwordCustomHint: "Use 4–64 characters. The password is stored securely and shown only after you save it.",+ passwordCustomInvalid: "Use a password between 4 and 64 characters.",+ passwordCustomSave: "Save password",+ passwordCustomCancel: "Cancel",passwordSet: "Password is set",passwordPrefix: "Password: ",passwordRequiredTitle: "Password required",@@ -3009,6 +3016,9 @@ export const enUS = {passwordSubmit: "View note",passwordInvalid: "Incorrect password. Please try again.",passwordRateLimited: "Too many attempts. Please try again later.",+ showUpdatedAt: "Show last-updated time",+ showBranding: "Show EdgeEver branding",+ publishedWith: "Published with EdgeEver",readOnly: "Read-only share",publicLoading: "Loading shared note",publicUpdated: "Updated {{time}}",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 188647fc..f2ecc063 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2991,6 +2991,13 @@ export const ja = {copyLinkAndPassword: "リンクとパスワードをコピー",regeneratePassword: "再生成",passwordUnavailableHint: "このパスワードは表示できません。再生成すると他の端末でも確認できます。以前のパスワードは無効になります。",+ passwordCustomAction: "カスタムパスワードを設定",+ passwordCustomLabel: "共有用カスタムパスワード",+ passwordCustomPlaceholder: "4〜64文字で入力",+ passwordCustomHint: "4〜64文字で設定します。パスワードは安全に保存され、保存後は管理画面でのみ表示されます。",+ passwordCustomInvalid: "4〜64文字のパスワードを入力してください。",+ passwordCustomSave: "パスワードを保存",+ passwordCustomCancel: "キャンセル",passwordSet: "パスワード設定済み",passwordPrefix: "パスワード:",passwordRequiredTitle: "パスワードが必要です",@@ -2998,6 +3005,9 @@ export const ja = {passwordSubmit: "ノートを表示",passwordInvalid: "パスワードが正しくありません。再試行してください。",passwordRateLimited: "試行回数が多すぎます。しばらくしてから再試行してください。",+ showUpdatedAt: "最終更新日時を表示",+ showBranding: "EdgeEver のブランドを表示",+ publishedWith: "EdgeEver で公開",readOnly: "読み取り専用の共有",publicLoading: "共有ノートを読み込み中",publicUpdated: "更新 {{time}}",diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex 344d59f5..1216510a 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -2991,6 +2991,13 @@ export const pl = {copyLinkAndPassword: "Kopiuj link i hasło",regeneratePassword: "Wygeneruj ponownie",passwordUnavailableHint: "Nie można wyświetlić tego hasła. Wygeneruj nowe, aby wyświetlać je na innych urządzeniach; poprzednie hasło przestanie działać.",+ passwordCustomAction: "Ustaw własne hasło",+ passwordCustomLabel: "Własne hasło udostępnienia",+ passwordCustomPlaceholder: "Wpisz 4–64 znaki",+ passwordCustomHint: "Użyj 4–64 znaków. Hasło jest bezpiecznie przechowywane i po zapisaniu widoczne tylko w panelu zarządzania.",+ passwordCustomInvalid: "Użyj hasła o długości od 4 do 64 znaków.",+ passwordCustomSave: "Zapisz hasło",+ passwordCustomCancel: "Anuluj",passwordSet: "Hasło jest ustawione",passwordPrefix: "Hasło: ",passwordRequiredTitle: "Wymagane hasło",@@ -2998,6 +3005,9 @@ export const pl = {passwordSubmit: "Wyświetl notatkę",passwordInvalid: "Nieprawidłowe hasło. Spróbuj ponownie.",passwordRateLimited: "Zbyt wiele prób. Spróbuj ponownie później.",+ showUpdatedAt: "Pokaż czas ostatniej aktualizacji",+ showBranding: "Pokaż markę EdgeEver",+ publishedWith: "Opublikowano za pomocą EdgeEver",readOnly: "Udostępnienie tylko do odczytu",publicLoading: "Wczytywanie udostępnionej notatki",publicUpdated: "Zaktualizowano: {{time}}",diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.tsindex 4cb97a20..75ff90e5 100644--- a/packages/shared/src/i18n/ru.ts+++ b/packages/shared/src/i18n/ru.ts@@ -3002,6 +3002,13 @@ export const ru = {copyLinkAndPassword: "Копировать ссылку и пароль",regeneratePassword: "Сгенерировать заново",passwordUnavailableHint: "Этот пароль нельзя показать. Создайте новый, чтобы видеть его на всех устройствах; прежний перестанет работать.",+ passwordCustomAction: "Задать свой пароль",+ passwordCustomLabel: "Свой пароль для общей ссылки",+ passwordCustomPlaceholder: "Введите 4–64 символа",+ passwordCustomHint: "Используйте 4–64 символа. Пароль хранится безопасно и после сохранения показывается только в управлении доступом.",+ passwordCustomInvalid: "Введите пароль длиной от 4 до 64 символов.",+ passwordCustomSave: "Сохранить пароль",+ passwordCustomCancel: "Отмена",passwordSet: "Пароль задан",passwordPrefix: "Пароль: ",passwordRequiredTitle: "Нужен пароль",@@ -3009,6 +3016,9 @@ export const ru = {passwordSubmit: "Открыть заметку",passwordInvalid: "Неверный пароль. Попробуйте снова.",passwordRateLimited: "Слишком много попыток. Попробуйте позже.",+ showUpdatedAt: "Показывать время обновления",+ showBranding: "Показывать бренд EdgeEver",+ publishedWith: "Опубликовано с помощью EdgeEver",readOnly: "Доступ только для чтения",publicLoading: "Загрузка общей заметки",publicUpdated: "Обновлено {{time}}",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex cf91c956..e8e32f2d 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -3000,6 +3000,13 @@ export const zhCN = {copyLinkAndPassword: "复制链接和密码",regeneratePassword: "重新生成",passwordUnavailableHint: "此密码暂时无法显示。重新生成后可跨设备查看,旧密码将失效。",+ passwordCustomAction: "自定义密码",+ passwordCustomLabel: "自定义分享密码",+ passwordCustomPlaceholder: "输入 4–64 个字符",+ passwordCustomHint: "使用 4–64 个字符。密码会安全保存,保存后仅在管理界面显示。",+ passwordCustomInvalid: "请输入 4–64 个字符的密码。",+ passwordCustomSave: "保存密码",+ passwordCustomCancel: "取消",passwordSet: "已设置访问密码",passwordPrefix: "密码:",passwordRequiredTitle: "需要访问密码",@@ -3007,6 +3014,9 @@ export const zhCN = {passwordSubmit: "查看笔记",passwordInvalid: "密码不正确,请重试。",passwordRateLimited: "尝试次数过多,请稍后再试。",+ showUpdatedAt: "显示最后更新时间",+ showBranding: "显示 EdgeEver 品牌",+ publishedWith: "使用 EdgeEver 发布",readOnly: "只读分享",publicLoading: "正在加载分享笔记",publicUpdated: "更新于 {{time}}",diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.tsindex 214f77cc..33486462 100644--- a/packages/shared/src/schemas.ts+++ b/packages/shared/src/schemas.ts@@ -447,8 +447,11 @@ export const SharePasswordUpdateSchema = z.object({export const MemoShareUpdateSchema = z.object({passwordProtected: z.boolean().optional(),+ password: z.string().trim().min(4).max(64).optional(),slug: z.string().trim().toLowerCase().refine(isValidMemoShareSlug).nullable().optional(),-}).refine((input) => input.passwordProtected !== undefined || input.slug !== undefined, {+ showUpdatedAt: z.boolean().optional(),+ showBranding: z.boolean().optional(),+}).refine((input) => input.passwordProtected !== undefined || input.password !== undefined || input.slug !== undefined || input.showUpdatedAt !== undefined || input.showBranding !== undefined, {message: "At least one field is required.",});export const NotebookShareUpdateSchema = SharePasswordUpdateSchema;diff --git a/packages/shared/src/sharing.ts b/packages/shared/src/sharing.tsindex 6c564cb5..74080157 100644--- a/packages/shared/src/sharing.ts+++ b/packages/shared/src/sharing.ts@@ -12,6 +12,9 @@ export type MemoShare = {createdAt: string;updatedAt: string;passwordProtected: boolean;+ /** Independent standalone-page controls; both default to visible. */+ showUpdatedAt: boolean;+ showBranding: boolean;/** Plaintext is returned only immediately after the owner enables or regenerates a password. */password?: string;};@@ -79,6 +82,9 @@ export type PublicMemoShare = {bodyFont: PublishedNoteBodyFont | null;/** Account reading settings for the article body. Column width stays on the author's editor. */prose: PublicNoteProse;+ /** Older servers and notebook shares may omit these; omission means visible. */+ showUpdatedAt?: boolean;+ showBranding?: boolean;};const RESOURCE_URL_PATTERN =diff --git a/tests/note-sharing-menu.test.ts b/tests/note-sharing-menu.test.tsindex 0c195bf9..a85328e0 100644--- a/tests/note-sharing-menu.test.ts+++ b/tests/note-sharing-menu.test.ts@@ -41,7 +41,7 @@ describe("note sharing menu", () => {expect(zhCN.sharing.passwordToggle).toBe("访问密码");expect(enUS.sharing.passwordToggle).toBe("Access password");expect(shareDialogSource).toContain('t("sharing.passwordToggle")');- expect(shareDialogSource).toContain("api.updateMemoShare(memoId, { passwordProtected })");+ expect(shareDialogSource).toContain("api.updateMemoShare(memoId, { passwordProtected, ...(password ? { password } : {}) })");expect(publicShareSource).toContain("api.unlockPublicMemoShare");expect(publicShareSource).toContain("parsePublishedNoteBodyFont(share.bodyFont)");expect(publicShareSource).toContain("applyEditorBodyFontPreference");