Kez/kez-chat/web/src/routes/Identity.svelte
Jason Tudisco c8370ffdf0 feat(kez-chat): three days of security + UX + protocol work
A multi-day batch covering: a security review punch list (Day 1-3),
the visual-encryption profile-picture feature, a fast deploy
infrastructure, ack resilience + UX polish, several nostr ecosystem
alignment changes, and a key server-independence fix.

Security review (Day 1)
  - Envelope v2 (ephemeral x25519 per message; AAD-bound AES-GCM;
    no plaintext from/to). Big metadata-leak fix flagged by reviews.
    Forward secrecy at the per-message level; v1 decrypt kept for
    a one-week migration window.
  - Routing tag rename h → q (NIP-29 collision fix).
  - Web Push payload now empty (was leaking recipient handle to FCM).
  - Log demotion + process-instance salt-hash of handles so debug
    logs don't permanently encode the social graph.

Security review (Day 2)
  - Replay protection: SEEN_CAP 500 → 10_000 ids; reject events with
    impossibly old/future created_at; openMessage enforces ±7d/+5min
    freshness on plaintext sent_at.
  - Reveal Recovery Phrase now requires a fresh passphrase prompt.
    Verifies via the same unlockIdentity that the initial unlock
    uses. Bonus: works for biometric-only sessions (recovers the
    phrase that wasn't in memory before).
  - POST /v1/messages per-IP rate limit (60/min, capacity 60, with
    a periodic idle-bucket sweep). New rate_limit.rs module + tests.

Security review (Day 3 Option A)
  - Unforgeable acks: kind-4244 events now carry a `kez-sig` tag,
    the recipient's ed25519 signature over the acked event id.
    Sender verifies against the conversation peer's KEZ primary.
    Unsigned acks still accepted during the migration window.
  - Default `since=` lookback shortened 7d → 48h (matches relay
    retention).
  - Bounded concurrency on push fanout: tokio::sync::Semaphore(32).

Security review (Day 3 Option B — nostr ecosystem alignment)
  - NIP-65 (kind:10002): publish our relay list so other clients
    can discover where to find us.
  - NIP-42 AUTH: attachSigner / detachSigner wires the user's seed
    into the relay pool so AUTH-gated relays (damus.io DMs) deliver.
  - Minimal kind:0 baseline on first session unlock (unblocks
    writes on relays that reject unknown pubkeys).
  - Acks now include ["p", senderNostrPubkey] for NIP-25 / NIP-10
    routing convention.

Web Push end-to-end
  - Server-side nostr listener (nostr_listener.rs): the chat-server
    subscribes to relays for every registered handle's addr, so
    Web Push fires even when chat goes over nostr (the live default).
  - Push fanout from messages.rs spawned with bounded concurrency.
  - Empty payload (no recipient handle leaked to FCM).
  - Self-heal endpoint GET /v1/push/subscriptions/:handle —
    auto-re-registers a subscription if server lost it.
  - Auto-enable push on first unlock (was opt-in toggle hunt).
  - In-chat nudge banner + iOS PWA install hint.

Persistent sessions
  - persistent-session.ts: AES-GCM encrypt seed under a
    non-extractable IDB key, 30-day sliding-window TTL, restore on
    every boot.
  - Auto-fetch own kind:0 from nostr on a fresh device so the user
    sees their own avatar without re-setting it.

Profile pictures + visual encryption
  - Avatar component accepts a `picture` prop (data URL); falls
    back to the deterministic identicon when absent.
  - profile-store.ts: pick → resize to 256×256 JPEG → save locally
    + publish as NIP-01 kind:0.
  - Visual encryption (visual-crypto.ts): keyed Fisher-Yates pixel
    permutation + xoshiro256** PRNG. Output is a valid PNG with
    scrambled content. Salt embedded as a #kez-visual-v1:<hex>
    URL fragment.
  - Default ON for new pictures. Strangers see colored noise on
    public nostr; contacts see the real face.
  - Per-recipient AES wraps embedded in kind:0 content
    (kez_visual_keys map). The picture's symmetric key is wrapped
    via the same SealedEnvelope crypto our DMs use.
  - Self-wrap (sender wraps to their own primary too) so a fresh
    device of the same user can descramble its own picture.
  - Stranger-view preview thumbnail in Settings (the badge tucked
    into the avatar's bottom-right corner — "this is what the
    world sees").
  - Tap-to-zoom: header avatar in a thread opens a fullscreen
    overlay.

Peer-profile resolution
  - peer-profile-store.ts: IDB-cached one-shot kind:0 fetch +
    descramble.
  - peer-profile-cell.svelte.ts: reactive mirror for UI.
  - 6h bulk-scan staleness + force-refresh on thread open.
  - Avatar usages in Messages.svelte pass peer.picture through.

Local-echo + delivery receipts
  - Outbound messages render instantly with status="sending"; flip
    to "sent" when ≥1 relay accepts; "delivered" (check-in-circle)
    when recipient's client publishes an ack.
  - SVG status icons inside the bubble; "via X" footer on outbound.
  - Persistent pending-ack queue with retry on next session start.
  - Catch-up scan (fetchAcksForEventIds) self-heals delivered
    state on conversation open.
  - markDeliveredByEventId verifies the ack signature.

Active-relay tracking + reply preference
  - SimplePool.trackRelays = true. Capture first-to-accept on send
    via Promise.any over per-relay publish promises.
  - InboxMessage.via_relay set from pool.seenOn on receive.
  - Conversation.peer_via_relay persisted on every inbound DM.
  - sendMessage takes `preferRelay` and orders publish targets
    accordingly. Acks bias the same way.
  - "via relay.X" footer renders on outbound bubbles.

Conversation list polish
  - Per-conversation `unread_count` on the Conversation type.
  - Bumped on every genuinely-new inbound; reset on thread open.
  - Accent-color pill badge in the sidebar (rounds at "99+").

Server-independence fix
  - sendMessage skips the /v1/u/:handle lookup when the caller
    passes recipientPrimary (which Messages.svelte does, from the
    cached peer_primary on the conversation row). Chat over nostr
    no longer breaks when the chat-server is down — only brand-new
    conversations still need the directory lookup.

Relay set
  - Added wss://relay.snort.social and wss://nostr.wine to the
    default pool (was 3, now 5).

Fast-deploy infrastructure (new in this batch)
  - Dockerfile gains an `export` scratch stage (extracts binary +
    web/dist only).
  - Dockerfile.runtime: tiny runtime image that COPYs prebuilt
    artifacts — no rust/npm on the remote.
  - docker-compose.fast.yml: compose override pointing chat-server
    build at Dockerfile.runtime.
  - .dockerignore: excludes target/, node_modules/, prebuilt/,
    .buildx-cache/, .git, *.db. Critical: without this, an earlier
    bug had the buildx cache nested under the build context and
    blew up to 17GB by feeding itself into itself.
  - Old: ~10 min remote build. New: 3–5 min local + 5s remote
    runtime swap. Cache lives at ~/.cache/kez-chat-buildx
    (outside any project tree).

UI polish (margins, layout, banners)
  - Authenticated routes (Welcome / Settings / Identity / Dashboard
    / Claims / AddClaim) wrapped in max-w-2xl mx-auto px-4 py-6.
  - WhatsApp-style chat bubbles: shrink-wrap to content, asymmetric
    rounded corners, inline bottom-right timestamp.
  - Push-notification nudge banner at top of /chats with iOS
    install hint.
  - Relay state popover off the "● live (N)" indicator.

WebAuthn biometric fix
  - user.id now uses the raw 32-byte ed25519 pubkey (was the
    72-byte "ed25519:<hex>" identity string, which exceeded
    WebAuthn's 64-byte limit — Android Chrome rejected it with
    "user handle exceeds 64 bytes").

Documentation
  - kez-chat/TODO.md tracks every reviewer finding with status,
    file:line references, and a phased plan. All Day 1-3 items
    marked DONE; remaining roadmap items (Double Ratchet,
    WebAuthn-gated rehydrate, addr rotation, NIP-65 peer-relay
    fetch on send) documented for future sprints.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-08 05:11:24 -06:00

226 lines
9.0 KiB
Svelte

<script lang="ts">
import { onMount } from "svelte";
import { push } from "svelte-spa-router";
import { lookup, setProofs, ApiError } from "../lib/api.js";
import { session } from "../lib/store.svelte.js";
import VerifiedBadge from "../lib/VerifiedBadge.svelte";
import {
listClaims,
setVerifyResult,
type StoredClaim,
} from "../lib/claims-store.js";
import { verifyClaim } from "../lib/verify.js";
import Avatar from "../lib/Avatar.svelte";
let registryRecord = $state<any | null>(null);
let claims = $state<StoredClaim[]>([]);
let verifyingAll = $state(false);
let copied = $state(false);
const verified = $derived(claims.filter((c) => c.last_verify?.status === "ok"));
const failed = $derived(claims.filter((c) => c.last_verify?.status === "fail"));
const pending = $derived(claims.filter((c) => !c.last_verify));
// Verified badge requires at least this many independently-verified
// proofs. Kept in sync with VERIFY_MIN_PROOFS in Messages.svelte so the
// badge means the same thing on the profile and in chat.
const VERIFY_MIN_PROOFS = 2;
const isVerified = $derived(verified.length >= VERIFY_MIN_PROOFS);
onMount(async () => {
if (!session.unlocked) {
push("/unlock");
return;
}
claims = await listClaims();
// Publish our verified proof subjects to the server profile so peers
// can discover + independently verify them (drives our badge in their
// chat). Previously this only happened on a manual "reverify all", so
// verified users were invisible to peers until they clicked it.
if (claims.some((c) => c.last_verify?.status === "ok")) {
void publishVerifiedSubjects();
}
try {
registryRecord = await lookup(session.unlocked.handle);
} catch (e) {
if (!(e instanceof ApiError && e.status === 404)) {
console.error(e);
}
}
});
async function reverifyAll() {
verifyingAll = true;
try {
for (const c of claims) {
const result = await verifyClaim($state.snapshot(c) as StoredClaim);
await setVerifyResult(c.id, result);
}
claims = await listClaims();
await publishVerifiedSubjects();
} finally {
verifyingAll = false;
}
}
/**
* Push the subjects of our currently-verified claims to the server
* profile so peers can discover + independently verify them (drives
* their verified badge for us). Best-effort — a failure here doesn't
* affect local verification.
*/
async function publishVerifiedSubjects() {
if (!session.unlocked) return;
const subjects = claims
.filter((c) => c.last_verify?.status === "ok")
.map((c) => c.envelope.payload.subject);
try {
await setProofs(session.unlocked.handle, session.unlocked.seed, subjects);
} catch (e) {
console.error("publishVerifiedSubjects failed", e);
}
}
function channelLabel(ch: string): string {
return (
{
github: "GitHub",
dns: "DNS",
web: "Website",
nostr: "Nostr",
bluesky: "Bluesky",
ap: "ActivityPub",
} as Record<string, string>
)[ch] ?? ch;
}
async function copyKez() {
if (!session.unlocked) return;
await navigator.clipboard.writeText(
`${session.unlocked.handle}@${session.unlocked.server}`,
);
copied = true;
setTimeout(() => (copied = false), 1500);
}
function fingerprint(primary: string): string {
// ed25519:<hex> → grouped short fingerprint for human comparison.
const hex = primary.startsWith("ed25519:")
? primary.slice("ed25519:".length)
: primary;
return (hex.match(/.{1,4}/g) ?? []).slice(0, 8).join(" ");
}
</script>
{#if session.unlocked}
<div class="max-w-2xl mx-auto px-4 py-6 space-y-6">
<!-- Identity card -->
<section class="bg-surface border border-border rounded-xl p-6">
<div class="flex items-start gap-4">
<Avatar
seed={session.unlocked.primary}
size={64}
ring
picture={session.myProfile?.picture}
/>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2 flex-wrap">
<span class="font-mono text-lg font-semibold text-text truncate inline-flex items-center gap-1">
<span class="truncate">{session.unlocked.handle}<span class="text-text-muted">@{session.unlocked.server}</span></span>
{#if isVerified}<VerifiedBadge size={16} />{/if}
</span>
<button
class="text-xs px-2 py-0.5 rounded-sm border border-border text-text-secondary hover:bg-elevated hover:text-text shrink-0"
onclick={copyKez}
>
{copied ? "✓ copied" : "copy"}
</button>
</div>
<p class="mt-2 text-xs text-text-muted uppercase tracking-wider">Key fingerprint</p>
<p class="font-mono text-sm text-text-secondary break-all">
{fingerprint(session.unlocked.primary)}<span class="text-text-muted"></span>
</p>
{#if registryRecord}
<p class="mt-2 text-xs text-text-muted">
Registered {new Date(registryRecord.registered_at).toLocaleDateString()}
</p>
{/if}
</div>
</div>
</section>
<!-- Proofs -->
<section class="bg-surface border border-border rounded-xl p-6">
<div class="flex items-start justify-between gap-4 mb-4">
<div>
<h2 class="text-sm font-semibold text-text uppercase tracking-wider">Proofs</h2>
<p class="text-sm text-text-secondary mt-1">
Other accounts cryptographically linked to your KEZ. Anyone can
verify these without trusting the server.
</p>
</div>
<div class="flex flex-col gap-2 shrink-0">
{#if claims.length > 0}
<button
class="px-3 py-1.5 text-sm border border-border rounded-md text-text-secondary hover:bg-elevated hover:text-text disabled:opacity-50"
onclick={reverifyAll}
disabled={verifyingAll}
>
{verifyingAll ? "Verifying…" : "Re-verify"}
</button>
{/if}
<a
href="#/claims/add"
class="px-3 py-1.5 text-sm bg-accent text-accent-contrast font-semibold rounded-md hover:bg-accent-dim no-underline text-center"
>
+ Add proof
</a>
</div>
</div>
{#if claims.length === 0}
<div class="border border-dashed border-border rounded-lg p-6 text-center">
<p class="text-sm text-text-muted">No proofs yet.</p>
<p class="text-xs text-text-muted mt-1">
Link GitHub, your domain, nostr, Bluesky — prove the accounts you control.
</p>
</div>
{:else}
<ul class="space-y-2">
{#each verified as c (c.id)}
<li class="flex items-center justify-between gap-3 p-3 bg-elevated border border-border rounded-lg">
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2 flex-wrap">
<span class="text-xs font-semibold px-1.5 py-0.5 rounded-sm bg-elevated border border-border text-text-secondary">
{channelLabel(c.channel)}
</span>
<span class="font-mono text-sm text-text truncate">{c.envelope.payload.subject}</span>
<span class="text-xs font-mono font-semibold px-1.5 py-0.5 rounded-sm" style="background:#4ade8014;border:1px solid #4ade8040;color:var(--color-verified);">✓ verified</span>
</div>
</div>
{#if c.last_verify?.evidence_url}
<a href={c.last_verify.evidence_url} target="_blank" rel="noopener noreferrer" class="text-xs text-accent hover:text-accent-dim underline shrink-0">proof ↗</a>
{/if}
</li>
{/each}
{#each failed as c (c.id)}
<li class="flex items-center gap-2 p-3 bg-elevated border border-border rounded-lg">
<span class="text-xs font-semibold px-1.5 py-0.5 rounded-sm bg-elevated border border-border text-text-secondary">{channelLabel(c.channel)}</span>
<span class="font-mono text-sm text-text truncate flex-1">{c.envelope.payload.subject}</span>
<span class="text-xs font-mono font-semibold text-danger shrink-0">✗ failed</span>
</li>
{/each}
{#each pending as c (c.id)}
<li class="flex items-center gap-2 p-3 bg-elevated border border-border rounded-lg">
<span class="text-xs font-semibold px-1.5 py-0.5 rounded-sm bg-elevated border border-border text-text-secondary">{channelLabel(c.channel)}</span>
<span class="font-mono text-sm text-text truncate flex-1">{c.envelope.payload.subject}</span>
<span class="text-xs font-mono text-warning shrink-0">pending</span>
</li>
{/each}
</ul>
<a href="#/claims" class="mt-3 inline-block text-xs text-text-secondary hover:text-text underline">Manage proofs →</a>
{/if}
</section>
</div>
{/if}