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
5 changes: 1 addition & 4 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export const opaqueLoginComplete = (loginId: string, finalizationHex: string) =>
credential_finalization: finalizationHex,
});

// --- recovery shares + key management + logout (authenticated) ---
// --- recovery shares + key management (authenticated) ---

export const storeShares = (
shares: { share_index: number; encrypted_share: string }[],
Expand Down Expand Up @@ -269,9 +269,6 @@ export const spkRotate = (
token: string,
) => post<{ rotated: boolean }>("/keys/spk/rotate", body, token);

export const logoutAll = (token: string) =>
post<{ revoked: boolean }>("/auth/logout_all", {}, token);

// --- encrypted history backup (Option A; authenticated, opt-in) ---
// Blobs are AES-GCM ciphertext under the client's history_key - the server can't
// read them. Scoped to the authenticated user.
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/components/KeyAlert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ export default function KeyAlert() {
{!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;.
If it was you — setting up a new phone or browser, or your other device updating its
keys — 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`}>
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/crypto/keystore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export async function hasMasterKey(): Promise<boolean> {
return (await get<CryptoKey>(MASTER_KEY_ID)) !== undefined;
}

/** Wipe ALL key material (logout): no-lock handle, lock meta, in-memory key. */
/** Wipe ALL key material ("Erase this device"): no-lock handle, lock meta, in-memory key. */
export async function clearMasterKey(): Promise<void> {
memKey = null;
memKeyBytes = null;
Expand Down
46 changes: 9 additions & 37 deletions apps/web/src/screens/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import {
setDeviceSyncEnabled,
type LinkedDeviceInfo,
} from "../services/device-sync";
import { eraseThisDevice as eraseThisDeviceSvc, logoutEverywhere as logoutEverywhereSvc } from "../services/session";
import { eraseThisDevice as eraseThisDeviceSvc } from "../services/session";
import ThemeToggle from "../components/ThemeToggle";
import BlockedContacts from "../components/BlockedContacts";
import SeedSave from "../components/SeedSave";
Expand Down Expand Up @@ -228,7 +228,7 @@ function AccountSecurityTab({ pxId }: { pxId: string }) {
<AppLockToggle />
</Row>
<Row>
<ActiveSessions />
<YourDevices />
</Row>
<Row>
<EraseDevice />
Expand Down Expand Up @@ -1399,45 +1399,17 @@ function EraseDevice() {
);
}

function ActiveSessions() {
const token = useAuth((s) => s.sessionToken);
const [busy, setBusy] = useState(false);

async function logoutEverywhere() {
if (!token) return;
if (
!window.confirm(
"Log out of ALL devices? Every session token is revoked and your signed prekey is " +
"rotated (forward secrecy). You'll sign back in on this device.",
)
)
return;
setBusy(true);
try {
await logoutEverywhereSvc(); // rotate SPK + revoke all tokens
// Drop the (now-revoked) token; reload re-authenticates this device from the
// stored keys with a fresh post-cutoff token.
location.reload();
} catch {
setBusy(false);
}
}

/** Why there's no "log out everywhere" (services/session.ts), and what to do instead. */
function YourDevices() {
return (
<div>
<div className="text-sm text-text-secondary">Active sessions</div>
<div className="text-sm text-text-secondary">Your devices</div>
<p className="text-xs text-text-muted">
Tokens live in memory only and can&rsquo;t be listed. &ldquo;Log out everywhere&rdquo;
revokes every device&rsquo;s token and rotates your signed prekey. It does NOT erase
this device&rsquo;s data &mdash; use &ldquo;Erase this device&rdquo; below for that.
Privex has no sign-in to end: each device holds your account&rsquo;s keys and signs itself
in with them, and our servers keep no list of your devices. To take Privex off a device,
use &ldquo;Erase this device&rdquo; on it. If a device is lost, App Lock keeps what&rsquo;s
on it locked; if App Lock wasn&rsquo;t on, move to a new account and tell your contacts.
</p>
<button
onClick={() => void logoutEverywhere()}
disabled={busy}
className="mt-2 rounded-lg bg-danger-bg hover:bg-danger-hover disabled:opacity-40 px-3 py-1.5 text-sm font-medium"
>
{busy ? "Logging out…" : "Log out everywhere"}
</button>
</div>
);
}
3 changes: 1 addition & 2 deletions apps/web/src/services/prekeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
// - The server's one-time supply is topped up in batches when it runs low.
// - The signed prekey rotates every 30 ± 5 days. Each retired private half is
// kept for the 60-day max message TTL (+ a day), so a handshake queued against
// it still opens - however many rotations (incl. "log out everywhere") happen
// meanwhile.
// it still opens - however many rotations happen meanwhile.
// Order is always: persist the new PRIVATE keys durably, then publish - the
// server must never hand out a public key whose private half we don't hold.
//
Expand Down
111 changes: 23 additions & 88 deletions apps/web/src/services/session.ts
Original file line number Diff line number Diff line change
@@ -1,99 +1,18 @@
// Session management (docs 4.9 / 16E). "Log out everywhere" does TWO things:
// On-device session actions (docs 4.9): lock the app, erase this device.
//
// 1. Token revocation (already the working mechanism): POST /auth/logout_all sets
// a per-user cutoff so every session token issued on every device dies at once
// (auth/extract.rs rejects issued_at < cutoff). This is what actually logs
// other devices out.
//
// 2. Signed-prekey rotation (added here): rotate the SPK so a future PQXDH init
// can't target the OLD signed prekey - forward secrecy against a lost/seized
// or other device that still holds the old SPK private key. This is scoped to
// the explicit "log out everywhere" action; routine, replenish-driven SPK
// rotation stays DECOUPLED from session life (docs/KNOWN_LIMITATIONS).
//
// NOTE (deliberate): we do NOT tie token validity to an spk_version (the build
// guide's Option C). That would log every device out on routine ~monthly rotation.
// The cutoff already invalidates tokens; SPK rotation here is orthogonal forward
// secrecy layered on top.
import * as api from "../api/client";
// There is deliberately no "log out everywhere". Each device holds the account's
// keys and signs itself in with them - there's no password - so no server action
// could remove a device that holds them without the server keeping a list of your
// devices, which Privex doesn't. A server-side token cutoff only looked like it did
// (every device signed straight back in), stored when you pressed it, and left
// connected devices untouched. See docs/private/KNOWN_LIMITATIONS.md.
import { db } from "../db";
import { useAuth } from "../store/auth";
import { cryptoCall } from "../workers/crypto-client";
import { lockNow, wipeKeystore } from "../crypto/keystore";
import { loadBundle, finalizeIdentity } from "../onboarding/store";
import { nextSpkRotation, retainSpks } from "./prekeys";
import { toHex, type SignedSpk } from "../crypto/onboarding-crypto";
import { disconnectWebSocket } from "./websocket";
import { stopCoverTraffic } from "./cover-traffic";
import { resetMessaging } from "./messaging";

export interface SessionCryptoApi {
generateSignedSpk(edPriv: Uint8Array, dilPriv: Uint8Array): Promise<SignedSpk>;
}

export const workerSessionCrypto: SessionCryptoApi = {
generateSignedSpk: (ed, dil) => cryptoCall("generate_signed_spk", [ed, dil]),
};

/** 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 saved below, so it can keep answering
* inbound PQXDH sessions. */
export async function logoutEverywhere(crypto: SessionCryptoApi = workerSessionCrypto): Promise<void> {
const bundle = await loadBundle();
const token = useAuth.getState().sessionToken;
if (!bundle || !token) throw new Error("not authenticated");

const spk = await crypto.generateSignedSpk(
bundle.identity.ed25519_priv,
bundle.identity.dilithium3_priv,
);

// 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 = 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);
}

/**
* "Erase this device": a full LOCAL reset - delete every message, contact,
* session, AND the identity key material, then sign out to a clean onboarding.
*
* IRREVERSIBLE: without a recovery phrase / OPAQUE password / server backup, the
* account is gone. This is DESTRUCTIVE by design.
*
* SAFETY CONTRACT (do not violate): this runs ONLY from the explicit, confirmed
* Settings action. It is NEVER wired to a 401, a boot/restore failure, a slow
* load, or any transient/network condition - the correct response to those is to
* RE-AUTHENTICATE from the local identity (auth-session.ts), never to delete data.
* So a latency spike or an ambiguous auth error can never nuke local data.
*
* Does NOT contact the server (nothing to tell it - the data was only ever local).
* The caller reloads afterwards so all in-memory module caches are dropped too.
*/
/**
* Lock the app: drop the in-memory data key AND fully tear down the live session,
* so a locked device is INERT - no WebSocket, no cover traffic, no session token,
Expand All @@ -117,6 +36,22 @@ export function lockApp(): void {
useAuth.getState().signOut(); // drop the session token + authenticated flag
}

/**
* "Erase this device": a full LOCAL reset - delete every message, contact,
* session, AND the identity key material, then sign out to a clean onboarding.
*
* IRREVERSIBLE: without a recovery phrase / OPAQUE password / server backup, the
* account is gone. This is DESTRUCTIVE by design.
*
* SAFETY CONTRACT (do not violate): this runs ONLY from the explicit, confirmed
* Settings action. It is NEVER wired to a 401, a boot/restore failure, a slow
* load, or any transient/network condition - the correct response to those is to
* RE-AUTHENTICATE from the local identity (auth-session.ts), never to delete data.
* So a latency spike or an ambiguous auth error can never nuke local data.
*
* Does NOT contact the server (nothing to tell it - the data was only ever local).
* The caller reloads afterwards so all in-memory module caches are dropped too.
*/
export async function eraseThisDevice(): Promise<void> {
// 1. Stop anything that could re-write IndexedDB mid-wipe.
stopCoverTraffic();
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/test/prekeys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,8 @@ describe("signed prekey rotation", () => {

// Not due yet → nothing happens.
expect(await rotateSpkIfDue(me, prekeyCrypto, "tok", t0 + DAY)).toBe(false);
// Two more rotations in quick succession (as "log out everywhere" can cause):
// every retired key is still inside its window, so all are kept.
// Two more rotations in quick succession: every retired key is still inside
// its window, so all are kept.
me.spkRotateAfter = undefined;
await rotateSpkIfDue(me, prekeyCrypto, "tok", t0 + 10);
me.spkRotateAfter = undefined;
Expand Down
Loading
Loading