From ec30880def7b9a2f5f7728ddae2eabfc83eec235 Mon Sep 17 00:00:00 2001 From: Maxim Raznatovski Date: Tue, 27 Oct 2026 13:04:30 +0100 Subject: [PATCH 1/7] fix: close the connection on out-of-sequence pairing messages A pairing message with no attempt running was always dropped silently, and server/pair-finalize was ignored in any phase without a pending PSK. --- src/core/pairing.ts | 23 ++++++++++++++---- tests/unit/pairing.test.ts | 49 ++++++++++++++++++++++++++++++++++---- 2 files changed, 62 insertions(+), 10 deletions(-) diff --git a/src/core/pairing.ts b/src/core/pairing.ts index 11223c2..2c2d190 100644 --- a/src/core/pairing.ts +++ b/src/core/pairing.ts @@ -135,6 +135,8 @@ export class PairingManager { /** The activation's spoken-PIN language preferences, in descending order. */ private languages: string[] | undefined; private failures: number; + /** Set once the client sends pair/abort, until the next server/activate. */ + private discardStray = false; constructor(private deps: PairingDeps) { if ( @@ -208,6 +210,7 @@ export class PairingManager { /** Called for every server/activate. */ onActivate(activities: string[], pairing?: ActivatePairing): void { + this.discardStray = false; const isPairing = activities.includes("pairing"); if (!isPairing) { // Non-pairing activate in place of pair-finalize = leave-pairing. @@ -292,8 +295,7 @@ export class PairingManager { /** server/pair-init: the server's nonce contribution (dynamic PIN). */ onPairInit(payload: { nonce_A?: string }): void { - // Leftover from an ended attempt (kept-open connection): discard silently. - if (this.phase === "idle") return; + if (this.phase === "idle") return this.strayMessage(); if (this.phase !== "await-init" || this.method !== "dynamic_pairing_code") { return this.fail(); } @@ -315,7 +317,7 @@ export class PairingManager { /** server/pair-auth: the server's CPace public share (both PIN methods). */ onPairAuth(payload: { pake_msg_1?: string }): void { - if (this.phase === "idle") return; // leftover from an ended attempt + if (this.phase === "idle") return this.strayMessage(); if (this.phase !== "await-auth" || !this.cpace) return this.fail(); const peerShare = this.decode(payload.pake_msg_1, SHARE_SIZE); if (!peerShare) return this.fail(); @@ -334,7 +336,7 @@ export class PairingManager { /** server/pair-confirm: verify the server's tag, then confirm and finalize. */ onPairConfirm(payload: { server_kc?: string }): void { - if (this.phase === "idle") return; // leftover from an ended attempt + if (this.phase === "idle") return this.strayMessage(); if (this.phase !== "await-confirm" || !this.cpace) return this.fail(); const serverKc = this.decode(payload.server_kc, TAG_SIZE); if (!serverKc) return this.fail(); @@ -359,7 +361,8 @@ export class PairingManager { } onPairFinalize(): void { - if (!this.pendingPsk) return; + if (this.phase === "idle") return this.strayMessage(); + if (this.phase !== "await-finalize" || !this.pendingPsk) return this.fail(); this.deps.pskStore.addLongTerm(this.pendingPsk, this.deps.serverId()); this.clearAttempt(); this.deps.onEvent?.("finalized"); @@ -379,6 +382,7 @@ export class PairingManager { /** Discard any in-flight pairing state and the activate counter (on handshake/close). */ reset(): void { this.clearAttempt(); + this.discardStray = false; this.pairingActivateCount = 0; this.attemptIndex = 0; } @@ -471,6 +475,7 @@ export class PairingManager { */ private abort(reason: PairAbortReason): void { this.clearAttempt(); + this.discardStray = true; this.deps.sendControl({ type: "pair/abort", payload: { reason } }); this.deps.onEvent?.("aborted", reason); if (reason === "concurrent_attempt") this.deps.close(); @@ -482,6 +487,14 @@ export class PairingManager { this.deps.close(); } + /** + * A pairing message with no attempt running. Messages still in flight after + * the client's own pair/abort are discarded, anything else is out of sequence. + */ + private strayMessage(): void { + if (!this.discardStray) this.fail(); + } + private clearAttempt(): void { if (this.attemptTimer) clearTimeout(this.attemptTimer); this.attemptTimer = null; diff --git a/tests/unit/pairing.test.ts b/tests/unit/pairing.test.ts index 230d6a9..026c176 100644 --- a/tests/unit/pairing.test.ts +++ b/tests/unit/pairing.test.ts @@ -222,11 +222,13 @@ describe("PairingManager (pairing_psk)", () => { }); it("discards the pending PSK on leave-pairing (non-pairing activate)", () => { - const { store, sent, mgr } = setup(); + const { store, sent, close, mgr } = setup(); mgr.onActivate(["pairing"], { method: "pairing_psk" }); const fin = sent[0] as { payload: { long_term_psk: string } }; mgr.onActivate(["playback"]); // leave pairing without finalize - mgr.onPairFinalize(); // must be a no-op now + // The server left pairing itself, so a later server/pair-finalize is out of sequence. + mgr.onPairFinalize(); + expect(close).toHaveBeenCalled(); expect( store.lookup(pskId(base64urlDecode(fin.payload.long_term_psk))), ).toBeNull(); @@ -620,14 +622,51 @@ describe("PairingManager (dynamic_pairing_code)", () => { ).toBe(2); }); - it("silently discards a stray pairing message after the attempt ended", () => { + it("fails closed on server/pair-finalize before the client finalized", () => { + const ctx = runToConfirm(); + ctx.mgr.onPairFinalize(); + expect(ctx.close).toHaveBeenCalled(); + }); + + it("fails closed on a pairing message when no attempt ran", () => { + const ctx = setup({ category: "sentinel", onPairingCode: vi.fn() }); + ctx.mgr.onPairAuth({ pake_msg_1: base64urlEncode(new Uint8Array(32)) }); + expect(ctx.close).toHaveBeenCalled(); + }); + + it.each([ + [ + "server/pair-init", + (mgr: PairingManager) => + mgr.onPairInit({ nonce_A: base64urlEncode(new Uint8Array(32)) }), + ], + [ + "server/pair-auth", + (mgr: PairingManager) => + mgr.onPairAuth({ pake_msg_1: base64urlEncode(new Uint8Array(32)) }), + ], + [ + "server/pair-confirm", + (mgr: PairingManager) => + mgr.onPairConfirm({ server_kc: base64urlEncode(new Uint8Array(64)) }), + ], + ["server/pair-finalize", (mgr: PairingManager) => mgr.onPairFinalize()], + ])("silently discards a stray %s after the client aborted", (_type, send) => { const ctx = setup({ category: "sentinel", onPairingCode: vi.fn() }); ctx.mgr.onActivate(["pairing"], dynamic()); ctx.mgr.cancelPairing(); // attempt ends, connection stays open - // A late server/pair-auth for the ended attempt is ignored, not fatal. - ctx.mgr.onPairAuth({ pake_msg_1: base64urlEncode(new Uint8Array(32)) }); + send(ctx.mgr); expect(ctx.close).not.toHaveBeenCalled(); }); + + it("stops discarding stray pairing messages at the next server/activate", () => { + const ctx = setup({ category: "sentinel", onPairingCode: vi.fn() }); + ctx.mgr.onActivate(["pairing"], dynamic()); + ctx.mgr.cancelPairing(); + ctx.mgr.onActivate(["playback"]); + ctx.mgr.onPairAuth({ pake_msg_1: base64urlEncode(new Uint8Array(32)) }); + expect(ctx.close).toHaveBeenCalled(); + }); }); describe("PairingManager (static_pairing_code)", () => { From 97ad6a89fe82c00b028c9ae866bacac75be309d3 Mon Sep 17 00:00:00 2001 From: Maxim Raznatovski Date: Tue, 27 Oct 2026 13:09:38 +0100 Subject: [PATCH 2/7] fix!: retry dynamic pairing code rounds up to the round limit A mistyped dynamic pairing code ended the whole attempt. After 10 failures every attempt needed the pairing window, the gesture never reset the count, and rounds that ended without a server_kc were not counted. BREAKING CHANGE: `isDynamicPinEscalated()` is now `isRoundLimitReached()`, and `releasePairingHold()` replaces `openPairingWindow()` for releasing dynamic pairing code attempts. --- CLAUDE.md | 2 +- README.md | 22 +-- index.html | 22 +-- public/app.js | 27 ++-- src/core/core.ts | 16 +- src/core/pairing.ts | 144 +++++++++++------- src/index.ts | 20 ++- src/types.ts | 17 ++- tests/e2e/sendspin-security.e2e.test.ts | 68 +++------ tests/helpers/aiosendspin-server.ts | 3 +- tests/helpers/sendspin-server.py | 10 +- tests/unit/pairing.test.ts | 189 ++++++++++++++---------- 12 files changed, 310 insertions(+), 230 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index fa97e83..8e57dcc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -76,7 +76,7 @@ Encryption and pairing options: - `suite`: Noise cipher suite, "chacha" (default) or "aesgcm" - `unpairedAccess`: Admit unpaired playback on the Sentinel PSK - `longTermPsks`: Preloaded long-term PSK records -- `storage`: Backing store for identity, PSKs, and pairing failure counters +- `storage`: Backing store for identity, PSKs, and the pairing round count - `onPairing`: Pairing lifecycle callback - `onPairingCode`: Enables the dynamic pairing code method, receives the derived code - `staticPairingCode`: Enables the static pairing code method with a fixed 8-digit code diff --git a/README.md b/README.md index 53760ce..0a16b56 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ const player = new SendspinPlayer({ ], onPairing: (event, detail) => { // event: "pending" | "started" | "finalized" | "aborted" - // "pending" means the attempt is waiting for openPairingWindow(). + // "pending" means the attempt is waiting for openPairingWindow() or releasePairingHold(). console.log('Pairing:', event, detail); }, // Dynamic pairing: show the derived code to the operator (null = hide). @@ -207,17 +207,18 @@ The SDK supports all three pairing methods from the spec: - **Pairing PSK** (always available): transfer the client-bound pairing token. - **Dynamic pairing code** (enabled by `onPairingCode`): the server starts pairing, the SDK derives a one-time code and passes it to `onPairingCode` for - display, and the operator enters it into the server. + display, and the operator enters it into the server. After a wrong entry the + SDK asks the server for another round and passes the same code again. - **Static pairing code** (enabled by `staticPairingCode`): the operator enters this device's fixed 8-digit code into the server, then makes a local gesture that calls `player.openPairingWindow()` (window lasts ~5 minutes, one attempt). -Some attempts are **gesture-gated**: the SDK withholds `client/pair-init` until -`openPairingWindow()` is called, signalling `client/pair-pending` meanwhile and -firing `onPairing("pending")`. That applies to every static pairing code -attempt, and to dynamic pairing code attempts when the method has escalated. -Ten consecutive dynamic pairing code failures escalate the method, and any -later success de-escalates it. +Some attempts are **held back**: the SDK withholds `client/pair-init`, +signalling `client/pair-pending` meanwhile and firing `onPairing("pending")`. +Every static pairing code attempt waits for `openPairingWindow()`. After 20 +failed dynamic pairing code rounds without a success, dynamic pairing code +attempts wait for `releasePairingHold()`, which also resets the count. Call it +only on a deliberate action on the device. ```typescript console.log('Client ID:', player.clientId); // 43-char base64url pubkey @@ -226,9 +227,10 @@ console.log('Pairing token:', player.pairingToken); // spec version 0 // Rotate the Pairing PSK (e.g. if it may have leaked) const newPsk = player.rotatePairingPsk(); -player.openPairingWindow(); // operator gesture for a gated attempt +player.openPairingWindow(); // operator gesture for a static code attempt +player.releasePairingHold(); // operator action after the round limit player.cancelPairing(); // abort an in-progress attempt -player.isDynamicPinEscalated(); // gesture-gated after 10 failures +player.isRoundLimitReached(); // held back after 20 failed rounds ``` Pairing requires a server speaking the current specification. A non-compliant diff --git a/index.html b/index.html index c147e96..45b328c 100644 --- a/index.html +++ b/index.html @@ -364,14 +364,15 @@

Pairing

>
- - - + + - + After 10 failed attempts every dynamic pairing attempt needs a - gesture, until one succeeds.After 20 rounds without a correct code dynamic pairing waits + until the operator releases it, which also resets the count.
diff --git a/public/app.js b/public/app.js index dc2539b..1dec9af 100644 --- a/public/app.js +++ b/public/app.js @@ -81,7 +81,8 @@ const pairingPskLocationInputs = document.querySelectorAll( ); const pinSpeakerInput = document.getElementById("pin-speaker"); const openPairingWindowBtn = document.getElementById("open-pairing-window"); -const pinEscalatedEl = document.getElementById("pin-escalated"); +const roundLimitEl = document.getElementById("round-limit"); +const releasePairingHoldBtn = document.getElementById("release-pairing-hold"); // Status elements const connectionStatus = document.getElementById("connection-status"); @@ -246,7 +247,7 @@ function resetStatusDisplay() { pairingPinGroup.hidden = true; pairingPendingGroup.hidden = true; pairingPinEl.textContent = "-"; - pinEscalatedEl.textContent = "-"; + roundLimitEl.textContent = "-"; } /** @@ -255,7 +256,7 @@ function resetStatusDisplay() { function updatePairingDisplay() { clientIdEl.textContent = player.clientId; pairingTokenEl.textContent = player.pairingToken; - updateEscalationDisplay(); + updateRoundLimitDisplay(); } function isValidStaticPin(pin) { @@ -272,11 +273,11 @@ function selectedLocations(inputs) { } /** - * Show whether dynamic PIN has escalated to gesture-gating. + * Show whether dynamic pairing is held back at the round limit. */ -function updateEscalationDisplay() { +function updateRoundLimitDisplay() { if (!player) return; - pinEscalatedEl.textContent = player.isDynamicPinEscalated() ? "yes" : "no"; + roundLimitEl.textContent = player.isRoundLimitReached() ? "yes" : "no"; } /** @@ -286,8 +287,8 @@ function onPairing(event, detail) { console.log("Pairing event:", event, detail ?? ""); pairingPendingGroup.hidden = event !== "pending"; if (event === "pending") { - trustLevelEl.textContent = "awaiting gesture..."; - showToast("Pairing needs the window opened", "info"); + trustLevelEl.textContent = "awaiting operator..."; + showToast("Pairing needs an operator action", "info"); } else if (event === "started") { trustLevelEl.textContent = "pairing..."; } else if (event === "finalized") { @@ -297,7 +298,7 @@ function onPairing(event, detail) { trustLevelEl.textContent = `aborted (${detail ?? "unknown"})`; showToast(`Pairing aborted: ${detail ?? "unknown"}`, "error"); } - updateEscalationDisplay(); + updateRoundLimitDisplay(); } /** @@ -1093,6 +1094,14 @@ function init() { player.openPairingWindow(); showToast("Pairing window open (~5 minutes, one attempt)", "info"); }); + releasePairingHoldBtn.addEventListener("click", () => { + if (!player) { + showToast("Connect first", "error"); + return; + } + player.releasePairingHold(); + updateRoundLimitDisplay(); + }); cancelPairingBtn.addEventListener("click", () => { if (!player) return; player.cancelPairing(); diff --git a/src/core/core.ts b/src/core/core.ts index 18ae1b4..d74c25c 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -69,7 +69,7 @@ export class SendspinCore implements StreamHandler { constructor(config: SendspinCoreConfig) { if (!config.storage) { console.warn( - "Sendspin: no storage provided, so the identity, Pairing PSK, paired servers and pairing failure count are kept in memory only and reset on reload.", + "Sendspin: no storage provided, so the identity, Pairing PSK, paired servers and pairing round count are kept in memory only and reset on reload.", ); } this.identity = Identity.loadOrCreate(config.storage ?? null); @@ -522,8 +522,7 @@ export class SendspinCore implements StreamHandler { /** * Operator gesture that opens the pairing window (~5 minutes, admits one - * attempt). Required before each gesture-gated attempt: every static - * pairing code attempt, and dynamic pairing code ones when escalated. + * attempt). Required before each static pairing code attempt. */ openPairingWindow(): void { this.pairing.openPairingWindow(); @@ -534,9 +533,14 @@ export class SendspinCore implements StreamHandler { this.pairing.cancelPairing(); } - /** Whether dynamic pairing code has escalated to gesture-gating (10 failures). */ - isDynamicPinEscalated(): boolean { - return this.pairing.isDynamicPinEscalated(); + /** Operator action that releases dynamic pairing code attempts held back at the round limit. */ + releasePairingHold(): void { + this.pairing.releasePairingHold(); + } + + /** Whether dynamic pairing code attempts are held back at the 20-round limit. */ + isRoundLimitReached(): boolean { + return this.pairing.isRoundLimitReached(); } get timeSyncInfo(): { synced: boolean; offset: number; error: number } { diff --git a/src/core/pairing.ts b/src/core/pairing.ts index 2c2d190..1fb3be4 100644 --- a/src/core/pairing.ts +++ b/src/core/pairing.ts @@ -35,8 +35,6 @@ function concatBytes(...parts: Uint8Array[]): Uint8Array { /** CPace session-id label. sid = label || Noise handshake hash || counter || round. */ const PAKE_SID_LABEL = "sendspin-pair-pake-v1"; -/** This client never asks for another round, so every attempt runs round 1 only. */ -const PAKE_ROUND = 1; /** Labels for the keys that wrap the PSK and nonce_B in code pairing (Wrapping). */ const PSK_WRAP_LABEL = utf8("sendspin-pair-psk-wrap-v1"); const NONCE_WRAP_LABEL = utf8("sendspin-pair-nonce-wrap-v1"); @@ -47,12 +45,12 @@ const CPACE_AD_B = utf8("client"); const ATTEMPT_TIMEOUT_MS = 120_000; /** Lifetime of an open pairing window, from the gesture until client/pair-init. */ const WINDOW_LIFETIME_MS = 300_000; -/** Dynamic PIN escalates to gesture-gating at this many consecutive failures. */ -const ESCALATION_THRESHOLD = 10; -/** Persisted PIN failure counter (dynamic PIN only, not partitioned by server). */ -const FAILURES_STORAGE_KEY = "sendspin-pair-failures"; -/** Field of the stored failure counter, kept as earlier releases wrote it. */ -const FAILURES_FIELD = "dynamic_pin"; +/** Rounds since the last verified server_kc that hold dynamic attempts back. */ +const ROUND_LIMIT = 20; +/** Persisted round count (dynamic pairing code only, not partitioned by server). */ +const ROUNDS_STORAGE_KEY = "sendspin-pair-failures"; +/** Field of the stored round count, kept as earlier releases wrote it. */ +const ROUNDS_FIELD = "dynamic_pin"; const CODE_METHODS: readonly PairMethod[] = [ "dynamic_pairing_code", @@ -76,9 +74,9 @@ function readLanguages(value: unknown): string[] | undefined { type Phase = | "idle" - /** Gesture-gated: client/pair-pending sent, waiting for the operator's gesture. */ - | "await-window" - /** Dynamic PIN: client/pair-init sent, awaiting server/pair-init. */ + /** Held back: client/pair-pending sent, waiting for the operator. */ + | "held-back" + /** Dynamic pairing code: awaiting server/pair-init, which begins a round. */ | "await-init" /** Awaiting server/pair-auth (the server's CPace share). */ | "await-auth" @@ -101,7 +99,7 @@ export interface PairingDeps { * empty AD). key is K_wrap. Returns the 48-byte wrapped value. */ aeadSeal(key: Uint8Array, plaintext: Uint8Array): Uint8Array; - /** Persists the dynamic-PIN failure counter. Null = in-memory only. */ + /** Persists the dynamic pairing code round count. Null = in-memory only. */ storage: SendspinStorage | null; /** Enables dynamic_pairing_code: surfaces the code (null = attempt ended, hide it). */ onPairingCode: ((code: string | null, languages?: string[]) => void) | null; @@ -134,7 +132,12 @@ export class PairingManager { private attemptIndex = 0; /** The activation's spoken-PIN language preferences, in descending order. */ private languages: string[] | undefined; - private failures: number; + /** The dynamic pairing code of the current attempt, derived in its first round. */ + private code: string | null = null; + /** The current round of the attempt, 0 before its first server/pair-init. */ + private round = 0; + /** Dynamic pairing code rounds since the last verified server_kc, persisted. */ + private rounds: number; /** Set once the client sends pair/abort, until the next server/activate. */ private discardStray = false; @@ -145,7 +148,7 @@ export class PairingManager { ) { throw new Error("staticPairingCode must be exactly 8 decimal digits"); } - this.failures = this.loadFailures(); + this.rounds = this.loadRounds(); } /** The pairing methods to advertise in client/hello. */ @@ -168,12 +171,23 @@ export class PairingManager { } /** - * Whether dynamic PIN has escalated to gesture-gating (spec: 10 failures). - * Escalation is not an error state: the method stays offered, and every - * attempt needs openPairingWindow() until a successful round de-escalates it. + * Whether dynamic pairing code attempts are held back at the round limit. + * The method stays offered, and attempts wait for releasePairingHold(). */ - isDynamicPinEscalated(): boolean { - return this.failures >= ESCALATION_THRESHOLD; + isRoundLimitReached(): boolean { + return this.rounds >= ROUND_LIMIT; + } + + /** + * Operator action that releases dynamic pairing code attempts held back at + * the round limit and resets the round count. Has no effect while an + * attempt is running. + */ + releasePairingHold(): void { + if (!this.isRoundLimitReached()) return; + if (this.phase !== "idle" && this.phase !== "held-back") return; + this.resetRounds(); + if (this.phase === "held-back" && !this.isHeldBack()) this.startAttempt(); } /** @@ -182,7 +196,7 @@ export class PairingManager { * one attempt within its lifetime (~5 minutes). */ openPairingWindow(): void { - if (this.phase === "await-window") { + if (this.phase === "held-back" && this.method === "static_pairing_code") { this.startAttempt(); return; } @@ -268,8 +282,8 @@ export class PairingManager { } this.languages = readLanguages(pairing.languages); } - if (this.isGestureGated() && !this.windowOpen) { - this.phase = "await-window"; + if (this.isHeldBack()) { + this.phase = "held-back"; // pair-pending does not start the attempt, so no attempt timer runs. The // server bounds the wait and cancels with a non-pairing server/activate. this.deps.sendControl({ @@ -283,36 +297,42 @@ export class PairingManager { } /** - * Whether the selected method withholds client/pair-init until a window is - * open: static pairing code always, dynamic pairing code when escalated. + * Whether the selected method withholds client/pair-init: static pairing + * code until a window is open, dynamic pairing code at the round limit. */ - private isGestureGated(): boolean { - if (this.method === "static_pairing_code") return true; - return ( - this.method === "dynamic_pairing_code" && this.isDynamicPinEscalated() - ); + private isHeldBack(): boolean { + if (this.method === "static_pairing_code") return !this.windowOpen; + return this.method === "dynamic_pairing_code" && this.isRoundLimitReached(); } - /** server/pair-init: the server's nonce contribution (dynamic PIN). */ + /** server/pair-init: begins a round, carrying the server's nonce in the first. */ onPairInit(payload: { nonce_A?: string }): void { if (this.phase === "idle") return this.strayMessage(); if (this.phase !== "await-init" || this.method !== "dynamic_pairing_code") { return this.fail(); } - const nonceA = this.decode(payload.nonce_A, NONCE_SIZE); - if (!nonceA) return this.fail(); const h = this.deps.handshakeHash(); - const pin = derivePairingCode(h, nonceA, this.nonceB!); - this.currentSid = this.sid(h, this.attemptIndex); + if (this.round === 0) { + const nonceA = this.decode(payload.nonce_A, NONCE_SIZE); + if (!nonceA) return this.fail(); + this.code = derivePairingCode(h, nonceA, this.nonceB!); + } else if (payload.nonce_A !== undefined) { + return this.fail(); + } + this.round += 1; + // Count the round before the code is shown, so an emitted code always counts. + this.rounds += 1; + this.saveRounds(); + this.currentSid = this.sid(h, this.attemptIndex, this.round); this.cpace = CPace.start({ role: "responder", - prs: new TextEncoder().encode(pin), + prs: new TextEncoder().encode(this.code!), sid: this.currentSid, ada: CPACE_AD_A, adb: CPACE_AD_B, }); this.phase = "await-auth"; - this.deps.onPairingCode?.(pin, this.languages); + this.deps.onPairingCode?.(this.code, this.languages); } /** server/pair-auth: the server's CPace public share (both PIN methods). */ @@ -341,11 +361,16 @@ export class PairingManager { const serverKc = this.decode(payload.server_kc, TAG_SIZE); if (!serverKc) return this.fail(); if (!this.cpace.verify(serverKc)) { - if (this.method === "dynamic_pairing_code") this.recordFailure(); + if ( + this.method === "dynamic_pairing_code" && + !this.isRoundLimitReached() + ) { + return this.retry(); + } return this.abort("pairing_code_mismatch"); } // Reset on a verified server_kc, whether or not the attempt finalizes. - if (this.method === "dynamic_pairing_code") this.resetFailures(); + if (this.method === "dynamic_pairing_code") this.resetRounds(); const confirm: { client_kc: string; wrapped_nonce_B?: string } = { client_kc: base64urlEncode(this.cpace.tag()), }; @@ -406,7 +431,7 @@ export class PairingManager { return; } const h = this.deps.handshakeHash(); - this.currentSid = this.sid(h, this.attemptIndex); + this.currentSid = this.sid(h, this.attemptIndex, 1); this.cpace = CPace.start({ role: "responder", prs: new TextEncoder().encode(this.deps.staticPairingCode!), @@ -421,6 +446,14 @@ export class PairingManager { }); } + /** Ask for another round, keeping the attempt, its code and its timer. */ + private retry(): void { + this.cpace = null; + this.currentSid = null; + this.phase = "await-init"; + this.deps.sendControl({ type: "client/pair-retry", payload: {} }); + } + /** Mint the long-term PSK and send client/pair-finalize. */ private sendFinalize(): void { // A Sendspin PSK must be a 32-byte CSPRNG value, not a clamped X25519 private key. @@ -449,7 +482,11 @@ export class PairingManager { return this.deps.aeadSeal(kWrap, value); } - private sid(handshakeHash: Uint8Array, index: number): Uint8Array { + private sid( + handshakeHash: Uint8Array, + index: number, + round: number, + ): Uint8Array { const label = utf8(PAKE_SID_LABEL); const offset = label.length + handshakeHash.length; const sid = new Uint8Array(offset + 8); @@ -458,7 +495,7 @@ export class PairingManager { // counter and round: big-endian uint32 each. const view = new DataView(sid.buffer); view.setUint32(offset, index, false); - view.setUint32(offset + 4, PAKE_ROUND, false); + view.setUint32(offset + 4, round, false); return sid; } @@ -507,6 +544,8 @@ export class PairingManager { this.cpace = null; this.currentSid = null; this.nonceB = null; + this.code = null; + this.round = 0; this.languages = undefined; } @@ -531,31 +570,26 @@ export class PairingManager { } } - private loadFailures(): number { + private loadRounds(): number { try { - const raw = this.deps.storage?.getItem(FAILURES_STORAGE_KEY); + const raw = this.deps.storage?.getItem(ROUNDS_STORAGE_KEY); if (!raw) return 0; const stored = JSON.parse(raw) as Record; - return stored[FAILURES_FIELD] ?? 0; + return stored[ROUNDS_FIELD] ?? 0; } catch { return 0; } } - private saveFailures(): void { + private saveRounds(): void { this.deps.storage?.setItem( - FAILURES_STORAGE_KEY, - JSON.stringify({ [FAILURES_FIELD]: this.failures }), + ROUNDS_STORAGE_KEY, + JSON.stringify({ [ROUNDS_FIELD]: this.rounds }), ); } - private recordFailure(): void { - this.failures += 1; - this.saveFailures(); - } - - private resetFailures(): void { - this.failures = 0; - this.saveFailures(); + private resetRounds(): void { + this.rounds = 0; + this.saveRounds(); } } diff --git a/src/index.ts b/src/index.ts index d95a84d..2088e14 100644 --- a/src/index.ts +++ b/src/index.ts @@ -353,8 +353,7 @@ export class SendspinPlayer { * Allows one pairing attempt in the next 5 minutes. * Call it only when the user presses a pairing button on the device, never * because the server asked. - * Static code pairing always needs it. Dynamic code pairing needs it after - * 10 failed attempts. + * Static code pairing always needs it. * onPairing("pending") fires while an attempt waits for it. */ openPairingWindow(): void { @@ -366,9 +365,20 @@ export class SendspinPlayer { this.core.cancelPairing(); } - /** Whether dynamic pairing code has escalated to gesture-gating (10 failures). */ - isDynamicPinEscalated(): boolean { - return this.core.isDynamicPinEscalated(); + /** + * Releases dynamic code pairing after 20 rounds without a correct code and + * resets the count. + * Call it only when the user acts on the device, never because the server + * asked. It has no effect while an attempt is running. + * onPairing("pending") fires while an attempt waits for it. + */ + releasePairingHold(): void { + this.core.releasePairingHold(); + } + + /** Whether dynamic code pairing is held back after 20 rounds without a correct code. */ + isRoundLimitReached(): boolean { + return this.core.isRoundLimitReached(); } // Get current correction mode diff --git a/src/types.ts b/src/types.ts index 64217bd..a9e69b5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -25,6 +25,7 @@ export enum MessageType { SERVER_PAIR_AUTH = "server/pair-auth", CLIENT_PAIR_AUTH = "client/pair-auth", SERVER_PAIR_CONFIRM = "server/pair-confirm", + CLIENT_PAIR_RETRY = "client/pair-retry", CLIENT_PAIR_CONFIRM = "client/pair-confirm", CLIENT_PAIR_FINALIZE = "client/pair-finalize", SERVER_PAIR_FINALIZE = "server/pair-finalize", @@ -329,7 +330,8 @@ export interface ClientPairInit { export interface ServerPairInit { type: MessageType.SERVER_PAIR_INIT; - payload: { nonce_A: string }; + /** nonce_A is present in the first round only. */ + payload: { nonce_A?: string }; } export interface ServerPairAuth { @@ -347,6 +349,11 @@ export interface ServerPairConfirm { payload: { server_kc: string }; } +export interface ClientPairRetry { + type: MessageType.CLIENT_PAIR_RETRY; + payload: Record; +} + export interface ClientPairConfirm { type: MessageType.CLIENT_PAIR_CONFIRM; /** wrapped_nonce_B (sealed preimage of commit_B) is present in dynamic pairing only. */ @@ -640,7 +647,7 @@ export interface SendspinCoreConfig { /** * Storage for persisting SDK state: the identity key, the Pairing PSK, - * paired server keys, the pairing failure count, cached output latency and + * paired server keys, the pairing round count, cached output latency and * the server-commanded output delay. Keys are stored as plain text. * SendspinCore persists only when this is provided. SendspinPlayer defaults * it to localStorage. Pass null to disable persistence. @@ -719,7 +726,7 @@ export interface SendspinCoreConfig { /** * Callback for pairing lifecycle events. "pending" means the attempt is - * gesture-gated and waiting for openPairingWindow(). + * held back, waiting for openPairingWindow() or releasePairingHold(). */ onPairing?: ( event: "pending" | "started" | "finalized" | "aborted", @@ -729,7 +736,9 @@ export interface SendspinCoreConfig { /** * Setting it turns on dynamic code pairing. * Called with a code to show or speak to the operator, who enters it on the - * server. Called with null when the attempt ends, so hide the code then. + * server. Called again with the same code in each new round after a wrong + * entry, so speak it again then. + * Called with null when the attempt ends, so hide the code then. * languages lists the operator's preferred languages for speaking it, most * preferred first, if the server sent any. * Avoid setting both this and staticPairingCode. diff --git a/tests/e2e/sendspin-security.e2e.test.ts b/tests/e2e/sendspin-security.e2e.test.ts index ea9da3d..510d710 100644 --- a/tests/e2e/sendspin-security.e2e.test.ts +++ b/tests/e2e/sendspin-security.e2e.test.ts @@ -7,6 +7,7 @@ import type { SuiteId } from "../../src/core/noise/suites"; import { AiosendspinServer, reportDeferredViolations, + type CodeWaitResult, type PairingResult, } from "../helpers/aiosendspin-server"; @@ -164,12 +165,14 @@ function wrongPin(pin: string): string { } function expectPairingResult( - result: PairingResult, + result: CodeWaitResult, status: PairingResult["status"], reason?: string, -): void { +): asserts result is PairingResult { expect(result.status, JSON.stringify(result)).toBe(status); - if (reason !== undefined) expect(result.reason).toBe(reason); + if (reason !== undefined) { + expect((result as PairingResult).reason).toBe(reason); + } } describe("Sendspin encryption and pairing E2E (aiosendspin)", () => { @@ -417,13 +420,11 @@ describe("Sendspin encryption and pairing E2E (aiosendspin)", () => { connection.core.setVolume(42); await new Promise((resolve) => setTimeout(resolve, 5_200)); expect(connection.socket.readyState).toBe(WebSocket.OPEN); + // A wrong code starts another round of the same attempt, with the same code. const first = await server.submitCode(wrongPin(pins[0])); - expectPairingResult(first, "aborted", "pairing_code_mismatch"); - expect(connection.socket.readyState).toBe(WebSocket.OPEN); - - await server.beginCodePairing("dynamic_pairing_code"); - expect((await server.waitForCodeRequest()).status).toBe("code_requested"); + expect(first.status, JSON.stringify(first)).toBe("code_requested"); await waitFor(() => pins.length === 2); + expect(pins[1]).toBe(pins[0]); const second = await server.submitCode(pins[1]); expectPairingResult(second, "success"); expect(second.connected).toBe(true); @@ -445,54 +446,31 @@ describe("Sendspin encryption and pairing E2E (aiosendspin)", () => { ); it( - "escalates Dynamic PIN to gesture-gating after ten mismatches", + "holds Dynamic PIN back at the round limit until released", async () => { const storage = memoryStorage(); + storage.setItem( + "sendspin-pair-failures", + JSON.stringify({ dynamic_pin: 20 }), + ); const pins: string[] = []; - const collectPin = (pin: string | null) => { - if (pin !== null) pins.push(pin); - }; const connection = await connect({ - clientName: "Dynamic PIN escalation client", + clientName: "Dynamic PIN round limit client", storage, - onPairingCode: collectPin, + onPairingCode: (pin) => { + if (pin !== null) pins.push(pin); + }, }); + expect(connection.core.isRoundLimitReached()).toBe(true); - for (let attempt = 0; attempt < 10; attempt++) { - await server.beginCodePairing("dynamic_pairing_code"); - expect((await server.waitForCodeRequest()).status).toBe( - "code_requested", - ); - await waitFor(() => pins.length === attempt + 1); - const result = await server.submitCode(wrongPin(pins[attempt])); - expectPairingResult(result, "aborted", "pairing_code_mismatch"); - } - expect(connection.core.isDynamicPinEscalated()).toBe(true); - expect(await server.hasPairingRecord(connection.core.clientId)).toBe( - false, - ); - - connection.core.disconnect(); - connection.socket.close(); - await waitForClose(connection.socket); - const reconnected = await connect({ - clientName: "Dynamic PIN escalation client", - storage, - onPairingCode: collectPin, - }); - // The counter survived the reconnect, so the method stays escalated: the - // client withholds pair-init until the operator opens the window. - expect(reconnected.core.isDynamicPinEscalated()).toBe(true); await server.beginCodePairing("dynamic_pairing_code"); expect((await server.waitForCodeRequest(200)).status).toBe("timeout"); - expect(reconnected.socket.readyState).toBe(WebSocket.OPEN); + expect(connection.socket.readyState).toBe(WebSocket.OPEN); - reconnected.core.openPairingWindow(); + connection.core.releasePairingHold(); expect((await server.waitForCodeRequest()).status).toBe("code_requested"); - await waitFor(() => pins.length === 11); - expectPairingResult(await server.submitCode(pins[10]), "success"); - // A verified round de-escalates the method. - expect(reconnected.core.isDynamicPinEscalated()).toBe(false); + await waitFor(() => pins.length === 1); + expectPairingResult(await server.submitCode(pins[0]), "success"); }, TEST_TIMEOUT_MS, ); diff --git a/tests/helpers/aiosendspin-server.ts b/tests/helpers/aiosendspin-server.ts index 843b909..b5c9e8f 100644 --- a/tests/helpers/aiosendspin-server.ts +++ b/tests/helpers/aiosendspin-server.ts @@ -320,7 +320,8 @@ export class AiosendspinServer { ); } - submitCode(code: string): Promise { + /** Resolves with the attempt's result, code_requested when the server begins another round, or timeout. */ + submitCode(code: string): Promise { return this.sendCommand("submit_code", { code }, 35_000); } diff --git a/tests/helpers/sendspin-server.py b/tests/helpers/sendspin-server.py index 420a269..43a5ce9 100644 --- a/tests/helpers/sendspin-server.py +++ b/tests/helpers/sendspin-server.py @@ -252,12 +252,13 @@ async def begin_code_pairing(self, method_name: str) -> dict[str, Any]: method = PairMethod(method_name) if method not in (PairMethod.DYNAMIC_PAIRING_CODE, PairMethod.STATIC_PAIRING_CODE): raise ValueError("code pairing requires dynamic_pairing_code or static_pairing_code") - self.code_future = asyncio.get_running_loop().create_future() + self.code_future = None self.code_requested = asyncio.Event() + # Called once per round, so each round waits for its own submitted code. async def provide_code() -> str: assert self.code_requested is not None - assert self.code_future is not None + self.code_future = asyncio.get_running_loop().create_future() self.code_requested.set() return await self.code_future @@ -302,11 +303,12 @@ async def wait_for_code_request(self, timeout_ms: int) -> dict[str, Any]: await waiter async def submit_code(self, code: str) -> dict[str, Any]: - if self.code_task is None or self.code_future is None: + if self.code_task is None or self.code_future is None or self.code_requested is None: raise RuntimeError("no pairing code attempt is running") if not self.code_future.done(): self.code_future.set_result(code) - return await self._finish_code_attempt() + self.code_requested.clear() + return await self.wait_for_code_request(30_000) async def _finish_code_attempt(self) -> dict[str, Any]: assert self.code_task is not None diff --git a/tests/unit/pairing.test.ts b/tests/unit/pairing.test.ts index 026c176..ae018d1 100644 --- a/tests/unit/pairing.test.ts +++ b/tests/unit/pairing.test.ts @@ -37,15 +37,15 @@ function concatBytes(...parts: Uint8Array[]): Uint8Array { return out; } -// CPace sid = label || h || big-endian uint32 attempt counter || uint32 round 1. -function sidFor(index: number): Uint8Array { +// CPace sid = label || h || big-endian uint32 attempt counter || uint32 round. +function sidFor(index: number, round = 1): Uint8Array { const label = utf8("sendspin-pair-pake-v1"); const sid = new Uint8Array(label.length + HANDSHAKE_HASH.length + 8); sid.set(label, 0); sid.set(HANDSHAKE_HASH, label.length); const view = new DataView(sid.buffer); view.setUint32(label.length + HANDSHAKE_HASH.length, index, false); - view.setUint32(label.length + HANDSHAKE_HASH.length + 4, 1, false); + view.setUint32(label.length + HANDSHAKE_HASH.length + 4, round, false); return sid; } @@ -128,11 +128,11 @@ function dynamic(languages?: string[]): ActivatePairing { } /** Drive the server (initiator) side of a PIN PAKE against the manager. */ -function serverPake(pin: string, index = 1) { +function serverPake(pin: string, index = 1, round = 1) { return CPace.start({ role: "initiator", prs: utf8(pin), - sid: sidFor(index), + sid: sidFor(index, round), ada: CPACE_AD_A, adb: CPACE_AD_B, }); @@ -302,8 +302,6 @@ describe("client/hello supported_pair_methods", () => { }); describe("PairingManager (dynamic_pairing_code)", () => { - const ESCALATION_THRESHOLD = 10; - /** The PIN most recently surfaced to the app. */ function shownPin(ctx: ReturnType): string { return (ctx.onPairingCode as ReturnType).mock.calls @@ -312,22 +310,24 @@ describe("PairingManager (dynamic_pairing_code)", () => { .at(-1)!; } - /** Drive one dynamic-PIN attempt through to a mismatched server tag. */ - function failAttempt(ctx: ReturnType, index: number): void { - ctx.mgr.onActivate(["pairing"], dynamic()); - // Once escalated, this attempt waits on a gesture instead of starting. - const pending = lastOfType(ctx.sent, "client/pair-pending"); - if (pending?.payload!.pairing_index === index) ctx.mgr.openPairingWindow(); - ctx.mgr.onPairInit({ - nonce_A: base64urlEncode(new Uint8Array(32).fill(0xa1)), - }); - const server = serverPake(shownPin(ctx), index); - ctx.mgr.onPairAuth({ pake_msg_1: base64urlEncode(server.publicShare) }); - const auth = lastOfType(ctx.sent, "client/pair-auth")!; - server.derive(base64urlDecode(auth.payload!.pake_msg_2 as string)); + /** Send a server_kc that fails to verify. */ + function failConfirm(server: CPace, mgr: PairingManager): void { const badTag = server.tag().slice(); badTag[0] ^= 1; - ctx.mgr.onPairConfirm({ server_kc: base64urlEncode(badTag) }); + mgr.onPairConfirm({ server_kc: base64urlEncode(badTag) }); + } + + function storedRounds(storage: { data: Map }): number { + return JSON.parse(storage.data.get("sendspin-pair-failures")!).dynamic_pin; + } + + function storageWithRounds(rounds: number) { + const storage = memStorage(); + storage.setItem( + "sendspin-pair-failures", + JSON.stringify({ dynamic_pin: rounds }), + ); + return storage; } function runToConfirm(opts: SetupOpts = {}, pairing = dynamic()) { @@ -470,52 +470,75 @@ describe("PairingManager (dynamic_pairing_code)", () => { expect(close).not.toHaveBeenCalled(); }); - it("aborts with pairing_code_mismatch and records a failure on a bad server tag", () => { - const storage = memStorage(); + it("asks for another round with the same code on a bad server tag", () => { + const ctx = runToConfirm(); + failConfirm(ctx.server, ctx.mgr); + expect(lastOfType(ctx.sent, "client/pair-retry")!.payload).toEqual({}); + expect(lastOfType(ctx.sent, "pair/abort")).toBeUndefined(); + + // Later rounds carry no nonce_A and bind their own round number into the sid. + ctx.mgr.onPairInit({}); + expect(shownPin(ctx)).toBe(ctx.shownPin); + const server = serverPake(ctx.shownPin, 1, 2); + ctx.mgr.onPairAuth({ pake_msg_1: base64urlEncode(server.publicShare) }); + const auth = lastOfType(ctx.sent, "client/pair-auth")!; + server.derive(base64urlDecode(auth.payload!.pake_msg_2 as string)); + ctx.mgr.onPairConfirm({ server_kc: base64urlEncode(server.tag()) }); + const confirm = lastOfType(ctx.sent, "client/pair-confirm")!; + expect( + server.verify(base64urlDecode(confirm.payload!.client_kc as string)), + ).toBe(true); + expect(ctx.close).not.toHaveBeenCalled(); + }); + + it("fails closed on a nonce_A in a later round", () => { + const ctx = runToConfirm(); + failConfirm(ctx.server, ctx.mgr); + ctx.mgr.onPairInit({ + nonce_A: base64urlEncode(new Uint8Array(32).fill(0xb2)), + }); + expect(ctx.close).toHaveBeenCalled(); + }); + + it("aborts instead of retrying at the round limit", () => { + const storage = storageWithRounds(19); const ctx = runToConfirm({ storage }); - const badTag = ctx.server.tag().slice(); - badTag[0] ^= 1; - ctx.mgr.onPairConfirm({ server_kc: base64urlEncode(badTag) }); + failConfirm(ctx.server, ctx.mgr); expect(lastOfType(ctx.sent, "pair/abort")!.payload!.reason).toBe( "pairing_code_mismatch", ); - expect(ctx.close).not.toHaveBeenCalled(); - expect( - JSON.parse(storage.data.get("sendspin-pair-failures")!).dynamic_pin, - ).toBe(1); + expect(lastOfType(ctx.sent, "client/pair-retry")).toBeUndefined(); + expect(ctx.mgr.isRoundLimitReached()).toBe(true); }); - it("resets the failure counter when the server tag verifies", () => { - const storage = memStorage(); - storage.setItem( - "sendspin-pair-failures", - JSON.stringify({ dynamic_pin: 9 }), - ); + it("resets the round count when the server tag verifies", () => { + const storage = storageWithRounds(9); const ctx = runToConfirm({ storage }); ctx.mgr.onPairConfirm({ server_kc: base64urlEncode(ctx.server.tag()) }); - expect( - JSON.parse(storage.data.get("sendspin-pair-failures")!).dynamic_pin, - ).toBe(0); + expect(storedRounds(storage)).toBe(0); }); - it("escalates on the tenth consecutive PIN mismatch", () => { + it("counts an abandoned attempt only once the code was shown", () => { + const storage = memStorage(); const ctx = setup({ category: "sentinel", onPairingCode: vi.fn(), - storage: memStorage(), + storage, + }); + ctx.mgr.onActivate(["pairing"], dynamic()); + ctx.mgr.onActivate(["playback"]); + expect(storage.data.get("sendspin-pair-failures")).toBeUndefined(); + + ctx.mgr.onActivate(["pairing"], dynamic()); + ctx.mgr.onPairInit({ + nonce_A: base64urlEncode(new Uint8Array(32).fill(0xa1)), }); - for (let i = 1; i < ESCALATION_THRESHOLD; i++) failAttempt(ctx, i); - expect(ctx.mgr.isDynamicPinEscalated()).toBe(false); - failAttempt(ctx, ESCALATION_THRESHOLD); - expect(ctx.mgr.isDynamicPinEscalated()).toBe(true); + ctx.mgr.onActivate(["playback"]); + expect(storedRounds(storage)).toBe(1); }); - it("gesture-gates every attempt once escalated, and still offers the method", () => { - const storage = memStorage(); - storage.setItem( - "sendspin-pair-failures", - JSON.stringify({ dynamic_pin: 10 }), - ); + it("holds attempts back at the round limit until released, and still offers the method", () => { + const storage = storageWithRounds(20); const { mgr, sent, events, close } = setup({ category: "sentinel", onPairingCode: vi.fn(), @@ -527,42 +550,23 @@ describe("PairingManager (dynamic_pairing_code)", () => { expect(lastOfType(sent, "client/pair-pending")!.payload).toEqual({ pairing_index: 1, }); - expect(lastOfType(sent, "client/pair-init")).toBeUndefined(); expect(events).toContain("pending"); expect(close).not.toHaveBeenCalled(); + // The static pairing window does not release a dynamic hold. mgr.openPairingWindow(); + expect(lastOfType(sent, "client/pair-init")).toBeUndefined(); + + mgr.releasePairingHold(); expect(lastOfType(sent, "client/pair-init")).toBeDefined(); + expect(storedRounds(storage)).toBe(0); }); - it("de-escalates once a round verifies, so the next attempt needs no gesture", () => { - const storage = memStorage(); - storage.setItem( - "sendspin-pair-failures", - JSON.stringify({ dynamic_pin: 10 }), - ); - const ctx = setup({ - category: "sentinel", - onPairingCode: vi.fn(), - storage, - }); - ctx.mgr.onActivate(["pairing"], dynamic()); - ctx.mgr.openPairingWindow(); - ctx.mgr.onPairInit({ - nonce_A: base64urlEncode(new Uint8Array(32).fill(0xa1)), - }); - const server = serverPake(shownPin(ctx)); - ctx.mgr.onPairAuth({ pake_msg_1: base64urlEncode(server.publicShare) }); - const auth = lastOfType(ctx.sent, "client/pair-auth")!; - server.derive(base64urlDecode(auth.payload!.pake_msg_2 as string)); - ctx.mgr.onPairConfirm({ server_kc: base64urlEncode(server.tag()) }); - ctx.mgr.onPairFinalize(); - - expect(ctx.mgr.isDynamicPinEscalated()).toBe(false); - ctx.mgr.onActivate(["pairing"], dynamic()); - expect( - lastOfType(ctx.sent, "client/pair-init")!.payload!.pairing_index, - ).toBe(2); + it("does not reset the round count on a release during an attempt", () => { + const storage = storageWithRounds(19); + const ctx = runToConfirm({ storage }); + ctx.mgr.releasePairingHold(); + expect(storedRounds(storage)).toBe(20); }); it("fails closed on a low-order server share", () => { @@ -755,7 +759,7 @@ describe("PairingManager (static_pairing_code)", () => { expect(lastOfType(ctx.sent, "client/pair-init")).toBeDefined(); }); - it("keeps no failure counter: repeated mismatches never escalate", () => { + it("keeps no round count: a mismatch aborts without counting", () => { const storage = memStorage(); const ctx = setup({ category: "sentinel", @@ -820,6 +824,29 @@ describe("PairingManager timers", () => { expect(close).not.toHaveBeenCalled(); }); + it("keeps the attempt timeout running across a retry", () => { + const { mgr, sent, onPairingCode } = setup({ + category: "sentinel", + onPairingCode: vi.fn(), + }); + mgr.onActivate(["pairing"], dynamic()); + vi.advanceTimersByTime(60_000); + mgr.onPairInit({ nonce_A: base64urlEncode(new Uint8Array(32).fill(0xa1)) }); + const pin = (onPairingCode as ReturnType).mock.calls[0][0]; + const server = serverPake(pin); + mgr.onPairAuth({ pake_msg_1: base64urlEncode(server.publicShare) }); + const auth = lastOfType(sent, "client/pair-auth")!; + server.derive(base64urlDecode(auth.payload!.pake_msg_2 as string)); + const badTag = server.tag().slice(); + badTag[0] ^= 1; + mgr.onPairConfirm({ server_kc: base64urlEncode(badTag) }); + expect(lastOfType(sent, "client/pair-retry")).toBeDefined(); + vi.advanceTimersByTime(60_000); + expect(lastOfType(sent, "pair/abort")!.payload!.reason).toBe( + "attempt_timeout", + ); + }); + it("expires an unused pairing window silently", () => { const ctx = setup({ category: "sentinel", From b159778f4fe4ace9a6bcf7d05d7d5edeeb9d4cb4 Mon Sep 17 00:00:00 2001 From: Maxim Raznatovski Date: Tue, 27 Oct 2026 13:11:20 +0100 Subject: [PATCH 3/7] fix: keep the pairing window open across attempts The pairing window closed as soon as one attempt started, so a timed-out or cancelled static pairing code attempt needed a new gesture. --- README.md | 12 ++++--- index.html | 10 +++--- public/app.js | 2 +- src/core/core.ts | 8 ++--- src/core/pairing.ts | 50 ++++++++++++++++---------- src/index.ts | 6 ++-- src/types.ts | 2 +- tests/unit/pairing.test.ts | 73 +++++++++++++++++++++++++++++++++++--- 8 files changed, 122 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 0a16b56..f18bb86 100644 --- a/README.md +++ b/README.md @@ -211,12 +211,14 @@ The SDK supports all three pairing methods from the spec: SDK asks the server for another round and passes the same code again. - **Static pairing code** (enabled by `staticPairingCode`): the operator enters this device's fixed 8-digit code into the server, then makes a local gesture - that calls `player.openPairingWindow()` (window lasts ~5 minutes, one attempt). + that calls `player.openPairingWindow()`. The window lasts ~5 minutes and + closes early after a completed pairing, five wrong codes, a drop of the + connection that used it, or `cancelPairing()`. Some attempts are **held back**: the SDK withholds `client/pair-init`, signalling `client/pair-pending` meanwhile and firing `onPairing("pending")`. -Every static pairing code attempt waits for `openPairingWindow()`. After 20 -failed dynamic pairing code rounds without a success, dynamic pairing code +A static pairing code attempt waits for an open pairing window. After 20 +dynamic pairing code rounds without a correct code, dynamic pairing code attempts wait for `releasePairingHold()`, which also resets the count. Call it only on a deliberate action on the device. @@ -229,8 +231,8 @@ const newPsk = player.rotatePairingPsk(); player.openPairingWindow(); // operator gesture for a static code attempt player.releasePairingHold(); // operator action after the round limit -player.cancelPairing(); // abort an in-progress attempt -player.isRoundLimitReached(); // held back after 20 failed rounds +player.cancelPairing(); // close the window and abort any attempt +player.isRoundLimitReached(); // held back after 20 rounds without a correct code ``` Pairing requires a server speaking the current specification. A non-compliant diff --git a/index.html b/index.html index 45b328c..9b17594 100644 --- a/index.html +++ b/index.html @@ -370,9 +370,9 @@

Pairing

continue. The server is waiting on the operator. Static pairing needs the - window every attempt, and dynamic pairing needs a release after - 20 failed rounds.The server is waiting on the operator. Static pairing needs an + open window, and dynamic pairing needs a release after 20 rounds + without a correct code.