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
+9 -6
View File
@@ -88,7 +88,10 @@ machine. The popup reflects the state of the currently active tab.
- `rejected` — account is suspended or deactivated.
- `unreachable` — backend could not be reached; status unknown. Displayed
distinctly from a confirmed rejection.
- `idle` — certificate valid, account confirmed; no active run.
- `idle` — certificate valid, account confirmed; no active run. Carries a
`sessionActive` hint (advisory only — interfaces.md's `session_status`
message) that changes the popup's copy/badge (`gui.md`) but nothing
about verification or the run flow itself.
**Run states** (only reachable from `idle`)
@@ -223,9 +226,7 @@ or overrides.
| `qr_ttl` | How long a single QR code remains valid (Phase 2 countdown) |
| `max_auto_refresh` | How many times the QR is automatically refreshed before the user must retry manually |
| `pin_ttl` | How long the user has to confirm the PIN (Phase 3 countdown) |
Further per-phase timeouts (e.g. Phase 4 relay wait) may be added to this blob
as the design progresses.
| `relay_wait_ttl` | How long Phase 4 waits for the credential after PIN confirmation before `run_error/relay_timeout` |
### Navigation rules
@@ -273,7 +274,8 @@ opened; it always shows at minimum the current state.
| `cert_invalid` (security) | security warning | Security warning; specific reason | — |
| `account_error / rejected` | error | Account inactive | — |
| `account_error / unreachable` | error | Cannot reach LOCQR server | — |
| `idle` | ready | Site verified; ready | Start run |
| `idle` (`sessionActive: false`) | ready | Site verified; ready | Sign in |
| `idle` (`sessionActive: true`) | ready | Already signed in (advisory hint) | Sign in again |
| `phase_1` | animated | Connecting… | Abort |
| `phase_2` | animated | QR code | Abort |
| `phase_3` | animated | PIN; confirm or reject | Confirm, Abort |
@@ -313,10 +315,11 @@ is a backend and account-management concern.
| Compiled-in pubkeys | Source constants | Build time |
| Per-tab state machine state | In-memory (worker) | Tab lifetime |
| Site verification result | `chrome.storage.session` | Browser session |
| Run parameters (qr_ttl, max_auto_refresh, pin_ttl) | In-memory | Phase 1–4; discarded on delivery or error |
| Run parameters (qr_ttl, max_auto_refresh, pin_ttl, relay_wait_ttl) | In-memory | Phase 1–4; discarded on delivery or error |
| auto_refresh_remaining counter | In-memory | Phase 2 only |
| Ephemeral keypairs (X25519, ML-KEM-768) | In-memory | Phase 1–2 only |
| Run key | In-memory | Phase 3–4; discarded on delivery or error |
| Session-active hint (advisory, from the site) | In-memory | Until the tab's next page load or close |
| GYBBR identity keys | `chrome.storage.session` | Browser session (see below) |
Private key material is never written to `chrome.storage.local`, `localStorage`,
+17 -4
View File
@@ -165,10 +165,23 @@ Same chrome, no countdown bar (none of these four are TTL-governed). A 48px
badge + heading + short body, centered, shared across all four; only the
badge color/glyph, heading, body, and action differ.
- **`idle`** — accent-blue tinted badge, checkmark glyph (matches the `ready`
toolbar icon). Heading "Ready to sign in," body naming the site
(`"{origin} supports secure sign-in with LOCQR."`). One primary action:
**Sign in**.
- **`idle`** — two variants depending on the site's advisory
`sessionActive` hint (`claude.md`, `interfaces.md`'s `session_status`
message); same badge treatment either way, copy and action differ:
- No session reported (default): accent-blue tinted badge, checkmark
glyph (matches the `ready` toolbar icon). Heading "Ready to sign in,"
body naming the site (`"{origin} supports secure sign-in with
LOCQR."`). One primary action: **Sign in**.
- Session reported active: green tinted badge, checkmark glyph (same
glyph, badge color shifts to match `delivered`'s green — reads as "a
settled, good state," not an action item). Heading "Signed in," body
(`"You're already signed in to {origin}."`). One primary action:
**Sign in again** — same underlying action as plain `idle`'s Sign in
(starts a new run), just worded for a user who's already
authenticated. No extra confirmation before it: starting a run
doesn't affect the existing session at all, and the run's own
multi-step confirmation (QR scan, PIN compare) is already real friction
against an accidental click.
- **`phase_1`** and **`phase_4`** share one template: accent-blue tinted
badge containing the rotating-ring spinner (real CSS rotation, not a
static frame; honors `prefers-reduced-motion` by holding still instead of
+30 -1
View File
@@ -8,6 +8,7 @@
import { queryDomainStatus, reportSecurityError } from './api.js';
import { abortRun, cleanupRun, confirmPin, dismissRunError, startRun } from './run.js';
import { clearSessionActive, getSessionActive, setSessionActive } from './session-status.js';
import { registerSdkPort, unregisterSdkPort } from './sdk-ports.js';
import { clearTabState, getTabState, setTabState } from './state.js';
import { verifyRegistrationCert } from './verify.js';
@@ -91,10 +92,30 @@ async function handleInit(port: chrome.runtime.Port, tabId: number, originUrl: s
return;
}
await setTabState(tabId, { kind: 'idle', origin: result.domain, features: result.features });
await setTabState(tabId, {
kind: 'idle',
origin: result.domain,
features: result.features,
sessionActive: getSessionActive(tabId),
});
respond(port, { type: 'verification', status: 'valid', features: result.features });
}
/**
* SDK `session_status` — advisory only (types.ts's SessionStatusMessage).
* Remembered even outside `idle` (e.g. reported before verification
* finishes, or during an unrelated run) so the *next* time `idle` is
* entered it reflects the latest report, not just whichever one happened
* to arrive while already idle.
*/
async function handleSessionStatus(tabId: number, active: boolean): Promise<void> {
setSessionActive(tabId, active);
const state = await getTabState(tabId);
if (state.kind === 'idle') {
await setTabState(tabId, { ...state, sessionActive: active });
}
}
function respond(port: chrome.runtime.Port, message: VerificationMessage): void {
try {
port.postMessage(message);
@@ -140,6 +161,9 @@ chrome.runtime.onConnectExternal.addListener((port) => {
registerSdkPort(tabId, port);
port.onDisconnect.addListener(() => unregisterSdkPort(tabId, port));
// A fresh connection is a fresh page load — any session hint from a
// previous page at this tab is stale until this page re-reports it.
clearSessionActive(tabId);
void setTabState(tabId, { kind: 'unverified' });
port.onMessage.addListener((raw: unknown) => {
@@ -150,6 +174,8 @@ chrome.runtime.onConnectExternal.addListener((port) => {
void handleRequestCredential(tabId, windowId);
} else if (message.type === 'abort') {
void handleAbort(tabId);
} else if (message.type === 'session_status') {
void handleSessionStatus(tabId, message.active);
}
});
});
@@ -170,6 +196,9 @@ chrome.runtime.onMessage.addListener((raw: unknown) => {
async function handlePopupAction(message: PopupActionMessage): Promise<void> {
const { tabId, action } = message;
const state = await getTabState(tabId);
// Diagnostic: distinguishes "message never arrived" from "arrived but
// no-opped because state didn't match" — both looked identical before.
console.log(`[locqr] popup_action received: action=${action} tabId=${tabId} currentState=${state.kind}`);
switch (action) {
case 'start_run':
+1
View File
@@ -16,6 +16,7 @@ export interface RunSecrets {
qrTtlSeconds: number;
maxAutoRefresh: number;
pinTtlSeconds: number;
relayWaitTtlSeconds: number;
autoRefreshRemaining: number; // claude.md: "the extension tracks auto_refresh_remaining"
}
+62 -7
View File
@@ -18,6 +18,7 @@ import {
} from './crypto.js';
import { closeRelay, openRelay } from './relay.js';
import { clearRunSecrets, getRunSecrets, setRunSecrets, type RunSecrets } from './run-secrets.js';
import { clearSessionActive, getSessionActive } from './session-status.js';
import { sendToSdk } from './sdk-ports.js';
import { getTabState, setTabState } from './state.js';
@@ -35,6 +36,7 @@ const DELIVERED_DISPLAY_MS = 2000;
// scheduling always clears any prior alarm of the same kind first.
const QR_ALARM_PREFIX = 'locqr-qr-ttl';
const PIN_ALARM_PREFIX = 'locqr-pin-ttl';
const RELAY_WAIT_ALARM_PREFIX = 'locqr-relay-wait';
function qrAlarmName(tabId: number): string {
return `${QR_ALARM_PREFIX}:${tabId}`;
@@ -42,6 +44,9 @@ function qrAlarmName(tabId: number): string {
function pinAlarmName(tabId: number): string {
return `${PIN_ALARM_PREFIX}:${tabId}`;
}
function relayWaitAlarmName(tabId: number): string {
return `${RELAY_WAIT_ALARM_PREFIX}:${tabId}`;
}
function scheduleQrTtlAlarm(tabId: number, qrTtlSeconds: number): void {
const name = qrAlarmName(tabId);
@@ -53,9 +58,15 @@ function schedulePinTtlAlarm(tabId: number, pinTtlSeconds: number): void {
chrome.alarms.clear(name);
chrome.alarms.create(name, { delayInMinutes: pinTtlSeconds / 60 });
}
function scheduleRelayWaitAlarm(tabId: number, relayWaitTtlSeconds: number): void {
const name = relayWaitAlarmName(tabId);
chrome.alarms.clear(name);
chrome.alarms.create(name, { delayInMinutes: relayWaitTtlSeconds / 60 });
}
function clearRunAlarms(tabId: number): void {
chrome.alarms.clear(qrAlarmName(tabId));
chrome.alarms.clear(pinAlarmName(tabId));
chrome.alarms.clear(relayWaitAlarmName(tabId));
}
export async function startRun(tabId: number, origin: string, features: string[]): Promise<void> {
@@ -82,6 +93,31 @@ export async function startRun(tabId: number, origin: string, features: string[]
});
}
/**
* interfaces.md's "Run bundle upload": "`origin` is the full HTTPS origin
* taken from `sender.tab.url`. The server bakes it verbatim into the
* signed token's `url` field." TabState's own `origin` field is *not*
* that — it's the bare hostname from cert verification (`result.domain`,
* index.ts's handleInit), reused everywhere else in this codebase for
* display and cert-domain matching, where a bare hostname is exactly
* right. Using it here instead sent a schemeless string like
* `"test.locqr.dev"` into the token's `url` field — invalid as a URL
* (`new URL(...)` throws on it), silently broken until the companion
* became the first client to actually parse that field. Re-fetches the
* tab's current URL fresh here rather than threading a second origin
* value through every call site down from `startRun`.
*/
async function resolveFullOrigin(tabId: number, fallbackHostname: string): Promise<string> {
try {
const tab = await chrome.tabs.get(tabId);
if (tab.url) return new URL(tab.url).origin;
} catch {
// Tab gone or inaccessible between the run starting and this upload
// (e.g. auto-refresh racing a closing tab) — fall through.
}
return `https://${fallbackHostname}`;
}
/**
* Generates a fresh ephemeral keypair, uploads it under `runId`, and shows
* the resulting QR — the whole of Phase 1's work. Used both for the
@@ -99,13 +135,19 @@ async function uploadBundleAndDisplayQr(tabId: number, origin: string, features:
const uploadResult = await uploadRunBundle({
runId,
origin,
origin: await resolveFullOrigin(tabId, origin),
x25519_pubkey: base64UrlEncode(x25519Keys.publicKey),
kem_pubkey: base64UrlEncode(kemKeys.publicKey),
});
if (!uploadResult.ok) return false;
const { signed_token: qrContent, qr_ttl: qrTtlSeconds, max_auto_refresh: maxAutoRefresh, pin_ttl: pinTtlSeconds } = uploadResult.response;
const {
signed_token: qrContent,
qr_ttl: qrTtlSeconds,
max_auto_refresh: maxAutoRefresh,
pin_ttl: pinTtlSeconds,
relay_wait_ttl: relayWaitTtlSeconds,
} = uploadResult.response;
const existing = getRunSecrets(tabId);
const secrets: RunSecrets = {
runId,
@@ -114,6 +156,7 @@ async function uploadBundleAndDisplayQr(tabId: number, origin: string, features:
qrTtlSeconds,
maxAutoRefresh,
pinTtlSeconds,
relayWaitTtlSeconds,
autoRefreshRemaining: existing?.autoRefreshRemaining ?? maxAutoRefresh,
};
setRunSecrets(tabId, secrets);
@@ -150,11 +193,19 @@ async function handlePinTtlExpiry(tabId: number): Promise<void> {
await failRun(tabId, state.origin, state.features, 'pin_timeout', 'timeout_user');
}
/** relay_wait_ttl expired waiting for the credential (claude.md's phase_4 transitions). */
async function handleRelayWaitExpiry(tabId: number): Promise<void> {
const state = await getTabState(tabId);
if (state.kind !== 'phase_4') return; // stale alarm — credential already arrived or run ended
await failRun(tabId, state.origin, state.features, 'relay_timeout', 'network');
}
chrome.alarms.onAlarm.addListener((alarm) => {
const [prefix, tabIdStr] = alarm.name.split(':');
const tabId = Number(tabIdStr);
if (prefix === QR_ALARM_PREFIX) void handleQrTtlExpiry(tabId);
else if (prefix === PIN_ALARM_PREFIX) void handlePinTtlExpiry(tabId);
else if (prefix === RELAY_WAIT_ALARM_PREFIX) void handleRelayWaitExpiry(tabId);
});
async function handleKemCiphertext(tabId: number, origin: string, features: string[], payloadB64: string): Promise<void> {
@@ -196,13 +247,14 @@ async function processCredential(tabId: number, origin: string, features: string
return;
}
chrome.alarms.clear(relayWaitAlarmName(tabId));
closeRelay(tabId);
clearRunSecrets(tabId);
await setTabState(tabId, { kind: 'delivered', origin, features });
sendToSdk(tabId, { type: 'run_delivered', credential });
setTimeout(() => {
void setTabState(tabId, { kind: 'idle', origin, features });
void setTabState(tabId, { kind: 'idle', origin, features, sessionActive: getSessionActive(tabId) });
}, DELIVERED_DISPLAY_MS);
}
@@ -229,12 +281,14 @@ export async function confirmPin(tabId: number, origin: string, features: string
chrome.alarms.clear(pinAlarmName(tabId));
await setTabState(tabId, { kind: 'phase_4', origin, features });
const secrets = getRunSecrets(tabId);
if (secrets) scheduleRelayWaitAlarm(tabId, secrets.relayWaitTtlSeconds);
// Unlocks the companion, which is gated on this arriving before it will
// proceed past its own local pin_display (interfaces.md, "PIN
// confirmation"). Fire-and-forget: this side's own phase_4 transition
// above is already the real local gate and doesn't depend on this call.
const runId = getRunSecrets(tabId)?.runId;
if (runId) void postPinConfirmation(runId);
if (secrets) void postPinConfirmation(secrets.runId);
}
/** Popup action: user tapped Abort at any run phase, or the SDK sent `abort`. */
@@ -244,14 +298,15 @@ export async function abortRun(tabId: number, origin: string, features: string[]
/** Popup action: user dismissed a run_error screen — clears back to idle. */
export async function dismissRunError(tabId: number, origin: string, features: string[]): Promise<void> {
await setTabState(tabId, { kind: 'idle', origin, features });
await setTabState(tabId, { kind: 'idle', origin, features, sessionActive: getSessionActive(tabId) });
}
/** Tab closed mid-run (index.ts's chrome.tabs.onRemoved) — release everything a run held. */
/** Tab closed (index.ts's chrome.tabs.onRemoved) — release everything a run or verification held. */
export function cleanupRun(tabId: number): void {
closeRelay(tabId);
clearRunSecrets(tabId);
clearRunAlarms(tabId);
clearSessionActive(tabId);
}
async function failRun(
@@ -0,0 +1,20 @@
// Per-tab "does the site think it has an active session" hint, reported by
// the SDK's session_status message. Advisory only — see types.ts's
// SessionStatusMessage comment. In-memory only, same lifecycle as
// sdk-ports.ts's Port map: lost on service worker restart, which just
// means the popup shows the plain idle screen until the site re-reports
// (harmless — it's a UI hint, nothing depends on it surviving).
const sessionActiveByTab = new Map<number, boolean>();
export function setSessionActive(tabId: number, active: boolean): void {
sessionActiveByTab.set(tabId, active);
}
export function getSessionActive(tabId: number): boolean {
return sessionActiveByTab.get(tabId) ?? false;
}
export function clearSessionActive(tabId: number): void {
sessionActiveByTab.delete(tabId);
}
+28 -8
View File
@@ -93,14 +93,26 @@ function contentFor(state: TabState, origin: string): Content {
body: origin ? `${origin} hasn't set up sign-in with LOCQR.` : "This site hasn't set up sign-in with LOCQR.",
};
case 'idle':
return {
badgeClass: 'accent-tint',
iconColor: 'accent',
glyph: 'check',
heading: 'Ready to sign in',
body: `${state.origin} supports secure sign-in with LOCQR.`,
actions: [{ label: 'Sign in', kind: 'start_run', style: 'primary' }],
};
// sessionActive is an advisory hint from the site's own SDK
// call (types.ts's SessionStatusMessage) — it only changes the
// copy/badge here, never anything about how a run itself works.
return state.sessionActive
? {
badgeClass: 'green-tint',
iconColor: 'green',
glyph: 'check',
heading: 'Signed in',
body: `You're already signed in to ${state.origin}.`,
actions: [{ label: 'Sign in again', kind: 'start_run', style: 'primary' }],
}
: {
badgeClass: 'accent-tint',
iconColor: 'accent',
glyph: 'check',
heading: 'Ready to sign in',
body: `${state.origin} supports secure sign-in with LOCQR.`,
actions: [{ label: 'Sign in', kind: 'start_run', style: 'primary' }],
};
case 'account_error':
return state.reason === 'unreachable'
? {
@@ -353,4 +365,12 @@ chrome.storage.onChanged.addListener((_changes, areaName) => {
if (areaName === 'session') void refresh();
});
// Mitigates a known Linux/X11 quirk: a freshly-opened window doesn't
// always have real window-manager input focus yet, so its first click can
// be consumed as a focus-transfer rather than delivered to the page as a
// click — the popup visibly closes and the click never reaches any
// button. Explicitly focusing on load gives the window a chance to
// already be focused by the time a real click arrives.
window.focus();
void refresh();
+14 -2
View File
@@ -26,7 +26,18 @@ export interface AbortMessage {
type: 'abort';
}
export type SdkMessage = InitMessage | RequestCredentialMessage | AbortMessage;
/**
* Advisory only, never a security signal — the site telling the extension
* "I have (or don't have) an active session" only ever shapes what the
* popup's idle screen shows (extension/claude.md). It cannot skip or
* shortcut any part of the actual credential-delivery flow.
*/
export interface SessionStatusMessage {
type: 'session_status';
active: boolean;
}
export type SdkMessage = InitMessage | RequestCredentialMessage | AbortMessage | SessionStatusMessage;
// --- Extension -> SDK ---
@@ -106,6 +117,7 @@ export interface RunBundleUploadResponse {
qr_ttl: number;
max_auto_refresh: number;
pin_ttl: number;
relay_wait_ttl: number;
}
// --- Per-tab state (extension/claude.md's state model) ---
@@ -149,7 +161,7 @@ export type TabState =
| { kind: 'not_registered' }
| { kind: 'cert_invalid'; reason: CertInvalidReason; security: boolean }
| { kind: 'account_error'; reason: AccountErrorReason }
| { kind: 'idle'; origin: string; features: string[] }
| { kind: 'idle'; origin: string; features: string[]; sessionActive: boolean }
| { kind: 'phase_1'; origin: string; features: string[] }
| { kind: 'phase_2'; origin: string; features: string[]; qrContent: string; qrTtlSeconds: number; phaseStartedAt: number }
| { kind: 'phase_3'; origin: string; features: string[]; pin: string; pinTtlSeconds: number; phaseStartedAt: number }