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): optional expiry and open counter for single-note links (#753)

Dariusz Korytoa9e1bcfbf0ab
diff --git a/apps/api/src/memo-share-access.ts b/apps/api/src/memo-share-access.ts
new file mode 100644
index 00000000..216d5706
--- /dev/null
+++ b/apps/api/src/memo-share-access.ts
@@ -0,0 +1,17 @@
+import { isoNow } from "./entity-utils";
+import type { DatabaseAdapter } from "./storage-contract";
+
+/** Expiry is decided on the server only; stored values are normalized UTC ISO strings. */
+export const isMemoShareExpired = (expiresAt: string | null | undefined, now = isoNow()) =>
+ Boolean(expiresAt) && (expiresAt as string) <= now;
+
+/** Counts note content served to a visitor. A failed write never blocks reading the note. */
+export const recordMemoShareView = async (db: DatabaseAdapter, token: string) => {
+ try {
+ await db.prepare(
+ `UPDATE memo_shares SET view_count = view_count + 1, last_viewed_at = ? WHERE token = ?`
+ ).bind(isoNow(), token).run();
+ } catch (error) {
+ console.warn("Could not record a shared note view", error);
+ }
+};
diff --git a/apps/api/src/share-page.test.mjs b/apps/api/src/share-page.test.mjs
index c704d4ba..ad6bc3b3 100644
--- a/apps/api/src/share-page.test.mjs
+++ b/apps/api/src/share-page.test.mjs
@@ -234,3 +234,52 @@ describe("public memo share pages", () => {
expect(webConfig).toContain("!/^\\/(?:share|s)\\//.test(url.pathname)");
});
});
+
+describe("expiring and counted share pages", () => {
+ const viewCount = (sqlite) => sqlite.query("SELECT view_count FROM memo_shares WHERE token = ?").get(token).view_count;
+
+ test("an expired link serves neither markdown nor the note in HTML", async () => {
+ const sqlite = createDatabase();
+ try {
+ sqlite.query("UPDATE memo_shares SET expires_at = '2020-01-01T00:00:00.000Z' WHERE token = ?").run(token);
+ const markdown = await render(sqlite, `/share/${token}.md`);
+ expect(markdown.status).toBe(410);
+ expect(await markdown.text()).toBe("This shared link has expired.\n");
+
+ const html = await render(sqlite, `/share/${token}`);
+ const page = await html.text();
+ expect(page).not.toContain("Hello");
+ expect(page).not.toContain("edgeever-shared-note");
+ expect(page).toContain("This shared link has expired.");
+ expect(html.headers.get("Link")).toBeNull();
+ expect(viewCount(sqlite)).toBe(0);
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("a future expiry keeps the page readable", async () => {
+ const sqlite = createDatabase();
+ try {
+ sqlite.query("UPDATE memo_shares SET expires_at = '2999-01-01T00:00:00.000Z' WHERE token = ?").run(token);
+ expect((await render(sqlite, `/share/${token}.md`)).status).toBe(200);
+ expect(await (await render(sqlite, `/share/${token}`)).text()).toContain("edgeever-shared-note");
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("counts markdown reads but not the HTML shell or HEAD requests", async () => {
+ const sqlite = createDatabase();
+ try {
+ await render(sqlite, `/share/${token}`);
+ expect(viewCount(sqlite)).toBe(0);
+ await renderPublicMemoSharePage(new Request(`https://note.example/share/${token}.md`, { method: "HEAD" }), dbOf(sqlite), async () => new Response(shell));
+ expect(viewCount(sqlite)).toBe(0);
+ expect((await render(sqlite, `/share/${token}.md`)).status).toBe(200);
+ expect(viewCount(sqlite)).toBe(1);
+ } finally {
+ sqlite.close();
+ }
+ });
+});
diff --git a/apps/api/src/share-page.ts b/apps/api/src/share-page.ts
index 6c662b94..ab9bb1c0 100644
--- a/apps/api/src/share-page.ts
+++ b/apps/api/src/share-page.ts
@@ -1,6 +1,7 @@
import { getMemoDisplayTitle } from "@edgeever/shared/memo-title";
import { isValidMemoShareSlug } from "@edgeever/shared/share-slug";
import { PUBLIC_PAGE_HEADERS, PUBLIC_PAGE_ROBOTS } from "@edgeever/shared/public-page-headers";
+import { isMemoShareExpired, recordMemoShareView } from "./memo-share-access";
import type { DatabaseAdapter } from "./storage-contract";
const SHARE_PAGE_PATH = /^\/share\/([^/]+?)(\.md)?\/?$/;
@@ -10,6 +11,7 @@ type SharePageRow = {
title: string | null;
content_markdown: string | null;
password_hash: string | null;
+ expires_at: string | null;
updated_at: string;
show_updated_at: number;
show_branding: number;
@@ -81,6 +83,7 @@ const describeNote = (markdown: string) => {
export const PUBLIC_SHARE_MARKDOWN_NOT_FOUND = "Shared note not found\n";
export const PUBLIC_SHARE_MARKDOWN_PASSWORD = "This shared note requires a password.\n";
+export const PUBLIC_SHARE_MARKDOWN_EXPIRED = "This shared link has expired.\n";
/** Markdown body for a public note. A title already used as the first heading is kept once. */
export const publicShareMarkdown = (title: string | null, body: string) => {
@@ -93,7 +96,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, m.updated_at, ms.show_updated_at, ms.show_branding
+ `SELECT m.title, mc.content_markdown, ms.password_hash, ms.expires_at, m.updated_at, ms.show_updated_at, ms.show_branding
FROM memo_shares ms
INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
INNER JOIN memo_contents mc ON mc.memo_id = m.id
@@ -140,8 +143,9 @@ export const renderPublicMemoSharePage = async (
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 expired = Boolean(row) && isMemoShareExpired(row?.expires_at);
+ const locked = !expired && Boolean(row?.password_hash);
+ const readable = Boolean(row) && !expired && !locked;
const body = row?.content_markdown ?? "";
const markdownUrl = `${url.origin}/share/${encodeURIComponent(target.segment)}.md`;
const canonical = `${url.origin}/share/${encodeURIComponent(target.segment)}`;
@@ -151,9 +155,14 @@ export const renderPublicMemoSharePage = async (
if (!row) {
return new Response(request.method === "HEAD" ? null : PUBLIC_SHARE_MARKDOWN_NOT_FOUND, { status: 404, headers });
}
+ if (expired) {
+ return new Response(request.method === "HEAD" ? null : PUBLIC_SHARE_MARKDOWN_EXPIRED, { status: 410, headers });
+ }
if (locked) {
return new Response(request.method === "HEAD" ? null : PUBLIC_SHARE_MARKDOWN_PASSWORD, { status: 403, headers });
}
+ // The HTML shell below is not counted: a browser opening it counts once through the share API.
+ if (request.method === "GET" && token) await recordMemoShareView(db, token);
headers.set("Content-Disposition", "inline");
return new Response(request.method === "HEAD" ? null : publicShareMarkdown(row.title, body), { status: 200, headers });
}
@@ -161,9 +170,11 @@ export const renderPublicMemoSharePage = async (
const title = readable ? (getMemoDisplayTitle(row?.title, "").replace(/[\r\n]+/g, " ").trim() || "Shared note") : "Shared note";
const description = readable
? describeNote(body)
- : locked
- ? "This shared note requires a password."
- : "Read a shared note on EdgeEver.";
+ : expired
+ ? "This shared link has expired."
+ : 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>`
: "";
diff --git a/apps/api/src/share-routes.test.mjs b/apps/api/src/share-routes.test.mjs
index 6ba3f6dc..a0447cec 100644
--- a/apps/api/src/share-routes.test.mjs
+++ b/apps/api/src/share-routes.test.mjs
@@ -881,3 +881,181 @@ describe("custom memo share addresses", () => {
sqlite.close();
});
});
+
+describe("memo share expiry and views", () => {
+ const past = "2020-01-01T00:00:00.000Z";
+ const json = (body) => ({ method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ const shareRow = (sqlite, token = sourceToken) =>
+ sqlite.query("SELECT expires_at, view_count, last_viewed_at, updated_at, password_hash FROM memo_shares WHERE token = ?").get(token);
+
+ test("adds the columns to existing shares without changing them", async () => {
+ const sqlite = new Database(":memory:");
+ try {
+ for (const migration of globSync("migrations/*.sql").sort()) {
+ if (migration.endsWith("0087_memo_share_expiry_views.sql")) continue;
+ sqlite.exec(readFileSync(migration, "utf8"));
+ }
+ sqlite.query("INSERT INTO workspaces (id, name, is_personal) VALUES ('ws_old', 'Old', 1)").run();
+ sqlite.query("INSERT INTO notebooks (id, workspace_id, name) VALUES ('nb_old', 'ws_old', 'Inbox')").run();
+ sqlite.query("INSERT INTO memos (id, workspace_id, notebook_id, title) VALUES ('memo_old', 'ws_old', 'nb_old', 'Old')").run();
+ sqlite.query("INSERT INTO memo_shares (id, memo_id, workspace_id, token) VALUES ('share_old', 'memo_old', 'ws_old', ?)").run(sourceToken);
+ const before = sqlite.query("SELECT * FROM memo_shares").all();
+ sqlite.exec(readFileSync("migrations/0087_memo_share_expiry_views.sql", "utf8"));
+ expect(sqlite.prepare("SELECT * FROM memo_shares").all()).toEqual(
+ before.map((row) => ({ ...row, expires_at: null, view_count: 0, last_viewed_at: null })),
+ );
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("sets, normalizes, extends and removes the expiry without touching the password", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ const app = createShareApp(environment);
+ const path = "/api/v1/memos/memo_source/share";
+ try {
+ await app.request(path, json({ passwordProtected: true, password: "keep-this" }), environment);
+ const passwordHash = shareRow(sqlite).password_hash;
+ expect(passwordHash).toBeTruthy();
+
+ const future = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000);
+ const offset = future.toISOString().replace("Z", "+00:00");
+ const set = await app.request(path, json({ expiresAt: offset }), environment);
+ expect(set.status).toBe(200);
+ expect((await set.json()).share).toMatchObject({ expiresAt: future.toISOString(), expired: false, passwordProtected: true });
+ expect(shareRow(sqlite)).toMatchObject({ expires_at: future.toISOString(), password_hash: passwordHash });
+
+ const later = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
+ expect((await (await app.request(path, json({ expiresAt: later }), environment)).json()).share.expiresAt).toBe(later);
+
+ const cleared = await app.request(path, json({ expiresAt: null }), environment);
+ expect((await cleared.json()).share).toMatchObject({ expiresAt: null, expired: false, passwordProtected: true });
+ expect(shareRow(sqlite)).toMatchObject({ expires_at: null, password_hash: passwordHash });
+
+ // Older clients keep sending only the password field.
+ const legacy = await app.request(path, json({ passwordProtected: false }), environment);
+ expect(legacy.status).toBe(200);
+ expect((await legacy.json()).share).toMatchObject({ passwordProtected: false, expiresAt: null });
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("rejects past and malformed expiry values", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ const app = createShareApp(environment);
+ const path = "/api/v1/memos/memo_source/share";
+ try {
+ const pastResponse = await app.request(path, json({ expiresAt: past }), environment);
+ expect(pastResponse.status).toBe(400);
+ expect((await pastResponse.json()).error.code).toBe("share_expiry_invalid");
+ expect((await app.request(path, json({ expiresAt: "tomorrow" }), environment)).status).toBe(400);
+ expect((await app.request(path, json({}), environment)).status).toBe(400);
+ expect(shareRow(sqlite).expires_at).toBeNull();
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("an expired link answers 410 on content, unlock and resources and reveals nothing", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ sqlite.query("UPDATE memo_shares SET expires_at = ?, password_hash = ? WHERE token = ?")
+ .run(past, await hashPassword("secret-pass"), sourceToken);
+ sqlite.query(`INSERT INTO resources (id, memo_id, object_key, kind, mime_type, filename, byte_size)
+ VALUES ('res_expired', 'memo_source', 'expired-key', 'attachment', 'application/pdf', 'a.pdf', 10)`).run();
+ environment.storage.resources = { get: async () => ({ body: new Blob([new Uint8Array(10)]).stream(), size: 10, writeHttpMetadata: () => {} }) };
+ const app = createShareApp(environment);
+ try {
+ const content = await app.request(`/api/public/shares/${sourceToken}`, {}, environment);
+ expect(content.status).toBe(410);
+ const body = await content.json();
+ expect(body.error.code).toBe("share_expired");
+ expect(JSON.stringify(body)).not.toContain("Source");
+
+ const unlock = await app.request(`/api/public/shares/${sourceToken}/unlock`, {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password: "secret-pass" }),
+ }, environment);
+ expect(unlock.status).toBe(410);
+ expect(unlock.headers.get("Set-Cookie")).toBeNull();
+
+ const resource = await app.request(`/api/public/shares/${sourceToken}/resources/res_expired/blob`, {}, environment);
+ expect(resource.status).toBe(410);
+
+ expect((await app.request(`/api/public/shares/${"x".repeat(43)}`, {}, environment)).status).toBe(404);
+ expect(shareRow(sqlite)).toMatchObject({ view_count: 0, last_viewed_at: null });
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("an expired linked note is not linked from another shared note", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ sqlite.query("UPDATE memo_shares SET expires_at = ? WHERE token = ?").run(past, targetToken);
+ const app = createShareApp(environment);
+ try {
+ const response = await app.request(`/api/public/shares/${sourceToken}`, {}, environment);
+ expect(response.status).toBe(200);
+ expect((await response.json()).share.memoShareTokens).toEqual({});
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("the owner still sees an expired share and the dialog does not create a new one", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ sqlite.query("UPDATE memo_shares SET expires_at = ? WHERE token = ?").run(past, sourceToken);
+ const app = createShareApp(environment);
+ try {
+ const read = await (await app.request("/api/v1/memos/memo_source/share", {}, environment)).json();
+ expect(read.share).toMatchObject({ token: sourceToken, expiresAt: past, expired: true });
+ const created = await app.request("/api/v1/memos/memo_source/share", { method: "POST" }, environment);
+ expect(created.status).toBe(200);
+ expect((await created.json()).share).toMatchObject({ token: sourceToken, expired: true });
+ const list = await (await app.request("/api/v1/memo-shares", {}, environment)).json();
+ expect(list.shares.find((share) => share.memoId === "memo_source")).toMatchObject({ expired: true, viewCount: 0 });
+ } finally {
+ sqlite.close();
+ }
+ });
+
+ test("counts served content only, and views do not reorder the share list", async () => {
+ const { sqlite, environment } = createDatabaseEnvironment();
+ const password = "count-pass";
+ sqlite.query("UPDATE memo_shares SET password_hash = ?, updated_at = '2026-01-01T00:00:00.000Z' WHERE token = ?")
+ .run(await hashPassword(password), sourceToken);
+ sqlite.query(`INSERT INTO resources (id, memo_id, object_key, kind, mime_type, filename, byte_size)
+ VALUES ('res_count', 'memo_source', 'count-key', 'attachment', 'application/pdf', 'a.pdf', 10)`).run();
+ environment.storage.resources = { get: async () => ({ body: new Blob([new Uint8Array(10)]).stream(), size: 10, writeHttpMetadata: () => {} }) };
+ const app = createShareApp(environment);
+ const unlock = (value) => app.request(`/api/public/shares/${sourceToken}/unlock`, {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password: value }),
+ }, environment);
+ try {
+ expect((await app.request(`/api/public/shares/${sourceToken}`, {}, environment)).status).toBe(403);
+ expect((await unlock("wrong-password")).status).toBe(403);
+ expect(shareRow(sqlite).view_count).toBe(0);
+
+ const cookie = readCookieValue(await unlock(password), "ee_share");
+ expect(shareRow(sqlite).view_count).toBe(0);
+ const headers = { Cookie: `ee_share=${cookie}` };
+ expect((await app.request(`/api/public/shares/${sourceToken}/resources/res_count/blob`, { headers }, environment)).status).toBe(200);
+ expect(shareRow(sqlite).view_count).toBe(0);
+
+ const probe = await app.request(`/api/public/shares/${sourceToken}`, { method: "HEAD", headers }, environment);
+ expect(probe.status).toBe(200);
+ expect(shareRow(sqlite)).toMatchObject({ view_count: 0, last_viewed_at: null });
+
+ expect((await app.request(`/api/public/shares/${sourceToken}`, { headers }, environment)).status).toBe(200);
+ expect((await app.request(`/api/public/shares/${sourceToken}`, { headers }, environment)).status).toBe(200);
+ const row = shareRow(sqlite);
+ expect(row.view_count).toBe(2);
+ expect(row.last_viewed_at).toBeTruthy();
+ expect(row.updated_at).toBe("2026-01-01T00:00:00.000Z");
+
+ const read = await (await app.request("/api/v1/memos/memo_source/share", {}, environment)).json();
+ expect(read.share).toMatchObject({ viewCount: 2, lastViewedAt: row.last_viewed_at });
+ } finally {
+ sqlite.close();
+ }
+ });
+});
diff --git a/apps/api/src/share-routes.ts b/apps/api/src/share-routes.ts
index cf6f54bb..368868ef 100644
--- a/apps/api/src/share-routes.ts
+++ b/apps/api/src/share-routes.ts
@@ -7,6 +7,7 @@ import { hashPassword, randomToken, verifyPassword } from "./auth-crypto";
import { parseByteRange, rangeNotSatisfiable } from "./byte-range";
import { createId, isoNow, parseJsonArray } from "./entity-utils";
import { apiError, notFound } from "./http-errors";
+import { isMemoShareExpired, recordMemoShareView } from "./memo-share-access";
import { resolveObjectStorage } from "./object-storage";
import { getAuditActor, getWorkspaceId, requireUser } from "./request-auth";
import { setResourceContentHeaders } from "./resource-service";
@@ -31,6 +32,9 @@ type MemoShareRow = {
password_hash: string | null;
show_updated_at?: number | null;
show_branding?: number | null;
+ expires_at?: string | null;
+ view_count?: number | null;
+ last_viewed_at?: string | null;
};
type ManagedMemoShareRow = MemoShareRow & {
title: string | null;
@@ -45,6 +49,7 @@ type PublicMemoShareRow = {
tags_json: string;
updated_at: string;
password_hash: string | null;
+ expires_at: string | null;
show_updated_at?: number | null;
show_branding?: number | null;
note_body_font: string | null;
@@ -52,6 +57,7 @@ type PublicMemoShareRow = {
type ShareGateRow = {
workspace_id: string;
password_hash: string | null;
+ expires_at: string | null;
unlock_failed_count: number;
unlock_window_started_at: string | null;
unlock_blocked_until: string | null;
@@ -66,6 +72,7 @@ type SharedResourceRow = {
byte_size: number;
workspace_id: string;
password_hash: string | null;
+ expires_at: string | null;
};
const mapMemoShare = (row: MemoShareRow, password?: string): MemoShare => ({
@@ -77,6 +84,10 @@ const mapMemoShare = (row: MemoShareRow, password?: string): MemoShare => ({
passwordProtected: Boolean(row.password_hash),
showUpdatedAt: row.show_updated_at !== 0,
showBranding: row.show_branding !== 0,
+ expiresAt: row.expires_at ?? null,
+ expired: isMemoShareExpired(row.expires_at),
+ viewCount: row.view_count ?? 0,
+ lastViewedAt: row.last_viewed_at ?? null,
...(password ? { password } : {}),
});
@@ -94,16 +105,24 @@ const sharePasswordInvalid = (c: AppContext) =>
const shareUnlockRateLimited = (c: AppContext) =>
apiError(c, "share_unlock_rate_limited", "Too many share password attempts. Try again later.", 429);
+// Distinct from 404 so the page can say the link expired; it reveals nothing about the note.
+const shareExpired = (c: AppContext) => {
+ c.header("Cache-Control", "private, no-store");
+ c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
+ return apiError(c, "share_expired", "This shared link has expired", 410);
+};
+
const loadShareGate = async (c: AppContext, token: string) =>
c.env.storage.db.prepare(
- `SELECT ms.workspace_id, ms.password_hash, ms.unlock_failed_count, ms.unlock_window_started_at, ms.unlock_blocked_until
+ `SELECT ms.workspace_id, ms.password_hash, ms.expires_at, ms.unlock_failed_count, ms.unlock_window_started_at, ms.unlock_blocked_until
FROM memo_shares ms
INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
WHERE ms.token = ? AND m.is_deleted = 0
LIMIT 1`
).bind(token).first<ShareGateRow>();
-const selectMemoShareSql = `SELECT memo_id, token, slug, created_at, updated_at, password_hash, password_encrypted, show_updated_at, show_branding
+const selectMemoShareSql = `SELECT memo_id, token, slug, created_at, updated_at, password_hash, password_encrypted, show_updated_at, show_branding,
+ expires_at, view_count, last_viewed_at
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`;
@@ -165,7 +184,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, ms.show_updated_at, ms.show_branding,
+ `SELECT ms.workspace_id, m.title, mc.content_json, mc.content_markdown, m.tags_json, m.updated_at, ms.password_hash, ms.expires_at, 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_colors
FROM memo_shares ms
@@ -176,6 +195,8 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
LIMIT 1`
).bind(token).first<PublicMemoShareRow>();
if (!row) return notFound(c, "Shared note not found");
+ const now = isoNow();
+ if (isMemoShareExpired(row.expires_at, now)) return shareExpired(c);
if (row.password_hash && !(await allowPasswordProtectedShare(c, token, row.password_hash))) {
return sharePasswordRequired(c);
}
@@ -190,8 +211,9 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
`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`
- ).bind(row.workspace_id, ...batch).all<ReferencedMemoShareRow>();
+ WHERE ms.workspace_id = ? AND ms.memo_id IN (${placeholders}) AND m.is_deleted = 0
+ AND (ms.expires_at IS NULL OR ms.expires_at > ?)`
+ ).bind(row.workspace_id, ...batch, now).all<ReferencedMemoShareRow>();
for (const linkedShare of linkedShares.results) {
memoShareTokens[linkedShare.memo_id] = linkedShare.token;
}
@@ -209,6 +231,8 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
showUpdatedAt: row.show_updated_at !== 0,
showBranding: row.show_branding !== 0,
};
+ // Hono answers HEAD through this GET handler; a probe is not a view.
+ if (c.req.method === "GET") await recordMemoShareView(c.env.storage.db, token);
c.header("Cache-Control", "private, no-store");
c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
return c.json({ share });
@@ -220,6 +244,7 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
const gate = await loadShareGate(c, token);
if (!gate) return notFound(c, "Shared note not found");
+ if (isMemoShareExpired(gate.expires_at)) return shareExpired(c);
if (!gate.password_hash) {
return apiError(c, "share_password_not_required", "This shared note does not require a password", 400);
}
@@ -256,7 +281,7 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
const resource = await c.env.storage.db.prepare(
`SELECT r.object_key, r.storage_config_id, r.kind, r.mime_type, r.filename, r.byte_size,
- ms.workspace_id, ms.password_hash
+ ms.workspace_id, ms.password_hash, ms.expires_at
FROM memo_shares ms
INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
INNER JOIN resources r ON r.memo_id = m.id
@@ -264,6 +289,7 @@ export const registerPublicShareRoutes = (app: Hono<AppEnv>) => {
LIMIT 1`
).bind(token, c.req.param("resourceId")).first<SharedResourceRow>();
if (!resource) return notFound(c, "Shared resource not found");
+ if (isMemoShareExpired(resource.expires_at)) return shareExpired(c);
if (resource.password_hash && !(await allowPasswordProtectedShare(c, token, resource.password_hash))) {
return sharePasswordRequired(c);
}
@@ -283,6 +309,7 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {
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, ms.show_updated_at, ms.show_branding,
+ ms.expires_at, ms.view_count, ms.last_viewed_at,
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
@@ -367,7 +394,8 @@ 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, ms.show_updated_at, ms.show_branding
+ `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_branding,
+ ms.expires_at, ms.view_count, ms.last_viewed_at
FROM memo_shares ms
INNER JOIN memos m ON m.id = ms.memo_id AND m.workspace_id = ms.workspace_id
WHERE ms.memo_id = ? AND ms.workspace_id = ? AND m.is_deleted = 0
@@ -427,7 +455,11 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {
const now = isoNow();
const actor = getAuditActor(c);
- const { passwordProtected, password, slug, showUpdatedAt, showBranding } = c.req.valid("json");
+ const { passwordProtected, password, slug, showUpdatedAt, showBranding, expiresAt } = c.req.valid("json");
+ const nextExpiresAt = expiresAt ? new Date(expiresAt).toISOString() : expiresAt;
+ if (nextExpiresAt && nextExpiresAt <= now) {
+ return apiError(c, "share_expiry_invalid", "The expiry must be in the future", 400);
+ }
if (slug !== undefined && slug !== (existing.slug ?? null)) {
if (slug !== null) {
await c.env.storage.db.prepare(
@@ -474,6 +506,20 @@ export const registerMemoShareRoutes = (app: Hono<AppEnv>) => {
{ showUpdatedAt, showBranding },
);
}
+ if (nextExpiresAt !== undefined && nextExpiresAt !== (existing.expires_at ?? null)) {
+ await c.env.storage.db.prepare(
+ `UPDATE memo_shares SET expires_at = ?, updated_at = ? WHERE memo_id = ? AND workspace_id = ?`
+ ).bind(nextExpiresAt, now, memoId, workspaceId).run();
+ await audit(
+ c.env.storage.db,
+ actor.actorType,
+ actor.actorId,
+ nextExpiresAt ? "memo.share_expiry_set" : "memo.share_expiry_clear",
+ "memo",
+ memoId,
+ nextExpiresAt ? { expiresAt: nextExpiresAt } : {},
+ );
+ }
if (passwordProtected === undefined && password === undefined) {
const current = await c.env.storage.db.prepare(selectMemoShareSql)
.bind(memoId, workspaceId).first<MemoShareRow>() ?? existing;
diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsx
index 130c7dcb..84088292 100644
--- a/apps/web/src/components/PublicSharePage.tsx
+++ b/apps/web/src/components/PublicSharePage.tsx
@@ -215,9 +215,15 @@ export const PublicSharePasswordForm = ({
if (!password.trim() || unlockMutation.isPending) return;
unlockMutation.mutate();
};
+ // A link that expired while the form was open shows the expiry page instead.
+ const onUnlockedRef = useRef(onUnlocked);
+ onUnlockedRef.current = onUnlocked;
+ useEffect(() => {
+ if (isSharePasswordError(unlockMutation.error, "share_expired")) void onUnlockedRef.current();
+ }, [unlockMutation.error]);
const errorKey = isSharePasswordError(unlockMutation.error, "share_unlock_rate_limited")
? "sharing.passwordRateLimited"
- : unlockMutation.error
+ : unlockMutation.error && !isSharePasswordError(unlockMutation.error, "share_expired")
? "sharing.passwordInvalid"
: null;
@@ -260,6 +266,7 @@ export const PublicSharePage = () => {
});
const share = shareQuery.data?.share;
const passwordRequired = isSharePasswordError(shareQuery.error, "share_password_required");
+ const expired = isSharePasswordError(shareQuery.error, "share_expired");
useEffect(() => {
const previousTitle = document.title;
@@ -300,9 +307,9 @@ export const PublicSharePage = () => {
return (
<main className="flex min-h-[100dvh] items-center justify-center bg-slate-50 px-5">
<section className="max-w-md rounded-2xl border border-slate-200 bg-card p-8 text-center shadow-sm">
- <FileText className="mx-auto h-9 w-9 text-slate-400" />
- <h1 className="mt-4 text-xl font-semibold text-slate-900">{t("sharing.publicUnavailable")}</h1>
- <p className="mt-2 text-sm leading-6 text-slate-500">{t("sharing.publicUnavailableHint")}</p>
+ {expired ? <Clock3 className="mx-auto h-9 w-9 text-slate-400" /> : <FileText className="mx-auto h-9 w-9 text-slate-400" />}
+ <h1 className="mt-4 text-xl font-semibold text-slate-900">{t(expired ? "sharing.publicExpired" : "sharing.publicUnavailable")}</h1>
+ <p className="mt-2 text-sm leading-6 text-slate-500">{t(expired ? "sharing.publicExpiredHint" : "sharing.publicUnavailableHint")}</p>
</section>
</main>
);
diff --git a/apps/web/src/components/dialogs/ShareExpiryControls.test.mjs b/apps/web/src/components/dialogs/ShareExpiryControls.test.mjs
new file mode 100644
index 00000000..8f7ce2e0
--- /dev/null
+++ b/apps/web/src/components/dialogs/ShareExpiryControls.test.mjs
@@ -0,0 +1,66 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { enUS } from "../../../../../packages/shared/src/i18n/en-US.ts";
+import { TooltipProvider } from "../ui/tooltip.tsx";
+import { ShareExpiryControls } from "./ShareExpiryControls.tsx";
+
+const render = async (props) => {
+ const i18n = createInstance();
+ await i18n.init({ lng: "en-US", resources: { "en-US": { translation: enUS } } });
+ return renderToStaticMarkup(createElement(I18nextProvider, { i18n }, createElement(TooltipProvider, null,
+ createElement(ShareExpiryControls, { expiresAt: null, expired: false, busy: false, invalid: false, onChange() {}, ...props }))));
+};
+
+describe("share expiry controls", () => {
+ test("a share without expiry shows the picker and no expiry status", async () => {
+ const html = await render();
+ expect(html).toContain('aria-label="Link expiry"');
+ expect(html).not.toContain("Expires ");
+ expect(html).not.toContain("This link has expired");
+ });
+
+ test("an active expiry shows its date", async () => {
+ const html = await render({ expiresAt: "2999-01-01T12:00:00.000Z" });
+ expect(html).toContain("Expires ");
+ expect(html).not.toContain("This link has expired");
+ });
+
+ test("an expired share explains the visitor state and keeps the choices", async () => {
+ const html = await render({ expiresAt: "2020-01-01T12:00:00.000Z", expired: true });
+ expect(html).toContain("Expired ");
+ expect(html).toContain("This link has expired. Visitors see an expiry message");
+ });
+
+ test("the custom date accepts today, whose end is still in the future", () => {
+ const source = readFileSync(new URL("./ShareExpiryControls.tsx", import.meta.url), "utf8");
+ expect(source).toContain("const today = toDateInputValue(new Date());");
+ expect(source).toContain("min={today}");
+ });
+
+ test("a rejected date is reported", async () => {
+ expect(await render({ invalid: true })).toContain("Choose a date in the future.");
+ });
+});
+
+describe("share dialog expiry and views", () => {
+ const dialog = readFileSync(new URL("./ShareMemoDialog.tsx", import.meta.url), "utf8");
+ const settings = readFileSync(new URL("../settings/ShareManagementCard.tsx", import.meta.url), "utf8");
+
+ test("the dialog reads expiry from the server and sends only the expiry", () => {
+ expect(dialog).toContain("expired={share.expired === true}");
+ expect(dialog).toContain("api.updateMemoShare(memoId, { expiresAt })");
+ expect(dialog).toContain('expiryMutation.error.code === "share_expiry_invalid"');
+ });
+
+ test("the dialog and the share list show how often a link was opened", () => {
+ for (const source of [dialog, settings]) {
+ expect(source).toContain('t("sharing.viewsCount", { count: share.viewCount })');
+ expect(source).toContain('t("sharing.viewsNone")');
+ }
+ expect(settings).toContain('t("sharing.expiredBadge")');
+ });
+});
diff --git a/apps/web/src/components/dialogs/ShareExpiryControls.tsx b/apps/web/src/components/dialogs/ShareExpiryControls.tsx
new file mode 100644
index 00000000..414ba6b1
--- /dev/null
+++ b/apps/web/src/components/dialogs/ShareExpiryControls.tsx
@@ -0,0 +1,130 @@
+import { Check, LoaderCircle } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ SHARE_EXPIRY_PRESET_DAYS,
+ shareExpiryFromDateInput,
+ shareExpiryFromPreset,
+ toDateInputValue,
+} from "@/lib/share-expiry";
+
+const presetLabelKeys: Record<(typeof SHARE_EXPIRY_PRESET_DAYS)[number], string> = {
+ 1: "sharing.expiry1Day",
+ 7: "sharing.expiry7Days",
+ 30: "sharing.expiry30Days",
+};
+
+export const ShareExpiryControls = ({
+ expiresAt,
+ expired,
+ busy,
+ invalid,
+ onChange,
+}: {
+ expiresAt: string | null;
+ /** Decided by the server; the dialog never compares the expiry itself. */
+ expired: boolean;
+ busy: boolean;
+ invalid: boolean;
+ onChange: (expiresAt: string | null) => void;
+}) => {
+ const { t, i18n } = useTranslation();
+ const dateInputId = useId();
+ const [customOpen, setCustomOpen] = useState(false);
+ const [customDate, setCustomDate] = useState("");
+ useEffect(() => {
+ setCustomOpen(false);
+ setCustomDate("");
+ }, [expiresAt]);
+
+ const locale = i18n.resolvedLanguage || i18n.language;
+ const formatDate = (value: string) =>
+ new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
+ const formatDay = (value: string) => new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(value));
+ // The end of today is still in the future; the server rejects anything that is not.
+ const today = toDateInputValue(new Date());
+ const customExpiresAt = shareExpiryFromDateInput(customDate);
+ const selected = customOpen ? "custom" : expiresAt ? "current" : "never";
+
+ return (
+ <div className="space-y-1.5 border-t border-slate-100 pt-3">
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-xs font-medium leading-5 text-slate-800">{t("sharing.expiryLabel")}</span>
+ <Select
+ value={selected}
+ disabled={busy}
+ onValueChange={(value) => {
+ if (value === "custom") {
+ setCustomOpen(true);
+ return;
+ }
+ setCustomOpen(false);
+ if (value === "never") onChange(null);
+ else if (value !== "current") onChange(shareExpiryFromPreset(Number(value)));
+ }}
+ >
+ <SelectTrigger className="h-8 w-44 text-xs" aria-label={t("sharing.expiryLabel")}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {expiresAt ? (
+ <SelectItem value="current" className="hidden">{formatDay(expiresAt)}</SelectItem>
+ ) : null}
+ <SelectItem value="never">{t("sharing.expiryNever")}</SelectItem>
+ {SHARE_EXPIRY_PRESET_DAYS.map((days) => (
+ <SelectItem key={days} value={String(days)}>{t(presetLabelKeys[days])}</SelectItem>
+ ))}
+ <SelectItem value="custom">{t("sharing.expiryCustom")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ {customOpen ? (
+ <form
+ className="flex items-center justify-end gap-1.5"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (customExpiresAt && !busy) onChange(customExpiresAt);
+ }}
+ >
+ <label htmlFor={dateInputId} className="sr-only">{t("sharing.expiryCustomLabel")}</label>
+ <Input
+ id={dateInputId}
+ type="date"
+ min={today}
+ value={customDate}
+ onChange={(event) => setCustomDate(event.target.value)}
+ className="h-8 w-44 text-xs"
+ />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="submit"
+ variant="outline"
+ size="icon"
+ className="h-8 w-8 shrink-0"
+ disabled={busy || !customExpiresAt}
+ aria-label={t("sharing.expiryCustomSave")}
+ >
+ {busy ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("sharing.expiryCustomSave")}</TooltipContent>
+ </Tooltip>
+ </form>
+ ) : null}
+ {expiresAt ? (
+ <p className={`text-xs leading-5 ${expired ? "text-rose-600" : "text-slate-500"}`} role="status">
+ {t(expired ? "sharing.expiredOn" : "sharing.expiresOn", { date: formatDate(expiresAt) })}
+ {expired ? ` · ${t("sharing.expiredNotice")}` : null}
+ </p>
+ ) : null}
+ {invalid ? (
+ <p className="text-xs leading-5 text-rose-600" role="alert">{t("sharing.expiryInvalid")}</p>
+ ) : null}
+ </div>
+ );
+};
diff --git a/apps/web/src/components/dialogs/ShareMemoDialog.tsx b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
index 9066af39..88ac79e4 100644
--- a/apps/web/src/components/dialogs/ShareMemoDialog.tsx
+++ b/apps/web/src/components/dialogs/ShareMemoDialog.tsx
@@ -1,5 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Check, Copy, ExternalLink, FileCode2, Globe, LoaderCircle, Share2, Trash2 } from "lucide-react";
+import { Check, Copy, ExternalLink, Eye, FileCode2, Globe, LoaderCircle, Share2, Trash2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router";
@@ -8,6 +8,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/u
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { memoSharePathSegment } from "@edgeever/shared";
+import { ShareExpiryControls } from "./ShareExpiryControls";
import { SharePasswordControls } from "./SharePasswordControls";
import { ShareSlugControls } from "./ShareSlugControls";
import { ShareQrCode } from "./ShareQrCode";
@@ -32,7 +33,7 @@ export const ShareMemoDialog = ({
open: boolean;
onOpenChange: (open: boolean) => void;
}) => {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const location = useLocation();
const queryClient = useQueryClient();
const [copyState, setCopyState] = useState<"idle" | "copied" | "error">("idle");
@@ -77,6 +78,13 @@ export const ShareMemoDialog = ({
void queryClient.invalidateQueries({ queryKey: ["memo-shares"] });
},
});
+ const expiryMutation = useMutation({
+ mutationFn: (expiresAt: string | null) => api.updateMemoShare(memoId, { expiresAt }),
+ onSuccess: (data) => {
+ queryClient.setQueryData(queryKey, data);
+ void queryClient.invalidateQueries({ queryKey: ["memo-shares"] });
+ },
+ });
const revokeMutation = useMutation({
mutationFn: (targetMemoId: string) => api.revokeMemoShare(targetMemoId),
onSuccess: (_, targetMemoId) => {
@@ -89,6 +97,7 @@ export const ShareMemoDialog = ({
passwordMutation.reset();
presentationMutation.reset();
slugMutation.reset();
+ expiryMutation.reset();
revokeMutation.reset();
setCopyState("idle");
setCopyTarget("link");
@@ -102,9 +111,12 @@ export const ShareMemoDialog = ({
const shareUrl = share ? getPublicShareUrl(memoSharePathSegment(share)) : "";
const markdownUrl = shareUrl ? `${shareUrl}.md` : "";
- const isWorking = shareQuery.isLoading || createMutation.isPending || passwordMutation.isPending || presentationMutation.isPending || slugMutation.isPending || revokeMutation.isPending;
+ const isWorking = shareQuery.isLoading || createMutation.isPending || passwordMutation.isPending || presentationMutation.isPending || slugMutation.isPending || expiryMutation.isPending || revokeMutation.isPending;
const slugTaken = slugMutation.error instanceof ApiRequestError && slugMutation.error.code === "share_slug_taken";
- const error = shareQuery.error || createMutation.error || passwordMutation.error || presentationMutation.error || (slugTaken ? null : slugMutation.error) || revokeMutation.error;
+ const expiryInvalid = expiryMutation.error instanceof ApiRequestError && expiryMutation.error.code === "share_expiry_invalid";
+ const error = shareQuery.error || createMutation.error || passwordMutation.error || presentationMutation.error || (slugTaken ? null : slugMutation.error) || (expiryInvalid ? null : expiryMutation.error) || revokeMutation.error;
+ const formatViewedAt = (value: string) =>
+ new Intl.DateTimeFormat(i18n.resolvedLanguage || i18n.language, { dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
const markCopied = (target: "link" | "password" | "both" | "markdown", copied: boolean) => {
setCopyTarget(target);
@@ -227,6 +239,26 @@ export const ShareMemoDialog = ({
}}
/>
+ <ShareExpiryControls
+ expiresAt={share.expiresAt ?? null}
+ expired={share.expired === true}
+ busy={isWorking}
+ invalid={expiryInvalid}
+ onChange={(expiresAt) => expiryMutation.mutate(expiresAt)}
+ />
+
+ {share.viewCount !== undefined ? (
+ <p className="flex items-center gap-1.5 text-xs leading-5 text-slate-500">
+ <Eye className="h-3.5 w-3.5 shrink-0" />
+ {share.viewCount > 0
+ ? [
+ t("sharing.viewsCount", { count: share.viewCount }),
+ share.lastViewedAt ? t("sharing.viewsLast", { date: formatViewedAt(share.lastViewedAt) }) : null,
+ ].filter(Boolean).join(" · ")
+ : t("sharing.viewsNone")}
+ </p>
+ ) : null}
+
<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-xs font-normal leading-5 text-slate-600">{t("sharing.showUpdatedAt")}</label>
diff --git a/apps/web/src/components/settings/ShareManagementCard.tsx b/apps/web/src/components/settings/ShareManagementCard.tsx
index be20b8b5..9553afa4 100644
--- a/apps/web/src/components/settings/ShareManagementCard.tsx
+++ b/apps/web/src/components/settings/ShareManagementCard.tsx
@@ -1,5 +1,5 @@
import { useInfiniteQuery } from "@tanstack/react-query";
-import { FileText, Link2, LoaderCircle, LockKeyhole } from "lucide-react";
+import { Clock3, Eye, FileText, Link2, LoaderCircle, LockKeyhole } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { memoSharePathSegment, type ManagedMemoShare } from "@edgeever/shared";
@@ -92,6 +92,23 @@ export const ShareManagementCard = ({ userId, onOpenMemo }: Props) => {
<LockKeyhole className="h-3 w-3" />{t("sharing.passwordProtected")}
</span>
) : null}
+ {share.expiresAt ? (
+ <span className={`inline-flex items-center gap-1 ${share.expired ? "text-rose-600" : "text-slate-600"}`}>
+ <Clock3 className="h-3 w-3" />
+ {share.expired ? t("sharing.expiredBadge") : t("sharing.expiresOn", { date: formatDate(share.expiresAt) })}
+ </span>
+ ) : null}
+ {share.viewCount !== undefined ? (
+ <span className="inline-flex items-center gap-1">
+ <Eye className="h-3 w-3" />
+ {share.viewCount > 0
+ ? [
+ t("sharing.viewsCount", { count: share.viewCount }),
+ share.lastViewedAt ? t("sharing.viewsLast", { date: formatDate(share.lastViewedAt) }) : null,
+ ].filter(Boolean).join(" · ")
+ : t("sharing.viewsNone")}
+ </span>
+ ) : null}
</p>
</div>
<ShareManagementActions
diff --git a/apps/web/src/lib/share-expiry.test.mjs b/apps/web/src/lib/share-expiry.test.mjs
new file mode 100644
index 00000000..bfd8547b
--- /dev/null
+++ b/apps/web/src/lib/share-expiry.test.mjs
@@ -0,0 +1,22 @@
+import { describe, expect, test } from "bun:test";
+import { shareExpiryFromDateInput, shareExpiryFromPreset, toDateInputValue } from "./share-expiry.ts";
+
+describe("share link expiry choices", () => {
+ test("presets count whole days from now", () => {
+ const now = new Date("2026-11-01T10:00:00.000Z");
+ expect(shareExpiryFromPreset(1, now)).toBe("2026-11-02T10:00:00.000Z");
+ expect(shareExpiryFromPreset(7, now)).toBe("2026-11-08T10:00:00.000Z");
+ expect(shareExpiryFromPreset(30, now)).toBe("2026-12-01T10:00:00.000Z");
+ });
+
+ test("a custom date lasts until the end of that local day", () => {
+ const expected = new Date(2026, 11, 24, 23, 59, 59, 999).toISOString();
+ expect(shareExpiryFromDateInput("2026-12-24")).toBe(expected);
+ expect(toDateInputValue(new Date(2026, 0, 5, 12))).toBe("2026-01-05");
+ });
+
+ test("an empty or malformed date gives no expiry to save", () => {
+ expect(shareExpiryFromDateInput("")).toBeNull();
+ expect(shareExpiryFromDateInput("24.12.2026")).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/share-expiry.ts b/apps/web/src/lib/share-expiry.ts
new file mode 100644
index 00000000..f9f73728
--- /dev/null
+++ b/apps/web/src/lib/share-expiry.ts
@@ -0,0 +1,21 @@
+export const SHARE_EXPIRY_PRESET_DAYS = [1, 7, 30] as const;
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+/** Expiry instant for a preset, counted from now. */
+export const shareExpiryFromPreset = (days: number, now = new Date()) =>
+ new Date(now.getTime() + days * DAY_MS).toISOString();
+
+const pad = (value: number) => String(value).padStart(2, "0");
+
+/** `YYYY-MM-DD` in local time, the format of a date input. */
+export const toDateInputValue = (date: Date) =>
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+
+/** A custom date keeps the link working until the end of that day in the owner's time zone. */
+export const shareExpiryFromDateInput = (value: string) => {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
+ if (!match) return null;
+ const end = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]), 23, 59, 59, 999);
+ return Number.isNaN(end.getTime()) ? null : end.toISOString();
+};
diff --git a/docs/changes/2026-11-01-memo-share-expiry-views.md b/docs/changes/2026-11-01-memo-share-expiry-views.md
new file mode 100644
index 00000000..4c5964c0
--- /dev/null
+++ b/docs/changes/2026-11-01-memo-share-expiry-views.md
@@ -0,0 +1,24 @@
+# Expiry and open counter for single-note share links
+
+[简体中文](2026-11-01-memo-share-expiry-views.zh-CN.md)
+
+## Problem and outcome
+
+Implements [Issue #607](https://github.com/tianma-if/edgeever/issues/607). A single-note share link stayed public until the owner remembered to revoke it, and the owner could not tell whether the link had been opened. The owner can now give a link an optional expiry and see how often it was opened. Shares without an expiry behave exactly as before.
+
+## Behavior
+
+| ID | Behavior | Acceptance |
+| --- | --- | --- |
+| E01 | Migration `0087` adds `memo_shares.expires_at` (UTC ISO, `NULL` = never), `view_count` (default 0) and `last_viewed_at`. Existing rows keep their token, password, address and presentation settings. | Migration test compares rows before and after. A self-hosted data directory and a local D1 database created on the previous version, each with a password-protected share, upgrade without changes to the share. |
+| E02 | `PATCH /api/v1/memos/:id/share` accepts `expiresAt` (ISO instant with an offset, or `null`) next to the existing fields. It is normalized to UTC; a past instant returns 400 `share_expiry_invalid`. An expiry-only request does not touch the password. Older clients that send only `{ passwordProtected }` keep working. | API tests cover set, normalize, extend, remove, past, malformed and empty payloads, and a password kept across expiry changes. |
+| E03 | The server alone decides expiry. After it, note content (`GET /api/public/shares/:token`), password unlock and shared attachments answer `410 share_expired` without the title or content, distinct from `404` for revoked or unknown links. `/share/<link>.md` answers 410 with a short message, and the server-rendered page leaves the note out. An expired note is not linked from other shared notes. | API and share-page tests cover all four paths, the 404 case and linked notes. |
+| E04 | The owner still sees an expired share: reopening the dialog shows the expired state and does not create a new link. The owner can extend the expiry, remove it or revoke the share. | API test reads and re-posts an expired share; manual check in the running app. |
+| E05 | `view_count` and `last_viewed_at` grow only when note content is served: the share API after the password gate, and the `.md` alternate. Password prompts, failed unlocks, expired links, attachment downloads, `HEAD` requests and the HTML shell (a browser counts once through the share API) do not count. No visitor data is stored. A view does not change `updated_at`, so the share list order is unaffected. A failed counter write never blocks reading. | API and share-page tests count each path, including `HEAD` on the share API and on `.md`. |
+| E06 | The web share dialog has a "Link expiry" picker: no expiry, 1, 7 or 30 days, or a custom date, today or later, that lasts until the end of that day in the owner's time zone. It shows the expiry, an expired notice, and "Opened N times · last on …". Settings → Shared notes shows the expiry or an "Expired" mark and the open count. The public page shows "This shared link has expired". Copy is in all shipped locales. | Rendering and unit tests; type check and web build; manual check of every state on the self-hosted server. |
+
+Android and iOS ignore the new fields and keep working. Notebook shares are out of scope.
+
+## Risk and rollback
+
+Worst case: an owner relies on an expiry, and the application is rolled back to a version before this change. Older code ignores `expires_at`, so expired links become reachable again until this version is redeployed. The counter is approximate: two visitors opening the link at the same moment are both counted, while reloads and automated readers of the `.md` alternate also count. Rolling back leaves the additive columns in place; older code keeps working with them, which was checked with the previous version on migrated data. No existing migration is modified.
diff --git a/docs/changes/2026-11-01-memo-share-expiry-views.zh-CN.md b/docs/changes/2026-11-01-memo-share-expiry-views.zh-CN.md
new file mode 100644
index 00000000..66b12f9a
--- /dev/null
+++ b/docs/changes/2026-11-01-memo-share-expiry-views.zh-CN.md
@@ -0,0 +1,24 @@
+# 单篇笔记分享链接的有效期与打开次数
+
+[English](2026-11-01-memo-share-expiry-views.md)
+
+## 问题与结果
+
+实现 [Issue #607](https://github.com/tianma-if/edgeever/issues/607)。单篇笔记分享链接会一直公开,直到所有者想起来撤销;所有者也无法知道链接是否被打开过。现在所有者可以为链接设置可选的有效期,并查看链接被打开的次数。未设置有效期的分享与之前完全一致。
+
+## 行为
+
+| 编号 | 行为 | 验收 |
+| --- | --- | --- |
+| E01 | Migration `0087` 为 `memo_shares` 新增 `expires_at`(UTC ISO,`NULL` 表示永久)、`view_count`(默认 0)和 `last_viewed_at`。现有记录保留令牌、密码、自定义地址和展示设置。 | Migration 测试比较迁移前后的记录。分别用旧版本创建的自托管数据目录和本地 D1 数据库(各含一个受密码保护的分享)升级后,分享不变。 |
+| E02 | `PATCH /api/v1/memos/:id/share` 在现有字段之外接受 `expiresAt`(带时区偏移的 ISO 时间或 `null`)。服务端统一转为 UTC;过去的时间返回 400 `share_expiry_invalid`。只修改有效期的请求不会改动密码。只发送 `{ passwordProtected }` 的旧客户端继续可用。 | API 测试覆盖设置、规范化、延长、取消、过去时间、格式错误和空请求,以及修改有效期时密码保持不变。 |
+| E03 | 是否过期只由服务端判断。过期后,笔记内容(`GET /api/public/shares/:token`)、密码解锁和分享附件均返回 `410 share_expired`,不包含标题或内容,与已撤销或不存在链接的 `404` 区分。`/share/<链接>.md` 返回 410 和简短说明,服务端渲染页面不包含笔记。已过期的笔记不会被其他公开笔记链接。 | API 与分享页测试覆盖上述四条路径、404 情况和笔记间链接。 |
+| E04 | 所有者仍能看到已过期的分享:重新打开对话框会显示过期状态,不会创建新链接。所有者可以延长有效期、取消期限或撤销分享。 | API 测试读取并重新提交已过期的分享;在运行中的应用里手动检查。 |
+| E05 | `view_count` 和 `last_viewed_at` 只在实际返回笔记内容时增加:通过密码门禁后的分享 API,以及 `.md` 版本。密码提示、解锁失败、已过期链接、附件下载、`HEAD` 请求以及 HTML 外壳(浏览器通过分享 API 计数一次)都不计数。不保存任何访问者信息。计数不会修改 `updated_at`,因此分享列表顺序不变。计数写入失败不会影响阅读。 | API 与分享页测试分别检查每条路径的计数,包括分享 API 和 `.md` 的 `HEAD` 请求。 |
+| E06 | Web 分享对话框新增“链接有效期”选择:永久有效、1 天、7 天、30 天或自定义日期(可选今天及以后,在所有者所在时区的当天结束时到期)。对话框显示到期时间、过期提示以及“已打开 N 次 · 最近一次 …”。设置 → 已分享的笔记显示到期时间或“已过期”标记以及打开次数。公开页面显示“此分享链接已过期”。所有已发布语言均有文案。 | 渲染与单元测试;类型检查与 Web 构建;在自托管服务上手动检查所有状态。 |
+
+Android 与 iOS 会忽略新字段并继续正常工作。笔记本分享不在本次范围内。
+
+## 风险与回滚
+
+最坏情况:所有者依赖有效期,而应用被回滚到本次变更之前的版本。旧代码会忽略 `expires_at`,因此在重新部署本版本之前,已过期的链接会重新可以访问。计数为近似值:两位访问者同时打开会各计一次,刷新页面以及自动读取 `.md` 版本也会计数。回滚后新增列保留,旧代码仍可正常使用这些数据,已用旧版本在迁移后的数据上验证。不修改任何已有 Migration。
diff --git a/migrations/0087_memo_share_expiry_views.sql b/migrations/0087_memo_share_expiry_views.sql
new file mode 100644
index 00000000..a1f227bf
--- /dev/null
+++ b/migrations/0087_memo_share_expiry_views.sql
@@ -0,0 +1,5 @@
+-- Optional expiry and an anonymous open counter for single-note shares.
+-- Existing shares keep today's behavior: no expiry and a count starting at 0.
+ALTER TABLE memo_shares ADD COLUMN expires_at TEXT;
+ALTER TABLE memo_shares ADD COLUMN view_count INTEGER NOT NULL DEFAULT 0;
+ALTER TABLE memo_shares ADD COLUMN last_viewed_at TEXT;
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 5b8962d2..90a998e4 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -1477,7 +1477,7 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
body: JSON.stringify({}),
}),
- updateMemoShare: (memoId: string, payload: { passwordProtected?: boolean; password?: string; slug?: string | null; showUpdatedAt?: boolean; showBranding?: boolean }) =>
+ updateMemoShare: (memoId: string, payload: { passwordProtected?: boolean; password?: string; slug?: string | null; showUpdatedAt?: boolean; showBranding?: boolean; expiresAt?: string | null }) =>
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.ts
index 47aadfe6..a28c810d 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -3081,6 +3081,24 @@ export const enUS = {
publicUpdated: "Updated {{time}}",
publicUnavailable: "This shared note is unavailable",
publicUnavailableHint: "The link may be invalid, the owner may have revoked it, or the note may have been deleted.",
+ expiryLabel: "Link expiry",
+ expiryNever: "No expiry",
+ expiry1Day: "1 day",
+ expiry7Days: "7 days",
+ expiry30Days: "30 days",
+ expiryCustom: "Custom date",
+ expiryCustomLabel: "Expiry date",
+ expiryCustomSave: "Set date",
+ expiryInvalid: "Choose a date in the future.",
+ expiresOn: "Expires {{date}}",
+ expiredOn: "Expired {{date}}",
+ expiredNotice: "This link has expired. Visitors see an expiry message instead of the note. Extend it, remove the expiry or revoke sharing.",
+ expiredBadge: "Expired",
+ viewsCount: "Opened {{count}} times",
+ viewsLast: "last on {{date}}",
+ viewsNone: "Not opened yet",
+ publicExpired: "This shared link has expired",
+ publicExpiredHint: "The owner set this link to stop working after a certain date. Ask them for a new link.",
},
slashMenu: {
menu: "Insert menu",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index f9bf1fde..aef27059 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -3070,6 +3070,24 @@ export const ja = {
publicUpdated: "更新 {{time}}",
publicUnavailable: "この共有ノートは利用できません",
publicUnavailableHint: "リンクが無効か、所有者が取り消したか、ノートが削除された可能性があります。",
+ expiryLabel: "リンクの有効期限",
+ expiryNever: "無期限",
+ expiry1Day: "1 日",
+ expiry7Days: "7 日",
+ expiry30Days: "30 日",
+ expiryCustom: "日付を指定",
+ expiryCustomLabel: "有効期限の日付",
+ expiryCustomSave: "日付を設定",
+ expiryInvalid: "今日より後の日付を選択してください。",
+ expiresOn: "{{date}} に期限切れ",
+ expiredOn: "{{date}} に期限切れになりました",
+ expiredNotice: "このリンクは期限切れです。閲覧者にはノートではなく期限切れのメッセージが表示されます。期限を延長するか、期限を外すか、共有を取り消してください。",
+ expiredBadge: "期限切れ",
+ viewsCount: "{{count}} 回表示",
+ viewsLast: "最終 {{date}}",
+ viewsNone: "まだ表示されていません",
+ publicExpired: "この共有リンクは期限切れです",
+ publicExpiredHint: "所有者がこのリンクに有効期限を設定しています。新しいリンクを依頼してください。",
},
slashMenu: {
menu: "挿入メニュー",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 1d97a5c2..c711bf11 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -3070,6 +3070,24 @@ export const pl = {
publicUpdated: "Zaktualizowano: {{time}}",
publicUnavailable: "Ta udostępniona notatka jest niedostępna",
publicUnavailableHint: "Link może być nieprawidłowy, właściciel mógł go unieważnić albo notatka mogła zostać usunięta.",
+ expiryLabel: "Ważność linku",
+ expiryNever: "Bez terminu",
+ expiry1Day: "1 dzień",
+ expiry7Days: "7 dni",
+ expiry30Days: "30 dni",
+ expiryCustom: "Własna data",
+ expiryCustomLabel: "Data wygaśnięcia",
+ expiryCustomSave: "Ustaw datę",
+ expiryInvalid: "Wybierz datę w przyszłości.",
+ expiresOn: "Wygasa {{date}}",
+ expiredOn: "Wygasł {{date}}",
+ expiredNotice: "Ten link wygasł. Odwiedzający widzą komunikat o wygaśnięciu zamiast notatki. Przedłuż go, usuń termin albo unieważnij udostępnianie.",
+ expiredBadge: "Wygasł",
+ viewsCount: "Otwarcia: {{count}}",
+ viewsLast: "ostatnio {{date}}",
+ viewsNone: "Jeszcze nie otwarto",
+ publicExpired: "Ten link udostępniania wygasł",
+ publicExpiredHint: "Właściciel ustawił termin ważności tego linku. Poproś go o nowy link.",
},
slashMenu: {
menu: "Menu wstawiania",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index 5b371397..e0a63ccc 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -3081,6 +3081,24 @@ export const ru = {
publicUpdated: "Обновлено {{time}}",
publicUnavailable: "Общая заметка недоступна",
publicUnavailableHint: "Ссылка может быть недействительной, владелец мог её отозвать, или заметка удалена.",
+ expiryLabel: "Срок действия ссылки",
+ expiryNever: "Без срока",
+ expiry1Day: "1 день",
+ expiry7Days: "7 дней",
+ expiry30Days: "30 дней",
+ expiryCustom: "Своя дата",
+ expiryCustomLabel: "Дата окончания",
+ expiryCustomSave: "Установить дату",
+ expiryInvalid: "Выберите дату в будущем.",
+ expiresOn: "Действует до {{date}}",
+ expiredOn: "Истекла {{date}}",
+ expiredNotice: "Срок действия ссылки истёк. Посетители видят сообщение об истечении вместо заметки. Продлите срок, снимите ограничение или отзовите доступ.",
+ expiredBadge: "Истекла",
+ viewsCount: "Открытий: {{count}}",
+ viewsLast: "последнее {{date}}",
+ viewsNone: "Ещё не открывали",
+ publicExpired: "Срок действия этой ссылки истёк",
+ publicExpiredHint: "Владелец ограничил срок действия ссылки. Попросите у него новую.",
},
slashMenu: {
menu: "Меню вставки",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index c263ff46..d198d4b7 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -3079,6 +3079,24 @@ export const zhCN = {
publicUpdated: "更新于 {{time}}",
publicUnavailable: "这篇分享笔记不可用",
publicUnavailableHint: "链接可能无效、已被分享者撤销,或原笔记已经删除。",
+ expiryLabel: "链接有效期",
+ expiryNever: "永久有效",
+ expiry1Day: "1 天",
+ expiry7Days: "7 天",
+ expiry30Days: "30 天",
+ expiryCustom: "自定义日期",
+ expiryCustomLabel: "到期日期",
+ expiryCustomSave: "设置日期",
+ expiryInvalid: "请选择一个将来的日期。",
+ expiresOn: "{{date}} 到期",
+ expiredOn: "已于 {{date}} 过期",
+ expiredNotice: "此链接已过期,访问者只会看到过期提示,看不到笔记。可以延长有效期、取消期限或撤销分享。",
+ expiredBadge: "已过期",
+ viewsCount: "已打开 {{count}} 次",
+ viewsLast: "最近一次 {{date}}",
+ viewsNone: "尚未被打开",
+ publicExpired: "此分享链接已过期",
+ publicExpiredHint: "分享者为此链接设置了有效期。如需查看,请向对方索取新的链接。",
},
slashMenu: {
menu: "插入功能菜单",
diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.ts
index 33486462..ccc3288f 100644
--- a/packages/shared/src/schemas.ts
+++ b/packages/shared/src/schemas.ts
@@ -451,7 +451,9 @@ export const MemoShareUpdateSchema = z.object({
slug: z.string().trim().toLowerCase().refine(isValidMemoShareSlug).nullable().optional(),
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, {
+ /** ISO instant with an offset, or null to remove the expiry. The server rejects past instants. */
+ expiresAt: z.string().datetime({ offset: true }).nullable().optional(),
+}).refine((input) => input.passwordProtected !== undefined || input.password !== undefined || input.slug !== undefined || input.showUpdatedAt !== undefined || input.showBranding !== undefined || input.expiresAt !== 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.ts
index 4113b5f1..eae7b83d 100644
--- a/packages/shared/src/sharing.ts
+++ b/packages/shared/src/sharing.ts
@@ -18,6 +18,13 @@ export type MemoShare = {
showBranding: boolean;
/** Plaintext is returned only immediately after the owner enables or regenerates a password. */
password?: string;
+ /** UTC instant after which the public link stops working; null never expires. Older servers omit it. */
+ expiresAt?: string | null;
+ /** Decided by the server when it answered; clients never compare expiry themselves. */
+ expired?: boolean;
+ /** Times the note content was served to a visitor, and when that last happened. */
+ viewCount?: number;
+ lastViewedAt?: string | null;
};
export { isValidMemoShareSlug, MEMO_SHARE_SLUG_MAX_LENGTH, MEMO_SHARE_SLUG_PATTERN, RESERVED_MEMO_SHARE_SLUGS } from "./share-slug";