Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 16 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -207,17 +207,20 @@ 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).
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 **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")`.
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.

```typescript
console.log('Client ID:', player.clientId); // 43-char base64url pubkey
Expand All @@ -226,9 +229,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.cancelPairing(); // abort an in-progress attempt
player.isDynamicPinEscalated(); // gesture-gated after 10 failures
player.openPairingWindow(); // operator gesture for a static code attempt
player.releasePairingHold(); // operator action after the round limit
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
Expand Down
26 changes: 15 additions & 11 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -364,14 +364,15 @@ <h2>Pairing</h2>
>
</div>
<div class="form-group" id="pairing-pending-group" hidden>
<label>Gesture required</label>
<label>Operator action required</label>
<span id="pairing-pending" class="status-value"
>Open the pairing window to continue.</span
>Open the pairing window or release the pairing hold to
continue.</span
>
<small
>The server is waiting on the operator gesture. Static pairing
needs one every attempt, and dynamic pairing only when
escalated.</small
>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.</small
>
</div>
<div class="form-group" id="pairing-pin-group" hidden>
Expand All @@ -398,8 +399,8 @@ <h2>Pairing</h2>
</button>
<small
>Optional fixed device code. It enables static pairing on the next
connect. Open the window (~5 min) before each gesture-gated
attempt.</small
connect. Open the window (~5 min) to admit static pairing
attempts.</small
>
<small id="static-pin-both" hidden
>Dynamic pairing is also on. Real devices should offer only one
Expand Down Expand Up @@ -456,11 +457,14 @@ <h2>Pairing</h2>
>
</div>
<div class="form-group">
<label>Dynamic pairing escalated</label>
<span id="pin-escalated" class="status-value">-</span>
<label>Dynamic pairing round limit reached</label>
<span id="round-limit" class="status-value">-</span>
<button id="release-pairing-hold" class="btn btn-secondary">
Release pairing hold
</button>
<small
>After 10 failed attempts every dynamic pairing attempt needs a
gesture, until one succeeds.</small
>After 20 rounds without a correct code dynamic pairing waits
until the operator releases it, which also resets the count.</small
>
</div>
<div class="form-group">
Expand Down
46 changes: 32 additions & 14 deletions public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -246,7 +247,7 @@ function resetStatusDisplay() {
pairingPinGroup.hidden = true;
pairingPendingGroup.hidden = true;
pairingPinEl.textContent = "-";
pinEscalatedEl.textContent = "-";
roundLimitEl.textContent = "-";
}

/**
Expand All @@ -255,7 +256,7 @@ function resetStatusDisplay() {
function updatePairingDisplay() {
clientIdEl.textContent = player.clientId;
pairingTokenEl.textContent = player.pairingToken;
updateEscalationDisplay();
updateRoundLimitDisplay();
}

function isValidStaticPin(pin) {
Expand All @@ -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";
}

/**
Expand All @@ -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") {
Expand All @@ -297,7 +298,7 @@ function onPairing(event, detail) {
trustLevelEl.textContent = `aborted (${detail ?? "unknown"})`;
showToast(`Pairing aborted: ${detail ?? "unknown"}`, "error");
}
updateEscalationDisplay();
updateRoundLimitDisplay();
}

/**
Expand All @@ -306,7 +307,7 @@ function onPairing(event, detail) {
*/
function onPairingCode(pin, languages) {
pairingPinGroup.hidden = pin === null;
pairingPinEl.textContent = pin ?? "-";
pairingPinEl.textContent = pin === null ? "-" : codeGroups(pin).join("-");
pairingPinHint.textContent = languages?.length
? `Enter this code into the server. Spoken preference: ${languages.join(", ")}.`
: "Enter this code into the server to complete pairing.";
Expand All @@ -318,13 +319,22 @@ function onPairingCode(pin, languages) {
if (pinSpeakerInput.checked) speakPin(pin, languages);
}

/** Split the 6-digit code into the 3-3 groups the spec presents it in. */
function codeGroups(pin) {
return [pin.slice(0, 3), pin.slice(3)];
}

/**
* Read the PIN aloud, picking the best voice for the server's language
* preferences under RFC 4647 Lookup matching.
* Read the PIN aloud, digit by digit with a longer pause between groups,
* picking the best voice for the server's language preferences under
* RFC 4647 Lookup matching.
*/
function speakPin(pin, languages) {
if (typeof speechSynthesis === "undefined") return;
const utterance = new SpeechSynthesisUtterance(pin.split("").join(" "));
const text = codeGroups(pin)
.map((group) => group.split("").join(" "))
.join(". ");
const utterance = new SpeechSynthesisUtterance(text);
const voice = bestVoice(languages ?? []);
if (voice) {
utterance.voice = voice;
Expand Down Expand Up @@ -1091,7 +1101,15 @@ function init() {
return;
}
player.openPairingWindow();
showToast("Pairing window open (~5 minutes, one attempt)", "info");
showToast("Pairing window open (~5 minutes)", "info");
});
releasePairingHoldBtn.addEventListener("click", () => {
if (!player) {
showToast("Connect first", "error");
return;
}
player.releasePairingHold();
updateRoundLimitDisplay();
});
cancelPairingBtn.addEventListener("click", () => {
if (!player) return;
Expand Down
32 changes: 21 additions & 11 deletions src/core/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -218,20 +218,24 @@ export class SendspinCore implements StreamHandler {
}

private onTransportClose(): void {
this.resetSession();
console.log("Sendspin: Connection closed");
this._onConnectionClose?.();
}

private resetSession(): void {
// Drop the transport's handshake timer and stale session so a reconnect
// starts clean and a synchronous send from onConnectionOpen can't emit a
// frame under the dead session's keys.
this.transport.onSocketClosed();
this.handshakeInfo = null;
this.protocolHandler.stopTimeSync();
this.protocolHandler.resetActivation();
this.pairing.reset();
this.pairing.onConnectionClosed();
Comment thread
maximmaxim345 marked this conversation as resolved.
Resolved
this.stateManager.clearConnectionState();
// Stop periodic state-update sends so they don't spam
// "WebSocket not connected" warnings after the transport is gone.
this.stateManager.clearStateUpdateInterval();
console.log("Sendspin: Connection closed");
this._onConnectionClose?.();
}

// ========================================
Expand Down Expand Up @@ -320,6 +324,8 @@ export class SendspinCore implements StreamHandler {
// ========================================

async connect(): Promise<void> {
// Replacing a live socket detaches its close handler, so reset its session here.
if (this.isConnected) this.resetSession();
const onOpen = () => {
this._onConnectionOpen?.();
this.transport.start();
Expand Down Expand Up @@ -521,22 +527,26 @@ 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.
* Operator gesture that opens the pairing window for about 5 minutes. Static
* pairing code attempts need an open window.
*/
openPairingWindow(): void {
this.pairing.openPairingWindow();
}

/** Cancel an in-progress pairing attempt (sends pair/abort user_cancelled). */
/** Close the pairing window and cancel an in-progress attempt with pair/abort user_cancelled. */
cancelPairing(): void {
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 } {
Expand Down
Loading
Loading