Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(notes): stop the share link button from silently breaking invitation emails (#2360)

Chad Pihaf21e5136e3e2
diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsx
index 6890bb040..f03ab7edb 100644
--- a/src/components/notes/NoteEditor.tsx
+++ b/src/components/notes/NoteEditor.tsx
@@ -18,6 +18,7 @@ import {
Users,
} from "../icons";
import ShareNoteDialog, { type NoteExportOption } from "./ShareNoteDialog";
+import { reconcileLocalShareState } from "./shareNoteRules";
import {
canOrganizeNote,
noteCapabilities,
@@ -317,12 +318,14 @@ export default function NoteEditor({
access: res.access ?? entry?.access,
rawToken: entry?.rawToken ?? null,
}));
- const serverShared = res.share.visibility !== "private";
- if (serverShared !== Boolean(note.is_shared)) {
- void persistNoteShareState(
- note.id,
- serverShared ? { is_shared: 1 } : { is_shared: 0, share_token: null }
- ).catch((err) => console.error("Share flag persist failed:", err));
+ const update = reconcileLocalShareState(
+ { isShared: Boolean(note.is_shared), shareToken: note.share_token ?? null },
+ res.share
+ );
+ if (update) {
+ void persistNoteShareState(note.id, update).catch((err) =>
+ console.error("Share flag persist failed:", err)
+ );
}
})
.catch((err) => {
@@ -333,7 +336,15 @@ export default function NoteEditor({
return () => {
cancelled = true;
};
- }, [aclRetryVersion, isSignedIn, note.cloud_id, note.id, note.is_shared, shareCache]);
+ }, [
+ aclRetryVersion,
+ isSignedIn,
+ note.cloud_id,
+ note.id,
+ note.is_shared,
+ note.share_token,
+ shareCache,
+ ]);
useEffect(() => {
if (
!isSignedIn ||
diff --git a/src/components/notes/ShareNoteDialog.tsx b/src/components/notes/ShareNoteDialog.tsx
index a882defdd..25f1aee65 100644
--- a/src/components/notes/ShareNoteDialog.tsx
+++ b/src/components/notes/ShareNoteDialog.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Check, Copy, FileText, Link2, Loader2, MoreHorizontal, Users } from "../icons";
-import { Dialog, DialogContent, DialogDescription, DialogTitle } from "../ui/dialog";
+import { ConfirmDialog, Dialog, DialogContent, DialogDescription, DialogTitle } from "../ui/dialog";
import { Button } from "../ui/button";
import {
DropdownMenu,
@@ -12,6 +12,13 @@ import {
import { cn } from "../lib/utils";
import ShareVisibilityMenu from "./ShareVisibilityMenu";
import { notesInputClass } from "./shared";
+import {
+ canManageAccessGrant,
+ currentShareToken,
+ reconcileLocalShareState,
+ resolveShareLink,
+ type LocalShareState,
+} from "./shareNoteRules";
import { useAuth } from "../../hooks/useAuth";
import {
NoteSharingService,
@@ -46,7 +53,6 @@ import type {
ShareVisibility,
} from "../../types/electron";
-const SHARE_VIEWER_BASE_URL = "https://notes.openwhispr.com";
const SHARE_VISIBILITY_OPTIONS: Array<{ id: ShareVisibility }> = [
{ id: "private" },
{ id: "invited" },
@@ -112,13 +118,22 @@ export default function ShareNoteDialog({
const [copied, setCopied] = useState(false);
const [resendingId, setResendingId] = useState<string | null>(null);
const [busyGrantId, setBusyGrantId] = useState<string | null>(null);
+ const [confirmingReplaceLink, setConfirmingReplaceLink] = useState(false);
+ // Copy on open waits for this: the cached share can be hours old.
+ const [refreshedCloudId, setRefreshedCloudId] = useState<string | null>(null);
const emailInputRef = useRef<HTMLInputElement>(null);
const copyTimeoutRef = useRef<number | null>(null);
- const localIsSharedRef = useRef(Boolean(note.is_shared));
+ const localShareStateRef = useRef<LocalShareState>({
+ isShared: Boolean(note.is_shared),
+ shareToken: note.share_token ?? null,
+ });
useEffect(() => {
- localIsSharedRef.current = Boolean(note.is_shared);
- }, [note.is_shared]);
+ localShareStateRef.current = {
+ isShared: Boolean(note.is_shared),
+ shareToken: note.share_token ?? null,
+ };
+ }, [note.is_shared, note.share_token]);
const policyState = usePolicySnapshot();
@@ -181,7 +196,7 @@ export default function ShareNoteDialog({
share: refreshed.share,
invitations: refreshed.invitations,
access: refreshed.access ?? resolveFallbackAccess?.(entry?.access) ?? entry?.access,
- rawToken: entry?.rawToken ?? null,
+ rawToken: currentShareToken(entry?.rawToken, refreshed.share.token_prefix),
}));
return refreshed;
},
@@ -216,12 +231,12 @@ export default function ShareNoteDialog({
refreshShareCache()
.then((res) => {
if (cancelled || !res) return;
- const serverShared = res.share.visibility !== "private";
- if (serverShared !== localIsSharedRef.current) {
- void persistNoteShareState(
- note.id,
- serverShared ? { is_shared: 1 } : { is_shared: 0, share_token: null }
- ).catch((err) => console.error("Share flag persist failed:", err));
+ setRefreshedCloudId(cloudId);
+ const update = reconcileLocalShareState(localShareStateRef.current, res.share);
+ if (update) {
+ void persistNoteShareState(note.id, update).catch((err) =>
+ console.error("Share flag persist failed:", err)
+ );
}
})
.catch((err) => {
@@ -244,6 +259,8 @@ export default function ShareNoteDialog({
setEmailInput("");
setInputError(null);
setCopied(false);
+ setConfirmingReplaceLink(false);
+ setRefreshedCloudId(null);
}
}, [open]);
@@ -365,11 +382,9 @@ export default function ShareNoteDialog({
);
const copyLink = useCallback(
- async (token: string) => {
+ async (url: string) => {
try {
- await navigator.clipboard.writeText(
- `${SHARE_VIEWER_BASE_URL}/n/${encodeURIComponent(token)}`
- );
+ await navigator.clipboard.writeText(url);
setCopied(true);
if (copyTimeoutRef.current) window.clearTimeout(copyTimeoutRef.current);
copyTimeoutRef.current = window.setTimeout(() => setCopied(false), 1500);
@@ -381,47 +396,76 @@ export default function ShareNoteDialog({
[t, toast]
);
- // Legacy shares can predate local token persistence; rotating is the only
+ // The raw token is returned only on generate or rotate, so a share made on
+ // another device, or by an invite, leaves none here; rotating is the only
// way to recover a copyable link (the old one stops working by design).
- const rotateAndCopy = useCallback(async () => {
- if (!cloudId || !canManageAccess || !shareActionAllowed("rotate-link")) return;
- try {
- const res = await NoteSharingService.rotateToken(cloudId);
- updateShareCache(cloudId, (entry) => ({
- share: res.share,
- invitations: entry?.invitations ?? [],
- rawToken: res.raw_token,
- }));
- void persistNoteShareState(note.id, { is_shared: 1, share_token: res.raw_token }).catch(
- (err) => console.error("Share flag persist failed:", err)
- );
- await copyLink(res.raw_token);
- } catch (err) {
- console.error("Share link recovery failed:", err);
- toast({ title: t("noteEditor.share.dialog.error.copyFailed"), variant: "destructive" });
- }
- }, [cloudId, canManageAccess, note.id, copyLink, t, toast, shareActionAllowed]);
+ const rotateAndCopy = useCallback(
+ async (visibility: ShareVisibility) => {
+ if (!cloudId || !canManageAccess || !shareActionAllowed("rotate-link", visibility)) {
+ toast({ title: t("noteEditor.share.dialog.error.copyFailed"), variant: "destructive" });
+ return;
+ }
+ try {
+ const res = await NoteSharingService.rotateToken(cloudId);
+ updateShareCache(cloudId, (entry) => ({
+ share: res.share,
+ invitations: entry?.invitations ?? [],
+ rawToken: res.raw_token,
+ }));
+ void persistNoteShareState(note.id, { is_shared: 1, share_token: res.raw_token }).catch(
+ (err) => console.error("Share flag persist failed:", err)
+ );
+ const link = resolveShareLink(res.share, [res.raw_token]);
+ if (link.kind !== "copy") throw new Error("Rotated share has no copyable link");
+ await copyLink(link.url);
+ } catch (err) {
+ console.error("Share link recovery failed:", err);
+ toast({ title: t("noteEditor.share.dialog.error.copyFailed"), variant: "destructive" });
+ }
+ },
+ [cloudId, canManageAccess, note.id, copyLink, t, toast, shareActionAllowed]
+ );
+
+ // Reads the cache rather than render state: a Create link click, or a
+ // refresh that lands while the replace confirm is open, may have changed it.
+ const copyCurrentLink = useCallback(
+ async (replaceConfirmed: boolean) => {
+ const entry = cloudId ? getShareCacheEntry(cloudId) : null;
+ if (!entry || entry.share.visibility === "private") {
+ toast({ title: t("noteEditor.share.dialog.error.copyFailed"), variant: "destructive" });
+ return;
+ }
+ const link = resolveShareLink(entry.share, [note.share_token, entry.rawToken]);
+ if (link.kind === "copy") await copyLink(link.url);
+ else if (link.needsConfirmation && !replaceConfirmed) setConfirmingReplaceLink(true);
+ else await rotateAndCopy(entry.share.visibility);
+ },
+ [cloudId, note.share_token, copyLink, rotateAndCopy, t, toast]
+ );
const handleLinkButton = useCallback(async () => {
if (!cloudId || !share || !canUseLink) return;
setLinkBusy(true);
try {
- if (share.visibility === "private") {
- // Create link: the click is the sharing consent.
- const res = await applyVisibility("link");
- if (!res) return;
- const token = res.raw_token ?? note.share_token ?? getShareCacheEntry(cloudId)?.rawToken;
- if (token) await copyLink(token);
- else await rotateAndCopy();
- return;
- }
- const known = note.share_token ?? getShareCacheEntry(cloudId)?.rawToken;
- if (known) await copyLink(known);
- else await rotateAndCopy();
+ // Create link: the click is the sharing consent.
+ if (share.visibility === "private" && !(await applyVisibility("link"))) return;
+ await copyCurrentLink(false);
} finally {
setLinkBusy(false);
}
- }, [cloudId, share, canUseLink, note.share_token, applyVisibility, copyLink, rotateAndCopy]);
+ }, [cloudId, share, canUseLink, applyVisibility, copyCurrentLink]);
+
+ const handleReplaceLink = useCallback(async () => {
+ // The confirm stays clickable through its exit animation, and a second
+ // rotation can leave this device holding a dead token.
+ if (linkBusy) return;
+ setLinkBusy(true);
+ try {
+ await copyCurrentLink(true);
+ } finally {
+ setLinkBusy(false);
+ }
+ }, [linkBusy, copyCurrentLink]);
const copyIntentHandled = useRef(false);
useEffect(() => {
@@ -429,11 +473,17 @@ export default function ShareNoteDialog({
copyIntentHandled.current = false;
return;
}
- if (copyLinkOnOpen && !copyIntentHandled.current && share && !loading && canUseLink) {
+ if (
+ copyLinkOnOpen &&
+ !copyIntentHandled.current &&
+ share &&
+ refreshedCloudId === cloudId &&
+ canUseLink
+ ) {
copyIntentHandled.current = true;
void handleLinkButton();
}
- }, [open, copyLinkOnOpen, share, loading, canUseLink, handleLinkButton]);
+ }, [open, copyLinkOnOpen, share, refreshedCloudId, cloudId, canUseLink, handleLinkButton]);
const handleInvite = useCallback(async () => {
if (!cloudId || !canInvite) return;
@@ -845,17 +895,13 @@ export default function ShareNoteDialog({
<AccessGrantRow
key={grant.id}
grant={grant}
- canChangePermission={Boolean(
- access?.can_manage_access &&
- (!grant.inherited || access.can_manage_inherited_access) &&
- shareActionAllowed("change-grant")
- )}
+ canChangePermission={
+ canManageAccessGrant(access, grant) && shareActionAllowed("change-grant")
+ }
showPermissionActions={shareActionAllowed("change-grant")}
- canRemove={Boolean(
- access?.can_manage_access &&
- (!grant.inherited || access.can_manage_inherited_access) &&
- shareActionAllowed("remove-grant")
- )}
+ canRemove={
+ canManageAccessGrant(access, grant) && shareActionAllowed("remove-grant")
+ }
busy={busyGrantId === grant.id}
onPermissionChange={(permission) => void handleGrantPermission(grant, permission)}
onRemove={() => void handleRemoveGrant(grant)}
@@ -1007,6 +1053,17 @@ export default function ShareNoteDialog({
</div>
</div>
)}
+
+ <ConfirmDialog
+ open={confirmingReplaceLink}
+ onOpenChange={setConfirmingReplaceLink}
+ title={t("noteEditor.share.dialog.replaceLink.title")}
+ description={t("noteEditor.share.dialog.replaceLink.description")}
+ confirmText={t("noteEditor.share.dialog.replaceLink.confirm")}
+ cancelText={t("common.cancel")}
+ variant="destructive"
+ onConfirm={() => void handleReplaceLink()}
+ />
</DialogContent>
</Dialog>
);
diff --git a/src/components/notes/shareNoteRules.ts b/src/components/notes/shareNoteRules.ts
new file mode 100644
index 000000000..4db524968
--- /dev/null
+++ b/src/components/notes/shareNoteRules.ts
@@ -0,0 +1,76 @@
+import type { NoteAccessGrant, NoteAccessState, ShareSettings } from "../../types/electron";
+
+const SHARE_VIEWER_BASE_URL = "https://notes.openwhispr.com";
+
+type ShareLinkSettings = Pick<ShareSettings, "visibility" | "token_prefix">;
+
+type ShareLinkResolution =
+ | { kind: "copy"; url: string }
+ // Rotating mints a new prefix, which kills every emailed /invite/<prefix>
+ // link, so it needs consent whenever a prefix already exists.
+ | { kind: "rotate"; needsConfirmation: boolean };
+
+export type LocalShareState = { isShared: boolean; shareToken: string | null };
+
+type LocalShareStateUpdate = { is_shared: number; share_token?: null };
+
+/** A raw token only opens the note while it belongs to the current prefix. */
+export function currentShareToken(
+ token: string | null | undefined,
+ prefix: string | null
+): string | null {
+ return token && prefix && token.startsWith(prefix) ? token : null;
+}
+
+/** A private note has no link: callers handle it before asking. */
+export function resolveShareLink(
+ share: ShareLinkSettings,
+ knownTokens: ReadonlyArray<string | null | undefined>
+): ShareLinkResolution {
+ const prefix = share.token_prefix;
+ // Invitation emails carry this link. It admits exactly the invited
+ // audience and, unlike the bearer link, stays closed if visibility widens.
+ if (share.visibility === "invited" && prefix) {
+ return { kind: "copy", url: `${SHARE_VIEWER_BASE_URL}/invite/${encodeURIComponent(prefix)}` };
+ }
+ for (const candidate of knownTokens) {
+ const token = currentShareToken(candidate, prefix);
+ if (token) {
+ return { kind: "copy", url: `${SHARE_VIEWER_BASE_URL}/n/${encodeURIComponent(token)}` };
+ }
+ }
+ return { kind: "rotate", needsConfirmation: prefix !== null };
+}
+
+/**
+ * The DB write that brings a note's local share flag in line with the server,
+ * or null when it already agrees. Every write re-pushes a shared note, so a
+ * stale stored token never triggers one on its own; it is cleared only when
+ * the flag is written anyway (resolveShareLink never copies it).
+ */
+export function reconcileLocalShareState(
+ local: LocalShareState,
+ share: ShareLinkSettings
+): LocalShareStateUpdate | null {
+ const serverShared = share.visibility !== "private";
+ if (serverShared === local.isShared) return null;
+ if (!serverShared) return { is_shared: 0, share_token: null };
+ return local.shareToken && !currentShareToken(local.shareToken, share.token_prefix)
+ ? { is_shared: 1, share_token: null }
+ : { is_shared: 1 };
+}
+
+/**
+ * Mirrors the mobile rule. `scope:` rows are synthesized from space or
+ * workspace membership, and the API rejects changing or removing them.
+ */
+export function canManageAccessGrant(
+ access: NoteAccessState | undefined,
+ grant: NoteAccessGrant
+): boolean {
+ return Boolean(
+ access?.can_manage_access &&
+ !grant.id.startsWith("scope:") &&
+ (!grant.inherited || access.can_manage_inherited_access)
+ );
+}
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index bc805a7d0..07194c91a 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -1294,6 +1294,11 @@
"createLink": "إنشاء رابط",
"copyLink": "نسخ الرابط",
"copied": "تم النسخ",
+ "replaceLink": {
+ "title": "استبدال رابط المشاركة؟",
+ "description": "لا يتوفر الرابط الحالي على هذا الجهاز، لذا يتطلب نسخه إنشاء رابط جديد. سيتوقف الرابط القديم عن العمل، بما في ذلك الروابط في رسائل الدعوة. أعد إرسال كل دعوة حتى يظل بإمكان المدعوين فتح الملاحظة.",
+ "confirm": "استبدال الرابط"
+ },
"export": "تصدير",
"owner": "المالك",
"editor": "يمكنه التعديل",
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 85147b4ab..cc388791f 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -4046,6 +4046,11 @@
"createLink": "Link erstellen",
"copyLink": "Link kopieren",
"copied": "Kopiert",
+ "replaceLink": {
+ "title": "Freigabelink ersetzen?",
+ "description": "Dieses Gerät hat den aktuellen Link nicht, daher wird zum Kopieren ein neuer erstellt. Der alte Link funktioniert dann nicht mehr, auch nicht in Einladungs-E-Mails. Sende jede Einladung erneut, damit Eingeladene die Notiz weiterhin öffnen können.",
+ "confirm": "Link ersetzen"
+ },
"export": "Exportieren",
"owner": "Eigentümer",
"editor": "Kann bearbeiten",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 2a4c14e66..2c766d143 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -4046,6 +4046,11 @@
"createLink": "Create link",
"copyLink": "Copy link",
"copied": "Copied",
+ "replaceLink": {
+ "title": "Replace the share link?",
+ "description": "This device doesn't have the current link, so copying it means creating a new one. The old link stops working, including the links in invitation emails. Resend each invitation so invitees can still open the note.",
+ "confirm": "Replace link"
+ },
"export": "Export",
"owner": "Owner",
"editor": "Can edit",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index d249f83d0..2c7aa4839 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -3970,6 +3970,11 @@
"createLink": "Crear enlace",
"copyLink": "Copiar enlace",
"copied": "Copiado",
+ "replaceLink": {
+ "title": "¿Reemplazar el enlace para compartir?",
+ "description": "Este dispositivo no tiene el enlace actual, así que copiarlo implica crear uno nuevo. El enlace anterior dejará de funcionar, incluidos los de los correos de invitación. Reenvía cada invitación para que las personas invitadas puedan seguir abriendo la nota.",
+ "confirm": "Reemplazar enlace"
+ },
"export": "Exportar",
"owner": "Propietario",
"editor": "Puede editar",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 0847eb034..a56a18517 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -4046,6 +4046,11 @@
"createLink": "Créer un lien",
"copyLink": "Copier le lien",
"copied": "Copié",
+ "replaceLink": {
+ "title": "Remplacer le lien de partage ?",
+ "description": "Cet appareil ne dispose pas du lien actuel : le copier implique d'en créer un nouveau. L'ancien lien cessera de fonctionner, y compris dans les e-mails d'invitation. Renvoyez chaque invitation pour que les personnes invitées puissent toujours ouvrir la note.",
+ "confirm": "Remplacer le lien"
+ },
"export": "Exporter",
"owner": "Propriétaire",
"editor": "Peut modifier",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 4767df3ca..629bcb89c 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -3917,6 +3917,11 @@
"createLink": "Crea link",
"copyLink": "Copia link",
"copied": "Copiato",
+ "replaceLink": {
+ "title": "Sostituire il link di condivisione?",
+ "description": "Questo dispositivo non ha il link attuale, quindi copiarlo significa crearne uno nuovo. Il vecchio link smetterà di funzionare, anche nelle email di invito. Reinvia ogni invito affinché le persone invitate possano continuare ad aprire la nota.",
+ "confirm": "Sostituisci link"
+ },
"export": "Esporta",
"owner": "Proprietario",
"editor": "Può modificare",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index cbe87b35b..23fa4bdc4 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -3917,6 +3917,11 @@
"createLink": "リンクを作成",
"copyLink": "リンクをコピー",
"copied": "コピーしました",
+ "replaceLink": {
+ "title": "共有リンクを置き換えますか?",
+ "description": "このデバイスには現在のリンクがないため、コピーするには新しいリンクを作成する必要があります。古いリンクは、招待メール内のリンクも含めて使えなくなります。招待された人が引き続きノートを開けるように、各招待を再送信してください。",
+ "confirm": "リンクを置き換え"
+ },
"export": "エクスポート",
"owner": "オーナー",
"editor": "編集可能",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 25d220411..50e6d0c1b 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -3917,6 +3917,11 @@
"createLink": "Criar link",
"copyLink": "Copiar link",
"copied": "Copiado",
+ "replaceLink": {
+ "title": "Substituir o link de compartilhamento?",
+ "description": "Este dispositivo não tem o link atual, então copiá-lo significa criar um novo. O link antigo deixará de funcionar, inclusive nos e-mails de convite. Reenvie cada convite para que as pessoas convidadas continuem podendo abrir a nota.",
+ "confirm": "Substituir link"
+ },
"export": "Exportar",
"owner": "Proprietário",
"editor": "Pode editar",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index b06994531..52e020e62 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -3961,6 +3961,11 @@
"createLink": "Создать ссылку",
"copyLink": "Скопировать ссылку",
"copied": "Скопировано",
+ "replaceLink": {
+ "title": "Заменить ссылку для доступа?",
+ "description": "На этом устройстве нет текущей ссылки, поэтому для копирования будет создана новая. Старая ссылка перестанет работать, в том числе в письмах с приглашениями. Отправьте каждое приглашение снова, чтобы приглашённые по-прежнему могли открыть заметку.",
+ "confirm": "Заменить ссылку"
+ },
"export": "Экспорт",
"owner": "Владелец",
"editor": "Может редактировать",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index cef35a093..f5851b154 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -3917,6 +3917,11 @@
"createLink": "创建链接",
"copyLink": "复制链接",
"copied": "已复制",
+ "replaceLink": {
+ "title": "替换分享链接?",
+ "description": "此设备上没有当前链接,因此复制时需要创建新链接。旧链接将失效,包括邀请邮件中的链接。请重新发送每个邀请,以便受邀者仍能打开此笔记。",
+ "confirm": "替换链接"
+ },
"export": "导出",
"owner": "所有者",
"editor": "可编辑",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 7fa2afa2a..31e99d283 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -3917,6 +3917,11 @@
"createLink": "建立連結",
"copyLink": "複製連結",
"copied": "已複製",
+ "replaceLink": {
+ "title": "要取代分享連結嗎?",
+ "description": "此裝置上沒有目前的連結,因此複製時需要建立新連結。舊連結將會失效,包括邀請電子郵件中的連結。請重新傳送每個邀請,讓受邀者仍能開啟這則筆記。",
+ "confirm": "取代連結"
+ },
"export": "匯出",
"owner": "擁有者",
"editor": "可編輯",
diff --git a/src/stores/policyRules.ts b/src/stores/policyRules.ts
index 44ac3b7f1..b31e2bb41 100644
--- a/src/stores/policyRules.ts
+++ b/src/stores/policyRules.ts
@@ -456,6 +456,8 @@ export function isShareActionAllowed(
}
if (action === "create-link") return isShareVisibilityAllowed(state, "link");
if (action === "set-domain") return isShareVisibilityAllowed(state, "domain");
+ // A private note suspends its invitations and has no link for the email to carry.
+ if (action === "resend-invitation" && currentVisibility === "private") return false;
return isShareVisibilityAllowed(state, "invited");
}
diff --git a/test/components/shareNoteDialogLink.test.js b/test/components/shareNoteDialogLink.test.js
new file mode 100644
index 000000000..879b14602
--- /dev/null
+++ b/test/components/shareNoteDialogLink.test.js
@@ -0,0 +1,544 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { act, createElement } = require("react");
+const { createRoot } = require("react-dom/client");
+const { renderToStaticMarkup } = require("react-dom/server");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHostDom,
+} = require("../lib/rendererTestHarness");
+
+// Server rendering runs no effects and drops state updates, so most tests
+// render the dialog once, capture the handlers its controls were given, and
+// call them directly. Tests that need effects mount it on a fake DOM instead.
+// Assertions are on what reaches the clipboard, the API, and the local DB,
+// never on intermediate state.
+
+const CLOUD_ID = "cloud-note-1";
+const PREFIX = "ow_share_abc1234";
+const TOKEN = `${PREFIX}${"x".repeat(25)}`;
+const ROTATED_AWAY_TOKEN = `ow_share_zzz9999${"y".repeat(25)}`;
+const NEW_PREFIX = "ow_share_new0000";
+const NEW_TOKEN = `${NEW_PREFIX}${"n".repeat(25)}`;
+
+function shareSettings(visibility, tokenPrefix) {
+ return {
+ visibility,
+ token_prefix: tokenPrefix,
+ domain_allowlist: [],
+ updated_by_user_id: null,
+ updated_at: null,
+ };
+}
+
+function accessGrant(id, overrides = {}) {
+ return {
+ id,
+ principal: { type: "user", id: `${id}-user`, email: `${id}@acme.com`, name: null, image: null },
+ permission: "viewer",
+ source: "direct",
+ inherited: false,
+ pending: false,
+ created_at: "2026-09-01T00:00:00Z",
+ updated_at: "2026-09-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+const MOCK_MODULES = {
+ "react-i18next": `
+ export const useTranslation = () => ({ t: (key) => key });
+ `,
+ "/hooks/useAuth": `
+ export const useAuth = () => ({ user: { name: "Owner", email: "[email protected]" } });
+ `,
+ "/hooks/usePolicy": `export const usePolicySnapshot = () => ({});`,
+ "/stores/policyRules": `
+ export const filterShareVisibilityOptions = (options) => options;
+ export const hasUsableExternalShareVisibility = () => true;
+ // The slice of the real rule these tests lean on: a private note has no
+ // link, and a test can withdraw link sharing by policy.
+ export const isShareActionAllowed = (_state, action, visibility) =>
+ !(
+ (action === "copy-link" || action === "rotate-link") &&
+ (visibility === "private" || globalThis.__shareTest.linkDenied)
+ );
+ `,
+ "/services/SyncService.js": `export const syncService = { ensureNoteSynced: async () => null };`,
+ "/services/NoteSharingService.js": `
+ const record = (name, ...args) => globalThis.__shareTest.calls.push({ name, args });
+ const cached = (id) => globalThis.__shareTest.cache.get(id);
+ export const NoteSharingService = {
+ async getShareSettings(id) {
+ record("getShareSettings", id);
+ const entry = globalThis.__shareTest.server ?? cached(id);
+ return { share: entry.share, invitations: entry.invitations, access: entry.access };
+ },
+ async updateShareSettings(id, visibility, domains) {
+ record("updateShareSettings", id, visibility, domains);
+ return globalThis.__shareTest.updateResult;
+ },
+ async rotateToken(id) {
+ record("rotateToken", id);
+ return globalThis.__shareTest.rotateResult;
+ },
+ async clearShare(id) {
+ record("clearShare", id);
+ return { share: { ...cached(id).share, visibility: "private", token_prefix: null } };
+ },
+ async updateAccessGrant(id, grantId, permission) {
+ record("updateAccessGrant", id, grantId, permission);
+ return cached(id).access.grants.find((grant) => grant.id === grantId);
+ },
+ async removeAccessGrant(id, grantId) {
+ record("removeAccessGrant", id, grantId);
+ },
+ async searchAccessPrincipals() {
+ return { suggestions: [] };
+ },
+ };
+ `,
+ "/stores/noteStore": `
+ const cache = () => globalThis.__shareTest.cache;
+ export const getShareCacheEntry = (id) => cache().get(id) ?? null;
+ export const updateShareCache = (id, updater) => {
+ const current = cache().get(id);
+ cache().set(id, { ...current, ...updater(current) });
+ };
+ export const persistNoteShareState = async (noteId, updates) => {
+ globalThis.__shareTest.persisted.push({ noteId, updates });
+ };
+ export const useSpaces = () => [];
+ export const useShareCacheEntry = (id) => (id ? (cache().get(id) ?? null) : null);
+ `,
+ "/ui/useToast": `
+ export const useToast = () => ({ toast: (props) => globalThis.__shareTest.toasts.push(props) });
+ `,
+ "/ui/dialog": `
+ import { createElement } from "react";
+ const passthrough = (props) => createElement("div", null, props.children);
+ export const Dialog = passthrough;
+ export const DialogContent = passthrough;
+ export const DialogTitle = passthrough;
+ export const DialogDescription = passthrough;
+ export const ConfirmDialog = (props) => {
+ globalThis.__shareTest.confirmDialogs.push(props);
+ return null;
+ };
+ `,
+ "/ui/button": `
+ import { createElement } from "react";
+ export const Button = (props) => {
+ globalThis.__shareTest.buttons.push(props);
+ return createElement("button", null, props.children);
+ };
+ `,
+ "/ui/dropdown-menu": `
+ import { createElement } from "react";
+ const passthrough = (props) => createElement("div", null, props.children);
+ export const DropdownMenu = passthrough;
+ export const DropdownMenuTrigger = passthrough;
+ export const DropdownMenuContent = passthrough;
+ export const DropdownMenuItem = (props) => {
+ globalThis.__shareTest.menuItems.push(props);
+ return createElement("div", null, props.children);
+ };
+ `,
+ "/MemberAvatar": `export default function MemberAvatar() { return null; }`,
+ "/ShareVisibilityMenu": `export default function ShareVisibilityMenu() { return null; }`,
+};
+
+// The dialog's handlers are fire-and-forget (`() => void handler()`), and every
+// mocked call resolves in microtasks, so one macrotask turn settles them.
+const settle = () => new Promise((resolve) => setImmediate(resolve));
+
+function textOf(node) {
+ if (node == null || typeof node === "boolean") return "";
+ if (typeof node === "string" || typeof node === "number") return String(node);
+ if (Array.isArray(node)) return node.map(textOf).join("");
+ return textOf(node.props?.children);
+}
+
+async function setupDialog(t, { entry, server, updateResult = null, rotateResult = null }) {
+ const clipboardWrites = [];
+ installBrowserGlobals(t, {
+ window: { setTimeout: () => 1, clearTimeout: () => {}, electronAPI: {} },
+ });
+ Object.defineProperty(globalThis.navigator, "clipboard", {
+ configurable: true,
+ value: { writeText: async (text) => void clipboardWrites.push(text) },
+ });
+ const state = {
+ cache: new Map([[CLOUD_ID, entry]]),
+ calls: [],
+ persisted: [],
+ toasts: [],
+ confirmDialogs: [],
+ buttons: [],
+ menuItems: [],
+ server,
+ updateResult,
+ rotateResult,
+ };
+ globalThis.__shareTest = state;
+ t.after(() => {
+ delete globalThis.__shareTest;
+ delete globalThis.navigator.clipboard;
+ });
+
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-share-note-dialog-test-",
+ noExternal: ["react-i18next"],
+ mockModules: MOCK_MODULES,
+ });
+ const { default: ShareNoteDialog } = await vite.ssrLoadModule(
+ "/components/notes/ShareNoteDialog.tsx"
+ );
+ const callsTo = (name) => state.calls.filter((call) => call.name === name);
+ return { state, clipboardWrites, callsTo, ShareNoteDialog };
+}
+
+function dialogProps(note, extra = {}) {
+ return {
+ open: true,
+ onOpenChange: () => {},
+ note: { id: 7, cloud_id: CLOUD_ID, is_shared: 1, share_token: null, ...note },
+ ...extra,
+ };
+}
+
+async function renderDialog(t, { note, ...options }) {
+ const { state, clipboardWrites, callsTo, ShareNoteDialog } = await setupDialog(t, options);
+ renderToStaticMarkup(createElement(ShareNoteDialog, dialogProps(note)));
+
+ return { state, linkButton: latestLinkButton(state), clipboardWrites, callsTo };
+}
+
+function latestLinkButton(state) {
+ const linkButton = state.buttons.findLast((props) =>
+ /noteEditor\.share\.dialog\.(copyLink|createLink)/.test(textOf(props.children))
+ );
+ assert.ok(linkButton, "expected the link button to render");
+ return linkButton;
+}
+
+// Mounts the dialog so its effects run. `setOpen` re-renders it open or closed,
+// as NoteEditor does; `copyLinkOnOpen` is the Share button's link segment.
+async function mountDialog(t, { note, copyLinkOnOpen = false, ...options }) {
+ let root = null;
+ // Registered first: after-hooks run in order, and unmounting needs the globals.
+ t.after(() => act(() => root?.unmount()));
+ const dialog = await setupDialog(t, options);
+ root = createRoot(installHostDom(t));
+ const setOpen = async (open) => {
+ await act(async () => {
+ root.render(
+ createElement(dialog.ShareNoteDialog, dialogProps(note, { open, copyLinkOnOpen }))
+ );
+ });
+ await act(settle);
+ };
+ await setOpen(true);
+ return { ...dialog, setOpen };
+}
+
+test("an invite-only note copies the invitation link and never rotates", async (t) => {
+ const { linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ note: { share_token: null },
+ entry: { share: shareSettings("invited", PREFIX), invitations: [], rawToken: null },
+ });
+
+ linkButton.onClick();
+ await settle();
+
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/invite/${PREFIX}`]);
+ assert.equal(callsTo("rotateToken").length, 0);
+});
+
+test("a link share with no local token does not rotate until the replacement is confirmed", async (t) => {
+ const { state, linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ note: { share_token: null },
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: null },
+ rotateResult: { share: shareSettings("link", NEW_PREFIX), raw_token: NEW_TOKEN },
+ });
+
+ linkButton.onClick();
+ await settle();
+
+ assert.equal(callsTo("rotateToken").length, 0, "the click alone must not rotate");
+ assert.deepEqual(clipboardWrites, []);
+
+ const confirm = state.confirmDialogs.find(
+ (props) => props.title === "noteEditor.share.dialog.replaceLink.title"
+ );
+ assert.ok(confirm, "expected a replace-link confirmation");
+ assert.equal(confirm.description, "noteEditor.share.dialog.replaceLink.description");
+ assert.equal(confirm.confirmText, "noteEditor.share.dialog.replaceLink.confirm");
+ assert.equal(confirm.cancelText, "common.cancel");
+
+ confirm.onConfirm();
+ await settle();
+
+ assert.equal(callsTo("rotateToken").length, 1);
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/n/${NEW_TOKEN}`]);
+ assert.deepEqual(state.persisted.at(-1), {
+ noteId: 7,
+ updates: { is_shared: 1, share_token: NEW_TOKEN },
+ });
+});
+
+test("a stored token rotated away on another device is never copied", async (t) => {
+ const { linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ note: { share_token: ROTATED_AWAY_TOKEN },
+ entry: {
+ share: shareSettings("link", PREFIX),
+ invitations: [],
+ rawToken: ROTATED_AWAY_TOKEN,
+ },
+ });
+
+ linkButton.onClick();
+ await settle();
+
+ assert.deepEqual(clipboardWrites, []);
+ assert.equal(callsTo("rotateToken").length, 0);
+});
+
+test("a current stored token is copied as the viewer link", async (t) => {
+ const { linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ note: { share_token: TOKEN },
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: null },
+ });
+
+ linkButton.onClick();
+ await settle();
+
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/n/${TOKEN}`]);
+ assert.equal(callsTo("rotateToken").length, 0);
+});
+
+test("creating a link on a private note copies the token the server just minted", async (t) => {
+ const { linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ note: { is_shared: 0, share_token: ROTATED_AWAY_TOKEN },
+ entry: { share: shareSettings("private", null), invitations: [], rawToken: null },
+ updateResult: { share: shareSettings("link", PREFIX), raw_token: TOKEN },
+ });
+
+ linkButton.onClick();
+ await settle();
+
+ assert.equal(callsTo("updateShareSettings").length, 1);
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/n/${TOKEN}`]);
+ assert.equal(callsTo("rotateToken").length, 0);
+});
+
+test("an invite-only note with no prefix yet rotates without asking and copies the invitation link", async (t) => {
+ const { state, linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ entry: { share: shareSettings("invited", null), invitations: [], rawToken: null },
+ rotateResult: { share: shareSettings("invited", NEW_PREFIX), raw_token: NEW_TOKEN },
+ });
+
+ linkButton.onClick();
+ await settle();
+
+ assert.equal(callsTo("rotateToken").length, 1);
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/invite/${NEW_PREFIX}`]);
+ assert.equal(state.toasts.length, 0);
+});
+
+test("creating a link that returns no token rotates once the share is off private", async (t) => {
+ const { linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ note: { is_shared: 0 },
+ entry: { share: shareSettings("private", null), invitations: [], rawToken: null },
+ updateResult: { share: shareSettings("link", null), raw_token: null },
+ rotateResult: { share: shareSettings("link", NEW_PREFIX), raw_token: NEW_TOKEN },
+ });
+
+ linkButton.onClick();
+ await settle();
+
+ assert.equal(callsTo("rotateToken").length, 1);
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/n/${NEW_TOKEN}`]);
+});
+
+test("confirming the replacement copies instead when a refresh made the note invite-only", async (t) => {
+ const { state, linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: null },
+ rotateResult: { share: shareSettings("link", NEW_PREFIX), raw_token: NEW_TOKEN },
+ });
+ linkButton.onClick();
+ await settle();
+
+ // The dialog's load refresh lands while the confirm is open.
+ state.cache.get(CLOUD_ID).share = shareSettings("invited", PREFIX);
+ state.confirmDialogs[0].onConfirm();
+ await settle();
+
+ assert.equal(callsTo("rotateToken").length, 0);
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/invite/${PREFIX}`]);
+});
+
+test("confirming the replacement after the note went private says the copy failed", async (t) => {
+ const { state, linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: null },
+ rotateResult: { share: shareSettings("link", NEW_PREFIX), raw_token: NEW_TOKEN },
+ });
+ linkButton.onClick();
+ await settle();
+
+ state.cache.get(CLOUD_ID).share = shareSettings("private", null);
+ state.confirmDialogs[0].onConfirm();
+ await settle();
+
+ assert.equal(callsTo("rotateToken").length, 0);
+ assert.deepEqual(clipboardWrites, []);
+ assert.deepEqual(
+ state.toasts.map((toast) => toast.title),
+ ["noteEditor.share.dialog.error.copyFailed"]
+ );
+});
+
+test("confirming the replacement after policy withdrew link sharing does not rotate", async (t) => {
+ const { state, linkButton, clipboardWrites, callsTo } = await renderDialog(t, {
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: null },
+ rotateResult: { share: shareSettings("link", NEW_PREFIX), raw_token: NEW_TOKEN },
+ });
+ linkButton.onClick();
+ await settle();
+
+ state.linkDenied = true;
+ state.confirmDialogs[0].onConfirm();
+ await settle();
+
+ assert.equal(callsTo("rotateToken").length, 0);
+ assert.deepEqual(clipboardWrites, []);
+ assert.deepEqual(
+ state.toasts.map((toast) => toast.title),
+ ["noteEditor.share.dialog.error.copyFailed"]
+ );
+});
+
+test("copy on open waits for the refreshed share instead of the cached one", async (t) => {
+ // Cached when the note opened: a link share whose token was since rotated
+ // away on another device, and the note has since become invite-only.
+ const { state, clipboardWrites, callsTo } = await mountDialog(t, {
+ copyLinkOnOpen: true,
+ note: { share_token: ROTATED_AWAY_TOKEN },
+ entry: {
+ share: shareSettings("link", ROTATED_AWAY_TOKEN.slice(0, 16)),
+ invitations: [],
+ rawToken: ROTATED_AWAY_TOKEN,
+ },
+ server: { share: shareSettings("invited", PREFIX), invitations: [] },
+ });
+
+ assert.equal(callsTo("getShareSettings").length, 1);
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/invite/${PREFIX}`]);
+ assert.equal(callsTo("rotateToken").length, 0);
+ assert.equal(state.cache.get(CLOUD_ID).rawToken, null, "the stale token leaves the cache");
+});
+
+test("reopening from the link segment waits for a new refresh too", async (t) => {
+ const { state, clipboardWrites, setOpen } = await mountDialog(t, {
+ copyLinkOnOpen: true,
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: TOKEN },
+ });
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/n/${TOKEN}`]);
+
+ await setOpen(false);
+ // Meanwhile the note becomes invite-only on another device.
+ state.server = { share: shareSettings("invited", NEW_PREFIX), invitations: [] };
+ await setOpen(true);
+
+ assert.deepEqual(clipboardWrites, [
+ `https://notes.openwhispr.com/n/${TOKEN}`,
+ `https://notes.openwhispr.com/invite/${NEW_PREFIX}`,
+ ]);
+});
+
+test("the replace confirm opens from the link button and closes with the dialog", async (t) => {
+ const { state, callsTo, setOpen } = await mountDialog(t, {
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: null },
+ });
+ const confirmOpen = () =>
+ state.confirmDialogs.findLast(
+ (props) => props.title === "noteEditor.share.dialog.replaceLink.title"
+ ).open;
+ assert.equal(confirmOpen(), false);
+
+ await act(async () => latestLinkButton(state).onClick());
+ await act(settle);
+ assert.equal(confirmOpen(), true);
+ assert.equal(callsTo("rotateToken").length, 0);
+
+ await setOpen(false);
+ await setOpen(true);
+ assert.equal(confirmOpen(), false);
+});
+
+test("a second confirm click while the replacement runs does not rotate again", async (t) => {
+ const { state, clipboardWrites, callsTo } = await mountDialog(t, {
+ entry: { share: shareSettings("link", PREFIX), invitations: [], rawToken: null },
+ });
+ let finishRotate;
+ state.rotateResult = new Promise((resolve) => {
+ finishRotate = () =>
+ resolve({ share: shareSettings("link", NEW_PREFIX), raw_token: NEW_TOKEN });
+ });
+ const latestConfirm = () =>
+ state.confirmDialogs.findLast(
+ (props) => props.title === "noteEditor.share.dialog.replaceLink.title"
+ );
+ await act(async () => latestLinkButton(state).onClick());
+ await act(settle);
+
+ await act(async () => latestConfirm().onConfirm());
+ await act(async () => latestConfirm().onConfirm());
+ await act(async () => finishRotate());
+ await act(settle);
+
+ assert.equal(callsTo("rotateToken").length, 1);
+ assert.deepEqual(clipboardWrites, [`https://notes.openwhispr.com/n/${NEW_TOKEN}`]);
+});
+
+test("synthetic scope rows offer no permission or remove controls", async (t) => {
+ const direct = accessGrant("grant-direct", { permission: "viewer" });
+ const scope = accessGrant("scope:workspace:w1", {
+ principal: {
+ type: "workspace",
+ id: "w1",
+ email: null,
+ name: "Acme",
+ image: null,
+ member_count: 4,
+ },
+ source: "workspace",
+ inherited: true,
+ });
+ const { state, callsTo } = await renderDialog(t, {
+ entry: {
+ share: shareSettings("invited", PREFIX),
+ invitations: [],
+ rawToken: null,
+ access: {
+ owner: { type: "user", id: "owner", email: "[email protected]", name: null, image: null },
+ grants: [direct, scope],
+ my_permission: "owner",
+ can_manage_access: true,
+ can_manage_inherited_access: true,
+ },
+ },
+ });
+
+ for (const item of state.menuItems.filter((props) => !props.disabled)) {
+ item.onClick?.();
+ }
+ await settle();
+
+ const targeted = [...callsTo("updateAccessGrant"), ...callsTo("removeAccessGrant")].map(
+ (call) => call.args[1]
+ );
+ assert.ok(targeted.includes(direct.id), "the direct grant keeps its controls");
+ assert.ok(!targeted.includes(scope.id), `scope row was offered controls: ${targeted}`);
+});
diff --git a/test/components/shareNoteRules.test.js b/test/components/shareNoteRules.test.js
new file mode 100644
index 000000000..88a85c0ff
--- /dev/null
+++ b/test/components/shareNoteRules.test.js
@@ -0,0 +1,220 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/components/notes/shareNoteRules.ts");
+
+const PREFIX = "ow_share_abc1234";
+const TOKEN = `${PREFIX}${"x".repeat(25)}`;
+// A token minted before a rotation on another device: same format, other prefix.
+const ROTATED_AWAY_TOKEN = `ow_share_zzz9999${"y".repeat(25)}`;
+
+function grant(overrides = {}) {
+ return {
+ id: "grant-1",
+ principal: { type: "user", id: "u1", email: "[email protected]", name: null, image: null },
+ permission: "viewer",
+ source: "direct",
+ inherited: false,
+ pending: false,
+ created_at: "2026-09-01T00:00:00Z",
+ updated_at: "2026-09-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function access(overrides = {}) {
+ return {
+ owner: { type: "user", id: "owner", email: "[email protected]", name: null, image: null },
+ grants: [],
+ my_permission: "owner",
+ can_manage_access: true,
+ can_manage_inherited_access: true,
+ ...overrides,
+ };
+}
+
+test("a stored token is current only while it starts with the note's prefix", async () => {
+ const { currentShareToken } = await load();
+
+ assert.equal(currentShareToken(TOKEN, PREFIX), TOKEN);
+ assert.equal(currentShareToken(ROTATED_AWAY_TOKEN, PREFIX), null);
+ assert.equal(currentShareToken(TOKEN, null), null);
+ assert.equal(currentShareToken(null, PREFIX), null);
+ assert.equal(currentShareToken(undefined, PREFIX), null);
+});
+
+test("an invite-only note copies the invitation link, which needs no raw token", async () => {
+ const { resolveShareLink } = await load();
+
+ assert.deepEqual(resolveShareLink({ visibility: "invited", token_prefix: PREFIX }, []), {
+ kind: "copy",
+ url: `https://notes.openwhispr.com/invite/${PREFIX}`,
+ });
+});
+
+// The bearer link would open the note for anyone if visibility later widens.
+test("an invite-only note copies the invitation link even when the raw token is known", async () => {
+ const { resolveShareLink } = await load();
+
+ assert.deepEqual(resolveShareLink({ visibility: "invited", token_prefix: PREFIX }, [TOKEN]), {
+ kind: "copy",
+ url: `https://notes.openwhispr.com/invite/${PREFIX}`,
+ });
+});
+
+test("a link share copies the viewer URL for a current token", async () => {
+ const { resolveShareLink } = await load();
+
+ for (const visibility of ["link", "domain"]) {
+ assert.deepEqual(resolveShareLink({ visibility, token_prefix: PREFIX }, [TOKEN]), {
+ kind: "copy",
+ url: `https://notes.openwhispr.com/n/${TOKEN}`,
+ });
+ }
+});
+
+test("a token rotated away elsewhere is skipped in favor of a current one", async () => {
+ const { resolveShareLink } = await load();
+
+ assert.deepEqual(
+ resolveShareLink({ visibility: "link", token_prefix: PREFIX }, [ROTATED_AWAY_TOKEN, TOKEN]),
+ { kind: "copy", url: `https://notes.openwhispr.com/n/${TOKEN}` }
+ );
+});
+
+// Rotating changes the prefix, which kills every emailed /invite/<prefix> link.
+test("a link share with no current token asks before replacing the link", async () => {
+ const { resolveShareLink } = await load();
+
+ for (const visibility of ["link", "domain"]) {
+ for (const known of [[], [null, undefined], [ROTATED_AWAY_TOKEN]]) {
+ assert.deepEqual(resolveShareLink({ visibility, token_prefix: PREFIX }, known), {
+ kind: "rotate",
+ needsConfirmation: true,
+ });
+ }
+ }
+});
+
+test("a shared note with no prefix at all mints one without asking: nothing can break", async () => {
+ const { resolveShareLink } = await load();
+
+ for (const visibility of ["invited", "link", "domain"]) {
+ assert.deepEqual(resolveShareLink({ visibility, token_prefix: null }, [TOKEN]), {
+ kind: "rotate",
+ needsConfirmation: false,
+ });
+ }
+});
+
+test("reconciling leaves a note alone when it already matches the server", async () => {
+ const { reconcileLocalShareState } = await load();
+
+ assert.equal(
+ reconcileLocalShareState(
+ { isShared: true, shareToken: TOKEN },
+ { visibility: "link", token_prefix: PREFIX }
+ ),
+ null
+ );
+ assert.equal(
+ reconcileLocalShareState(
+ { isShared: true, shareToken: null },
+ { visibility: "invited", token_prefix: PREFIX }
+ ),
+ null
+ );
+ assert.equal(
+ reconcileLocalShareState(
+ { isShared: false, shareToken: null },
+ { visibility: "private", token_prefix: null }
+ ),
+ null
+ );
+});
+
+// Every share-state write re-pushes a shared note, and while share mutations
+// bump the cloud version that push can 409 into a conflict banner. A stale
+// token is already ignored when copying, so it never earns a write alone.
+test("a stale token alone does not cause a write", async () => {
+ const { reconcileLocalShareState } = await load();
+
+ assert.equal(
+ reconcileLocalShareState(
+ { isShared: true, shareToken: ROTATED_AWAY_TOKEN },
+ { visibility: "link", token_prefix: PREFIX }
+ ),
+ null
+ );
+ assert.equal(
+ reconcileLocalShareState(
+ { isShared: false, shareToken: TOKEN },
+ { visibility: "private", token_prefix: null }
+ ),
+ null
+ );
+});
+
+test("a flag write also clears a stored token that a rotation elsewhere made stale", async () => {
+ const { reconcileLocalShareState } = await load();
+
+ assert.deepEqual(
+ reconcileLocalShareState(
+ { isShared: false, shareToken: ROTATED_AWAY_TOKEN },
+ { visibility: "domain", token_prefix: PREFIX }
+ ),
+ { is_shared: 1, share_token: null }
+ );
+});
+
+test("reconciling follows the server's shared flag", async () => {
+ const { reconcileLocalShareState } = await load();
+
+ assert.deepEqual(
+ reconcileLocalShareState(
+ { isShared: false, shareToken: null },
+ { visibility: "invited", token_prefix: PREFIX }
+ ),
+ { is_shared: 1 }
+ );
+ assert.deepEqual(
+ reconcileLocalShareState(
+ { isShared: true, shareToken: TOKEN },
+ { visibility: "private", token_prefix: null }
+ ),
+ { is_shared: 0, share_token: null }
+ );
+});
+
+test("a direct grant is manageable by someone who manages access", async () => {
+ const { canManageAccessGrant } = await load();
+
+ assert.equal(canManageAccessGrant(access(), grant()), true);
+ assert.equal(canManageAccessGrant(access({ can_manage_access: false }), grant()), false);
+ assert.equal(canManageAccessGrant(undefined, grant()), false);
+});
+
+test("an inherited grant needs inherited-access management", async () => {
+ const { canManageAccessGrant } = await load();
+ const inherited = grant({ inherited: true, source: "team" });
+
+ assert.equal(canManageAccessGrant(access(), inherited), true);
+ assert.equal(
+ canManageAccessGrant(access({ can_manage_inherited_access: false }), inherited),
+ false
+ );
+});
+
+// Space/workspace membership rows are synthesized by the API, which rejects
+// PATCH/DELETE on them with 400.
+test("a synthetic scope row is never manageable", async () => {
+ const { canManageAccessGrant } = await load();
+
+ for (const id of ["scope:workspace:w1", "scope:team:t1"]) {
+ assert.equal(
+ canManageAccessGrant(access(), grant({ id, inherited: true, source: "workspace" })),
+ false
+ );
+ assert.equal(canManageAccessGrant(access(), grant({ id })), false);
+ }
+});
diff --git a/test/helpers/policyRules.test.js b/test/helpers/policyRules.test.js
index cfea4542b..e6b6f9802 100644
--- a/test/helpers/policyRules.test.js
+++ b/test/helpers/policyRules.test.js
@@ -598,6 +598,21 @@ test("copying an existing share link follows its own visibility", async () => {
}
});
+test("resending an invitation needs sharing to be on", async () => {
+ const { isShareActionAllowed } = await load();
+ const unmanaged = { status: "unmanaged", policy: null, appVersion: "1.8.1" };
+ const allowed = { status: "managed", policy, appVersion: "1.8.1" };
+
+ for (const snapshot of [unmanaged, allowed]) {
+ for (const visibility of ["link", "domain", "invited"]) {
+ assert.equal(isShareActionAllowed(snapshot, "resend-invitation", visibility), true);
+ }
+ // Disabling sharing suspends invitations, so the email could not open the note.
+ assert.equal(isShareActionAllowed(snapshot, "resend-invitation", "private"), false);
+ assert.equal(isShareActionAllowed(snapshot, "revoke-invitation", "private"), true);
+ }
+});
+
test("sharing recovery remains available when exposure-increasing actions are blocked", async () => {
const { isShareActionAllowed } = await load();
const blockedSnapshots = [