happy path working with stub companion app

This commit is contained in:
2026-08-18 02:16:05 +02:00
parent 3c11a88a33
commit bc025d007c
41 changed files with 1512 additions and 102 deletions
+18
View File
@@ -0,0 +1,18 @@
import * as esbuild from 'esbuild';
import { cpSync, mkdirSync } from 'node:fs';
const outdir = 'dist';
mkdirSync(outdir, { recursive: true });
await esbuild.build({
entryPoints: { main: 'src/main.ts' },
bundle: true,
format: 'esm',
target: 'es2022',
outdir,
logLevel: 'info',
});
cpSync('index.html', `${outdir}/index.html`);
console.log(`Built -> ${outdir}/`);
+33
View File
@@ -0,0 +1,33 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>LOCQR companion (stub)</title>
<style>
/* Bare (mobile/claude.md: "the visual design specified in gui.md does not
apply to the stub"). Functional correctness only. */
body { font-family: system-ui, sans-serif; max-width: 420px; margin: 40px auto; padding: 0 16px; color: #111; }
h1 { font-size: 18px; }
h2 { font-size: 16px; margin-top: 0; }
#app { border: 1px solid #ddd; border-radius: 8px; padding: 20px; }
button { padding: 8px 16px; font-size: 14px; cursor: pointer; margin: 4px 8px 4px 0; }
.btn-primary { background: #1a73e8; color: #fff; border: none; border-radius: 4px; }
.btn-ghost { background: none; border: 1px solid #ccc; border-radius: 4px; }
input { display: block; width: 100%; box-sizing: border-box; padding: 8px; margin: 6px 0; font-size: 14px; }
.camera-preview { width: 100%; border-radius: 4px; background: #000; }
.credential-item { display: flex; align-items: center; gap: 8px; padding: 8px; border: 1px solid #eee; border-radius: 4px; margin-bottom: 6px; }
.pin-groups { display: flex; gap: 16px; justify-content: center; margin: 16px 0; }
.pin-group { display: flex; gap: 4px; }
.pin-digit { width: 28px; height: 36px; display: flex; align-items: center; justify-content: center;
border: 1px solid #ccc; border-radius: 4px; font-family: ui-monospace, monospace; font-size: 18px; }
.error-text { color: #b3261e; }
details summary { cursor: pointer; margin-top: 8px; }
</style>
</head>
<body>
<h1>LOCQR companion — dev stub</h1>
<p><small>Not the native app (mobile/claude.md). Full protocol, no persistence, no real biometrics.</small></p>
<div id="app"></div>
<script type="module" src="main.js"></script>
</body>
</html>
+20
View File
@@ -0,0 +1,20 @@
{
"name": "locqr-companion",
"private": true,
"version": "0.1.0",
"description": "LOCQR web companion stub (development tool, not the native app). See mobile/claude.md.",
"type": "module",
"scripts": {
"build": "node build.js"
},
"dependencies": {
"@noble/curves": "^2.3.0",
"@noble/post-quantum": "0.6.1",
"canonicalize": "3.0.0",
"jsqr": "^1.4.0"
},
"devDependencies": {
"esbuild": "^0.28.0",
"typescript": "^5.6.0"
}
}
+109
View File
@@ -0,0 +1,109 @@
// Backend calls the companion makes directly (mobile/claude.md's "Backend
// API surface"; schemas in interfaces.md). Mirrors extension/src/background/api.ts's
// shape — try/catch around fetch, boolean/result objects instead of thrown
// errors, so callers can render distinct states instead of a single generic
// failure.
import { base64UrlDecode } from './base64url.js';
const API_BASE = 'https://api.locqr.dev:3000';
export interface RunBundle {
x25519Pubkey: Uint8Array;
kemPubkey: Uint8Array;
}
export type BundleFetchResult =
| { ok: true; bundle: RunBundle }
| { ok: false; reason: 'bundle_consumed' | 'backend_unreachable' };
/**
* GET /run/bundle/:runId (interfaces.md, "Run bundle fetch") — at-most-once,
* atomically destroyed on this fetch. A 404 specifically means "already
* consumed or expired," a security-class outcome (possible QR hijack), not
* a generic network failure — every other non-2xx or a thrown fetch error
* is the network class instead.
*/
export async function fetchRunBundle(runId: string): Promise<BundleFetchResult> {
try {
const response = await fetch(`${API_BASE}/run/bundle/${runId}`);
if (response.status === 404) {
return { ok: false, reason: 'bundle_consumed' };
}
if (!response.ok) {
return { ok: false, reason: 'backend_unreachable' };
}
const body = (await response.json()) as { x25519_pubkey: string; kem_pubkey: string };
return {
ok: true,
bundle: { x25519Pubkey: base64UrlDecode(body.x25519_pubkey), kemPubkey: base64UrlDecode(body.kem_pubkey) },
};
} catch {
return { ok: false, reason: 'backend_unreachable' };
}
}
async function postRelay(runId: string, type: 'kem_ciphertext' | 'credential', payloadB64: string): Promise<boolean> {
try {
const response = await fetch(`${API_BASE}/run/relay/${runId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type, payload_b64: payloadB64 }),
});
return response.ok;
} catch {
return false;
}
}
/** POST /run/relay/:runId, type "kem_ciphertext" (interfaces.md, "Relay messages"), Phase 2. */
export function postKemCiphertext(runId: string, payloadB64: string): Promise<boolean> {
return postRelay(runId, 'kem_ciphertext', payloadB64);
}
/** POST /run/relay/:runId, type "credential" (interfaces.md, "Relay messages"), Phase 4. */
export function postCredential(runId: string, payloadB64: string): Promise<boolean> {
return postRelay(runId, 'credential', payloadB64);
}
/**
* GET /run/relay/:runId/confirm (interfaces.md, "PIN confirmation") — a
* single poll. `main.ts`'s waitForConfirmation loop (started automatically
* on entering pin_display) calls this repeatedly rather than looping in
* here, so a user's Cancel can interrupt between polls instead of only
* after a bounded wait elapses.
*/
export async function getConfirmation(runId: string): Promise<boolean> {
try {
const response = await fetch(`${API_BASE}/run/relay/${runId}/confirm`);
if (!response.ok) return false;
const body = (await response.json()) as { confirmed: boolean };
return body.confirmed;
} catch {
return false;
}
}
export type CompanionSecurityErrorType = 'bundle_consumed' | 'alpha_hash_mismatch' | 'token_signature_invalid';
/**
* POST /security/report (interfaces.md) — best-effort, same as the
* extension's reportSecurityError: a failed report must not block the
* user-facing outcome, which is already determined by this point.
* `runId` is omitted for a bad token, per interfaces.md — no run
* has been joined yet at that point.
*/
export async function reportSecurityError(runId: string | undefined, errorType: CompanionSecurityErrorType): Promise<void> {
try {
const response = await fetch(`${API_BASE}/security/report`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ runId, error_type: errorType, timestamp: Math.floor(Date.now() / 1000) }),
});
if (!response.ok) {
console.error(`[locqr companion] security report rejected: ${response.status}`);
}
} catch (err) {
console.error('[locqr companion] security report failed to send:', err);
}
}
+22
View File
@@ -0,0 +1,22 @@
// base64url (RFC 4648 §5), no padding — interfaces.md's shared conventions.
// Same implementation as extension/src/base64url.ts; duplicated rather than
// shared across the two independent build targets.
export function base64UrlDecode(s: string): Uint8Array {
const unpadded = s.replace(/-/g, '+').replace(/_/g, '/');
const padded = unpadded + '='.repeat((4 - (unpadded.length % 4)) % 4);
const binary = atob(padded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
export function base64UrlEncode(bytes: Uint8Array): string {
let binary = '';
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
+10
View File
@@ -0,0 +1,10 @@
// Compile-time pinned constant (mobile/claude.md's "Compile-time constants"
// table; crypto.md's "Compile-time key constants"). Real dev value from
// dev/keys/ed25519-public.b64 — hand-set for this slice, same as the
// extension's ED25519_PUBLIC_KEY_B64 (extension/src/constants.ts); both
// name the same key material under their own component's constant name.
// scripts/setup-dev.js's constant-patching automation is a documented
// fast-follow once this pattern is proven (dev.md).
/** Ed25519 — verifies signed key exchange tokens (interfaces.md, "Signed token (QR payload)"). */
export const ED25519_PUBKEY = 'Z9ppr33AB5gznf-mQU2F9Y3E-MEoNcGHtmlh7rzaTh4';
+37
View File
@@ -0,0 +1,37 @@
// Session-only, in-memory credential store (mobile/claude.md's web stub
// scope: "No persistent credential storage" — deliberately, this is not a
// preview of the native app's Keystore-backed store). Stored per domain,
// each domain mapping to an ordered list, matching the native app's
// storage structure (mobile/claude.md, "Credential storage") minus
// encryption at rest and persistence. Seeded with more than one entry for
// test.locqr.dev so the `credential_select` state's multi-credential
// branch is actually reachable in testing — a single hardcoded credential
// would never exercise it.
export interface CredentialEntry {
label: string;
username: string;
password: string;
}
const store = new Map<string, CredentialEntry[]>([
[
'test.locqr.dev',
[
{ label: 'Personal', username: 'alice@example.com', password: 'hunter2' },
{ label: 'Work', username: 'alice.work@example.com', password: 'correct-horse-battery-staple' },
],
],
]);
/** Returns a copy — callers (main.ts's state) must not observe later addCredential() mutations of the store's own array. */
export function credentialsForDomain(domain: string): CredentialEntry[] {
return [...(store.get(domain) ?? [])];
}
/** Manual entry (flows.md's "Manual entry" provisioning path) — session-only, lost on refresh. */
export function addCredential(domain: string, entry: CredentialEntry): void {
const list = store.get(domain) ?? [];
list.push(entry);
store.set(domain, list);
}
+175
View File
@@ -0,0 +1,175 @@
// Companion-side run cryptography (crypto.md; mobile/claude.md's
// "Cryptographic responsibilities"; interfaces.md's "Signed token (QR
// payload)" and "Encrypted credential payload"). Pure functions — no DOM
// access — mirrors the shape of extension/src/background/crypto.ts and
// scripts/companion-harness.mjs, which implement the extension's and a
// Node stand-in's halves of the same protocol respectively.
//
// Library choice: @noble/post-quantum + @noble/curves, not @oqs/liboqs-js —
// resolving the "open call for whoever builds the companion" left by
// crypto.md's Library choices section. liboqs-js would work here (a normal
// page context has no service-worker WASM restriction), but there's no
// reason to carry a second ~17MB WASM PQ library across the two browser
// components when @noble/post-quantum is already proven working, pure TS,
// and — via scripts/companion-harness.mjs, the closest existing reference
// for this component's protocol behaviour — already the de facto choice.
// See crypto.md's updated Library choices table.
import { ed25519, x25519 } from '@noble/curves/ed25519.js';
import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';
import canonicalize from 'canonicalize';
import { base64UrlDecode } from './base64url.js';
import { ED25519_PUBKEY } from './constants.js';
function concat(...parts: Uint8Array[]): Uint8Array {
const total = parts.reduce((sum, p) => sum + p.length, 0);
const out = new Uint8Array(total);
let offset = 0;
for (const part of parts) {
out.set(part, offset);
offset += part.length;
}
return out;
}
export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
// interfaces.md: "The companion accepts tokens up to 30 seconds past
// expires_at to cover device clock skew. This is the only clock tolerance
// in the protocol."
const EXPIRY_LEEWAY_SECONDS = 30;
export interface SignedTokenPayload {
v: number;
runId: string;
url: string;
expires_at: number;
alpha_hash: string;
}
export type TokenVerificationResult =
| { ok: true; payload: SignedTokenPayload }
| { ok: false; reason: 'signature_invalid' | 'ttl_expired' };
/**
* verifying state (mobile/claude.md): decode, check the Ed25519 signature
* over the JCS-canonicalised payload, then check expiry. mobile/claude.md
* defines no separate "malformed" error class for the companion (unlike
* the extension's cert verification) — unparseable or structurally invalid
* content is just as untrusted as a bad signature, so it folds into the
* same signature_invalid security-class bucket rather than inventing a
* fourth class nothing else in the protocol expects.
*/
export function verifySignedToken(qrContent: string): TokenVerificationResult {
let envelope: Record<string, unknown>;
try {
envelope = JSON.parse(new TextDecoder().decode(base64UrlDecode(qrContent))) as Record<string, unknown>;
} catch {
return { ok: false, reason: 'signature_invalid' };
}
const { sig, ...payload } = envelope;
if (
typeof sig !== 'string' ||
typeof payload.v !== 'number' ||
typeof payload.runId !== 'string' ||
typeof payload.url !== 'string' ||
typeof payload.expires_at !== 'number' ||
typeof payload.alpha_hash !== 'string'
) {
return { ok: false, reason: 'signature_invalid' };
}
let signatureValid: boolean;
try {
const canonical = canonicalize(payload) as string;
const message = new TextEncoder().encode(canonical);
signatureValid = ed25519.verify(base64UrlDecode(sig), message, base64UrlDecode(ED25519_PUBKEY));
} catch {
return { ok: false, reason: 'signature_invalid' };
}
if (!signatureValid) {
return { ok: false, reason: 'signature_invalid' };
}
const nowSeconds = Date.now() / 1000;
if (nowSeconds > (payload.expires_at as number) + EXPIRY_LEEWAY_SECONDS) {
return { ok: false, reason: 'ttl_expired' };
}
return { ok: true, payload: payload as unknown as SignedTokenPayload };
}
export interface X25519Keypair {
secretKey: Uint8Array;
publicKey: Uint8Array;
}
export function generateX25519Keypair(): X25519Keypair {
return x25519.keygen();
}
export function x25519SharedSecret(secretKey: Uint8Array, peerPublicKey: Uint8Array): Uint8Array {
return x25519.getSharedSecret(secretKey, peerPublicKey);
}
export function mlKem768Encapsulate(publicKey: Uint8Array): { cipherText: Uint8Array; sharedSecret: Uint8Array } {
return ml_kem768.encapsulate(publicKey);
}
/**
* alpha_hash recomputation (interfaces.md) — must equal the commitment
* carried in the signed token, or the fetched key bundle has been tampered
* with between the extension and the backend (`alpha_hash_mismatch`,
* security-class).
*/
export async function alphaHash(x25519Pub: Uint8Array, kemPub: Uint8Array): Promise<Uint8Array> {
const digest = await crypto.subtle.digest('SHA-256', concat(x25519Pub, kemPub) as BufferSource);
return new Uint8Array(digest);
}
async function hkdfSha256(ikm: Uint8Array, salt: Uint8Array, info: string, lengthBytes: number): Promise<Uint8Array> {
const key = await crypto.subtle.importKey('raw', ikm as BufferSource, 'HKDF', false, ['deriveBits']);
const bits = await crypto.subtle.deriveBits(
{ name: 'HKDF', hash: 'SHA-256', salt: salt as BufferSource, info: new TextEncoder().encode(info) },
key,
lengthBytes * 8,
);
return new Uint8Array(bits);
}
/** run_key = HKDF-SHA256(x25519_shared || kem_shared_secret, salt=runId_utf8, info="locqr-run-key-v1", 32) — crypto.md. */
export async function deriveRunKey(x25519Shared: Uint8Array, kemSharedSecret: Uint8Array, runId: string): Promise<Uint8Array> {
const ikm = concat(x25519Shared, kemSharedSecret);
const salt = new TextEncoder().encode(runId);
return hkdfSha256(ikm, salt, 'locqr-run-key-v1', 32);
}
/**
* PIN = HKDF-SHA256(run_key, salt=[], info="locqr-pin-v1", length=4),
* interpreted big-endian, mod 1,000,000, zero-padded to six digits
* (mobile/claude.md). Must match the extension's derivePin() exactly.
*/
export async function derivePin(runKey: Uint8Array): Promise<string> {
const bits = await hkdfSha256(runKey, new Uint8Array(0), 'locqr-pin-v1', 4);
const value = new DataView(bits.buffer, bits.byteOffset, bits.byteLength).getUint32(0, false);
return (value % 1_000_000).toString().padStart(6, '0');
}
export interface Credential {
username: string;
password: string;
}
/** Wire framing (interfaces.md): nonce[12] || ciphertext[N] || tag[16], one encryption per run key. */
export async function encryptCredential(runKey: Uint8Array, credential: Credential): Promise<Uint8Array> {
const nonce = crypto.getRandomValues(new Uint8Array(12));
const plaintext = new TextEncoder().encode(JSON.stringify(credential));
const key = await crypto.subtle.importKey('raw', runKey as BufferSource, 'AES-GCM', false, ['encrypt']);
const ciphertextAndTag = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce as BufferSource }, key, plaintext));
return concat(nonce, ciphertextAndTag);
}
export { concat };
+398
View File
@@ -0,0 +1,398 @@
// Companion web stub entry point — drives mobile/claude.md's state model
// end to end against the real server and a real running extension. Plain
// DOM rendering (innerHTML template strings + data-action click delegation),
// no framework: same approach as extension/src/popup/popup.ts. Visual
// design is out of scope (mobile/gui.md is empty; mobile/claude.md: "Adhere
// to gui.md only where doing so costs nothing").
import { getConfirmation, fetchRunBundle, postCredential, postKemCiphertext, reportSecurityError } from './api.js';
import { base64UrlDecode, base64UrlEncode } from './base64url.js';
import { addCredential, credentialsForDomain, type CredentialEntry } from './credentials.js';
import {
alphaHash,
bytesEqual,
concat,
deriveRunKey,
derivePin,
encryptCredential,
generateX25519Keypair,
mlKem768Encapsulate,
verifySignedToken,
x25519SharedSecret,
} from './crypto.js';
import { startScanner, type ScannerHandle } from './scanner.js';
import { ERROR_CLASS, type CompanionState, type ErrorReason } from './state.js';
const CONFIRMATION_POLL_INTERVAL_MS = 1000;
// Generous safety net, not the authoritative deadline — the extension's own
// pin_ttl alarm on the other side is what actually bounds a real wait
// (mirrors scripts/companion-harness.mjs's identical choice).
const CONFIRMATION_POLL_TIMEOUT_MS = 180_000;
const COMPLETE_DISPLAY_MS = 2000;
let state: CompanionState = { kind: 'idle' };
let scannerHandle: ScannerHandle | null = null;
// Bumped on every user-initiated cancel/reset so in-flight async chains
// (verify -> key exchange -> confirmation poll) can tell they've been
// superseded and stop applying their result to a state the user has
// already left. Checked, not cleared: cheaper than plumbing an
// AbortController through every await in the chain.
let generation = 0;
function setState(next: CompanionState): void {
state = next;
render();
}
/** Cancel button at any pre-delivery stage — mobile/claude.md's `→ idle (user cancels; run key discarded)`. */
function cancelToIdle(): void {
generation++;
if (scannerHandle) {
scannerHandle.stop();
scannerHandle = null;
}
activeVideoEl = null;
setState({ kind: 'idle' });
}
async function beginAuthenticating(): Promise<void> {
setState({ kind: 'authenticating' });
}
/** Stub stand-in for BiometricPrompt (mobile/claude.md's web stub scope). */
async function unlockAndScan(): Promise<void> {
const myGeneration = ++generation;
setState({ kind: 'scanning' });
const video = document.createElement('video');
video.setAttribute('playsinline', ''); // iOS Safari: without this, play() opens fullscreen instead of inline
video.muted = true;
const canvas = document.createElement('canvas');
canvas.hidden = true;
try {
scannerHandle = await startScanner(video, canvas, (content) => {
if (myGeneration !== generation) return;
scannerHandle?.stop();
scannerHandle = null;
void handleQrDecoded(content);
});
} catch (err) {
if (myGeneration !== generation) return;
// Camera permission/hardware failures happen before any run exists
// and aren't in mobile/claude.md's post-scan error taxonomy — shown
// inline on the scanning screen itself rather than forced into one
// of the three formal error classes.
setState({ kind: 'scanning', cameraError: err instanceof Error ? err.message : String(err) });
return;
}
if (myGeneration !== generation) {
scannerHandle?.stop();
scannerHandle = null;
return;
}
// No state transition happens here — still 'scanning' — so nothing
// would otherwise trigger a re-render between entering this state and
// the stream becoming ready. Attach directly and force one so the
// preview actually appears instead of sitting in a detached element.
activeVideoEl = video;
render();
}
let activeVideoEl: HTMLVideoElement | null = null;
async function handleQrDecoded(content: string): Promise<void> {
const myGeneration = generation;
setState({ kind: 'verifying' });
const result = verifySignedToken(content);
if (!result.ok) {
if (result.reason === 'signature_invalid') {
await reportSecurityError(undefined, 'token_signature_invalid');
}
if (myGeneration !== generation) return;
setState({ kind: 'error', reason: result.reason });
return;
}
const { runId, url, expires_at: _expiresAt, alpha_hash: alphaHashB64 } = result.payload;
if (myGeneration !== generation) return;
setState({ kind: 'key_exchange', runId, url });
const bundleResult = await fetchRunBundle(runId);
if (!bundleResult.ok) {
if (bundleResult.reason === 'bundle_consumed') {
await reportSecurityError(runId, 'bundle_consumed');
}
if (myGeneration !== generation) return;
setState({ kind: 'error', reason: bundleResult.reason });
return;
}
const { x25519Pubkey, kemPubkey } = bundleResult.bundle;
const recomputedAlphaHash = await alphaHash(x25519Pubkey, kemPubkey);
if (!bytesEqual(recomputedAlphaHash, base64UrlDecode(alphaHashB64))) {
await reportSecurityError(runId, 'alpha_hash_mismatch');
if (myGeneration !== generation) return;
setState({ kind: 'error', reason: 'alpha_hash_mismatch' });
return;
}
const companionX25519 = generateX25519Keypair();
const x25519Shared = x25519SharedSecret(companionX25519.secretKey, x25519Pubkey);
const { cipherText: kemCiphertext, sharedSecret: kemSharedSecret } = mlKem768Encapsulate(kemPubkey);
const runKey = await deriveRunKey(x25519Shared, kemSharedSecret, runId);
const pin = await derivePin(runKey);
const posted = await postKemCiphertext(runId, base64UrlEncode(concat(companionX25519.publicKey, kemCiphertext)));
if (!posted) {
if (myGeneration !== generation) return;
setState({ kind: 'error', reason: 'relay_error' });
return;
}
if (myGeneration !== generation) return;
setState({ kind: 'pin_display', runId, url, pin, runKey });
// No local gate here — the PIN is shown for the person to compare
// against the extension's independently-derived one (the real
// anti-MITM check), but only the extension's own Confirm click
// advances the run. Polling starts the instant the PIN exists.
void waitForConfirmation(runId, url, runKey, myGeneration);
}
/**
* Polls interfaces.md's PIN confirmation endpoint until the extension's
* user clicks Confirm there. Wrapped in try/catch and called with `void`
* from its caller (fire-and-forget, no attached .catch) — without this,
* any unexpected throw here (e.g. a malformed `url`) would silently
* reject and leave the UI frozen on pin_display forever with no visible
* sign anything went wrong. Surfacing it as `error/relay_error` instead
* is a diagnostic net as much as a fix: if this ever actually fires, the
* console.error pinpoints what threw.
*/
async function waitForConfirmation(runId: string, url: string, runKey: Uint8Array, myGeneration: number): Promise<void> {
try {
const deadline = Date.now() + CONFIRMATION_POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
if (myGeneration !== generation) return;
const confirmed = await getConfirmation(runId);
if (confirmed) {
if (myGeneration !== generation) return;
const domain = new URL(url).hostname;
setState({ kind: 'credential_select', runId, url, runKey, domain, credentials: credentialsForDomain(domain) });
return;
}
await new Promise((resolve) => setTimeout(resolve, CONFIRMATION_POLL_INTERVAL_MS));
}
if (myGeneration !== generation) return;
setState({ kind: 'error', reason: 'confirmation_timeout' });
} catch (err) {
console.error('[locqr companion] waitForConfirmation crashed:', err);
if (myGeneration !== generation) return;
setState({ kind: 'error', reason: 'relay_error' });
}
}
function refreshCredentialSelect(): void {
if (state.kind !== 'credential_select') return;
setState({ ...state, credentials: credentialsForDomain(state.domain) });
}
async function deliverCredential(credential: CredentialEntry): Promise<void> {
if (state.kind !== 'credential_select') return;
const { runId, runKey } = state;
const myGeneration = generation;
setState({ kind: 'delivering' });
const payload = await encryptCredential(runKey, credential);
const posted = await postCredential(runId, base64UrlEncode(payload));
if (!posted) {
if (myGeneration !== generation) return;
setState({ kind: 'error', reason: 'relay_error' });
return;
}
if (myGeneration !== generation) return;
setState({ kind: 'complete' });
setTimeout(() => {
if (myGeneration === generation) setState({ kind: 'idle' });
}, COMPLETE_DISPLAY_MS);
}
function retryFromError(): void {
void beginAuthenticating();
}
// --- Rendering ---
const ERROR_COPY: Record<ErrorReason, { heading: string; body: string }> = {
signature_invalid: { heading: 'Invalid code', body: "This code's signature didn't verify. It may be forged or corrupted." },
alpha_hash_mismatch: { heading: 'Key mismatch', body: 'The key bundle from the server did not match this code. Possible tampering.' },
bundle_consumed: { heading: 'Already used', body: 'This code was already used by another device, or has expired.' },
ttl_expired: { heading: 'Code expired', body: 'This code expired before it was scanned. Try scanning a fresh one.' },
user_abort: { heading: 'Cancelled', body: 'Sign-in was cancelled.' },
backend_unreachable: { heading: "Can't reach LOCQR", body: "We couldn't reach the LOCQR server. Check your connection and try again." },
relay_error: { heading: 'Something went wrong', body: "We couldn't complete sign-in. Please try again." },
confirmation_timeout: {
heading: 'No response from browser',
body: "The browser didn't confirm the code in time. Make sure you clicked Confirm there.",
},
};
function credentialListHtml(state: Extract<CompanionState, { kind: 'credential_select' }>): string {
if (state.credentials.length === 0) {
return `
<p>No stored credentials for <strong>${state.domain}</strong> yet.</p>
<form id="add-credential-form">
<input name="label" placeholder="Label" required />
<input name="username" placeholder="Username" required />
<input name="password" type="password" placeholder="Password" required />
<button type="submit" class="btn-primary">Add & use</button>
</form>
`;
}
const items = state.credentials
.map(
(c, i) => `
<label class="credential-item">
<input type="radio" name="credential" value="${i}" ${i === 0 ? 'checked' : ''} />
<span><strong>${c.label}</strong><br /><small>${c.username}</small></span>
</label>`,
)
.join('');
return `
<p>Sign in to <strong>${state.domain}</strong> with:</p>
<form id="credential-select-form">
${items}
<button type="submit" class="btn-primary">Deliver credential</button>
</form>
<details>
<summary>Add another credential</summary>
<form id="add-credential-form">
<input name="label" placeholder="Label" required />
<input name="username" placeholder="Username" required />
<input name="password" type="password" placeholder="Password" required />
<button type="submit" class="btn-primary">Add</button>
</form>
</details>
`;
}
function pinGroupsHtml(pin: string): string {
const digits = pin.split('');
const group = (d: string[]) => `<div class="pin-group">${d.map((x) => `<div class="pin-digit">${x}</div>`).join('')}</div>`;
return `<div class="pin-groups">${group(digits.slice(0, 3))}${group(digits.slice(3, 6))}</div>`;
}
function contentHtml(): string {
switch (state.kind) {
case 'idle':
return `
<h2>Ready</h2>
<p>Tap Scan QR to sign in to a site using LOCQR.</p>
<button class="btn-primary" data-action="scan_qr">Scan QR</button>
`;
case 'authenticating':
return `
<h2>Unlock</h2>
<p>Stub stand-in for biometric/device PIN (mobile/claude.md).</p>
<button class="btn-primary" data-action="unlock">Continue</button>
<button class="btn-ghost" data-action="cancel">Cancel</button>
`;
case 'scanning':
return `
<h2>Scan QR</h2>
<div id="scanner-mount"></div>
${state.cameraError ? `<p class="error-text">Camera error: ${state.cameraError}</p>` : ''}
<button class="btn-ghost" data-action="cancel">Cancel</button>
`;
case 'verifying':
return `<h2>Verifying…</h2><p>Checking the code's signature and fetching the key bundle.</p>`;
case 'key_exchange':
return `<h2>Connecting…</h2><p>Performing key exchange with ${state.url}.</p>`;
case 'pin_display':
return `
<h2>Compare this code</h2>
${pinGroupsHtml(state.pin)}
<p>Check this matches the code shown in the browser extension for ${state.url}, then confirm there — no action needed here.</p>
<button class="btn-ghost" data-action="cancel">Cancel</button>
`;
case 'credential_select':
return `<h2>Choose a credential</h2>${credentialListHtml(state)}<button class="btn-ghost" data-action="cancel">Cancel</button>`;
case 'delivering':
return `<h2>Delivering…</h2><p>Sending the encrypted credential.</p>`;
case 'complete':
return `<h2>Done</h2><p>Credential delivered. The browser should now show "Signed in".</p>`;
case 'error': {
const { heading, body } = ERROR_COPY[state.reason];
const errorClass = ERROR_CLASS[state.reason];
const retryButton = errorClass !== 'security' ? `<button class="btn-primary" data-action="retry">Retry</button>` : '';
return `
<h2>${errorClass === 'security' ? '⚠ ' : ''}${heading}</h2>
<p>${body}</p>
${retryButton}
<button class="btn-ghost" data-action="dismiss">Dismiss</button>
`;
}
}
}
function wireActions(): void {
document.querySelectorAll<HTMLButtonElement>('#app button[data-action]').forEach((btn) => {
const action = btn.dataset.action;
btn.addEventListener('click', () => {
if (action === 'scan_qr') void beginAuthenticating();
else if (action === 'unlock') void unlockAndScan();
else if (action === 'cancel' || action === 'dismiss') cancelToIdle();
else if (action === 'retry') retryFromError();
});
});
const selectForm = document.getElementById('credential-select-form') as HTMLFormElement | null;
selectForm?.addEventListener('submit', (e) => {
e.preventDefault();
if (state.kind !== 'credential_select') return;
const selected = new FormData(selectForm).get('credential');
const index = Number(selected);
const credential = state.credentials[index];
if (credential) void deliverCredential(credential);
});
const addForm = document.getElementById('add-credential-form') as HTMLFormElement | null;
addForm?.addEventListener('submit', (e) => {
e.preventDefault();
if (state.kind !== 'credential_select') return;
const data = new FormData(addForm);
const entry: CredentialEntry = {
label: String(data.get('label')),
username: String(data.get('username')),
password: String(data.get('password')),
};
addCredential(state.domain, entry);
// Deliver immediately when this was the only-credential add path
// (empty-state form's "Add & use"); otherwise just refresh the list.
if (state.credentials.length === 0) void deliverCredential(entry);
else refreshCredentialSelect();
});
}
function render(): void {
const app = document.getElementById('app');
if (!app) return;
app.innerHTML = contentHtml();
if (state.kind === 'scanning' && activeVideoEl) {
const mount = document.getElementById('scanner-mount');
mount?.appendChild(activeVideoEl);
activeVideoEl.className = 'camera-preview';
}
wireActions();
}
render();
+58
View File
@@ -0,0 +1,58 @@
// Camera-based QR scanning (mobile/claude.md web stub: "Scans QR codes via
// the browser MediaDevices camera API"). Decode library: jsQR — pure JS,
// no WASM, the standard lightweight choice for in-browser barcode reading;
// not a crypto primitive, so it isn't subject to crypto.md's pinned-library
// list.
import jsQR from 'jsqr';
export interface ScannerHandle {
stop: () => void;
}
/**
* Opens the camera and polls frames via requestAnimationFrame until a QR
* code decodes, then calls `onDecode` once and stops polling on its own
* (the caller is still responsible for calling `stop()` to release the
* camera stream once it's done with the decoded content).
*/
export async function startScanner(
video: HTMLVideoElement,
canvas: HTMLCanvasElement,
onDecode: (content: string) => void,
): Promise<ScannerHandle> {
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
video.srcObject = stream;
await video.play();
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) throw new Error('2D canvas context unavailable');
let stopped = false;
let decoded = false;
function tick(): void {
if (stopped || decoded) return;
if (video.readyState === video.HAVE_ENOUGH_DATA) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx!.drawImage(video, 0, 0, canvas.width, canvas.height);
const frame = ctx!.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(frame.data, frame.width, frame.height);
if (code) {
decoded = true;
onDecode(code.data);
return;
}
}
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
return {
stop: () => {
stopped = true;
stream.getTracks().forEach((track) => track.stop());
},
};
}
+49
View File
@@ -0,0 +1,49 @@
// Companion state model (mobile/claude.md's "State model" — states and
// transitions are normative there; this is that diagram as a discriminated
// union). `authenticating` stands in for the native app's biometric/device
// PIN gate with a plain button (mobile/claude.md's web stub scope).
import type { CredentialEntry } from './credentials.js';
/** mobile/claude.md, "Error classes". */
export type ErrorReason =
| 'signature_invalid'
| 'alpha_hash_mismatch'
| 'bundle_consumed'
| 'ttl_expired'
| 'user_abort'
| 'backend_unreachable'
| 'relay_error'
| 'confirmation_timeout';
export type ErrorClass = 'security' | 'timeout_user' | 'network';
export const ERROR_CLASS: Record<ErrorReason, ErrorClass> = {
signature_invalid: 'security',
alpha_hash_mismatch: 'security',
bundle_consumed: 'security',
ttl_expired: 'timeout_user',
user_abort: 'timeout_user',
backend_unreachable: 'network',
relay_error: 'network',
confirmation_timeout: 'network',
};
// `pin_display` covers both showing the PIN and waiting for the extension's
// confirmation — there is no separate user-gated step between them. The
// companion polls automatically the instant the PIN is derived; the PIN is
// still shown the whole time so the person can compare it against the
// extension's independently-derived PIN (the actual anti-MITM check), but
// nothing on the companion side gates advancement — only the extension's
// own Confirm click does (mobile/claude.md's "State model").
export type CompanionState =
| { kind: 'idle' }
| { kind: 'authenticating' }
| { kind: 'scanning'; cameraError?: string }
| { kind: 'verifying' }
| { kind: 'key_exchange'; runId: string; url: string }
| { kind: 'pin_display'; runId: string; url: string; pin: string; runKey: Uint8Array }
| { kind: 'credential_select'; runId: string; url: string; runKey: Uint8Array; domain: string; credentials: CredentialEntry[] }
| { kind: 'delivering' }
| { kind: 'complete' }
| { kind: 'error'; reason: ErrorReason };
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"skipLibCheck": true,
"noEmit": true
},
"include": ["src"]
}