Account sync: Mullvad-style, end-to-end encrypted

Options -> Konto: random 16-digit account number, optional random password,
no personal data. The browser derives account id, AES key and auth secret,
so the new standalone sync server (node dist/sync-server.js, SYNC_DATA_DIR)
only stores padded encrypted blobs. Proof-of-work on account creation,
1 year expiry, no IP logging. Pulled at startup, pushed when synced keys
change, conflict prompt when both sides changed. QR link, recovery file,
per-category selection; device-specific keys stay local. Self-hosters can
run their own and set SYNC_URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Opus 5.5 committed 2026-10-24 07:40:00 +00:00
1 parent a82c99972e
commit 0a9dd545b1
16 files changed
+1559 -11

No files matched your search

+30
View File
@@ -4899,3 +4899,33 @@
margin: 0;
font-size: 0.9em;
}
/* Options -> Konto */
.ts-sync-secret {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.ts-sync-secret code {
font-size: 1.1em;
letter-spacing: 0.05em;
user-select: all;
}
.ts-sync-buttons {
display: flex;
gap: 6px;
flex-wrap: wrap;
margin-top: 6px;
}
.ts-sync-warning {
color: var(--ts-warning, #e0a030);
}
.ts-sync-qr-box {
margin-top: 8px;
}
.ts-sync-qr {
display: block;
max-width: 100%;
height: auto;
}
+305 -1
View File
@@ -1,4 +1,15 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type ReactNode,
} from "react";
import qrcode from "qrcode-generator";
import { useRegisterSW } from "virtual:pwa-register/react";
import "./App.css";
// After App.css: its :where() base variables have the same (zero) specificity.
@@ -124,6 +135,29 @@ import {
} from "./publish";
import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode";
import {
DEFAULT_SYNC_SERVER,
SYNC_CATEGORIES,
accountInfo,
changeSyncPassword,
createSyncAccount,
deleteSyncAccount,
formatAccountNumber,
getSyncStatus,
loadSyncAccount,
loginSyncAccount,
logoutSyncAccount,
normalizeAccountNumber,
normalizePassword,
recoveryText,
resolveConflict,
setSyncCategories,
subscribeSyncStatus,
syncErrorKey,
syncLink,
syncNow,
type SyncCategory,
} from "./sync";
import {
SOUND_EVENTS,
clearCustomSound,
@@ -5924,6 +5958,7 @@ function AwayDialog({
const OPTIONS_SECTIONS = [
{ id: "anwendung", icon: "🎧" },
{ id: "konto", icon: "👤" },
{ id: "wiedergabe", icon: "🔊" },
{ id: "aufnahme", icon: "🎙️" },
{ id: "sounds", icon: "🔔" },
@@ -6410,6 +6445,273 @@ function AnwendungPanel({
);
}
/** QR code as inline SVG (no data: URL, so no CSP img-src exception needed). */
function QrCode({ text }: { text: string }) {
const { n, d } = useMemo(() => {
const qr = qrcode(0, "M");
qr.addData(text);
qr.make();
const n = qr.getModuleCount();
let d = "";
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) if (qr.isDark(r, c)) d += `M${c} ${r}h1v1h-1z`;
return { n, d };
}, [text]);
return (
<svg className="ts-sync-qr" viewBox={`-3 -3 ${n + 6} ${n + 6}`} width="220" height="220" role="img">
<rect x={-3} y={-3} width={n + 6} height={n + 6} fill="#fff" />
<path d={d} fill="#000" />
</svg>
);
}
/** Options -> Konto: Mullvad-style sync account (see sync.ts). */
function KontoPanel() {
const t = useT();
const status = useSyncExternalStore(subscribeSyncStatus, getSyncStatus);
const [account, setAccount] = useState(loadSyncAccount);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState("");
const [withPassword, setWithPassword] = useState(true);
const [server, setServer] = useState(DEFAULT_SYNC_SERVER);
const [loginNumber, setLoginNumber] = useState("");
const [loginPassword, setLoginPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [showQr, setShowQr] = useState(false);
const [copied, setCopied] = useState<string | null>(null);
// Status changes (a push in the background) also move version/lastSync.
useEffect(() => setAccount(loadSyncAccount()), [status]);
const run = async (label: string, fn: () => Promise<void>) => {
setBusy(label);
setError("");
try {
await fn();
setAccount(loadSyncAccount());
} catch (err) {
setError(t(syncErrorKey(err)));
} finally {
setBusy(null);
}
};
const copy = (what: string, text: string) => {
void navigator.clipboard?.writeText(text);
setCopied(what);
window.setTimeout(() => setCopied(null), 1500);
};
if (!account) {
const number = normalizeAccountNumber(loginNumber);
return (
<>
<h3>{t("options.section.konto")}</h3>
<p className="ts-options-subtitle">{t("sync.subtitle")}</p>
<p className="ts-options-hint">{t("sync.intro")}</p>
<div className="ts-options-fields">
<fieldset className="ts-options-fieldset">
<legend>{t("sync.create.title")}</legend>
<label className="ts-options-checkbox">
<input type="checkbox" checked={withPassword} onChange={(e) => setWithPassword(e.target.checked)} />
{t("sync.create.withPassword")}
</label>
<p className="ts-options-hint">{t("sync.create.withPasswordHint")}</p>
<button
disabled={busy !== null}
onClick={() => void run("create", () => createSyncAccount(withPassword, server.trim(), SYNC_CATEGORIES))}
>
{busy === "create" ? t("sync.create.busy") : t("sync.create.button")}
</button>
</fieldset>
<fieldset className="ts-options-fieldset">
<legend>{t("sync.login.title")}</legend>
<label className="ts-options-field">
{t("sync.number")}
<input
value={loginNumber}
inputMode="numeric"
placeholder="0000 0000 0000 0000"
onChange={(e) => setLoginNumber(e.target.value)}
/>
</label>
<label className="ts-options-field">
{t("sync.passwordOptional")}
<input value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} />
</label>
<p className="ts-options-hint">{t("sync.login.hint")}</p>
<button
disabled={busy !== null || !number}
onClick={() =>
void run("login", async () => {
const password = loginPassword.trim() ? normalizePassword(loginPassword) : undefined;
if (!password && (await accountInfo(number!, server.trim())).hasPassword) throw new Error("password_required");
await loginSyncAccount(number!, password, server.trim(), SYNC_CATEGORIES);
window.location.reload();
})
}
>
{t("sync.login.button")}
</button>
</fieldset>
<label className="ts-options-field">
{t("sync.server")}
<input value={server} onChange={(e) => setServer(e.target.value)} />
</label>
<p className="ts-options-hint">{t("sync.serverHint")}</p>
{error && <p className="ts-vault-wrong">{error}</p>}
</div>
</>
);
}
const toggleCategory = (c: SyncCategory, on: boolean) =>
void run("categories", () =>
setSyncCategories(on ? [...account.categories, c] : account.categories.filter((x) => x !== c))
);
return (
<>
<h3>{t("options.section.konto")}</h3>
<p className="ts-options-subtitle">{t("sync.subtitle")}</p>
<div className="ts-options-columns">
<div className="ts-options-fields">
<fieldset className="ts-options-fieldset">
<legend>{t("sync.account.title")}</legend>
<label className="ts-options-field">
{t("sync.number")}
<span className="ts-sync-secret">
<code>{formatAccountNumber(account.number)}</code>
<button onClick={() => copy("number", account.number)}>
{copied === "number" ? t("sync.copied") : t("sync.copy")}
</button>
</span>
</label>
<label className="ts-options-field">
{t("sync.password")}
{account.password ? (
<span className="ts-sync-secret">
<code>{showPassword ? account.password : "•••••-•••••-•••••-•••••"}</code>
<button onClick={() => setShowPassword((v) => !v)}>
{showPassword ? t("sync.hide") : t("sync.show")}
</button>
<button onClick={() => copy("password", account.password!)}>
{copied === "password" ? t("sync.copied") : t("sync.copy")}
</button>
</span>
) : (
<span className="ts-sync-secret">{t("sync.noPassword")}</span>
)}
</label>
<p className="ts-options-hint ts-sync-warning">{t("sync.keepSafe")}</p>
<div className="ts-sync-buttons">
<button
onClick={() => {
const url = URL.createObjectURL(new Blob([recoveryText(account)], { type: "text/plain" }));
const a = document.createElement("a");
a.href = url;
a.download = "webspeak3-account.txt";
a.click();
URL.revokeObjectURL(url);
}}
>
{t("sync.recoveryFile")}
</button>
<button onClick={() => setShowQr((v) => !v)}>{showQr ? t("sync.qr.hide") : t("sync.qr.show")}</button>
<button
disabled={busy !== null}
onClick={() => {
if (window.confirm(t(account.password ? "sync.password.removeConfirm" : "sync.password.addConfirm")))
void run("password", () => changeSyncPassword(!account.password));
}}
>
{account.password ? t("sync.password.remove") : t("sync.password.add")}
</button>
</div>
{showQr && (
<div className="ts-sync-qr-box">
<QrCode text={syncLink(account)} />
<p className="ts-options-hint">{t("sync.qr.hint")}</p>
</div>
)}
</fieldset>
</div>
<div className="ts-options-fields">
<fieldset className="ts-options-fieldset">
<legend>{t("sync.categories")}</legend>
{SYNC_CATEGORIES.map((c) => (
<label key={c} className="ts-options-checkbox">
<input
type="checkbox"
checked={account.categories.includes(c)}
disabled={busy !== null}
onChange={(e) => toggleCategory(c, e.target.checked)}
/>
{t(`sync.category.${c}`)}
</label>
))}
<p className="ts-options-hint">{t("sync.categoriesHint")}</p>
</fieldset>
<fieldset className="ts-options-fieldset">
<legend>{t("sync.status")}</legend>
<p>
{status.state === "syncing"
? t("sync.status.syncing")
: status.state === "error"
? t(syncErrorKey(status.error))
: status.state === "conflict"
? t("sync.conflict.text")
: account.lastSync
? t("sync.status.last", { time: new Date(account.lastSync).toLocaleString() })
: t("sync.status.never")}
</p>
{status.state === "conflict" ? (
<div className="ts-sync-buttons">
<button disabled={busy !== null} onClick={() => void run("resolve", () => resolveConflict("local"))}>
{t("sync.conflict.local")}
</button>
<button
disabled={busy !== null}
onClick={() =>
void run("resolve", async () => {
await resolveConflict("server");
window.location.reload();
})
}
>
{t("sync.conflict.server")}
</button>
</div>
) : (
<button disabled={busy !== null || status.state === "syncing"} onClick={() => void run("sync", syncNow)}>
{t("sync.syncNow")}
</button>
)}
<p className="ts-options-hint">{t("sync.serverInfo", { server: account.server })}</p>
</fieldset>
<div className="ts-sync-buttons">
<button
onClick={() => {
if (!window.confirm(t("sync.logoutConfirm"))) return;
logoutSyncAccount();
setAccount(null);
}}
>
{t("sync.logout")}
</button>
<button
disabled={busy !== null}
onClick={() => {
if (window.confirm(t("sync.deleteConfirm"))) void run("delete", deleteSyncAccount);
}}
>
{t("sync.delete")}
</button>
</div>
{error && <p className="ts-vault-wrong">{error}</p>}
</div>
</div>
</>
);
}
type CustomThemeDraft = { id: string | null; name: string; baseTheme: DesignTheme; css: string };
/** Shared stroke-icon wrapper for the custom-theme-card action row, so all
@@ -8141,6 +8443,8 @@ function OptionsDialog({
<ChatPanel />
) : active.id === "sicherheit" ? (
<SecurityPanel onOpenIdentities={onOpenIdentities} onClearCache={onClearCache} />
) : active.id === "konto" ? (
<KontoPanel />
) : active.id === "meldungen" ? (
<MeldungenPanel onOpenFavorites={onOpenFavorites} onApplyPackToFavorites={onApplyPackToFavorites} />
) : (
+65 -1
View File
@@ -289,6 +289,7 @@
"options.cancel": "Zrušit",
"options.notImplemented": "Toto nastavení zatím není implementováno.",
"options.section.anwendung": "Aplikace",
"options.section.konto": "Účet",
"options.section.wiedergabe": "Přehrávání",
"options.section.aufnahme": "Snímání",
"options.section.design": "Vzhled",
@@ -930,5 +931,68 @@
"securitySettings.masterNew": "Nové hlavní heslo",
"securitySettings.masterRepeat": "Zopakovat",
"securitySettings.masterMismatch": "Hesla se neshodují.",
"securitySettings.masterNote": "Dobře si ho zapamatujte: bez něj přijdete o identity a uložená hesla."
"securitySettings.masterNote": "Dobře si ho zapamatujte: bez něj přijdete o identity a uložená hesla.",
"sync.subtitle": "Tvá data na všech zařízeních",
"sync.intro": "Účet je jen náhodné číslo, volitelně s heslem. Žádný e-mail, žádné jméno. Vše se před nahráním zašifruje na tvém zařízení. Server vidí jen nečitelná data.",
"sync.create.title": "Nový účet",
"sync.create.withPassword": "Vygenerovat i náhodné heslo (doporučeno)",
"sync.create.withPasswordHint": "Bez hesla stačí k tvým datům samotné číslo účtu.",
"sync.create.button": "Vytvořit účet",
"sync.create.busy": "Účet se vytváří …",
"sync.login.title": "Existující účet",
"sync.number": "Číslo účtu",
"sync.password": "Heslo",
"sync.passwordOptional": "Heslo (pokud existuje)",
"sync.login.hint": "Data účtu pak nahradí data na tomto zařízení.",
"sync.login.button": "Přihlásit",
"sync.server": "Synchronizační server",
"sync.serverHint": "Účet existuje jen na serveru, na kterém byl vytvořen.",
"sync.account.title": "Tvůj účet",
"sync.copy": "Kopírovat",
"sync.copied": "Zkopírováno",
"sync.show": "Zobrazit",
"sync.hide": "Skrýt",
"sync.noPassword": "Bez hesla",
"sync.keepSafe": "Číslo a heslo dobře uschovej. Když je ztratíš, nikdo tvá data neobnoví, ani my.",
"sync.recoveryFile": "Stáhnout soubor pro obnovení",
"sync.qr.show": "Zobrazit QR kód",
"sync.qr.hide": "Skrýt QR kód",
"sync.qr.hint": "Naskenuj ho druhým zařízením a přihlas se tam. Kdo kód uvidí, má přístup k tvému účtu.",
"sync.password.add": "Přidat heslo",
"sync.password.remove": "Odebrat heslo",
"sync.password.addConfirm": "Vygenerovat nové náhodné heslo? Ostatní zařízení se pak musí znovu přihlásit číslem a heslem.",
"sync.password.removeConfirm": "Odebrat heslo? Pak bude stačit samotné číslo účtu. Ostatní zařízení se musí znovu přihlásit.",
"sync.categories": "Synchronizovat",
"sync.category.identities": "Identity (včetně soukromých klíčů)",
"sync.category.favorites": "Oblíbené, hesla kanálů a kontakty",
"sync.category.settings": "Nastavení",
"sync.category.designs": "Vzhledy a balíčky ikon",
"sync.category.whisper": "Seznamy šeptání",
"sync.categoriesHint": "Zvuková zařízení, hlasitosti, klávesa PTT a záznamy chatu zůstávají vždy na zařízení.",
"sync.status": "Stav",
"sync.status.syncing": "Synchronizuje se …",
"sync.status.last": "Naposledy synchronizováno: {time}",
"sync.status.never": "Zatím nesynchronizováno",
"sync.conflict.title": "Synchronizace",
"sync.conflict.text": "Od poslední synchronizace se změnilo něco na tomto zařízení i v účtu. Který stav má platit?",
"sync.conflict.local": "Nahrát stav tohoto zařízení",
"sync.conflict.server": "Načíst stav z účtu",
"sync.syncNow": "Synchronizovat teď",
"sync.serverInfo": "Server: {server}",
"sync.logout": "Odhlásit",
"sync.logoutConfirm": "Odhlásit toto zařízení z účtu? Účet i data zůstanou zachovány.",
"sync.delete": "Smazat účet",
"sync.deleteConfirm": "Trvale smazat účet a všechna jeho data na serveru? Data na tomto zařízení zůstanou.",
"sync.link.title": "Připojit k účtu",
"sync.link.prompt": "Připojit toto zařízení k účtu {number}? Data účtu nahradí data na tomto zařízení.",
"sync.link.connect": "Připojit",
"sync.error.password_required": "Tento účet má heslo.",
"sync.error.unreachable": "Synchronizační server není dostupný.",
"sync.error.not_found": "Účet nenalezen nebo špatné heslo. Pokud bylo heslo změněno na jiném zařízení, přihlas se znovu.",
"sync.error.rate_limited": "Příliš mnoho požadavků, zkus to později.",
"sync.error.full": "Synchronizační server teď nepřijímá nové účty.",
"sync.error.pow_required": "Bezpečnostní kontrola selhala, zkus to znovu.",
"sync.error.conflict": "Jiné zařízení mezitím něco změnilo.",
"sync.error.payload_too_large": "Příliš mnoho dat pro synchronizaci (max. 1 MB).",
"sync.error.generic": "Synchronizace selhala."
}
+65 -1
View File
@@ -289,6 +289,7 @@
"options.cancel": "Abbrechen",
"options.notImplemented": "Diese Einstellungen sind noch nicht implementiert.",
"options.section.anwendung": "Anwendung",
"options.section.konto": "Konto",
"options.section.wiedergabe": "Wiedergabe",
"options.section.aufnahme": "Aufnahme",
"options.section.design": "Design",
@@ -930,5 +931,68 @@
"securitySettings.masterNew": "Neues Master Passwort",
"securitySettings.masterRepeat": "Wiederholen",
"securitySettings.masterMismatch": "Die Passwörter stimmen nicht überein.",
"securitySettings.masterNote": "Merk es dir gut: Ohne das Passwort sind Identitäten und gespeicherte Passwörter weg."
"securitySettings.masterNote": "Merk es dir gut: Ohne das Passwort sind Identitäten und gespeicherte Passwörter weg.",
"sync.subtitle": "Deine Daten auf allen Geräten",
"sync.intro": "Ein Konto besteht nur aus einer zufälligen Nummer, optional mit Passwort. Keine Mail, kein Name. Alles wird auf deinem Gerät verschlüsselt, bevor es hochgeladen wird. Der Server sieht nur unlesbare Daten.",
"sync.create.title": "Neues Konto",
"sync.create.withPassword": "Zusätzlich ein zufälliges Passwort erzeugen (empfohlen)",
"sync.create.withPasswordHint": "Ohne Passwort reicht die Kontonummer allein, um an deine Daten zu kommen.",
"sync.create.button": "Konto erstellen",
"sync.create.busy": "Konto wird erstellt …",
"sync.login.title": "Bestehendes Konto",
"sync.number": "Kontonummer",
"sync.password": "Passwort",
"sync.passwordOptional": "Passwort (falls vorhanden)",
"sync.login.hint": "Die Daten des Kontos ersetzen danach die auf diesem Gerät.",
"sync.login.button": "Anmelden",
"sync.server": "Sync-Server",
"sync.serverHint": "Ein Konto gibt es nur auf dem Server, auf dem es erstellt wurde.",
"sync.account.title": "Dein Konto",
"sync.copy": "Kopieren",
"sync.copied": "Kopiert",
"sync.show": "Anzeigen",
"sync.hide": "Verbergen",
"sync.noPassword": "Kein Passwort",
"sync.keepSafe": "Bewahre Nummer und Passwort gut auf. Gehen sie verloren, kann niemand deine Daten wiederherstellen, auch wir nicht.",
"sync.recoveryFile": "Wiederherstellungsdatei herunterladen",
"sync.qr.show": "QR-Code anzeigen",
"sync.qr.hide": "QR-Code verbergen",
"sync.qr.hint": "Mit dem anderen Gerät scannen, um es dort anzumelden. Wer den Code sieht, hat Zugriff auf dein Konto.",
"sync.password.add": "Passwort hinzufügen",
"sync.password.remove": "Passwort entfernen",
"sync.password.addConfirm": "Ein neues zufälliges Passwort erzeugen? Andere Geräte müssen sich danach mit Nummer und Passwort neu anmelden.",
"sync.password.removeConfirm": "Passwort entfernen? Dann reicht die Kontonummer allein. Andere Geräte müssen sich neu anmelden.",
"sync.categories": "Synchronisieren",
"sync.category.identities": "Identitäten (inkl. privater Schlüssel)",
"sync.category.favorites": "Favoriten, Channel-Passwörter und Kontakte",
"sync.category.settings": "Einstellungen",
"sync.category.designs": "Designs und Icon Packs",
"sync.category.whisper": "Whisper-Listen",
"sync.categoriesHint": "Audiogeräte, Lautstärken, PTT-Taste und Chatprotokolle bleiben immer auf dem Gerät.",
"sync.status": "Status",
"sync.status.syncing": "Wird synchronisiert …",
"sync.status.last": "Zuletzt synchronisiert: {time}",
"sync.status.never": "Noch nicht synchronisiert",
"sync.conflict.title": "Synchronisierung",
"sync.conflict.text": "Auf diesem Gerät und im Konto wurde seit dem letzten Abgleich etwas geändert. Welcher Stand soll gelten?",
"sync.conflict.local": "Diesen Stand hochladen",
"sync.conflict.server": "Stand aus dem Konto laden",
"sync.syncNow": "Jetzt synchronisieren",
"sync.serverInfo": "Server: {server}",
"sync.logout": "Abmelden",
"sync.logoutConfirm": "Dieses Gerät vom Konto abmelden? Konto und Daten bleiben erhalten.",
"sync.delete": "Konto löschen",
"sync.deleteConfirm": "Konto mit allen Daten auf dem Server endgültig löschen? Die Daten auf diesem Gerät bleiben.",
"sync.link.title": "Mit Konto verbinden",
"sync.link.prompt": "Dieses Gerät mit dem Konto {number} verbinden? Die Daten des Kontos ersetzen die auf diesem Gerät.",
"sync.link.connect": "Verbinden",
"sync.error.password_required": "Dieses Konto hat ein Passwort.",
"sync.error.unreachable": "Sync-Server nicht erreichbar.",
"sync.error.not_found": "Konto nicht gefunden oder Passwort falsch. Wurde das Passwort auf einem anderen Gerät geändert, melde dich neu an.",
"sync.error.rate_limited": "Zu viele Anfragen, bitte später nochmal.",
"sync.error.full": "Der Sync-Server nimmt gerade keine neuen Konten an.",
"sync.error.pow_required": "Sicherheitsprüfung fehlgeschlagen, bitte nochmal versuchen.",
"sync.error.conflict": "Ein anderes Gerät hat inzwischen etwas geändert.",
"sync.error.payload_too_large": "Zu viele Daten für die Synchronisierung (max. 1 MB).",
"sync.error.generic": "Synchronisierung fehlgeschlagen."
}
+65 -1
View File
@@ -289,6 +289,7 @@
"options.cancel": "Cancel",
"options.notImplemented": "This setting isn't implemented yet.",
"options.section.anwendung": "Application",
"options.section.konto": "Account",
"options.section.wiedergabe": "Playback",
"options.section.aufnahme": "Capture",
"options.section.design": "Appearance",
@@ -930,5 +931,68 @@
"securitySettings.masterNew": "New master password",
"securitySettings.masterRepeat": "Repeat",
"securitySettings.masterMismatch": "The passwords don't match.",
"securitySettings.masterNote": "Remember it well: without it, identities and saved passwords are lost."
"securitySettings.masterNote": "Remember it well: without it, identities and saved passwords are lost.",
"sync.subtitle": "Your data on all your devices",
"sync.intro": "An account is just a random number, optionally with a password. No email, no name. Everything is encrypted on your device before it is uploaded. The server only sees unreadable data.",
"sync.create.title": "New account",
"sync.create.withPassword": "Also generate a random password (recommended)",
"sync.create.withPasswordHint": "Without a password, the account number alone gives access to your data.",
"sync.create.button": "Create account",
"sync.create.busy": "Creating account …",
"sync.login.title": "Existing account",
"sync.number": "Account number",
"sync.password": "Password",
"sync.passwordOptional": "Password (if any)",
"sync.login.hint": "The account's data then replaces the data on this device.",
"sync.login.button": "Log in",
"sync.server": "Sync server",
"sync.serverHint": "An account only exists on the server it was created on.",
"sync.account.title": "Your account",
"sync.copy": "Copy",
"sync.copied": "Copied",
"sync.show": "Show",
"sync.hide": "Hide",
"sync.noPassword": "No password",
"sync.keepSafe": "Keep the number and password safe. If you lose them, nobody can recover your data, not even us.",
"sync.recoveryFile": "Download recovery file",
"sync.qr.show": "Show QR code",
"sync.qr.hide": "Hide QR code",
"sync.qr.hint": "Scan it with the other device to log in there. Anyone who sees this code can access your account.",
"sync.password.add": "Add password",
"sync.password.remove": "Remove password",
"sync.password.addConfirm": "Generate a new random password? Other devices will have to log in again with number and password.",
"sync.password.removeConfirm": "Remove the password? The account number alone will then be enough. Other devices will have to log in again.",
"sync.categories": "Sync",
"sync.category.identities": "Identities (including private keys)",
"sync.category.favorites": "Favorites, channel passwords and contacts",
"sync.category.settings": "Settings",
"sync.category.designs": "Designs and icon packs",
"sync.category.whisper": "Whisper lists",
"sync.categoriesHint": "Audio devices, volumes, PTT key and chat logs always stay on the device.",
"sync.status": "Status",
"sync.status.syncing": "Syncing …",
"sync.status.last": "Last synced: {time}",
"sync.status.never": "Not synced yet",
"sync.conflict.title": "Sync",
"sync.conflict.text": "Both this device and the account changed since the last sync. Which one should win?",
"sync.conflict.local": "Upload this device's data",
"sync.conflict.server": "Load the account's data",
"sync.syncNow": "Sync now",
"sync.serverInfo": "Server: {server}",
"sync.logout": "Log out",
"sync.logoutConfirm": "Log this device out of the account? The account and its data are kept.",
"sync.delete": "Delete account",
"sync.deleteConfirm": "Permanently delete the account and all its data on the server? The data on this device stays.",
"sync.link.title": "Connect to account",
"sync.link.prompt": "Connect this device to account {number}? The account's data replaces the data on this device.",
"sync.link.connect": "Connect",
"sync.error.password_required": "This account has a password.",
"sync.error.unreachable": "Sync server not reachable.",
"sync.error.not_found": "Account not found or wrong password. If the password was changed on another device, log in again.",
"sync.error.rate_limited": "Too many requests, please try again later.",
"sync.error.full": "The sync server isn't accepting new accounts right now.",
"sync.error.pow_required": "Security check failed, please try again.",
"sync.error.conflict": "Another device changed something in the meantime.",
"sync.error.payload_too_large": "Too much data to sync (max. 1 MB).",
"sync.error.generic": "Sync failed."
}
+65 -1
View File
@@ -289,6 +289,7 @@
"options.cancel": "لغو",
"options.notImplemented": "این تنظیم هنوز پیاده‌سازی نشده است.",
"options.section.anwendung": "برنامه",
"options.section.konto": "حساب",
"options.section.wiedergabe": "پخش",
"options.section.aufnahme": "ضبط",
"options.section.design": "ظاهر",
@@ -929,5 +930,68 @@
"securitySettings.masterNew": "رمز اصلی جدید",
"securitySettings.masterRepeat": "تکرار",
"securitySettings.masterMismatch": "رمزها یکسان نیستند.",
"securitySettings.masterNote": "آن را به خاطر بسپارید: بدون آن، هویت‌ها و رمزهای ذخیره‌شده از دست می‌روند."
"securitySettings.masterNote": "آن را به خاطر بسپارید: بدون آن، هویت‌ها و رمزهای ذخیره‌شده از دست می‌روند.",
"sync.subtitle": "داده‌های تو روی همه دستگاه‌ها",
"sync.intro": "حساب فقط یک شماره تصادفی است، در صورت تمایل با رمز عبور. بدون ایمیل، بدون نام. همه چیز پیش از بارگذاری روی دستگاه تو رمزگذاری می‌شود. سرور فقط داده‌های ناخوانا می‌بیند.",
"sync.create.title": "حساب جدید",
"sync.create.withPassword": "یک رمز عبور تصادفی هم بساز (پیشنهادی)",
"sync.create.withPasswordHint": "بدون رمز عبور، شماره حساب به‌تنهایی برای دسترسی به داده‌هایت کافی است.",
"sync.create.button": "ساخت حساب",
"sync.create.busy": "در حال ساخت حساب …",
"sync.login.title": "حساب موجود",
"sync.number": "شماره حساب",
"sync.password": "رمز عبور",
"sync.passwordOptional": "رمز عبور (در صورت وجود)",
"sync.login.hint": "پس از آن داده‌های حساب جایگزین داده‌های این دستگاه می‌شوند.",
"sync.login.button": "ورود",
"sync.server": "سرور همگام‌سازی",
"sync.serverHint": "هر حساب فقط روی سروری وجود دارد که روی آن ساخته شده است.",
"sync.account.title": "حساب تو",
"sync.copy": "کپی",
"sync.copied": "کپی شد",
"sync.show": "نمایش",
"sync.hide": "پنهان",
"sync.noPassword": "بدون رمز عبور",
"sync.keepSafe": "شماره و رمز عبور را در جای امن نگه دار. اگر گم شوند، هیچ‌کس نمی‌تواند داده‌هایت را بازیابی کند، حتی ما.",
"sync.recoveryFile": "دانلود فایل بازیابی",
"sync.qr.show": "نمایش کد QR",
"sync.qr.hide": "پنهان کردن کد QR",
"sync.qr.hint": "با دستگاه دیگر اسکن کن تا آنجا وارد شوی. هر کسی این کد را ببیند به حسابت دسترسی دارد.",
"sync.password.add": "افزودن رمز عبور",
"sync.password.remove": "حذف رمز عبور",
"sync.password.addConfirm": "یک رمز عبور تصادفی جدید ساخته شود؟ دستگاه‌های دیگر باید با شماره و رمز عبور دوباره وارد شوند.",
"sync.password.removeConfirm": "رمز عبور حذف شود؟ آن‌گاه شماره حساب به‌تنهایی کافی است. دستگاه‌های دیگر باید دوباره وارد شوند.",
"sync.categories": "همگام‌سازی",
"sync.category.identities": "هویت‌ها (شامل کلیدهای خصوصی)",
"sync.category.favorites": "علاقه‌مندی‌ها، رمز کانال‌ها و مخاطبان",
"sync.category.settings": "تنظیمات",
"sync.category.designs": "طرح‌ها و بسته‌های آیکون",
"sync.category.whisper": "فهرست‌های نجوا",
"sync.categoriesHint": "دستگاه‌های صوتی، حجم صدا، کلید PTT و گزارش‌های چت همیشه روی دستگاه می‌مانند.",
"sync.status": "وضعیت",
"sync.status.syncing": "در حال همگام‌سازی …",
"sync.status.last": "آخرین همگام‌سازی: {time}",
"sync.status.never": "هنوز همگام‌سازی نشده",
"sync.conflict.title": "همگام‌سازی",
"sync.conflict.text": "از آخرین همگام‌سازی، هم این دستگاه و هم حساب تغییر کرده‌اند. کدام معتبر باشد؟",
"sync.conflict.local": "بارگذاری داده‌های این دستگاه",
"sync.conflict.server": "بارگیری داده‌های حساب",
"sync.syncNow": "همگام‌سازی اکنون",
"sync.serverInfo": "سرور: {server}",
"sync.logout": "خروج",
"sync.logoutConfirm": "این دستگاه از حساب خارج شود؟ حساب و داده‌هایش حفظ می‌شوند.",
"sync.delete": "حذف حساب",
"sync.deleteConfirm": "حساب و همه داده‌هایش روی سرور برای همیشه حذف شود؟ داده‌های این دستگاه باقی می‌مانند.",
"sync.link.title": "اتصال به حساب",
"sync.link.prompt": "این دستگاه به حساب {number} متصل شود؟ داده‌های حساب جایگزین داده‌های این دستگاه می‌شوند.",
"sync.link.connect": "اتصال",
"sync.error.password_required": "این حساب رمز عبور دارد.",
"sync.error.unreachable": "سرور همگام‌سازی در دسترس نیست.",
"sync.error.not_found": "حساب پیدا نشد یا رمز عبور اشتباه است. اگر رمز عبور روی دستگاه دیگری تغییر کرده، دوباره وارد شو.",
"sync.error.rate_limited": "درخواست‌ها بیش از حد است، لطفاً بعداً دوباره امتحان کن.",
"sync.error.full": "سرور همگام‌سازی فعلاً حساب جدید نمی‌پذیرد.",
"sync.error.pow_required": "بررسی امنیتی ناموفق بود، دوباره امتحان کن.",
"sync.error.conflict": "دستگاه دیگری در این فاصله چیزی را تغییر داده است.",
"sync.error.payload_too_large": "داده برای همگام‌سازی بیش از حد است (حداکثر ۱ مگابایت).",
"sync.error.generic": "همگام‌سازی ناموفق بود."
}
+65 -1
View File
@@ -228,6 +228,7 @@
"options.cancel": "取消",
"options.notImplemented": "此设置尚未实现。",
"options.section.anwendung": "应用",
"options.section.konto": "账户",
"options.section.wiedergabe": "播放",
"options.section.aufnahme": "录音",
"options.section.design": "外观",
@@ -929,5 +930,68 @@
"securitySettings.masterNew": "新主密码",
"securitySettings.masterRepeat": "重复",
"securitySettings.masterMismatch": "两次密码不一致。",
"securitySettings.masterNote": "请牢记:没有它,身份和已保存的密码将丢失。"
"securitySettings.masterNote": "请牢记:没有它,身份和已保存的密码将丢失。",
"sync.subtitle": "在所有设备上使用你的数据",
"sync.intro": "账户只是一个随机号码,可选附加密码。无需邮箱,无需姓名。所有数据在上传前都会在你的设备上加密,服务器只能看到无法读取的数据。",
"sync.create.title": "新账户",
"sync.create.withPassword": "同时生成随机密码(推荐)",
"sync.create.withPasswordHint": "没有密码时,仅凭账户号码就能访问你的数据。",
"sync.create.button": "创建账户",
"sync.create.busy": "正在创建账户 …",
"sync.login.title": "已有账户",
"sync.number": "账户号码",
"sync.password": "密码",
"sync.passwordOptional": "密码(如有)",
"sync.login.hint": "之后账户中的数据将替换此设备上的数据。",
"sync.login.button": "登录",
"sync.server": "同步服务器",
"sync.serverHint": "账户只存在于创建它的服务器上。",
"sync.account.title": "你的账户",
"sync.copy": "复制",
"sync.copied": "已复制",
"sync.show": "显示",
"sync.hide": "隐藏",
"sync.noPassword": "无密码",
"sync.keepSafe": "请妥善保管号码和密码。一旦丢失,任何人都无法恢复你的数据,包括我们。",
"sync.recoveryFile": "下载恢复文件",
"sync.qr.show": "显示二维码",
"sync.qr.hide": "隐藏二维码",
"sync.qr.hint": "用另一台设备扫描即可在那里登录。看到此二维码的人都能访问你的账户。",
"sync.password.add": "添加密码",
"sync.password.remove": "移除密码",
"sync.password.addConfirm": "生成新的随机密码?其他设备之后需要用号码和密码重新登录。",
"sync.password.removeConfirm": "移除密码?之后仅凭账户号码即可访问。其他设备需要重新登录。",
"sync.categories": "同步内容",
"sync.category.identities": "身份(包括私钥)",
"sync.category.favorites": "收藏、频道密码和联系人",
"sync.category.settings": "设置",
"sync.category.designs": "主题和图标包",
"sync.category.whisper": "悄悄话列表",
"sync.categoriesHint": "音频设备、音量、按键通话键和聊天记录始终保留在本设备上。",
"sync.status": "状态",
"sync.status.syncing": "正在同步 …",
"sync.status.last": "上次同步:{time}",
"sync.status.never": "尚未同步",
"sync.conflict.title": "同步",
"sync.conflict.text": "自上次同步以来,此设备和账户都有更改。以哪个为准?",
"sync.conflict.local": "上传此设备的数据",
"sync.conflict.server": "加载账户中的数据",
"sync.syncNow": "立即同步",
"sync.serverInfo": "服务器:{server}",
"sync.logout": "退出登录",
"sync.logoutConfirm": "将此设备退出账户?账户及其数据会保留。",
"sync.delete": "删除账户",
"sync.deleteConfirm": "永久删除服务器上的账户及其所有数据?此设备上的数据会保留。",
"sync.link.title": "连接账户",
"sync.link.prompt": "将此设备连接到账户 {number}?账户中的数据将替换此设备上的数据。",
"sync.link.connect": "连接",
"sync.error.password_required": "此账户设有密码。",
"sync.error.unreachable": "无法连接同步服务器。",
"sync.error.not_found": "账户不存在或密码错误。如果密码已在其他设备上更改,请重新登录。",
"sync.error.rate_limited": "请求过多,请稍后再试。",
"sync.error.full": "同步服务器暂不接受新账户。",
"sync.error.pow_required": "安全检查失败,请重试。",
"sync.error.conflict": "另一台设备在此期间做了更改。",
"sync.error.payload_too_large": "同步数据过多(最多 1 MB)。",
"sync.error.generic": "同步失败。"
}
+116 -5
View File
@@ -1,17 +1,31 @@
import './storageFallback'
import { StrictMode, useState, type FormEvent } from 'react'
import { StrictMode, useState, type FormEvent, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './styles/greenteaspeak.css'
import './App.css'
import { LanguageProvider, useT } from './i18n'
import { discardVault, hasVault, unlockVault } from './vault'
import {
SYNC_CATEGORIES,
accountInfo,
formatAccountNumber,
loginSyncAccount,
normalizePassword,
pullAtStartup,
resolveConflict,
startAutoSync,
syncErrorKey,
takeSyncLink,
} from './sync'
const root = createRoot(document.getElementById('root')!)
// App reads its stored identities/favorites while loading, so it's imported only after the vault is open.
// App reads its stored identities/favorites while loading, so it's imported only after the vault is open
// and the sync account (Options -> Konto) had its chance to bring in newer data.
async function start() {
const { default: App } = await import('./App.tsx')
startAutoSync()
root.render(
<StrictMode>
<App />
@@ -19,6 +33,103 @@ async function start() {
)
}
const dialog = (node: ReactNode) => root.render(<LanguageProvider>{node}</LanguageProvider>)
async function boot() {
const link = takeSyncLink()
if (link) return dialog(<SyncLinkDialog link={link} />)
// Don't hold the client hostage to a slow sync server.
const deadline = Date.now() + 5000
const result = await Promise.race([
pullAtStartup(deadline),
new Promise<'ok'>((resolve) => setTimeout(() => resolve('ok'), 5000)),
])
if (result === 'conflict') return dialog(<SyncConflictDialog />)
void start()
}
/** Opened through the QR code / link from Options -> Konto on another device. */
function SyncLinkDialog({ link }: { link: { number: string; password?: string; server: string } }) {
const t = useT()
const [password, setPassword] = useState(link.password ?? '')
const [askPassword, setAskPassword] = useState(false)
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const submit = async (e: FormEvent) => {
e.preventDefault()
setBusy(true)
setError('')
try {
if (!password) {
const info = await accountInfo(link.number, link.server)
if (!info.exists) throw new Error('not_found')
if (info.hasPassword) {
setAskPassword(true)
setBusy(false)
return
}
}
await loginSyncAccount(link.number, password ? normalizePassword(password) : undefined, link.server, SYNC_CATEGORIES)
void start()
} catch (err) {
setError(t(syncErrorKey(err)))
setBusy(false)
}
}
return (
<div className="ts-dialog-backdrop">
<form className="ts-dialog ts-vault-dialog" onSubmit={submit}>
<h3>{t('sync.link.title')}</h3>
<p>{t('sync.link.prompt', { number: formatAccountNumber(link.number) })}</p>
{askPassword && (
<label className="ts-dialog-field">
{t('sync.password')}
<input autoFocus value={password} onChange={(e) => setPassword(e.target.value)} />
</label>
)}
{error && <p className="ts-vault-wrong">{error}</p>}
<div className="ts-dialog-buttons">
<button type="button" onClick={() => void start()}>
{t('dialog.cancel')}
</button>
<button type="submit" disabled={busy || (askPassword && !password)}>
{t('sync.link.connect')}
</button>
</div>
</form>
</div>
)
}
function SyncConflictDialog() {
const t = useT()
const [busy, setBusy] = useState(false)
const take = async (side: 'server' | 'local') => {
setBusy(true)
try {
await resolveConflict(side)
} finally {
void start()
}
}
return (
<div className="ts-dialog-backdrop">
<div className="ts-dialog ts-vault-dialog">
<h3>{t('sync.conflict.title')}</h3>
<p>{t('sync.conflict.text')}</p>
<div className="ts-dialog-buttons">
<button disabled={busy} onClick={() => void take('local')}>
{t('sync.conflict.local')}
</button>
<button disabled={busy} onClick={() => void take('server')}>
{t('sync.conflict.server')}
</button>
</div>
</div>
</div>
)
}
function Unlock() {
const t = useT()
const [password, setPassword] = useState('')
@@ -27,7 +138,7 @@ function Unlock() {
const submit = async (e: FormEvent) => {
e.preventDefault()
setBusy(true)
if (await unlockVault(password)) return void start()
if (await unlockVault(password)) return void boot()
setBusy(false)
setWrong(true)
}
@@ -44,7 +155,7 @@ function Unlock() {
onClick={() => {
if (!window.confirm(t('vault.forgotConfirm'))) return
discardVault()
void start()
void boot()
}}
>
{t('vault.forgot')}
@@ -64,4 +175,4 @@ if (hasVault())
<Unlock />
</LanguageProvider>,
)
else void start()
else void boot()
+477
View File
@@ -0,0 +1,477 @@
// Options -> Konto: Mullvad-style account sync. A random 16-digit account number
// (+ an optional random password) is all there is. Both derive, on this device,
// the account id the server files the data under, the AES key and the auth
// secret, so the server only ever holds an encrypted blob (gateway/src/sync.ts).
//
// Pulled once at startup (main.tsx, before App reads localStorage) and pushed on
// a timer whenever a synced key changed. A remote change made while this tab is
// open shows up as a conflict on the next push, not live.
export type SyncCategory = "identities" | "favorites" | "settings" | "designs" | "whisper";
export const SYNC_CATEGORIES: SyncCategory[] = ["identities", "favorites", "settings", "designs", "whisper"];
// Device-specific keys (audio devices, volumes, PTT key, chat logs, caches) stay local.
const CATEGORY_KEYS: Record<SyncCategory, string[]> = {
identities: ["webspeak3:identities", "webspeak3:identity", "webspeak3:active-identity"],
favorites: ["webspeak3:favorites", "webspeak3:channel-passwords", "webspeak3:contacts"],
settings: [
"webspeak3:app-settings",
"webspeak3:chat-settings",
"webspeak3:chat-images",
"webspeak3:server-banner",
"webspeak3:download-settings",
"webspeak3:notification-settings",
"webspeak3:security-settings",
"webspeak3:away-presets",
"webspeak3:disconnect-message",
"webspeak3:language",
"webspeak3:sounds-enabled",
"webspeak3:sounds-volume",
"webspeak3:other-mic-clicks",
"webspeak3:own-mic-clicks",
],
designs: [
"webspeak3:custom-themes",
"webspeak3:design-selection",
"webspeak3:design-theme",
"webspeak3:icon-pack",
"webspeak3:icon-packs",
"webspeak3:ide-pixel-font",
"webspeak3:tree-options",
],
whisper: ["webspeak3:whisper-lists", "webspeak3:whisper-settings"],
};
/** Per-sound toggles are stored as "webspeak3:sounds-enabled:<id>". */
function categoryOf(key: string): SyncCategory | null {
for (const c of SYNC_CATEGORIES)
if (CATEGORY_KEYS[c].some((k) => key === k || (k === "webspeak3:sounds-enabled" && key.startsWith(`${k}:`)))) return c;
return null;
}
export const SYNC_ACCOUNT_KEY = "webspeak3:sync-account";
const meta = (name: string) => document.querySelector<HTMLMetaElement>(`meta[name="webspeak3-${name}"]`)?.content;
export const DEFAULT_SYNC_SERVER =
meta("sync-url") ||
import.meta.env.VITE_SYNC_URL ||
(import.meta.env.DEV ? "http://localhost:8081/api/sync" : "https://gateway.webspeak3.de/api/sync");
export interface SyncAccount {
number: string;
password?: string;
server: string;
categories: SyncCategory[];
/** Server version this device last wrote or read. */
version: number;
/** Hash of the synced keys at that point; differs = local changes to push. */
syncedHash: string;
lastSync?: number;
}
export type SyncState = "off" | "idle" | "syncing" | "error" | "conflict";
export interface SyncStatus {
state: SyncState;
error?: string;
lastSync?: number;
}
// --- tiny external store for the Konto panel ---------------------------------
let status: SyncStatus = { state: "off" };
const listeners = new Set<() => void>();
function setStatus(next: SyncStatus) {
status = next;
for (const l of listeners) l();
}
export const getSyncStatus = () => status;
export function subscribeSyncStatus(l: () => void) {
listeners.add(l);
return () => void listeners.delete(l);
}
export function loadSyncAccount(): SyncAccount | null {
try {
const raw = localStorage.getItem(SYNC_ACCOUNT_KEY);
return raw ? (JSON.parse(raw) as SyncAccount) : null;
} catch {
return null;
}
}
function saveSyncAccount(account: SyncAccount | null) {
if (account) localStorage.setItem(SYNC_ACCOUNT_KEY, JSON.stringify(account));
else localStorage.removeItem(SYNC_ACCOUNT_KEY);
}
// --- number, password, crypto -------------------------------------------------
function randomChars(alphabet: string, count: number): string {
let out = "";
const limit = 256 - (256 % alphabet.length); // reject to avoid modulo bias
while (out.length < count) {
for (const b of crypto.getRandomValues(new Uint8Array(count))) {
if (b < limit && out.length < count) out += alphabet[b % alphabet.length];
}
}
return out;
}
export const generateAccountNumber = () => randomChars("0123456789", 16);
/** 20 characters (~100 bits) without look-alikes, in groups of five. */
export const generatePassword = () => randomChars("ABCDEFGHJKLMNPQRSTUVWXYZ23456789", 20).replace(/(.{5})(?=.)/g, "$1-");
export const formatAccountNumber = (n: string) => n.replace(/(\d{4})(?=\d)/g, "$1 ");
/** null unless exactly 16 digits (spaces and dashes are ignored). */
export const normalizeAccountNumber = (s: string) => {
const digits = s.replace(/[\s-]/g, "");
return /^\d{16}$/.test(digits) ? digits : null;
};
export const normalizePassword = (s: string) => s.trim().toUpperCase();
const enc = (s: string) => new TextEncoder().encode(s);
const hex = (bytes: ArrayBuffer | Uint8Array) =>
[...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
const b64 = (bytes: Uint8Array) => {
let s = "";
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(s);
};
const unb64 = (s: string) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
const sha256Hex = async (s: string) => hex(await crypto.subtle.digest("SHA-256", enc(s)));
interface Keys {
id: string;
key: CryptoKey;
auth: string;
}
const keyCache = new Map<string, Promise<Keys>>();
function deriveKeys(number: string, password = ""): Promise<Keys> {
const cacheKey = `${number}\n${password}`;
let keys = keyCache.get(cacheKey);
if (!keys) {
keys = (async () => {
const base = await crypto.subtle.importKey("raw", enc(cacheKey), "PBKDF2", false, ["deriveBits"]);
const bits = new Uint8Array(
await crypto.subtle.deriveBits(
{ name: "PBKDF2", salt: enc(`webspeak3-sync:${number}`), iterations: 310_000, hash: "SHA-256" },
base,
512
)
);
return {
// The id depends on the number only, so a new device can ask whether a password is needed.
id: await sha256Hex(`webspeak3-sync-id:${number}`),
key: await crypto.subtle.importKey("raw", bits.slice(0, 32), "AES-GCM", false, ["encrypt", "decrypt"]),
auth: hex(bits.slice(32)),
};
})();
keyCache.set(cacheKey, keys);
}
return keys;
}
interface Payload {
v: 1;
categories: SyncCategory[];
items: Record<string, string>;
}
/** Padded to a power of two (min 4 KB) so the blob size says little about its content. */
async function encrypt(key: CryptoKey, payload: Payload): Promise<string> {
const json = enc(JSON.stringify(payload));
let size = 4096;
while (size < json.length) size *= 2;
const plain = new Uint8Array(size).fill(0x20); // trailing spaces: JSON.parse ignores them
plain.set(json);
const iv = crypto.getRandomValues(new Uint8Array(12));
const data = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plain));
const out = new Uint8Array(12 + data.length);
out.set(iv);
out.set(data, 12);
return b64(out);
}
async function decrypt(key: CryptoKey, data: string): Promise<Payload> {
const bytes = unb64(data);
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.subarray(0, 12) }, key, bytes.subarray(12));
return JSON.parse(new TextDecoder().decode(plain)) as Payload;
}
// --- local snapshot -------------------------------------------------------------
/** Goes through length/key(i), which the vault's stand-in Storage also answers for secrets. */
function snapshot(categories: SyncCategory[]): Record<string, string> {
const items: Record<string, string> = {};
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (!k) continue;
const c = categoryOf(k);
if (c && categories.includes(c)) items[k] = localStorage.getItem(k) ?? "";
}
return items;
}
const hashItems = (items: Record<string, string>) =>
sha256Hex(JSON.stringify(Object.keys(items).sort().map((k) => [k, items[k]])));
/** Remote replaces local for every category both sides sync; keys gone remotely go locally too. */
function applyPayload(payload: Payload, categories: SyncCategory[]) {
const shared = categories.filter((c) => payload.categories.includes(c));
for (const k of Object.keys(snapshot(shared))) if (!(k in payload.items)) localStorage.removeItem(k);
for (const [k, v] of Object.entries(payload.items)) {
const c = categoryOf(k);
if (c && shared.includes(c)) localStorage.setItem(k, v);
}
}
// --- server calls ---------------------------------------------------------------
const ERROR_CODES = new Set(["password_required", "unreachable", "not_found", "rate_limited", "full", "pow_required", "conflict", "payload_too_large"]);
/** Locale key for an error thrown by the functions below. */
export const syncErrorKey = (err: unknown) => {
const code = err instanceof Error ? err.message : String(err);
return ERROR_CODES.has(code) ? `sync.error.${code}` : "sync.error.generic";
};
async function call(server: string, path: string, init: RequestInit = {}, auth?: string) {
let res: Response;
try {
res = await fetch(`${server.replace(/\/$/, "")}${path}`, {
...init,
headers: {
...(init.body ? { "Content-Type": "application/json" } : {}),
...(auth ? { Authorization: `Bearer ${auth}` } : {}),
},
});
} catch {
throw new Error("unreachable");
}
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (!res.ok) throw new Error(String(body.error ?? res.status));
return body;
}
export async function accountInfo(number: string, server: string): Promise<{ exists: boolean; hasPassword?: boolean }> {
const { id } = await deriveKeys(number);
return (await call(server, `/${id}/meta`)) as { exists: boolean; hasPassword?: boolean };
}
/** Same check as gateway/src/sync.ts: leading zero bits of sha256(challenge:nonce).
* Batched, because one awaited digest at a time is dominated by the await. */
async function solvePow(challenge: string, bits: number): Promise<string> {
const zeroBits = (hash: Uint8Array) => {
let zeros = 0;
for (const b of hash) {
if (b !== 0) return zeros + Math.clz32(b) - 24;
zeros += 8;
}
return zeros;
};
for (let start = 0; ; start += 256) {
const hashes = await Promise.all(
Array.from({ length: 256 }, (_, i) => crypto.subtle.digest("SHA-256", enc(`${challenge}:${start + i}`)))
);
const hit = hashes.findIndex((h) => zeroBits(new Uint8Array(h)) >= bits);
if (hit >= 0) return String(start + hit);
}
}
async function push(account: SyncAccount, items: Record<string, string>, extra: Record<string, unknown> = {}) {
const k = await deriveKeys(account.number, account.password);
const data = await encrypt(k.key, { v: 1, categories: account.categories, items });
return (await call(
account.server,
`/${k.id}`,
{ method: "PUT", body: JSON.stringify({ version: account.version, data, hasPassword: !!account.password, ...extra }) },
k.auth
)) as { version: number };
}
async function pull(account: Pick<SyncAccount, "number" | "password" | "server">) {
const k = await deriveKeys(account.number, account.password);
const body = (await call(account.server, `/${k.id}`, {}, k.auth)) as { version: number; data: string };
return { version: body.version, payload: await decrypt(k.key, body.data) };
}
// --- what the Konto panel and main.tsx use ------------------------------------
export async function createSyncAccount(withPassword: boolean, server: string, categories: SyncCategory[]) {
const account: SyncAccount = {
number: generateAccountNumber(),
password: withPassword ? generatePassword() : undefined,
server,
categories,
version: 0,
syncedHash: "",
};
const { challenge, bits } = (await call(server, "/challenge", { method: "POST" })) as { challenge: string; bits: number };
const nonce = await solvePow(challenge, bits);
const items = snapshot(categories);
const { version } = await push(account, items, { pow: { challenge, nonce } });
saveSyncAccount({ ...account, version, syncedHash: await hashItems(items), lastSync: Date.now() });
setStatus({ state: "idle", lastSync: Date.now() });
}
/** Logs this device into an existing account: the account's data replaces the local one. Reload afterwards. */
export async function loginSyncAccount(number: string, password: string | undefined, server: string, categories: SyncCategory[]) {
const { version, payload } = await pull({ number, password, server });
applyPayload(payload, categories);
saveSyncAccount({
number,
password,
server,
categories,
version,
syncedHash: await hashItems(snapshot(categories)),
lastSync: Date.now(),
});
}
/** Startup pull (main.tsx). Returns "conflict" when both sides changed. Past
* `deadline` App is already running on the local data, so nothing is applied. */
export async function pullAtStartup(deadline: number): Promise<"ok" | "conflict"> {
const account = loadSyncAccount();
if (!account) return "ok";
setStatus({ state: "syncing", lastSync: account.lastSync });
try {
const { version, payload } = await pull(account);
if (version === account.version || Date.now() > deadline) {
setStatus({ state: "idle", lastSync: account.lastSync });
return "ok";
}
if ((await hashItems(snapshot(account.categories))) !== account.syncedHash) {
setStatus({ state: "conflict", lastSync: account.lastSync });
return "conflict";
}
applyPayload(payload, account.categories);
const lastSync = Date.now();
saveSyncAccount({ ...account, version, syncedHash: await hashItems(snapshot(account.categories)), lastSync });
setStatus({ state: "idle", lastSync });
return "ok";
} catch (err) {
setStatus({ state: "error", error: (err as Error).message, lastSync: account.lastSync });
return "ok";
}
}
/** "server": take the account's data (reload afterwards). "local": overwrite it with this device's. */
export async function resolveConflict(take: "server" | "local") {
const account = loadSyncAccount();
if (!account) return;
const { version, payload } = await pull(account);
if (take === "server") {
applyPayload(payload, account.categories);
saveSyncAccount({ ...account, version, syncedHash: await hashItems(snapshot(account.categories)), lastSync: Date.now() });
return;
}
saveSyncAccount({ ...account, version, syncedHash: "" });
setStatus({ state: "idle", lastSync: account.lastSync });
await syncNow();
}
let pushing = false;
/** Pushes when a synced key changed since the last sync. */
export async function syncNow() {
const account = loadSyncAccount();
if (!account || pushing || status.state === "conflict") return;
const items = snapshot(account.categories);
const hash = await hashItems(items);
if (hash === account.syncedHash) return;
pushing = true;
setStatus({ state: "syncing", lastSync: account.lastSync });
try {
const { version } = await push(account, items);
const lastSync = Date.now();
saveSyncAccount({ ...account, version, syncedHash: hash, lastSync });
setStatus({ state: "idle", lastSync });
} catch (err) {
const code = (err as Error).message;
setStatus({ state: code === "conflict" ? "conflict" : "error", error: code, lastSync: account.lastSync });
} finally {
pushing = false;
}
}
let timer: number | undefined;
export function startAutoSync() {
if (timer !== undefined) return;
if (loadSyncAccount() && status.state === "off") setStatus({ state: "idle", lastSync: loadSyncAccount()?.lastSync });
timer = window.setInterval(() => void syncNow(), 15_000);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") void syncNow();
});
}
export async function setSyncCategories(categories: SyncCategory[]) {
const account = loadSyncAccount();
if (!account) return;
// syncedHash no longer matches the new selection, so the next tick pushes it.
saveSyncAccount({ ...account, categories, syncedHash: "" });
await syncNow();
}
/** Adds (random) or removes the password. Re-encrypts under the new key on the server. */
export async function changeSyncPassword(withPassword: boolean) {
const account = loadSyncAccount();
if (!account) return;
const next: SyncAccount = { ...account, password: withPassword ? generatePassword() : undefined };
const newKeys = await deriveKeys(next.number, next.password);
const items = snapshot(account.categories);
// Encrypted with the new key, authorized with the old one, handing over the new auth.
const k = await deriveKeys(account.number, account.password);
const data = await encrypt(newKeys.key, { v: 1, categories: account.categories, items });
const { version } = (await call(
account.server,
`/${k.id}`,
{ method: "PUT", body: JSON.stringify({ version: account.version, data, hasPassword: withPassword, newAuth: newKeys.auth }) },
k.auth
)) as { version: number };
saveSyncAccount({ ...next, version, syncedHash: await hashItems(items), lastSync: Date.now() });
setStatus({ state: "idle", lastSync: Date.now() });
}
/** Unlinks this device only; the account and its data stay on the server. */
export function logoutSyncAccount() {
saveSyncAccount(null);
setStatus({ state: "off" });
}
export async function deleteSyncAccount() {
const account = loadSyncAccount();
if (!account) return;
const k = await deriveKeys(account.number, account.password);
await call(account.server, `/${k.id}`, { method: "DELETE" }, k.auth);
logoutSyncAccount();
}
/** Link for the QR code: the fragment never reaches any server. */
export function syncLink(account: SyncAccount): string {
const params = new URLSearchParams({ sync: account.number });
if (account.password) params.set("syncpw", account.password);
if (account.server !== DEFAULT_SYNC_SERVER) params.set("syncserver", account.server);
return `${location.origin}${location.pathname}#${params}`;
}
/** Reads (and strips from the address bar) a link made by syncLink(). */
export function takeSyncLink(): { number: string; password?: string; server: string } | null {
const params = new URLSearchParams(location.hash.slice(1));
const number = normalizeAccountNumber(params.get("sync") ?? "");
if (!number) return null;
const password = params.get("syncpw") ?? undefined;
const server = params.get("syncserver") ?? DEFAULT_SYNC_SERVER;
for (const k of ["sync", "syncpw", "syncserver"]) params.delete(k);
history.replaceState(null, "", location.pathname + location.search + (params.size ? `#${params}` : ""));
return { number, password, server };
}
export function recoveryText(account: SyncAccount): string {
return [
"WebSpeak3",
"",
`Account number: ${formatAccountNumber(account.number)}`,
...(account.password ? [`Password: ${account.password}`] : []),
`Server: ${account.server}`,
"",
].join("\n");
}
+1
View File
@@ -11,6 +11,7 @@ export const PROTECTED_KEYS = [
"webspeak3:favorites",
"webspeak3:channel-passwords",
"webspeak3:store-admin-token",
"webspeak3:sync-account",
];
const VAULT_KEY = "webspeak3:vault";