Skip to content

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

feat(sharing): let owners set a custom address for a shared note (#692)

Dariusz Korytoc89e126345d6
diff --git a/apps/api/src/share-http-access.ts b/apps/api/src/share-http-access.ts
index 0a90624e..54239f44 100644
--- a/apps/api/src/share-http-access.ts
+++ b/apps/api/src/share-http-access.ts
@@ -2,7 +2,7 @@ import { getCookie, setCookie } from "hono/cookie";
import type { AppContext } from "./api-context";
import { createShareAccessCookieValue, isValidShareAccessCookieValue, SHARE_ACCESS_COOKIE, SHARE_ACCESS_MAX_AGE_SECONDS } from "./share-access";
-const shareAccessCookiePath = (token: string) => `/api/public/shares/${encodeURIComponent(token)}`;
+export const shareAccessCookiePath = (token: string) => `/api/public/shares/${encodeURIComponent(token)}`;
export const setShareAccessCookie = async (c: AppContext, token: string, passwordHash: string, path = shareAccessCookiePath(token)) => {
const value = await createShareAccessCookieValue(passwordHash, token);
diff --git a/apps/api/src/share-page.test.mjs b/apps/api/src/share-page.test.mjs
index e60d50f4..f0bc7fc5 100644
--- a/apps/api/src/share-page.test.mjs
+++ b/apps/api/src/share-page.test.mjs
@@ -69,11 +69,13 @@ const render = (sqlite, path, accept) => renderPublicMemoSharePage(
describe("public memo share pages", () => {
test("recognizes only a single-note share path", () => {
- expect(parsePublicMemoSharePagePath(`/share/${token}`)).toEqual({ token, markdown: false });
- expect(parsePublicMemoSharePagePath(`/share/${token}.md`)).toEqual({ token, markdown: true });
- expect(parsePublicMemoSharePagePath(`/share/${token}/`)).toEqual({ token, markdown: false });
+ expect(parsePublicMemoSharePagePath(`/share/${token}`)).toEqual({ segment: token, markdown: false });
+ expect(parsePublicMemoSharePagePath(`/share/${token}.md`)).toEqual({ segment: token, markdown: true });
+ expect(parsePublicMemoSharePagePath(`/share/${token}/`)).toEqual({ segment: token, markdown: false });
+ expect(parsePublicMemoSharePagePath("/share/Meeting-Notes.md")).toEqual({ segment: "meeting-notes", markdown: true });
expect(isPublicMemoSharePagePath(`/share/notebook/${token}`)).toBe(false);
- expect(isPublicMemoSharePagePath("/share/not-a-token")).toBe(false);
+ expect(isPublicMemoSharePagePath("/share/notebook")).toBe(false);
+ expect(isPublicMemoSharePagePath("/share/not_a_token")).toBe(false);
expect(parsePublicMemoSharePagePath("/share/%2e%2e/secret")).toBeNull();
});
@@ -146,6 +148,32 @@ describe("public memo share pages", () => {
expect(await lockedMarkdown.text()).toBe("This shared note requires a password.\n");
});
+ test("serves a custom address like the token and keeps password-protected notes out", async () => {
+ const sqlite = createDatabase();
+ sqlite.query("UPDATE memo_shares SET slug = ? WHERE token = ?").run("meeting-notes", token);
+
+ const page = await render(sqlite, "/share/Meeting-Notes");
+ const html = await page.text();
+ expect(html).toContain("Hello <script>secret()</script>");
+ expect(html).toContain('rel="canonical" href="https://note.example/share/meeting-notes"');
+ expect(page.headers.get("link")).toBe('<https://note.example/share/meeting-notes.md>; rel="alternate"; type="text/markdown"');
+
+ const markdown = await render(sqlite, "/share/meeting-notes.md");
+ expect(markdown.status).toBe(200);
+ expect(await markdown.text()).toContain("Hello <script>secret()</script>");
+
+ const missing = await render(sqlite, "/share/other-notes.md");
+ expect(missing.status).toBe(404);
+
+ sqlite.query("UPDATE memo_shares SET password_hash = ? WHERE token = ?").run("hash", token);
+ const lockedHtml = await (await render(sqlite, "/share/meeting-notes")).text();
+ expect(lockedHtml).not.toContain("secret()");
+ expect(lockedHtml).toContain("This shared note requires a password.");
+ const lockedMarkdown = await render(sqlite, "/share/meeting-notes.md");
+ expect(lockedMarkdown.status).toBe(403);
+ expect(await lockedMarkdown.text()).not.toContain("secret()");
+ });
+
test("HEAD keeps the headers and omits the body", async () => {
const response = await renderPublicMemoSharePage(
new Request(`https://note.example/share/${token}.md`, { method: "HEAD" }),
diff --git a/apps/api/src/share-page.ts b/apps/api/src/share-page.ts
index c01f70ee..4aa50969 100644
--- a/apps/api/src/share-page.ts
+++ b/apps/api/src/share-page.ts
@@ -1,7 +1,9 @@
+import { isValidMemoShareSlug } from "@edgeever/shared/share-slug";
import { PUBLIC_PAGE_HEADERS, PUBLIC_PAGE_ROBOTS } from "@edgeever/shared/public-page-headers";
import type { DatabaseAdapter } from "./storage-contract";
-const SHARE_PAGE_PATH = /^\/share\/([A-Za-z0-9_-]{43})(\.md)?\/?$/;
+const SHARE_PAGE_PATH = /^\/share\/([^/]+?)(\.md)?\/?$/;
+const SHARE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
type SharePageRow = {
title: string | null;
@@ -10,7 +12,8 @@ type SharePageRow = {
};
export type PublicMemoSharePageTarget = {
- token: string;
+ /** The random token, or a custom address already lowercased. */
+ segment: string;
markdown: boolean;
};
@@ -22,6 +25,28 @@ const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (char) => ({
"'": "&#39;",
})[char]!);
+/**
+ * A public link segment is either the case-sensitive random token or a custom
+ * address. Only the custom address is lowercased, so `/share/Meeting-Notes`
+ * opens the saved `meeting-notes`.
+ */
+export const normalizeMemoSharePathSegment = (value: string) => {
+ const segment = value.trim();
+ if (SHARE_TOKEN_PATTERN.test(segment)) return segment;
+ const slug = segment.toLowerCase();
+ return isValidMemoShareSlug(slug) ? slug : null;
+};
+
+/** Resolves a public link segment to the share token, or null when nothing matches. */
+export const resolveMemoShareToken = async (db: DatabaseAdapter, value: string) => {
+ const segment = normalizeMemoSharePathSegment(value);
+ if (!segment || SHARE_TOKEN_PATTERN.test(segment)) return segment;
+ const row = await db.prepare(
+ `SELECT token FROM memo_shares WHERE slug = ? LIMIT 1`,
+ ).bind(segment).first<{ token: string }>();
+ return row?.token ?? null;
+};
+
/** Single-note public links. Notebook sites stay on their own renderer. */
export const parsePublicMemoSharePagePath = (pathname: string): PublicMemoSharePageTarget | null => {
let path = pathname;
@@ -31,8 +56,9 @@ export const parsePublicMemoSharePagePath = (pathname: string): PublicMemoShareP
return null;
}
const match = SHARE_PAGE_PATH.exec(path);
- if (!match?.[1]) return null;
- return { token: match[1], markdown: match[2] === ".md" };
+ const segment = match?.[1] ? normalizeMemoSharePathSegment(match[1]) : null;
+ if (!segment) return null;
+ return { segment, markdown: match![2] === ".md" };
};
export const isPublicMemoSharePagePath = (pathname: string) => parsePublicMemoSharePagePath(pathname) !== null;
@@ -107,12 +133,13 @@ export const renderPublicMemoSharePage = async (
const target = parsePublicMemoSharePagePath(url.pathname);
if (!target) return null;
- const row = await loadShare(db, target.token);
+ const token = await resolveMemoShareToken(db, target.segment);
+ const row = token ? await loadShare(db, token) : null;
const locked = Boolean(row?.password_hash);
const readable = Boolean(row) && !locked;
const body = row?.content_markdown ?? "";
- const markdownUrl = `${url.origin}/share/${encodeURIComponent(target.token)}.md`;
- const canonical = `${url.origin}/share/${encodeURIComponent(target.token)}`;
+ const markdownUrl = `${url.origin}/share/${encodeURIComponent(target.segment)}.md`;
+ const canonical = `${url.origin}/share/${encodeURIComponent(target.segment)}`;
if (prefersMarkdown(request.headers.get("accept"), target.markdown)) {
const headers = pageHeaders("text/markdown; charset=utf-8");
diff --git a/apps/api/src/share-routes.test.mjs b/apps/api/src/share-routes.test.mjs
index e42dcce2..4f9a6641 100644
--- a/apps/api/src/share-routes.test.mjs
+++ b/apps/api/src/share-routes.test.mjs
@@ -650,3 +650,121 @@ test("public SVG previews use the same sandbox and preserve the original", async
expect(await response.text()).toBe(svg);
sqlite.close();
});
+
+describe("custom memo share addresses", () => {
+ const patchShare = (app, environment, memoId, body) => app.request(`/api/v1/memos/${memoId}/share`, {
+ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
+ }, environment);
+
+ test("serves the note at the custom address while the token link keeps working", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ const app = createShareApp(environment);
+ const updated = await patchShare(app, environment, "memo_source", { slug: " My-Notes-2026 " });
+ expect(updated.status).toBe(200);
+ expect((await updated.json()).share).toMatchObject({ token: sourceToken, slug: "my-notes-2026", passwordProtected: false });
+
+ for (const segment of ["my-notes-2026", "My-Notes-2026", sourceToken]) {
+ const response = await app.request(`/api/public/shares/${segment}`, {}, environment);
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ share: { title: "Source" } });
+ }
+ expect((await (await app.request("/api/v1/memo-shares", {}, environment)).json()).shares)
+ .toContainEqual(expect.objectContaining({ memoId: "memo_source", slug: "my-notes-2026" }));
+ sqlite.close();
+ });
+
+ test("links between public notes prefer the custom address", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ const app = createShareApp(environment);
+ expect((await patchShare(app, environment, "memo_target", { slug: "target-note" })).status).toBe(200);
+ const response = await app.request(`/api/public/shares/${sourceToken}`, {}, environment);
+ expect((await response.json()).share.memoShareTokens).toEqual({ memo_target: "target-note" });
+ sqlite.close();
+ });
+
+ test("rejects invalid, reserved and already used addresses", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ const app = createShareApp(environment);
+ for (const slug of ["ab", "-lead", "trail-", "double--dash", "spa ce", "ünï", "x".repeat(41), "notebook", ""]) {
+ expect((await patchShare(app, environment, "memo_source", { slug })).status).toBe(400);
+ }
+ expect((await patchShare(app, environment, "memo_source", { slug: "taken" })).status).toBe(200);
+ const conflict = await patchShare(app, environment, "memo_target", { slug: "TAKEN" });
+ expect(conflict.status).toBe(409);
+ expect((await conflict.json()).error.code).toBe("share_slug_taken");
+ expect((await patchShare(app, environment, "memo_source", { slug: "taken" })).status).toBe(200);
+ expect((await patchShare(app, environment, "memo_source", {})).status).toBe(400);
+ sqlite.close();
+ });
+
+ test("clearing or changing the address retires the old one immediately", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ const app = createShareApp(environment);
+ await patchShare(app, environment, "memo_source", { slug: "first-name" });
+ await patchShare(app, environment, "memo_source", { slug: "second-name" });
+ expect((await app.request("/api/public/shares/first-name", {}, environment)).status).toBe(404);
+ expect((await app.request("/api/public/shares/second-name", {}, environment)).status).toBe(200);
+
+ const cleared = await patchShare(app, environment, "memo_source", { slug: null });
+ expect((await cleared.json()).share.slug).toBeNull();
+ expect((await app.request("/api/public/shares/second-name", {}, environment)).status).toBe(404);
+ expect((await app.request(`/api/public/shares/${sourceToken}`, {}, environment)).status).toBe(200);
+
+ await patchShare(app, environment, "memo_target", { slug: "second-name" });
+ await app.request("/api/v1/memos/memo_target/share", { method: "DELETE" }, environment);
+ expect((await app.request("/api/public/shares/second-name", {}, environment)).status).toBe(404);
+ sqlite.close();
+ });
+
+ test("keeps a released address bound to its workspace so other tenants cannot take over old links", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ sqlite.query("INSERT INTO workspaces (id, name, is_personal) VALUES (?, ?, 1)").run("ws_other", "Other workspace");
+ sqlite.query("INSERT INTO notebooks (id, workspace_id, name) VALUES (?, ?, ?)").run("nb_other", "ws_other", "Other");
+ sqlite.query("INSERT INTO memos (id, workspace_id, notebook_id, title) VALUES (?, ?, ?, ?)").run("memo_other", "ws_other", "nb_other", "Other");
+ sqlite.query("INSERT INTO memo_shares (id, memo_id, workspace_id, token) VALUES (?, ?, ?, ?)").run("share_other", "memo_other", "ws_other", "o".repeat(43));
+ const app = createShareApp(environment);
+ const otherApp = new Hono();
+ otherApp.use("/api/v1/*", async (c, next) => {
+ c.set("auth", { ...memberAuth, actorId: "user_other", workspaceId: "ws_other" });
+ await next();
+ });
+ registerMemoShareRoutes(otherApp);
+
+ expect((await patchShare(app, environment, "memo_source", { slug: "team-handbook" })).status).toBe(200);
+ expect((await patchShare(app, environment, "memo_source", { slug: null })).status).toBe(200);
+ await app.request("/api/v1/memos/memo_source/share", { method: "DELETE" }, environment);
+
+ const takeover = await patchShare(otherApp, environment, "memo_other", { slug: "team-handbook" });
+ expect(takeover.status).toBe(409);
+ expect((await takeover.json()).error.code).toBe("share_slug_taken");
+ expect((await app.request("/api/public/shares/team-handbook", {}, environment)).status).toBe(404);
+ expect((await patchShare(app, environment, "memo_target", { slug: "team-handbook" })).status).toBe(200);
+ sqlite.close();
+ });
+
+ test("keeps the password gate and scopes the unlock grant to the custom address", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ sqlite.query("INSERT INTO resources (id, memo_id, object_key, kind, byte_size) VALUES ('res_slug', 'memo_source', 'slug-key', 'image', 10)").run();
+ environment.storage.resources = {
+ get: async () => ({ body: new Blob([new Uint8Array(10)]).stream(), size: 10, writeHttpMetadata: () => {} }),
+ };
+ const app = createShareApp(environment);
+ const protectedShare = (await (await patchShare(app, environment, "memo_source", { passwordProtected: true })).json()).share;
+ const renamed = (await (await patchShare(app, environment, "memo_source", { slug: "locked-note" })).json()).share;
+ expect(renamed).toMatchObject({ slug: "locked-note", passwordProtected: true, password: protectedShare.password });
+
+ const base = "/api/public/shares/locked-note";
+ expect((await app.request(base, {}, environment)).status).toBe(403);
+ expect((await app.request(`${base}/resources/res_slug/blob`, {}, environment)).status).toBe(403);
+ const unlocked = await app.request(`${base}/unlock`, {
+ method: "POST", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password: protectedShare.password }),
+ }, environment);
+ expect(unlocked.status).toBe(200);
+ expect(unlocked.headers.get("Set-Cookie")).toContain(`Path=${base}`);
+ const headers = { Cookie: `ee_share=${readCookieValue(unlocked, "ee_share")}` };
+ expect((await app.request(base, { headers }, environment)).status).toBe(200);
+ expect((await app.request(`${base}/resources/res_slug/blob`, { headers }, environment)).status).toBe(200);
+ sqlite.close();
+ });
+});
diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.ts
index 0083f729..aba6d249 100644
--- a/apps/api/src/share-routes.ts
+++ b/apps/api/src/share-routes.ts
@@ -14,17 +14,18 @@ import {
isShareUnlockBlocked,
nextShareUnlockFailure,
} from "./share-access";
-import { allowPasswordProtectedShare, setShareAccessCookie } from "./share-http-access";
+import { allowPasswordProtectedShare, setShareAccessCookie, shareAccessCookiePath } from "./share-http-access";
import { encryptSharePassword, readSharePassword } from "./share-password-encryption";
+import { resolveMemoShareToken } from "./share-page";
import { generateSharePassword } from "./share-password";
const SHARE_TOKEN_BYTES = 32;
-const SHARE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
type MemoShareRow = {
password_encrypted?: string | null;
memo_id: string;
token: string;
+ slug?: string | null;
created_at: string;
updated_at: string;
password_hash: string | null;
@@ -66,6 +67,7 @@ type SharedResourceRow = {
const mapMemoShare = (row: MemoShareRow, password?: string): MemoShare => ({
memoId: row.memo_id,
token: row.token,
+ slug: row.slug ?? null,
createdAt: row.created_at,
updatedAt: row.updated_at,
passwordProtected: Boolean(row.password_hash),
@@ -77,10 +79,10 @@ const contentDisposition = (kind: SharedResourceRow["kind"], mimeType: string |
return inline ? contentDispositionInline(filename) : contentDispositionAttachment(filename);
};
-const normalizeShareToken = (value: string) => {
- const token = value.trim();
- return SHARE_TOKEN_PATTERN.test(token) ? token : null;
-};
+const resolveShareToken = (c: AppContext, value: string) => resolveMemoShareToken(c.env.storage.db, value);
+
+const shareSlugTaken = (c: AppContext) =>
+ apiError(c, "share_slug_taken", "This share address is already in use", 409);
const sharePasswordRequired = (c: AppContext) =>
apiError(c, "share_password_required", "Password required to view this shared note", 403);
@@ -100,7 +102,7 @@ const loadShareGate = async (c: AppContext, token: string) =>
LIMIT 1`
).bind(token).first<ShareGateRow>();
-const selectMemoShareSql = `SELECT memo_id, token, created_at, updated_at, password_hash, password_encrypted
+const selectMemoShareSql = `SELECT memo_id, token, slug, created_at, updated_at, password_hash, password_encrypted
FROM 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`;
@@ -167,7 +169,7 @@ export const serveSharedResource = async (c: AppContext, resource: SharedResourc
export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
app.get("/api/public/shares/:token", async (c) => {
- const token = normalizeShareToken(c.req.param("token"));
+ const token = await resolveShareToken(c, c.req.param("token"));
if (!token) return notFound(c, "Shared note not found");
const row = await c.env.storage.db.prepare(
@@ -193,7 +195,7 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
const batch = referencedMemoIds.slice(offset, offset + 80);
const placeholders = batch.map(() => "?").join(", ");
const linkedShares = await c.env.storage.db.prepare(
- `SELECT ms.memo_id, ms.token
+ `SELECT ms.memo_id, COALESCE(ms.slug, ms.token) AS token
FROM memo_shares ms
INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
WHERE ms.workspace_id = ? AND ms.memo_id IN (${placeholders}) AND m.is_deleted = 0`
@@ -219,7 +221,7 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
});
app.post("/api/public/shares/:token/unlock", zValidator("json", PublicShareUnlockSchema), async (c) => {
- const token = normalizeShareToken(c.req.param("token"));
+ const token = await resolveShareToken(c, c.req.param("token"));
if (!token) return notFound(c, "Shared note not found");
const gate = await loadShareGate(c, token);
@@ -247,14 +249,15 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
SET unlock_failed_count = 0, unlock_window_started_at = NULL, unlock_blocked_until = NULL
WHERE token = ?`
).bind(token).run();
- await setShareAccessCookie(c, token, gate.password_hash);
+ // Scope the grant to the address the visitor used, so a slug link keeps its unlock.
+ await setShareAccessCookie(c, token, gate.password_hash, shareAccessCookiePath(c.req.param("token").trim()));
c.header("Cache-Control", "private, no-store");
c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
return c.json({ ok: true });
});
app.get("/api/public/shares/:token/resources/:resourceId/blob", async (c) => {
- const token = normalizeShareToken(c.req.param("token"));
+ const token = await resolveShareToken(c, c.req.param("token"));
if (!token) return notFound(c, "Shared resource not found");
const resource = await c.env.storage.db.prepare(
@@ -285,7 +288,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.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,
m.title, m.notebook_id, n.name AS notebook_name
FROM memo_shares ms
INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
@@ -370,7 +373,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.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
FROM memo_shares ms
INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
WHERE ms.memo_id = ? AND ms.workspace_id = ? AND m.is_deleted = 0
@@ -430,7 +433,38 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {
const now = isoNow();
const actor = getAuditActor(c);
- if (!c.req.valid("json").passwordProtected) {
+ const { passwordProtected, slug } = c.req.valid("json");
+ if (slug !== undefined && slug !== (existing.slug ?? null)) {
+ if (slug !== null) {
+ await c.env.storage.db.prepare(
+ `INSERT OR IGNORE INTO memo_share_slug_claims (slug, workspace_id, created_at) VALUES (?, ?, ?)`
+ ).bind(slug, workspaceId, now).run();
+ const claim = await c.env.storage.db.prepare(
+ `SELECT workspace_id FROM memo_share_slug_claims WHERE slug = ?`
+ ).bind(slug).first<{ workspace_id: string }>();
+ if (claim?.workspace_id !== workspaceId) return shareSlugTaken(c);
+ const owner = await c.env.storage.db.prepare(
+ `SELECT memo_id FROM memo_shares WHERE slug = ? LIMIT 1`
+ ).bind(slug).first<{ memo_id: string }>();
+ if (owner) return shareSlugTaken(c);
+ }
+ try {
+ await c.env.storage.db.prepare(
+ `UPDATE memo_shares SET slug = ?, updated_at = ? WHERE memo_id = ? AND workspace_id = ?`
+ ).bind(slug, now, memoId, workspaceId).run();
+ } catch (error) {
+ // A concurrent claim of the same slug loses on the unique index.
+ if (String(error).includes("UNIQUE")) return shareSlugTaken(c);
+ throw error;
+ }
+ await audit(c.env.storage.db, actor.actorType, actor.actorId, slug ? "memo.share_slug_set" : "memo.share_slug_clear", "memo", memoId, {});
+ }
+ if (passwordProtected === 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) {
await c.env.storage.db.prepare(
`UPDATE memo_shares
SET password_hash = NULL, password_encrypted = NULL, unlock_failed_count = 0, unlock_window_started_at = NULL,
diff --git a/apps/web/share-markdown-dev.test.mjs b/apps/web/share-markdown-dev.test.mjs
index ebe82928..3bc4557e 100644
--- a/apps/web/share-markdown-dev.test.mjs
+++ b/apps/web/share-markdown-dev.test.mjs
@@ -13,6 +13,7 @@ describe("local share markdown", () => {
expect(devShareMarkdownToken(`/share/${token}.md`)).toBe(token);
expect(devShareMarkdownToken(`/share/${token}`)).toBeNull();
expect(devShareMarkdownToken(`/share/${token}.md/extra`)).toBeNull();
+ expect(devShareMarkdownToken("/share/Meeting-Notes.md")).toBe("meeting-notes");
});
test("uses the worker markdown response when it is already markdown", async () => {
diff --git a/apps/web/share-markdown-dev.ts b/apps/web/share-markdown-dev.ts
index 446fc44d..f1738996 100644
--- a/apps/web/share-markdown-dev.ts
+++ b/apps/web/share-markdown-dev.ts
@@ -1,4 +1,5 @@
import {
+ parsePublicMemoSharePagePath,
PUBLIC_SHARE_MARKDOWN_NOT_FOUND,
PUBLIC_SHARE_MARKDOWN_PASSWORD,
publicShareMarkdown,
@@ -6,9 +7,10 @@ import {
import { PUBLIC_PAGE_HEADERS } from "@edgeever/shared/public-page-headers";
import type { Plugin } from "vite";
-const SHARE_MARKDOWN_PATH = /^\/share\/([A-Za-z0-9_-]{43})\.md\/?$/;
-
-export const devShareMarkdownToken = (pathname: string) => SHARE_MARKDOWN_PATH.exec(pathname)?.[1] ?? null;
+export const devShareMarkdownToken = (pathname: string) => {
+ const target = parsePublicMemoSharePagePath(pathname);
+ return target?.markdown ? target.segment : null;
+};
const LOCAL_API_ORIGIN = "http://127.0.0.1:8787";
type ShareMarkdownResult = { status: number; body: string };
diff --git a/apps/web/src/components/dialogs/ShareMemoDialog.tsx b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
index 4c5b78f0..fdf00528 100644
--- a/apps/web/src/components/dialogs/ShareMemoDialog.tsx
+++ b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
@@ -6,10 +6,12 @@ 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 { memoSharePathSegment } from "@edgeever/shared";
import { SharePasswordControls } from "./SharePasswordControls";
+import { ShareSlugControls } from "./ShareSlugControls";
import { ShareQrCode } from "./ShareQrCode";
import { SHARE_DIALOG_PRIMARY_BUTTON_CLASS_NAME, SHARE_DIALOG_WIDTH_CLASS_NAME } from "./share-dialog-layout";
-import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
+import { api, ApiRequestError, getConfiguredDesktopApiBaseUrl } from "@/lib/api";
import { copyTextToClipboard } from "@/lib/clipboard";
import { MemoNotebookSites } from "../MemoNotebookSites";
@@ -59,6 +61,13 @@ export const ShareMemoDialog = ({
void queryClient.invalidateQueries({ queryKey: ["memo-shares"] });
},
});
+ const slugMutation = useMutation({
+ mutationFn: (slug: string | null) => api.updateMemoShare(memoId, { slug }),
+ onSuccess: (data) => {
+ queryClient.setQueryData(queryKey, data);
+ void queryClient.invalidateQueries({ queryKey: ["memo-shares"] });
+ },
+ });
const revokeMutation = useMutation({
mutationFn: (targetMemoId: string) => api.revokeMemoShare(targetMemoId),
onSuccess: (_, targetMemoId) => {
@@ -69,6 +78,7 @@ export const ShareMemoDialog = ({
useEffect(() => {
createMutation.reset();
passwordMutation.reset();
+ slugMutation.reset();
revokeMutation.reset();
setCopyState("idle");
setCopyTarget("link");
@@ -80,9 +90,10 @@ export const ShareMemoDialog = ({
const share = shareQuery.data?.share ?? null;
const revealedPassword = share?.passwordProtected ? share.password ?? "" : "";
- const shareUrl = share ? getPublicShareUrl(share.token) : "";
- const isWorking = shareQuery.isLoading || createMutation.isPending || passwordMutation.isPending || revokeMutation.isPending;
- const error = shareQuery.error || createMutation.error || passwordMutation.error || revokeMutation.error;
+ const shareUrl = share ? getPublicShareUrl(memoSharePathSegment(share)) : "";
+ const isWorking = shareQuery.isLoading || createMutation.isPending || passwordMutation.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 markCopied = (target: "link" | "password" | "both", copied: boolean) => {
setCopyTarget(target);
@@ -153,6 +164,13 @@ export const ShareMemoDialog = ({
</Button>
</div>
+ <ShareSlugControls
+ slug={share.slug ?? null}
+ busy={isWorking}
+ taken={slugTaken}
+ onChange={(slug) => slugMutation.mutate(slug)}
+ />
+
<SharePasswordControls
passwordProtected={share.passwordProtected}
password={revealedPassword}
diff --git a/apps/web/src/components/dialogs/ShareSlugControls.tsx b/apps/web/src/components/dialogs/ShareSlugControls.tsx
new file mode 100644
index 00000000..add09956
--- /dev/null
+++ b/apps/web/src/components/dialogs/ShareSlugControls.tsx
@@ -0,0 +1,101 @@
+import { isValidMemoShareSlug, MEMO_SHARE_SLUG_MAX_LENGTH } from "@edgeever/shared";
+import { Check, LoaderCircle, X } from "lucide-react";
+import { useEffect, useId, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+
+export const ShareSlugControls = ({
+ slug,
+ busy,
+ taken,
+ onChange,
+}: {
+ slug: string | null;
+ busy: boolean;
+ taken: boolean;
+ onChange: (slug: string | null) => void;
+}) => {
+ const { t } = useTranslation();
+ const inputId = useId();
+ const [draft, setDraft] = useState(slug ?? "");
+ const [submitted, setSubmitted] = useState<string | null>(null);
+ useEffect(() => setDraft(slug ?? ""), [slug]);
+
+ const normalized = draft.trim().toLowerCase();
+ const invalid = normalized !== "" && !isValidMemoShareSlug(normalized);
+ // A taken address only describes the value that was sent; editing the field clears it.
+ const showTaken = taken && normalized === submitted;
+ const canSave = !busy && normalized !== "" && !invalid && normalized !== slug;
+
+ return (
+ <form
+ className="space-y-1.5 pt-1"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (!canSave) return;
+ setSubmitted(normalized);
+ onChange(normalized);
+ }}
+ >
+ <label htmlFor={inputId} className="block text-xs font-medium leading-5 text-slate-800">
+ {t("sharing.customSlugLabel")}
+ </label>
+ <div className="flex items-center gap-1.5">
+ <span className="shrink-0 font-mono text-xs text-slate-500">/share/</span>
+ <Input
+ id={inputId}
+ value={draft}
+ maxLength={MEMO_SHARE_SLUG_MAX_LENGTH}
+ autoCapitalize="off"
+ autoComplete="off"
+ spellCheck={false}
+ aria-invalid={invalid || showTaken}
+ onChange={(event) => setDraft(event.target.value)}
+ className="min-w-0 font-mono text-xs"
+ />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="submit"
+ variant="outline"
+ size="icon"
+ className="h-9 w-9 shrink-0"
+ disabled={!canSave}
+ aria-label={t("sharing.customSlugSave")}
+ >
+ {busy ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("sharing.customSlugSave")}</TooltipContent>
+ </Tooltip>
+ {slug ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="h-9 w-9 shrink-0"
+ disabled={busy}
+ aria-label={t("sharing.customSlugClear")}
+ onClick={() => onChange(null)}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("sharing.customSlugClear")}</TooltipContent>
+ </Tooltip>
+ ) : null}
+ </div>
+ {invalid || showTaken ? (
+ <p className="text-xs leading-5 text-rose-600" role="alert">
+ {t(invalid ? "sharing.customSlugInvalid" : "sharing.customSlugTaken")}
+ </p>
+ ) : (
+ <p className="text-xs leading-5 text-slate-500">{t("sharing.customSlugHint")}</p>
+ )}
+ </form>
+ );
+};
diff --git a/apps/web/src/components/settings/ShareManagementCard.tsx b/apps/web/src/components/settings/ShareManagementCard.tsx
index 9b5b8da2..be20b8b5 100644
--- a/apps/web/src/components/settings/ShareManagementCard.tsx
+++ b/apps/web/src/components/settings/ShareManagementCard.tsx
@@ -2,7 +2,7 @@ import { useInfiniteQuery } from "@tanstack/react-query";
import { FileText, Link2, LoaderCircle, LockKeyhole } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
-import type { ManagedMemoShare } from "@edgeever/shared";
+import { memoSharePathSegment, type ManagedMemoShare } from "@edgeever/shared";
import { ShareManagementActions } from "./ShareManagementActions";
import { NotebookShareManagement } from "./NotebookShareManagement";
import { Button } from "@/components/ui/button";
@@ -39,7 +39,7 @@ export const ShareManagementCard = ({ userId, onOpenMemo }: Props) => {
const locale = i18n.resolvedLanguage || i18n.language;
const formatDate = (value: string) => new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(value));
const copyLink = async (share: ManagedMemoShare) => {
- setCopyResult({ memoId: share.memoId, success: await copyTextToClipboard(getPublicShareUrl(share.token)) });
+ setCopyResult({ memoId: share.memoId, success: await copyTextToClipboard(getPublicShareUrl(memoSharePathSegment(share))) });
};
return (
@@ -97,7 +97,7 @@ export const ShareManagementCard = ({ userId, onOpenMemo }: Props) => {
<ShareManagementActions
onCopy={() => void copyLink(share)}
copyLabel={copyResult?.memoId === share.memoId ? t(copyResult.success ? "sharing.copied" : "sharing.copyFailed") : undefined}
- onOpen={() => window.open(getPublicShareUrl(share.token), "_blank", "noopener,noreferrer")}
+ onOpen={() => window.open(getPublicShareUrl(memoSharePathSegment(share)), "_blank", "noopener,noreferrer")}
onManage={() => setManagedMemoId(share.memoId)}
/>
</div>
diff --git a/docs/changes/2026-10-27-memo-share-custom-address.md b/docs/changes/2026-10-27-memo-share-custom-address.md
new file mode 100644
index 00000000..98b6fcd2
--- /dev/null
+++ b/docs/changes/2026-10-27-memo-share-custom-address.md
@@ -0,0 +1,23 @@
+# Custom address for single-note share links
+
+[简体中文](2026-10-27-memo-share-custom-address.zh-CN.md)
+
+## Problem and outcome
+
+Implements [Issue #691](https://github.com/tianma-if/edgeever/issues/691). A single-note share link is always `/share/<43-character random token>`. It is safe but cannot be read aloud, typed or remembered. The owner can now give an active note share an optional custom address, for example `/share/meeting-notes`, from the share dialog. The random token link keeps working, so links that were already sent and clients that do not know the new field are unaffected.
+
+## Behavior
+
+| ID | Behavior | Acceptance |
+| --- | --- | --- |
+| S01 | Migration `0081` adds a nullable `memo_shares.slug` with a partial unique index and a `memo_share_slug_claims` table. Existing rows keep their token, password and unlock state; `slug` starts as `NULL`. | Upgrading a database with existing password-protected and public shares keeps both reachable by token. |
+| S02 | `PATCH /api/v1/memos/:id/share` accepts `slug` (string or `null`) in addition to `passwordProtected`; at least one is required. Slugs are trimmed and lowercased, 3–40 characters of `a-z`, `0-9` and single inner hyphens, and `notebook` is reserved. Invalid input returns 400; an address used by any other share on the instance returns 409 `share_slug_taken`. The first workspace to claim an address keeps it in `memo_share_slug_claims` even after it is cleared or the share is revoked, so another tenant cannot take over links that were already sent. | API tests cover valid, invalid, reserved, duplicate, unchanged and empty payloads, and a cross-workspace claim after release. |
+| S03 | Public note routes and the server-rendered `/share/<address>` page and `/share/<address>.md` resolve either the token or the slug to the same share. Only the slug is lowercased on lookup, so `/share/Meeting-Notes` opens `meeting-notes`; the token stays case-sensitive. Password-protected notes stay out of the HTML and Markdown. Password gates, rate limits and attachment checks are unchanged. The unlock cookie is scoped to the address the visitor used. Links between public notes prefer the custom address. | API tests unlock through the slug and then read the note and an attachment; token links still work. Share page tests cover a slug in HTML and Markdown, mixed case and a password-protected slug. |
+| S04 | Changing or clearing the address retires the previous one immediately; revoking the share retires both. | API tests check 404 for retired addresses. |
+| S05 | The web share dialog shows a "Custom address" field with validation, a save action and a remove action with a Tooltip. The "already in use" message clears as soon as the field changes. The dialog link, copy action and the settings share list use the custom address when set. Copy is in all shipped locales. | Type check and web build; manual check in the running app. |
+
+Android and iOS keep showing the token link, which remains valid. They can adopt the `slug` field later.
+
+## Risk and rollback
+
+Worst case: a short custom address is easier to guess than a random token, so the hint states this and password protection still applies. Rolling back the application leaves the additive column in place; custom addresses stop resolving and token links keep working. No existing migration is modified.
diff --git a/docs/changes/2026-10-27-memo-share-custom-address.zh-CN.md b/docs/changes/2026-10-27-memo-share-custom-address.zh-CN.md
new file mode 100644
index 00000000..3419b5b3
--- /dev/null
+++ b/docs/changes/2026-10-27-memo-share-custom-address.zh-CN.md
@@ -0,0 +1,23 @@
+# 单篇笔记分享链接的自定义地址
+
+[English](2026-10-27-memo-share-custom-address.md)
+
+## 问题与结果
+
+实现 [Issue #691](https://github.com/tianma-if/edgeever/issues/691)。单篇笔记分享链接固定为 `/share/<43 位随机令牌>`,安全但难以口述、输入或记忆。现在所有者可以在分享对话框中为已开启的笔记分享设置可选的自定义地址,例如 `/share/meeting-notes`。随机令牌链接继续有效,已经发出的链接和不认识新字段的客户端都不受影响。
+
+## 行为
+
+| 编号 | 行为 | 验收 |
+| --- | --- | --- |
+| S01 | Migration `0081` 为 `memo_shares` 新增可空的 `slug` 列及部分唯一索引,并新增 `memo_share_slug_claims` 表。现有记录保留令牌、密码和解锁状态,`slug` 初始为 `NULL`。 | 升级包含公开分享和密码分享的旧数据库后,两者仍可通过令牌访问。 |
+| S02 | `PATCH /api/v1/memos/:id/share` 在 `passwordProtected` 之外接受 `slug`(字符串或 `null`),二者至少提供一个。地址会去除首尾空白并转为小写,长度 3–40,仅允许 `a-z`、`0-9` 和中间的单个连字符,`notebook` 为保留字。非法输入返回 400;实例内其他分享已使用的地址返回 409 `share_slug_taken`。地址由首个占用它的工作区记录在 `memo_share_slug_claims` 中,即使清除地址或撤销分享也不会释放给其他工作区,避免他人接管已经发出的链接。 | API 测试覆盖合法、非法、保留、重复、未变化和空请求,以及地址释放后其他工作区的占用尝试。 |
+| S03 | 公开笔记路由以及服务端渲染的 `/share/<地址>` 页面和 `/share/<地址>.md` 将令牌或自定义地址解析到同一分享。查找时只将自定义地址转为小写,因此 `/share/Meeting-Notes` 可打开 `meeting-notes`;令牌仍区分大小写。受密码保护的笔记不会出现在 HTML 和 Markdown 中。密码门禁、频率限制和附件校验不变。解锁 Cookie 的作用域为访问者使用的地址。公开笔记之间的链接优先使用自定义地址。 | API 测试通过自定义地址解锁后读取笔记和附件;令牌链接仍可用。分享页测试覆盖 HTML 与 Markdown 中的自定义地址、大小写混合以及受密码保护的自定义地址。 |
+| S04 | 修改或清除地址会立即使旧地址失效;撤销分享会使两者同时失效。 | API 测试确认失效地址返回 404。 |
+| S05 | Web 分享对话框新增“自定义地址”字段,带校验、保存操作和带 Tooltip 的移除操作。字段内容一旦变化,“地址已被使用”提示即清除。对话框中的链接、复制操作以及设置中的分享列表在设置后使用自定义地址。所有已发布语言均有文案。 | 类型检查与 Web 构建;在运行中的应用里手动检查。 |
+
+Android 与 iOS 继续显示仍然有效的令牌链接,之后可以再接入 `slug` 字段。
+
+## 风险与回滚
+
+最坏情况:较短的自定义地址比随机令牌更容易被猜到,因此提示文案会说明这一点,密码保护依然可用。回滚应用后新增列保留,自定义地址不再解析,令牌链接继续有效。不修改任何已有 Migration。
diff --git a/migrations/0081_memo_share_slugs.sql b/migrations/0081_memo_share_slugs.sql
new file mode 100644
index 00000000..47105315
--- /dev/null
+++ b/migrations/0081_memo_share_slugs.sql
@@ -0,0 +1,13 @@
+-- Optional owner-chosen address for a single-note share. The random token keeps
+-- working, so older clients and previously copied links are unaffected.
+ALTER TABLE memo_shares ADD COLUMN slug TEXT;
+CREATE UNIQUE INDEX idx_memo_shares_slug ON memo_shares(slug) WHERE slug IS NOT NULL;
+
+-- An address stays bound to the first workspace that claimed it, even after it is
+-- cleared or the share is revoked, so another tenant cannot take over links that
+-- were already sent.
+CREATE TABLE memo_share_slug_claims (
+ slug TEXT PRIMARY KEY,
+ workspace_id TEXT NOT NULL,
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
+);
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 651bf95c..ec854bbf 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 }) =>
+ updateMemoShare: (memoId: string, payload: { passwordProtected?: boolean; slug?: string | null }) =>
request<{ share: MemoShare }>(`/api/v1/memos/${memoId}/share`, {
method: "PATCH",
body: JSON.stringify(payload),
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 8694fb64..4d54b27e 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -7,6 +7,7 @@
".": "./src/index.ts",
"./diagram-canvas": "./src/diagram-canvas.ts",
"./public-demo": "./src/public-demo.ts",
+ "./share-slug": "./src/share-slug.ts",
"./ai-generation": "./src/ai-generation.ts",
"./diagram-layout": "./src/diagram-layout.ts",
"./ai-prompt-seeds": "./src/ai-prompt-seeds.ts",
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 44f9f135..f14e855f 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2932,6 +2932,12 @@ export const enUS = {
description: "Anyone with the link can view the latest saved version of this note without signing in.",
descriptionProtected: "Anyone with the link must enter the password to view the latest saved version of this note.",
linkLabel: "Public share link",
+ customSlugLabel: "Custom address",
+ customSlugHint: "Lowercase letters, digits and hyphens, 3–40 characters. The original random link keeps working. A short address is easier to guess.",
+ customSlugSave: "Save address",
+ customSlugClear: "Remove address",
+ customSlugInvalid: "Use 3–40 lowercase letters, digits or single hyphens. It cannot start or end with a hyphen.",
+ customSlugTaken: "This address is already in use. Choose another one.",
inactiveHint: "Create a private, unguessable link that you can revoke at any time.",
liveContentHint: "The link always shows the latest saved content. Revoking it disables the note and its attachments immediately.",
create: "Create share link",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index cc4c3928..8070b103 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2921,6 +2921,12 @@ export const ja = {
description: "リンクを持つ人は、サインインなしでこのノートの最新の保存版を閲覧できます。",
descriptionProtected: "リンクを持つ人は、パスワードを入力するとこのノートの最新の保存版を閲覧できます。",
linkLabel: "公開共有リンク",
+ customSlugLabel: "カスタムアドレス",
+ customSlugHint: "英小文字・数字・ハイフンで 3〜40 文字。元のランダムリンクも引き続き使えます。短いアドレスは推測されやすくなります。",
+ customSlugSave: "アドレスを保存",
+ customSlugClear: "アドレスを削除",
+ customSlugInvalid: "英小文字・数字・単一のハイフンで 3〜40 文字にしてください。先頭と末尾にハイフンは使えません。",
+ customSlugTaken: "このアドレスは既に使われています。別のアドレスを選んでください。",
inactiveHint: "推測しにくい専用リンクを作成します。いつでも取り消せます。",
liveContentHint: "リンクは常に最新の保存内容を表示します。取り消すと、ノートとその添付はすぐに非公開になります。",
create: "共有リンクを作成",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 934be101..ad5de4df 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2921,6 +2921,12 @@ export const pl = {
description: "Każdy, kto ma link, może bez logowania wyświetlić najnowszą zapisaną wersję tej notatki.",
descriptionProtected: "Każdy, kto ma link, musi wpisać hasło, aby wyświetlić najnowszą zapisaną wersję tej notatki.",
linkLabel: "Publiczny link udostępniania",
+ customSlugLabel: "Własny adres",
+ customSlugHint: "Małe litery, cyfry i myślniki, 3–40 znaków. Pierwotny losowy link nadal działa. Krótki adres łatwiej odgadnąć.",
+ customSlugSave: "Zapisz adres",
+ customSlugClear: "Usuń adres",
+ customSlugInvalid: "Użyj 3–40 małych liter, cyfr lub pojedynczych myślników. Adres nie może zaczynać się ani kończyć myślnikiem.",
+ customSlugTaken: "Ten adres jest już zajęty. Wybierz inny.",
inactiveHint: "Utwórz prywatny, niemożliwy do odgadnięcia link, który możesz w każdej chwili unieważnić.",
liveContentHint: "Link zawsze pokazuje najnowszą zapisaną treść. Unieważnienie go natychmiast blokuje dostęp do notatki i jej załączników.",
create: "Utwórz link udostępniania",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index f3e297bd..e150e65d 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -2932,6 +2932,12 @@ export const ru = {
description: "Любой, у кого есть ссылка, может просмотреть последнюю сохранённую версию этой заметки без входа.",
descriptionProtected: "Любой, у кого есть ссылка, должен ввести пароль, чтобы просмотреть последнюю сохранённую версию этой заметки.",
linkLabel: "Публичная ссылка",
+ customSlugLabel: "Свой адрес",
+ customSlugHint: "Строчные латинские буквы, цифры и дефисы, 3–40 символов. Исходная случайная ссылка продолжает работать. Короткий адрес легче угадать.",
+ customSlugSave: "Сохранить адрес",
+ customSlugClear: "Удалить адрес",
+ customSlugInvalid: "Используйте 3–40 строчных латинских букв, цифр или одиночных дефисов. Адрес не может начинаться или заканчиваться дефисом.",
+ customSlugTaken: "Этот адрес уже занят. Выберите другой.",
inactiveHint: "Создайте приватную, неугадываемую ссылку, которую можно отозвать в любой момент.",
liveContentHint: "Ссылка всегда показывает последнее сохранённое содержимое. При отзыве доступ к заметке и вложениям отключается сразу.",
create: "Создать ссылку для доступа",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index daed86e6..6ce9cbaa 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2930,6 +2930,12 @@ export const zhCN = {
description: "任何获得链接的人无需登录,即可查看这篇笔记最新保存的内容。",
descriptionProtected: "获得链接的人需要输入密码后,才能查看这篇笔记最新保存的内容。",
linkLabel: "公开分享链接",
+ customSlugLabel: "自定义地址",
+ customSlugHint: "小写字母、数字和连字符,3–40 个字符。原随机链接仍然有效。较短的地址更容易被猜到。",
+ customSlugSave: "保存地址",
+ customSlugClear: "移除地址",
+ customSlugInvalid: "请使用 3–40 个小写字母、数字或单个连字符,且不能以连字符开头或结尾。",
+ customSlugTaken: "该地址已被使用,请换一个。",
inactiveHint: "创建一个难以猜测的专属链接;你可以随时撤销。",
liveContentHint: "链接会展示最新保存的内容。撤销后,笔记及其中的附件会立即停止公开访问。",
create: "创建分享链接",
diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.ts
index 2011e47c..214f77cc 100644
--- a/packages/shared/src/schemas.ts
+++ b/packages/shared/src/schemas.ts
@@ -1,4 +1,4 @@
-import { PUBLISHED_NOTE_BODY_FONTS } from "./sharing";
+import { isValidMemoShareSlug, PUBLISHED_NOTE_BODY_FONTS } from "./sharing";
import { z } from "zod";
import {
MAX_NOTE_PROSE_CSS_BYTES,
@@ -445,7 +445,12 @@ export const SharePasswordUpdateSchema = z.object({
passwordProtected: z.boolean(),
});
-export const MemoShareUpdateSchema = SharePasswordUpdateSchema;
+export const MemoShareUpdateSchema = z.object({
+ passwordProtected: z.boolean().optional(),
+ slug: z.string().trim().toLowerCase().refine(isValidMemoShareSlug).nullable().optional(),
+}).refine((input) => input.passwordProtected !== undefined || input.slug !== undefined, {
+ message: "At least one field is required.",
+});
export const NotebookShareUpdateSchema = SharePasswordUpdateSchema;
export const NoteBodyFontUpdateSchema = z.object({
diff --git a/packages/shared/src/share-slug.ts b/packages/shared/src/share-slug.ts
new file mode 100644
index 00000000..373c2242
--- /dev/null
+++ b/packages/shared/src/share-slug.ts
@@ -0,0 +1,10 @@
+/** Kept free of imports so server entry points loaded by Node can use it. */
+
+/** 3-40 lowercase letters, digits and inner hyphens; never as long as a 43-character token. */
+export const MEMO_SHARE_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
+export const MEMO_SHARE_SLUG_MAX_LENGTH = 40;
+/** Segments that already mean something under /share/. */
+export const RESERVED_MEMO_SHARE_SLUGS: readonly string[] = ["notebook"];
+
+export const isValidMemoShareSlug = (value: string) =>
+ MEMO_SHARE_SLUG_PATTERN.test(value) && !value.includes("--") && !RESERVED_MEMO_SHARE_SLUGS.includes(value);
diff --git a/packages/shared/src/sharing.ts b/packages/shared/src/sharing.ts
index 729a0f74..6c564cb5 100644
--- a/packages/shared/src/sharing.ts
+++ b/packages/shared/src/sharing.ts
@@ -7,6 +7,8 @@ import type { NotebookSiteSettings } from "./notebook-site";
export type MemoShare = {
memoId: string;
token: string;
+ /** Owner-chosen public address. The token link keeps working alongside it. */
+ slug: string | null;
createdAt: string;
updatedAt: string;
passwordProtected: boolean;
@@ -14,6 +16,11 @@ export type MemoShare = {
password?: string;
};
+export { isValidMemoShareSlug, MEMO_SHARE_SLUG_MAX_LENGTH, MEMO_SHARE_SLUG_PATTERN, RESERVED_MEMO_SHARE_SLUGS } from "./share-slug";
+
+/** Path segment for the public link: the custom address when set, otherwise the token. */
+export const memoSharePathSegment = (share: Pick<MemoShare, "slug" | "token">) => share.slug ?? share.token;
+
export type ManagedMemoShare = MemoShare & {
memoTitle: string | null;
notebookId: string;
diff --git a/tests/auth-fail-closed.test.ts b/tests/auth-fail-closed.test.ts
index d56a1b19..635c5cdb 100644
--- a/tests/auth-fail-closed.test.ts
+++ b/tests/auth-fail-closed.test.ts
@@ -11,6 +11,9 @@ const createDatabase = (options: { userId?: string; error?: Error } = {}) =>
({
prepare(sql: string) {
return {
+ bind() {
+ return this;
+ },
async first() {
if (options.error) throw options.error;
if (sql.includes("d1_migrations")) return { name: "0035_normalized_memo_tags.sql" };