Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<VerifyResp>("/auth/verify", req);

// --- OPAQUE recovery setup (authenticated) ---

Expand Down
72 changes: 72 additions & 0 deletions apps/web/src/components/KeyAlert.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// 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 { 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(() => {
if (!userId) {
setShown(false);
return;
}
const refresh = () => void hasKeyAlert(userId).then(setShown);
refresh();
return onKeyAlertChanged(refresh);
}, [userId]);

if (!shown || !userId) return null;

const btn = "rounded-lg px-3 py-1.5 text-xs font-medium transition-colors";
return (
<div role="alert" className="mb-4 rounded-xl border border-danger bg-danger-subtle p-3 text-sm">
<p className="flex items-center gap-1.5 font-medium text-danger">
<WarningTriangleIcon className="h-4 w-4 shrink-0" />
Your account was set up on another device
</p>
<p className="mt-1 text-xs text-text-secondary">
Another device published new keys for your account. That happens when someone restores it
with your recovery phrase or password.
</p>
{!notMe ? (
<>
<p className="mt-1 text-xs text-text-secondary">
If it was you — a new phone or browser, or &ldquo;Log out everywhere&rdquo; on another of
your devices — tap &ldquo;That was me&rdquo;.
</p>
<div className="mt-2 flex gap-2">
<button onClick={() => void dismissKeyAlert(userId)} className={`${btn} bg-raised text-text-secondary hover:bg-border-strong`}>
That was me
</button>
<button onClick={() => setNotMe(true)} className={`${btn} border border-danger text-danger hover:bg-danger-subtle`}>
It wasn&rsquo;t me
</button>
</div>
</>
) : (
<>
<p className="mt-2 text-xs text-text-secondary">
Then someone has your recovery phrase or password. They hold your account&rsquo;s keys:
they can receive messages sent to you and message people as you, and that can&rsquo;t be
undone for this account.
</p>
<ul className="mt-1 list-disc space-y-0.5 pl-4 text-xs text-text-secondary">
<li>Warn your contacts in person or by call — not in Privex.</li>
<li>When you&rsquo;re ready, move to a new account and share its ID with them the same way.</li>
<li>If chat backup is on, turn it off in Settings → Recovery. That deletes it from our servers.</li>
</ul>
<button onClick={() => void dismissKeyAlert(userId)} className={`${btn} mt-2 bg-raised text-text-secondary hover:bg-border-strong`}>
Hide this warning
</button>
</>
)}
</div>
);
}
2 changes: 2 additions & 0 deletions apps/web/src/screens/ConversationList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -49,6 +50,7 @@ export default function ConversationList() {
</header>

<div className="mt-6">
<KeyAlert />
<FinishSetup />
<ContactList />
</div>
Expand Down
18 changes: 11 additions & 7 deletions apps/web/src/services/auth-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
* (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<api.VerifyResp> {
const chal = await api.authChallenge(bundle.userId);
const ts = Math.floor(Date.now() / 1000);
const sig = await cryptoCall<HybridSig>("sign_challenge", [
Expand All @@ -28,7 +30,7 @@ export async function authenticateBundle(bundle: IdentityBundle): Promise<string
sig_dil: toHex(sig.dil),
timestamp: ts,
});
return res.session_token;
return res;
}

// Two concurrent restores (e.g. React StrictMode double-invoking the boot effect
Expand All @@ -55,9 +57,10 @@ async function doRestore(): Promise<boolean> {
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;
Expand Down Expand Up @@ -133,15 +136,16 @@ async function doReauth(): Promise<boolean> {
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
// session or clobber a different account, so drop it unless the session is
// 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.
Expand Down
16 changes: 15 additions & 1 deletion apps/web/src/services/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
};
}

Expand Down Expand Up @@ -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" });
}
100 changes: 100 additions & 0 deletions apps/web/src/services/key-watch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// "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";

// Per account, so an alert or trusted key never carries over to a different
// account restored on this device.
const knownKey = (userId: string) => `known_spks:${userId}`; // hex SPK pubs: ours, or ones the user said were theirs
const alertKey = (userId: string) => `key_alert:${userId}`; // the unanswered foreign key (hex)

export interface KeyWatchDeps {
loadBundle(): Promise<IdentityBundle | undefined>;
verifyHybrid(
data: Uint8Array,
sigEd: Uint8Array,
edPub: Uint8Array,
sigDil: Uint8Array,
dilPub: Uint8Array,
): Promise<boolean>;
}

const workerDeps: KeyWatchDeps = {
loadBundle: () => loadBundle(),
verifyHybrid: (...a) => cryptoCall<boolean>("verify_hybrid", a),
};

async function knownKeys(userId: string): Promise<Set<string>> {
return new Set((await db.settings.get(knownKey(userId)))?.value as string[] | undefined);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/** 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<void> {
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(me.userId);
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: knownKey(me.userId), 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(alertKey(me.userId)))?.value === spk) return;
await db.settings.put({ key: alertKey(me.userId), value: spk });
emitKeyAlertChanged();
} catch {
// Malformed reply / storage hiccup: the next reply checks again.
}
}

export async function hasKeyAlert(userId: string): Promise<boolean> {
return typeof (await db.settings.get(alertKey(userId)))?.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(userId: string): Promise<void> {
const spk = (await db.settings.get(alertKey(userId)))?.value;
if (typeof spk === "string") {
const known = await knownKeys(userId);
known.add(spk);
await db.settings.put({ key: knownKey(userId), value: [...known] });
}
await db.settings.delete(alertKey(userId));
emitKeyAlertChanged();
}
6 changes: 4 additions & 2 deletions apps/web/src/services/recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 };
Expand Down
30 changes: 17 additions & 13 deletions apps/web/src/services/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
const bundle = await loadBundle();
Expand All @@ -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);
}
Expand Down
Loading
Loading