From 4b4a9b8a889d8f62e6a5aa66c7cb8465af21f3b1 Mon Sep 17 00:00:00 2001
From: sonix aka privex
Date: Sun, 27 Sep 2026 12:17:31 +0530
Subject: [PATCH 1/2] feat: warn when the account is set up on another device
Every recovery publishes a new signed prekey for the account. The sign-in and
WS-ticket replies now carry the account's current signed prekey with its two
signatures (`account_spk`), and the device warns ("Your account was set up on
another device") when that key is signed by the account's identity but is one
it never made. This is the docs 8.2 self-check, done without any new request.
Zero-knowledge properties:
- nothing new is stored server-side, and nothing about the check or the user's
answer is sent back; the field is the public data the key directory already
serves, in every such reply, at a fixed size
- a server can't fake an alert: the key must carry this identity's hybrid
signature, and replays of old keys are caught by a local list of every key the
device has held (public keys only, kept on the device)
- it can hide a real change - documented, like the other limits
The check runs on every WS connect, at boot, and at the daily token renewal,
never mid-recovery (the server still has the old key then). "That was me"
trusts that key; a different new one warns again.
Also: "Log out everywhere" now saves its new key before publishing it, like a
routine rotation, so the server never holds a signed prekey this device lacks
(it couldn't answer handshakes to it, and the check would flag it).
Co-Authored-By: Claude Opus 5.5
---
apps/web/src/api/client.ts | 18 ++++-
apps/web/src/components/KeyAlert.tsx | 66 +++++++++++++++
apps/web/src/screens/ConversationList.tsx | 2 +
apps/web/src/services/auth-session.ts | 18 +++--
apps/web/src/services/events.ts | 16 +++-
apps/web/src/services/key-watch.ts | 98 +++++++++++++++++++++++
apps/web/src/services/recovery.ts | 6 +-
apps/web/src/services/session.ts | 30 ++++---
apps/web/src/services/websocket.ts | 5 +-
apps/web/src/test/key-watch.test.ts | 87 ++++++++++++++++++++
apps/web/src/test/session.test.ts | 15 +++-
docs/API_REFERENCE.md | 5 +-
server/src/routes/auth.rs | 31 +++++++
server/tests/integration.rs | 26 +++++-
14 files changed, 390 insertions(+), 33 deletions(-)
create mode 100644 apps/web/src/components/KeyAlert.tsx
create mode 100644 apps/web/src/services/key-watch.ts
create mode 100644 apps/web/src/test/key-watch.test.ts
diff --git a/apps/web/src/api/client.ts b/apps/web/src/api/client.ts
index 12b07ee..aedbeef 100644
--- a/apps/web/src/api/client.ts
+++ b/apps/web/src/api/client.ts
@@ -132,7 +132,7 @@ export const replenishPrekeys = (opks: OpkUpload[], token: string, replace = fal
// --- messaging + WS ticket (authenticated) ---
export const wsTicket = (token: string) =>
- post<{ ticket: string; expires_at: number }>("/auth/ws_ticket", {}, token);
+ post<{ ticket: string; expires_at: number; account_spk?: AccountSpk }>("/auth/ws_ticket", {}, token);
/** Server default queue TTL (docs 4.12). Sent explicitly on EVERY send so the
* presence of a custom ttl_seconds never distinguishes a real message from
@@ -186,8 +186,20 @@ export interface VerifyReq {
sig_dil: string; // hex
timestamp: number;
}
-export const authVerify = (req: VerifyReq) =>
- post<{ session_token: string; expires_at: number }>("/auth/verify", req);
+/** The account's current signed prekey (hex), in sign-in and WS-ticket replies -
+ * how this device notices another device publishing keys for the account
+ * (services/key-watch.ts). Absent from servers that predate it. */
+export interface AccountSpk {
+ spk_x25519: string;
+ spk_sig_ed: string;
+ spk_sig_dil: string;
+}
+export interface VerifyResp {
+ session_token: string;
+ expires_at: number;
+ account_spk?: AccountSpk;
+}
+export const authVerify = (req: VerifyReq) => post("/auth/verify", req);
// --- OPAQUE recovery setup (authenticated) ---
diff --git a/apps/web/src/components/KeyAlert.tsx b/apps/web/src/components/KeyAlert.tsx
new file mode 100644
index 0000000..bc0ea13
--- /dev/null
+++ b/apps/web/src/components/KeyAlert.tsx
@@ -0,0 +1,66 @@
+// Home-screen warning raised by services/key-watch.ts: another device published
+// keys for this account. Shown on this device only, until answered; nothing about
+// it (or the answer) is ever sent anywhere.
+import { useEffect, useState } from "react";
+import { dismissKeyAlert, hasKeyAlert } from "../services/key-watch";
+import { onKeyAlertChanged } from "../services/events";
+import { WarningTriangleIcon } from "./icons";
+
+export default function KeyAlert() {
+ const [shown, setShown] = useState(false);
+ const [notMe, setNotMe] = useState(false);
+
+ useEffect(() => {
+ const refresh = () => void hasKeyAlert().then(setShown);
+ refresh();
+ return onKeyAlertChanged(refresh);
+ }, []);
+
+ if (!shown) return null;
+
+ const btn = "rounded-lg px-3 py-1.5 text-xs font-medium transition-colors";
+ return (
+
+
+
+ Your account was set up on another device
+
+
+ Another device published new keys for your account. That happens when someone restores it
+ with your recovery phrase or password.
+
+ {!notMe ? (
+ <>
+
+ If it was you — a new phone or browser, or “Log out everywhere” on another of
+ your devices — tap “That was me”.
+
+
+
+
+
+ >
+ ) : (
+ <>
+
+ Then someone has your recovery phrase or password. They hold your account’s keys:
+ they can receive messages sent to you and message people as you, and that can’t be
+ undone for this account.
+
+
+
Warn your contacts in person or by call — not in Privex.
+
When you’re ready, move to a new account and share its ID with them the same way.
+
If chat backup is on, turn it off in Settings → Recovery. That deletes it from our servers.
+
+
+ >
+ )}
+
+ );
+}
diff --git a/apps/web/src/screens/ConversationList.tsx b/apps/web/src/screens/ConversationList.tsx
index f9d0184..a990570 100644
--- a/apps/web/src/screens/ConversationList.tsx
+++ b/apps/web/src/screens/ConversationList.tsx
@@ -6,6 +6,7 @@ import { useNavigate } from "react-router-dom";
import ContactList from "../components/ContactList";
import ConnectionStatus from "../components/ConnectionStatus";
import FinishSetup from "../components/FinishSetup";
+import KeyAlert from "../components/KeyAlert";
export default function ConversationList() {
const nav = useNavigate();
@@ -49,6 +50,7 @@ export default function ConversationList() {
+
diff --git a/apps/web/src/services/auth-session.ts b/apps/web/src/services/auth-session.ts
index 0ef0c8b..c36c3cd 100644
--- a/apps/web/src/services/auth-session.ts
+++ b/apps/web/src/services/auth-session.ts
@@ -8,10 +8,12 @@ import { cryptoCall } from "../workers/crypto-client";
import { useAuth } from "../store/auth";
import { loadBundle, loadProgress } from "../onboarding/store";
import { fromHex, toHex, type HybridSig, type IdentityBundle } from "../crypto/onboarding-crypto";
+import { checkAccountKeys } from "./key-watch";
/** Sign a fresh auth challenge with the identity's keys → a 24h session token
- * (docs 4.9). Used by boot-restore and by seed-phrase recovery. */
-export async function authenticateBundle(bundle: IdentityBundle): Promise {
+ * (docs 4.9), plus the account's current signed prekey. Used by boot-restore,
+ * renewal and seed-phrase recovery. */
+export async function authenticateBundle(bundle: IdentityBundle): Promise {
const chal = await api.authChallenge(bundle.userId);
const ts = Math.floor(Date.now() / 1000);
const sig = await cryptoCall("sign_challenge", [
@@ -28,7 +30,7 @@ export async function authenticateBundle(bundle: IdentityBundle): Promise {
const bundle = await loadBundle();
if (!bundle) return false;
- const token = await authenticateBundle(bundle);
- useAuth.getState().setSession(token, bundle.userId);
+ const res = await authenticateBundle(bundle);
+ useAuth.getState().setSession(res.session_token, bundle.userId);
useAuth.getState().setAuthenticated(bundle.userId);
+ void checkAccountKeys(res.account_spk);
// Renewal is started by App's boot==="ready" effect (startTokenRenewal), so it
// stops correctly on lock/sign-out - don't schedule a detached timer here.
return true;
@@ -133,7 +136,7 @@ async function doReauth(): Promise {
try {
const bundle = await loadBundle();
if (!bundle) return false;
- const token = await authenticateBundle(bundle);
+ const res = await authenticateBundle(bundle);
// Guard a stale result: the session can be torn down (lock / sign-out /
// erase all clear `authenticated`) or switched to another identity while the
// auth round trip is in flight. Applying `token` then would revive a dead
@@ -141,7 +144,8 @@ async function doReauth(): Promise {
// still authenticated AND still this identity.
const s = useAuth.getState();
if (!s.authenticated || s.userId !== bundle.userId) return false;
- useAuth.getState().setSession(token, bundle.userId);
+ useAuth.getState().setSession(res.session_token, bundle.userId);
+ void checkAccountKeys(res.account_spk); // the daily renewal re-checks
return true;
} catch {
// Server unreachable / transient - the caller (or the renewal backoff) retries.
diff --git a/apps/web/src/services/events.ts b/apps/web/src/services/events.ts
index d630e85..135f06f 100644
--- a/apps/web/src/services/events.ts
+++ b/apps/web/src/services/events.ts
@@ -16,11 +16,13 @@ export interface MessageEvent {
type WireEvent =
| { kind: "message"; peerId: string }
| { kind: "contacts" }
- | { kind: "outbox" };
+ | { kind: "outbox" }
+ | { kind: "keyAlert" };
const listeners = new Set<(e: MessageEvent) => void>();
const contactListeners = new Set<() => void>();
const outboxListeners = new Set<() => void>();
+const keyAlertListeners = new Set<() => void>();
const channel: BroadcastChannel | null =
typeof BroadcastChannel !== "undefined" ? new BroadcastChannel("privex-ui-events") : null;
@@ -31,6 +33,7 @@ if (channel) {
if (w.kind === "message") for (const fn of listeners) fn({ peerId: w.peerId });
else if (w.kind === "contacts") for (const fn of contactListeners) fn();
else if (w.kind === "outbox") for (const fn of outboxListeners) fn();
+ else if (w.kind === "keyAlert") for (const fn of keyAlertListeners) fn();
};
}
@@ -73,3 +76,14 @@ export function emitOutboxChanged(): void {
for (const fn of outboxListeners) fn();
broadcast({ kind: "outbox" });
}
+
+// The "set up on another device" alert was raised or dismissed (key-watch.ts).
+export function onKeyAlertChanged(fn: () => void): () => void {
+ keyAlertListeners.add(fn);
+ return () => keyAlertListeners.delete(fn);
+}
+
+export function emitKeyAlertChanged(): void {
+ for (const fn of keyAlertListeners) fn();
+ broadcast({ kind: "keyAlert" });
+}
diff --git a/apps/web/src/services/key-watch.ts b/apps/web/src/services/key-watch.ts
new file mode 100644
index 0000000..4d88531
--- /dev/null
+++ b/apps/web/src/services/key-watch.ts
@@ -0,0 +1,98 @@
+// "Your account was set up on another device" (docs 8.2 self-check, without any
+// new request). Sign-in and WS-ticket replies carry the account's current signed
+// prekey. Every recovery publishes a new one, and this device saves each of its
+// own before publishing it - so a key this device never made, signed by this
+// account's identity, means another device holding the account's keys published
+// it. It all happens here: nothing is sent, and the server never learns whether
+// an alert was raised or what the user answered.
+//
+// A lying server can hide a real change (by serving our own key back) but can't
+// fake one: the key must carry this identity's hybrid signature, and a replay of
+// an old key of ours is caught by KNOWN - every key this device has held, plus
+// any the user said were theirs. Public keys only, kept on this device.
+import { db } from "../db";
+import type { AccountSpk } from "../api/client";
+import { loadBundle } from "../onboarding/store";
+import { fromHex, toHex, type IdentityBundle } from "../crypto/onboarding-crypto";
+import { cryptoCall } from "../workers/crypto-client";
+import { emitKeyAlertChanged } from "./events";
+
+const KNOWN = "known_spks"; // hex signed-prekey pubs: ours, or ones the user said were theirs
+const ALERT = "key_alert"; // the unanswered foreign key (hex)
+
+export interface KeyWatchDeps {
+ loadBundle(): Promise;
+ verifyHybrid(
+ data: Uint8Array,
+ sigEd: Uint8Array,
+ edPub: Uint8Array,
+ sigDil: Uint8Array,
+ dilPub: Uint8Array,
+ ): Promise;
+}
+
+const workerDeps: KeyWatchDeps = {
+ loadBundle: () => loadBundle(),
+ verifyHybrid: (...a) => cryptoCall("verify_hybrid", a),
+};
+
+async function knownKeys(): Promise> {
+ return new Set((await db.settings.get(KNOWN))?.value as string[] | undefined);
+}
+
+/** Check a reply's account key. Best effort: never throws, and does nothing on a
+ * reply from a server that predates the field. Call it only after this device
+ * has published its keys (not mid-recovery: the server still has the old ones). */
+export async function checkAccountKeys(
+ reply: AccountSpk | undefined,
+ deps: KeyWatchDeps = workerDeps,
+): Promise {
+ if (!reply) return;
+ try {
+ // Loaded AFTER the reply: our keys are saved before they're published, so this
+ // copy is never older than what the server could have from us.
+ const me = await deps.loadBundle();
+ if (!me) return;
+ const known = await knownKeys();
+ const mine = [me.spk, ...(me.prevSpks ?? [])].map((k) => toHex(k.pub));
+ if (mine.some((k) => !known.has(k))) {
+ mine.forEach((k) => known.add(k));
+ await db.settings.put({ key: KNOWN, value: [...known] });
+ }
+
+ const spk = reply.spk_x25519.toLowerCase();
+ if (known.has(spk)) return;
+ const signedByUs = await deps.verifyHybrid(
+ fromHex(spk),
+ fromHex(reply.spk_sig_ed),
+ me.identity.ed25519_pub,
+ fromHex(reply.spk_sig_dil),
+ me.identity.dilithium3_pub,
+ );
+ // Not signed by this account: a broken or lying server, not another device
+ // with our keys - nothing to warn about.
+ if (!signedByUs) return;
+ if ((await db.settings.get(ALERT))?.value === spk) return;
+ await db.settings.put({ key: ALERT, value: spk });
+ emitKeyAlertChanged();
+ } catch {
+ // Malformed reply / storage hiccup: the next reply checks again.
+ }
+}
+
+export async function hasKeyAlert(): Promise {
+ return typeof (await db.settings.get(ALERT))?.value === "string";
+}
+
+/** "That was me" (or read and dismissed): remember that key as the user's and
+ * clear the alert. A different new key alerts again. */
+export async function dismissKeyAlert(): Promise {
+ const spk = (await db.settings.get(ALERT))?.value;
+ if (typeof spk === "string") {
+ const known = await knownKeys();
+ known.add(spk);
+ await db.settings.put({ key: KNOWN, value: [...known] });
+ }
+ await db.settings.delete(ALERT);
+ emitKeyAlertChanged();
+}
diff --git a/apps/web/src/services/recovery.ts b/apps/web/src/services/recovery.ts
index 955f4a1..4f35205 100644
--- a/apps/web/src/services/recovery.ts
+++ b/apps/web/src/services/recovery.ts
@@ -86,7 +86,9 @@ async function completeRecovery(bundle: IdentityBundle, tokenOpt?: string): Prom
// first rotation is a full period away (unset = "rotate now" to prekey upkeep).
bundle.spkRotateAfter = nextSpkRotation(Math.floor(Date.now() / 1000));
await persistGeneratedIdentity(bundle);
- const token = tokenOpt ?? (await authenticateBundle(bundle));
+ // No key check here: the server still has the account's old signed prekey until
+ // provisionPrekeys below publishes ours.
+ const token = tokenOpt ?? (await authenticateBundle(bundle)).session_token;
useAuth.getState().setSession(token, bundle.userId);
await provisionPrekeys(bundle, token);
await finalizeIdentity(bundle);
@@ -128,7 +130,7 @@ async function requireRecoverySession(): Promise<{ bundle: IdentityBundle; token
let token = useAuth.getState().sessionToken;
if (!token) {
- token = await authenticateBundle(bundle);
+ token = (await authenticateBundle(bundle)).session_token;
useAuth.getState().setSession(token, bundle.userId);
}
return { bundle, token };
diff --git a/apps/web/src/services/session.ts b/apps/web/src/services/session.ts
index 45721b1..e0bbdcb 100644
--- a/apps/web/src/services/session.ts
+++ b/apps/web/src/services/session.ts
@@ -38,7 +38,7 @@ export const workerSessionCrypto: SessionCryptoApi = {
/** Log out of ALL devices: rotate the SPK (forward secrecy) then revoke every
* token. Order matters: spk_rotate needs the still-valid token, and logout_all
* revokes it. On reload this device re-authenticates (identity key unchanged) and
- * already holds the new SPK private key persisted below, so it can keep answering
+ * already holds the new SPK private key saved below, so it can keep answering
* inbound PQXDH sessions. */
export async function logoutEverywhere(crypto: SessionCryptoApi = workerSessionCrypto): Promise {
const bundle = await loadBundle();
@@ -50,26 +50,30 @@ export async function logoutEverywhere(crypto: SessionCryptoApi = workerSessionC
bundle.identity.dilithium3_priv,
);
- // Server first: spk_rotate OVERWRITES the stored SPK (no OPK-style id collision)
- // and appends a KT entry. If this throws, nothing local changed - abort.
- await api.spkRotate(
- { spk_x25519_pub: toHex(spk.pub), spk_sig_ed: toHex(spk.sigEd), spk_sig_dil: toHex(spk.sigDil) },
- token,
- );
-
- // Persist the new SPK private key locally ONLY after the server accepted the new
- // public key (keeps device + server in sync; a future Bob answers with spk.priv).
- // The old private half is kept briefly (prekeys.ts) so a handshake already in
- // flight against it still opens; the server no longer hands it out.
+ // Save the new key BEFORE publishing it, like a routine rotation (prekeys.ts):
+ // the server must never hold a signed prekey this device lacks - it couldn't
+ // answer handshakes to it, and key-watch would take it for another device. If
+ // the publish fails, the key stays pending and prekey upkeep publishes it
+ // later; nothing is revoked. The old private half is kept briefly so a
+ // handshake already in flight against it still opens.
const now = Math.floor(Date.now() / 1000);
bundle.prevSpks = retainSpks([{ ...bundle.spk, retiredAt: now }, ...(bundle.prevSpks ?? [])], now);
bundle.spk = { pub: spk.pub, priv: spk.priv };
bundle.spkSig = { ed: spk.sigEd, dil: spk.sigDil };
bundle.spkRotateAfter = nextSpkRotation(now);
- bundle.spkPending = false;
+ bundle.spkPending = true;
await finalizeIdentity(bundle); // rewrites priv_bundle_enc; keeps opks + mnemonic + progress
resetMessaging(); // the cached identity must pick up the new signed prekey
+ // spk_rotate OVERWRITES the stored SPK and appends a KT entry.
+ await api.spkRotate(
+ { spk_x25519_pub: toHex(spk.pub), spk_sig_ed: toHex(spk.sigEd), spk_sig_dil: toHex(spk.sigDil) },
+ token,
+ );
+ bundle.spkPending = false;
+ await finalizeIdentity(bundle);
+ resetMessaging();
+
// Revoke every token across all devices (incl. this one - we re-auth on reload).
await api.logoutAll(token);
}
diff --git a/apps/web/src/services/websocket.ts b/apps/web/src/services/websocket.ts
index adcf05a..fa43aa5 100644
--- a/apps/web/src/services/websocket.ts
+++ b/apps/web/src/services/websocket.ts
@@ -4,6 +4,7 @@
// answered with pong; drops reconnect with exponential backoff (cap 300s).
import * as api from "../api/client";
import { prekeyUpkeep, pruneReceived, receiveMessage } from "./messaging";
+import { checkAccountKeys } from "./key-watch";
import { flushOutbox } from "./outbox";
const MAX_BACKOFF = 300_000;
@@ -73,7 +74,9 @@ async function open(myGen: number): Promise {
if (stopped || !token || myGen !== gen) return;
let ticket: string;
try {
- ticket = (await api.wsTicket(token)).ticket;
+ const t = await api.wsTicket(token);
+ ticket = t.ticket;
+ void checkAccountKeys(t.account_spk); // "set up on another device?" (key-watch.ts)
} catch {
return scheduleReconnect(myGen);
}
diff --git a/apps/web/src/test/key-watch.test.ts b/apps/web/src/test/key-watch.test.ts
new file mode 100644
index 0000000..f50d1c1
--- /dev/null
+++ b/apps/web/src/test/key-watch.test.ts
@@ -0,0 +1,87 @@
+// key-watch: "your account was set up on another device" from the account key in
+// sign-in / WS-ticket replies. Real wasm signatures, so "the server can't fake an
+// alert" is tested against the actual hybrid verification.
+import { readFileSync } from "node:fs";
+import { beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { initCrypto, wasm } from "../crypto/wasm";
+import { generateSignedSpk, genIdentityBundle, toHex, type IdentityBundle } from "../crypto/onboarding-crypto";
+import { db } from "../db";
+import type { AccountSpk } from "../api/client";
+import { checkAccountKeys, dismissKeyAlert, hasKeyAlert, type KeyWatchDeps } from "../services/key-watch";
+
+beforeAll(async () => {
+ const wasmUrl = new URL("../../../../packages/crypto-wasm/pkg/privex_crypto_wasm_bg.wasm", import.meta.url);
+ await initCrypto({ module_or_path: readFileSync(wasmUrl) });
+});
+beforeEach(() => db.settings.clear());
+
+const entropy = (f: number) => new Uint8Array(32).fill(f);
+const reply = (pub: Uint8Array, sigEd: Uint8Array, sigDil: Uint8Array): AccountSpk => ({
+ spk_x25519: toHex(pub),
+ spk_sig_ed: toHex(sigEd),
+ spk_sig_dil: toHex(sigDil),
+});
+const deps = (me: IdentityBundle): KeyWatchDeps => ({
+ loadBundle: async () => me,
+ verifyHybrid: async (...a) => wasm.verify_hybrid(...a),
+});
+/** A new signed prekey made with this account's identity - what another device
+ * holding the account's keys (a recovery) publishes. */
+const anotherDevicesKey = (me: IdentityBundle) => {
+ const k = generateSignedSpk(wasm, me.identity.ed25519_priv, me.identity.dilithium3_priv);
+ return reply(k.pub, k.sigEd, k.sigDil);
+};
+
+describe("account key watch", () => {
+ it("stays quiet for this device's own key", async () => {
+ const me = genIdentityBundle(wasm, entropy(0x41));
+ await checkAccountKeys(reply(me.spk.pub, me.spkSig.ed, me.spkSig.dil), deps(me));
+ await checkAccountKeys(undefined, deps(me)); // a server that predates the field
+ expect(await hasKeyAlert()).toBe(false);
+ });
+
+ it("stays quiet mid-rotation, while the server still has the key we just retired", async () => {
+ const me = genIdentityBundle(wasm, entropy(0x46));
+ const next = generateSignedSpk(wasm, me.identity.ed25519_priv, me.identity.dilithium3_priv);
+ const rotated = { ...me, spk: next, spkSig: { ed: next.sigEd, dil: next.sigDil }, prevSpks: [me.spk] };
+ // First check this device ever makes: the old key is known only as retired.
+ await checkAccountKeys(reply(me.spk.pub, me.spkSig.ed, me.spkSig.dil), deps(rotated));
+ expect(await hasKeyAlert()).toBe(false);
+ });
+
+ it("warns about a key signed by this account that this device never made", async () => {
+ const me = genIdentityBundle(wasm, entropy(0x42));
+ const theirs = anotherDevicesKey(me);
+ await checkAccountKeys(theirs, deps(me));
+ expect(await hasKeyAlert()).toBe(true);
+
+ // "That was me": cleared, and that key stays trusted...
+ await dismissKeyAlert();
+ await checkAccountKeys(theirs, deps(me));
+ expect(await hasKeyAlert()).toBe(false);
+ // ...but a different new one warns again.
+ await checkAccountKeys(anotherDevicesKey(me), deps(me));
+ expect(await hasKeyAlert()).toBe(true);
+ });
+
+ it("can't be faked by the server: keys not signed by this account never warn", async () => {
+ const me = genIdentityBundle(wasm, entropy(0x43));
+ const stranger = genIdentityBundle(wasm, entropy(0x44)); // validly signed, wrong account
+ await checkAccountKeys(reply(stranger.spk.pub, stranger.spkSig.ed, stranger.spkSig.dil), deps(me));
+ const k = generateSignedSpk(wasm, me.identity.ed25519_priv, me.identity.dilithium3_priv);
+ await checkAccountKeys(reply(k.pub, new Uint8Array(64), k.sigDil), deps(me)); // bad Ed25519 sig
+ await checkAccountKeys(reply(k.pub, k.sigEd, new Uint8Array(k.sigDil.length)), deps(me)); // bad Dilithium sig
+ await checkAccountKeys({ spk_x25519: "zz", spk_sig_ed: "", spk_sig_dil: "" }, deps(me)); // garbage
+ expect(await hasKeyAlert()).toBe(false);
+ });
+
+ it("isn't fooled by the server replaying an old key of ours this device has dropped", async () => {
+ const me = genIdentityBundle(wasm, entropy(0x45));
+ const old = reply(me.spk.pub, me.spkSig.ed, me.spkSig.dil);
+ await checkAccountKeys(old, deps(me)); // seen while it was ours
+ const next = generateSignedSpk(wasm, me.identity.ed25519_priv, me.identity.dilithium3_priv);
+ const later = { ...me, spk: next, spkSig: { ed: next.sigEd, dil: next.sigDil }, prevSpks: [] };
+ await checkAccountKeys(old, deps(later)); // past its retention window, replayed
+ expect(await hasKeyAlert()).toBe(false);
+ });
+});
diff --git a/apps/web/src/test/session.test.ts b/apps/web/src/test/session.test.ts
index 0e4b0c0..1f014fd 100644
--- a/apps/web/src/test/session.test.ts
+++ b/apps/web/src/test/session.test.ts
@@ -70,8 +70,11 @@ describe("log out everywhere (16E)", () => {
const oldSpkPriv = toHex(me.spk.priv);
const order: string[] = [];
- const rotateSpy = vi.spyOn(api, "spkRotate").mockImplementation(async () => {
+ let savedBeforePublish = false;
+ const rotateSpy = vi.spyOn(api, "spkRotate").mockImplementation(async (req) => {
order.push("rotate");
+ // The device already holds the key it's publishing (never the other way round).
+ savedBeforePublish = toHex((await loadBundle())!.spk.pub) === req.spk_x25519_pub;
return { rotated: true };
});
const logoutSpy = vi.spyOn(api, "logoutAll").mockImplementation(async () => {
@@ -87,6 +90,7 @@ describe("log out everywhere (16E)", () => {
// SPK rotated with the still-valid token BEFORE the token is revoked.
expect(order).toEqual(["rotate", "logout"]);
+ expect(savedBeforePublish).toBe(true);
const rotatedArg = rotateSpy.mock.calls[0];
expect(rotatedArg[1]).toBe("tok-1"); // authed with the pre-revocation token
@@ -104,6 +108,7 @@ describe("log out everywhere (16E)", () => {
// Identity + mnemonic preserved (same account; seed-view still works).
expect(reloaded!.userId).toBe(me.userId);
expect(reloaded!.mnemonic).toBe(me.mnemonic);
+ expect(reloaded!.spkPending).toBe(false); // published
rotateSpy.mockRestore();
logoutSpy.mockRestore();
@@ -129,8 +134,12 @@ describe("log out everywhere (16E)", () => {
).rejects.toBeInstanceOf(api.ApiError);
expect(logoutSpy).not.toHaveBeenCalled(); // token NOT revoked on rotate failure
- // Local SPK untouched (rotate happens server-first, persist only on success).
- expect(toHex((await loadBundle())!.spk.priv)).toBe(toHex(me.spk.priv));
+ // The new key was saved first and stays pending (prekey upkeep publishes it
+ // later); the old one - still the server's - is kept.
+ const after = (await loadBundle())!;
+ expect(toHex(after.spk.pub)).toBe(toHex(stub.pub));
+ expect(after.spkPending).toBe(true);
+ expect(after.prevSpks!.map((k) => toHex(k.pub))).toContain(toHex(me.spk.pub));
rotateSpy.mockRestore();
logoutSpy.mockRestore();
diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md
index 462c895..33cdf0c 100644
--- a/docs/API_REFERENCE.md
+++ b/docs/API_REFERENCE.md
@@ -9,9 +9,12 @@ Privex's API is designed around zero-knowledge principles. The server acts as a
All authenticated requests use a 24-hour session token. The token is derived from a Zero-Knowledge Signed Challenge.
- `POST /auth/challenge`: Returns a 32-byte cryptographic challenge with a 90-second TTL.
-- `POST /auth/verify`: Submits Ed25519 and CRYSTALS-Dilithium3 signatures over the challenge. Returns a 24-hour session token.
+- `POST /auth/verify`: Submits Ed25519 and CRYSTALS-Dilithium3 signatures over the challenge. Returns a 24-hour session token and the account's current signed prekey (`account_spk`, below).
+- `POST /auth/ws_ticket`: Returns a single-use, 60-second ticket for opening the WebSocket, and `account_spk`.
- `POST /auth/pow_challenge`: Returns a dynamic Proof-of-Work (PoW) challenge used for rate limiting public endpoints without requiring IP addresses.
+`account_spk` is the account's current signed prekey with its Ed25519 and Dilithium3 signatures. Every recovery publishes a new one, so the owner's device can tell, on its own, when another device has published keys for the account, and warn the user. It is the same public data the key directory serves to anyone, it is in every such reply at the same size, and nothing about the check is sent back to the server.
+
## Key Management Endpoints
Key endpoints are PoW-gated to prevent enumeration attacks and preserve privacy.
diff --git a/server/src/routes/auth.rs b/server/src/routes/auth.rs
index 6d351fa..837251d 100644
--- a/server/src/routes/auth.rs
+++ b/server/src/routes/auth.rs
@@ -149,6 +149,30 @@ pub struct VerifyReq {
pub struct VerifyResp {
session_token: String,
expires_at: i64,
+ account_spk: AccountSpk,
+}
+
+/// The account's current signed prekey, in the owner's sign-in and WS-ticket
+/// replies. Every recovery publishes a new one, so the owner's device can tell
+/// (on the device, alone) when another device published keys for its account
+/// (docs 8.2). It is the same public data the key directory already serves to
+/// anyone, it goes in EVERY such reply at the same size, and nothing about the
+/// check comes back to the server - so it adds nothing the server knows or stores.
+#[derive(Serialize)]
+pub struct AccountSpk {
+ spk_x25519: String, // hex
+ spk_sig_ed: String, // hex
+ spk_sig_dil: String, // hex
+}
+
+impl From<&crate::db::queries::key_directory::KeyBundle> for AccountSpk {
+ fn from(b: &crate::db::queries::key_directory::KeyBundle) -> Self {
+ Self {
+ spk_x25519: hex::encode(&b.spk_x25519),
+ spk_sig_ed: hex::encode(&b.spk_sig_ed),
+ spk_sig_dil: hex::encode(&b.spk_sig_dil),
+ }
+ }
}
pub async fn verify(
@@ -238,6 +262,7 @@ pub async fn verify(
Ok(Json(VerifyResp {
session_token,
expires_at: now + token::TTL_SECS,
+ account_spk: AccountSpk::from(&bundle),
}))
}
@@ -251,6 +276,7 @@ const WS_TICKET_TTL: i64 = 60;
pub struct WsTicketResp {
ticket: String,
expires_at: i64,
+ account_spk: AccountSpk,
}
pub async fn ws_ticket(
@@ -260,6 +286,10 @@ pub async fn ws_ticket(
// Bound ticket minting per user → bounds devlink rendezvous rooms a single
// account can open.
crate::routes::rate_limit(&st, "wsticket", &user_id, 60, 60).await?;
+ let bundle = crate::db::queries::key_directory::get_key(&st.db, &user_id)
+ .await
+ .map_err(|_| ApiError::internal())?
+ .ok_or_else(ApiError::unauthorized)?;
let mut raw = [0u8; 32];
getrandom::getrandom(&mut raw).map_err(|_| ApiError::internal())?;
let ticket = hex::encode(raw);
@@ -277,6 +307,7 @@ pub async fn ws_ticket(
Ok(Json(WsTicketResp {
ticket,
expires_at: now_unix() + WS_TICKET_TTL,
+ account_spk: AccountSpk::from(&bundle),
}))
}
diff --git a/server/tests/integration.rs b/server/tests/integration.rs
index 96fbdcf..f82b0a8 100644
--- a/server/tests/integration.rs
+++ b/server/tests/integration.rs
@@ -239,6 +239,11 @@ async fn register_and_auth(http: &reqwest::Client, base: &str) -> (Identity, Str
.json()
.await
.unwrap();
+ // Sign-in carries the account's current signed prekey (docs 8.2 self-check).
+ for f in ["spk_x25519", "spk_sig_ed", "spk_sig_dil"] {
+ let registered = body[if f == "spk_x25519" { "spk_x25519_pub" } else { f }].clone();
+ assert_eq!(vr["account_spk"][f], registered, "verify reply {f}");
+ }
let token = vr["session_token"].as_str().unwrap().to_string();
(id, token)
}
@@ -1355,13 +1360,15 @@ async fn server_end_to_end() {
// SPK rotate with a valid hybrid signature → appends a KT entry.
let mut new_spk = [0u8; 32];
getrandom::getrandom(&mut new_spk).unwrap();
+ let new_sig_ed = hex::encode(bob.signing.sign(&new_spk).to_bytes());
+ let new_sig_dil = hex::encode(bob.dsk.try_sign(&new_spk, &[]).unwrap());
let rot: serde_json::Value = http
.post(format!("{base}/keys/spk/rotate"))
.header("X-Privex-Auth", &bob_token)
.json(&serde_json::json!({
"spk_x25519_pub": hex::encode(new_spk),
- "spk_sig_ed": hex::encode(bob.signing.sign(&new_spk).to_bytes()),
- "spk_sig_dil": hex::encode(bob.dsk.try_sign(&new_spk, &[]).unwrap()),
+ "spk_sig_ed": new_sig_ed,
+ "spk_sig_dil": new_sig_dil,
}))
.send()
.await
@@ -1389,6 +1396,21 @@ async fn server_end_to_end() {
"rotated bundle proof must verify"
);
+ // The owner's WS-ticket reply now carries the NEW signed prekey, signatures
+ // included, so a device that didn't publish it can tell (docs 8.2).
+ let tkt: serde_json::Value = http
+ .post(format!("{base}/auth/ws_ticket"))
+ .header("X-Privex-Auth", &bob_token)
+ .send()
+ .await
+ .unwrap()
+ .json()
+ .await
+ .unwrap();
+ assert_eq!(tkt["account_spk"]["spk_x25519"].as_str().unwrap(), hex::encode(new_spk));
+ assert_eq!(tkt["account_spk"]["spk_sig_ed"].as_str().unwrap(), new_sig_ed);
+ assert_eq!(tkt["account_spk"]["spk_sig_dil"].as_str().unwrap(), new_sig_dil);
+
// SPK rotate with a bad signature → generic 400.
let bad_rot = http
.post(format!("{base}/keys/spk/rotate"))
From 28f232f3239ca98c93002e1124c13e1bacdc57d4 Mon Sep 17 00:00:00 2001
From: sonix aka privex
Date: Sun, 27 Sep 2026 12:29:18 +0530
Subject: [PATCH 2/2] fix(web): keep the key alert and trusted keys per account
The alert and the known-keys list were stored device-wide, so a different
account restored on the same device could show the previous account's warning
(and dismissing it would trust the previous account's key). Both are now keyed
by the account's px_id.
Co-Authored-By: Claude Opus 5.5
---
apps/web/src/components/KeyAlert.tsx | 16 +++++++++-----
apps/web/src/services/key-watch.ts | 32 +++++++++++++++-------------
apps/web/src/test/key-watch.test.ts | 27 ++++++++++++++++-------
3 files changed, 47 insertions(+), 28 deletions(-)
diff --git a/apps/web/src/components/KeyAlert.tsx b/apps/web/src/components/KeyAlert.tsx
index bc0ea13..346610d 100644
--- a/apps/web/src/components/KeyAlert.tsx
+++ b/apps/web/src/components/KeyAlert.tsx
@@ -4,19 +4,25 @@
import { useEffect, useState } from "react";
import { dismissKeyAlert, hasKeyAlert } from "../services/key-watch";
import { onKeyAlertChanged } from "../services/events";
+import { useAuth } from "../store/auth";
import { WarningTriangleIcon } from "./icons";
export default function KeyAlert() {
+ const userId = useAuth((s) => s.userId);
const [shown, setShown] = useState(false);
const [notMe, setNotMe] = useState(false);
useEffect(() => {
- const refresh = () => void hasKeyAlert().then(setShown);
+ if (!userId) {
+ setShown(false);
+ return;
+ }
+ const refresh = () => void hasKeyAlert(userId).then(setShown);
refresh();
return onKeyAlertChanged(refresh);
- }, []);
+ }, [userId]);
- if (!shown) return null;
+ if (!shown || !userId) return null;
const btn = "rounded-lg px-3 py-1.5 text-xs font-medium transition-colors";
return (
@@ -36,7 +42,7 @@ export default function KeyAlert() {
your devices — tap “That was me”.