From 905e2ef34768125b4a8bfbeefd812fb7ba0ab23b Mon Sep 17 00:00:00 2001 From: Egor Kolesnikov Date: Fri, 20 Nov 2026 18:48:07 +0200 Subject: [PATCH 1/2] Rescue: pair when there is no key, and retry a pairing nobody confirmed A watch with no saved key in this browser used to be refused outright. Pairing is the only way in for it, so rescue now pairs, and the wait for the confirmation ends on a 30 s timeout or the moment the watch drops the link, so the retry loop comes back and asks again instead of stopping on the first try. A saved key is still never dropped on rescue; an outright refusal of it leads to a pairing, and the key stays until a new one replaces it. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01CQSU8Nr9jJ3ALiRfiDuC6m --- src/lib/modules/device/i18n.ts | 10 ++-- src/lib/modules/device/lib/ble.ts | 63 +++++++++++++------- src/lib/modules/device/messages.ts | 22 +++---- src/lib/modules/device/model/rescue.model.ts | 4 +- tests/ble-pair-timeout.browser.test.ts | 28 +++++++++ 5 files changed, 87 insertions(+), 40 deletions(-) create mode 100644 tests/ble-pair-timeout.browser.test.ts diff --git a/src/lib/modules/device/i18n.ts b/src/lib/modules/device/i18n.ts index 2bd490b..cfe3497 100644 --- a/src/lib/modules/device/i18n.ts +++ b/src/lib/modules/device/i18n.ts @@ -86,7 +86,7 @@ export const t = dict( rescueRetrying: (n: number) => `waiting for the watch — attempt ${n}…`, stopRescue: "Stop", rescueNoKey: - "This browser has no saved key for a watch. Without one, connecting means pairing, which needs a tap on the watch — open this page in the browser you installed the face from.", + "This browser has no saved key for a watch, so rescue has to pair, and pairing waits for a tap on the watch. If you installed the face from another browser, open this page there. Otherwise start anyway: each time the status says “confirm on the watch”, press the crown and tap the screen, even if it stays black. We haven't confirmed that a black screen takes the tap.", sendingReset: "sending factory reset…", // rescue page rescueTitle: "Rescue — FMC", @@ -185,7 +185,7 @@ export const t = dict( rescueRetrying: (n: number) => `ожидание часов — попытка ${n}…`, stopRescue: "Стоп", rescueNoKey: - "В этом браузере нет сохранённого ключа часов. Без него подключение — это сопряжение, а его нужно подтвердить на часах. Откройте эту страницу в браузере, из которого ставили циферблат.", + "В этом браузере нет сохранённого ключа часов, поэтому восстановлению придётся выполнить сопряжение, а его нужно подтвердить нажатием на часах. Если вы ставили циферблат из другого браузера, откройте эту страницу там. Иначе всё равно запускайте: каждый раз, когда статус просит подтвердить на часах, нажмите колёсико и коснитесь экрана, даже если он остаётся чёрным. Мы не проверяли, что чёрный экран принимает нажатие.", sendingReset: "отправка сброса до заводских настроек…", rescueTitle: "Восстановление — FMC", rescue: "Восстановление", @@ -282,7 +282,7 @@ export const t = dict( rescueRetrying: (n: number) => `очікування годинника — спроба ${n}…`, stopRescue: "Стоп", rescueNoKey: - "У цьому браузері немає збереженого ключа годинника. Без нього під'єднання — це сполучення, а його треба підтвердити на годиннику. Відкрийте цю сторінку в браузері, з якого встановлювали циферблат.", + "У цьому браузері немає збереженого ключа годинника, тому відновленню доведеться виконати сполучення, а його треба підтвердити дотиком на годиннику. Якщо ви встановлювали циферблат з іншого браузера, відкрийте цю сторінку там. Інакше все одно запускайте: щоразу, коли статус просить підтвердити на годиннику, натисніть коліщатко й торкніться екрана, навіть якщо він лишається чорним. Ми не перевіряли, що чорний екран приймає дотик.", sendingReset: "надсилання скидання до заводських налаштувань…", rescueTitle: "Відновлення — FMC", rescue: "Відновлення", @@ -380,7 +380,7 @@ export const t = dict( rescueRetrying: (n: number) => `esperando al reloj — intento ${n}…`, stopRescue: "Detener", rescueNoKey: - "Este navegador no tiene guardada una clave del reloj. Sin ella, conectar significa emparejar, y eso hay que confirmarlo en el reloj. Abre esta página en el navegador desde el que instalaste la esfera.", + "Este navegador no tiene guardada una clave del reloj, así que el rescate tiene que emparejar, y eso hay que confirmarlo con un toque en el reloj. Si instalaste la esfera desde otro navegador, abre esta página allí. Si no, empieza igualmente: cada vez que el estado pida confirmar en el reloj, pulsa la corona y toca la pantalla, aunque siga en negro. No hemos comprobado que una pantalla en negro acepte el toque.", sendingReset: "enviando restablecimiento de fábrica…", rescueTitle: "Rescate — FMC", rescue: "Rescate", @@ -473,7 +473,7 @@ export const t = dict( rescueRetrying: (n: number) => `घड़ी का इंतज़ार — प्रयास ${n}…`, stopRescue: "रोकें", rescueNoKey: - "इस ब्राउज़र में घड़ी की कोई सेव की हुई key नहीं है। इसके बिना कनेक्ट करने का मतलब पेयरिंग है, जिसे घड़ी पर पुष्टि करना पड़ता है। यह पेज उसी ब्राउज़र में खोलें जिससे आपने फ़ेस इंस्टॉल किया था।", + "इस ब्राउज़र में घड़ी की कोई सेव की हुई key नहीं है, इसलिए रेस्क्यू को पेयरिंग करनी होगी, और उसे घड़ी पर टैप करके पुष्टि करना पड़ता है। अगर आपने फ़ेस किसी और ब्राउज़र से इंस्टॉल किया था, तो यह पेज वहीं खोलें। नहीं तो फिर भी शुरू करें: जब भी स्टेटस घड़ी पर पुष्टि करने को कहे, क्राउन दबाएँ और स्क्रीन पर टैप करें, भले ही वह काली रहे। काली स्क्रीन टैप लेती है या नहीं, यह हमने जाँचा नहीं है।", sendingReset: "फ़ैक्टरी रीसेट भेजा जा रहा है…", rescueTitle: "रेस्क्यू — FMC", rescue: "रेस्क्यू", diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index 079ad6e..971ff26 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -76,6 +76,8 @@ export const capacityOf = (name: string | null) => /watch (3 pro|pro 3)/i.test(name ?? "") ? WF_CAPACITY_PRO3 : WF_CAPACITY; const KEY_STORE = "fmc_authkey"; +// how long the rescue page waits for a pairing to be confirmed before it reconnects and asks again +const RESCUE_PAIR_MS = 30000; const loadKey = (): Uint8Array | null => { const h = localStorage.getItem(KEY_STORE); @@ -325,27 +327,26 @@ export class Watch { dbg("subscriptions done, key saved:", Boolean(loadKey())); const k = loadKey(); - // rescue never pairs: pairing waits for a tap on a watch whose screen may never light up. - // Fail now and say why, instead of hanging on a confirmation nobody can give - if (rescue && !k) - throw new Error( - "no saved key for this watch in this browser — rescue can't pair, it needs a tap on the watch", - ); + // rescue pairs only when it must, and never waits on it for long: the confirmation is a tap + // on a watch whose screen may never light up, so a try that gets no answer ends and the + // caller comes back for another + const pairMs = rescue ? RESCUE_PAIR_MS : undefined; + if (k) { try { await this.authenticate(k); } catch (e) { // a stale key (the watch was re-paired/reset) shows up as authFailed or silence on the first // encrypted exchange (authMac = 0x49); other errors don't touch the saved key. On rescue - // the key is all there is, and a wedged watch going silent proves nothing: keep it, and - // let the caller try again - if ( - rescue || - !/rejected the auth key|timeout waiting for 0x49/.test((e as Error).message) - ) - throw e; - dbg("stored key stale, clearing:", (e as Error).message); - localStorage.removeItem(KEY_STORE); + // a wedged watch going silent proves nothing — keep the key and let the caller try again; + // an outright refusal does mean pairing, but the key stays until a new one replaces it + const stale = rescue + ? /rejected the auth key/ + : /rejected the auth key|timeout waiting for 0x49/; + + if (!stale.test((e as Error).message)) throw e; + dbg("stored key stale:", (e as Error).message); + if (!rescue) localStorage.removeItem(KEY_STORE); // pairing needs the shell service — if it's not visible on the current connection, reconnect, // same as on first pairing (§233), and re-subscribe to notifications if (!this.chars[UUID.shellWrite]) { @@ -355,9 +356,9 @@ export class Watch { await connectOrRepick("reconnection"); await subscribe(); } - await this.pair(); + await this.pair(pairMs); } - } else await this.pair(); + } else await this.pair(pairMs); if (!rescue) await this.fetchInfo(); } catch (e) { // without this a failed pair()/authenticate() leaves the physical GATT link hanging: @@ -897,7 +898,8 @@ export class Watch { // then rebooted and factory-reset the watch. Guessing at this firmware costs more than it // returns; read what it volunteers instead (onNotify dumps the payload of unknown commands). - async pair() { + /** `ms`: give up on the confirmation after this long (rescue); without it the wait is the user's. */ + async pair(ms?: number) { if (!this.chars[UUID.shellWrite]) { // the shell service's own UUID isn't fixed (seen as 77d4e67c, docs assumed 77d4ff00) — // Web Bluetooth only exposes services listed in optionalServices at requestDevice() time, @@ -908,10 +910,27 @@ export class Watch { } this.status("pairing — confirm on the watch"); await this.codec.setKey(null); - const gotSecret = new Promise((res) => (this.shellWaiter = res)); - - await this.chars[UUID.shellWrite].writeValue(utf8("AT GETSECRET") as BufferSource); - const str = (await gotSecret).trim(); + let giveUp: (e: Error) => void = () => {}; + const gotSecret = new Promise((res, rej) => { + this.shellWaiter = res; + giveUp = rej; + }); + // a watch that drops the link will never answer: without this the wait outlives the connection + const dropped = () => + giveUp(new Error("the watch disconnected before the pairing was confirmed")); + const timer = + ms && setTimeout(() => giveUp(new Error("timeout waiting for the pairing confirmation")), ms); + let str: string; + + this.device?.addEventListener("gattserverdisconnected", dropped); + try { + await this.chars[UUID.shellWrite].writeValue(utf8("AT GETSECRET") as BufferSource); + str = (await gotSecret).trim(); + } finally { + clearTimeout(timer); + this.device?.removeEventListener("gattserverdisconnected", dropped); + this.shellWaiter = null; + } if (!str.endsWith(",OK") || str.length < 42) throw new Error(`pairing rejected: ${str}`); const secret = fromHex(str.slice(10, 42)); diff --git a/src/lib/modules/device/messages.ts b/src/lib/modules/device/messages.ts index 184c89d..4bd73bc 100644 --- a/src/lib/modules/device/messages.ts +++ b/src/lib/modules/device/messages.ts @@ -25,6 +25,8 @@ const en = { fwSent: "firmware sent — the watch installs it and restarts", installing: (name: string) => `installing ${name}…`, confirmOnWatch: "pairing — confirm on the watch", + pairingDropped: "the watch disconnected before the pairing was confirmed", + pairingTimeout: "timeout waiting for the pairing confirmation", authenticating: "authenticating…", // connecting noWebBluetooth: @@ -51,8 +53,6 @@ const en = { dialNotInstalled: (id: string, d: string) => `dial ${id} not installed (${d})`, notAccepted: (why: string, kb: string) => `watch did not accept the file (${why}; ${kb} KB)`, storedNotActivated: "stored but not activated", - rescueNoKey: - "no saved key for this watch in this browser — rescue can't pair, it needs a tap on the watch", deleteFailed: (d: string) => `dial delete failed (${d})`, refusedReplace: (name: string) => `the watch refused to replace “${name}” — flash again and pick a different dial to replace`, @@ -127,6 +127,8 @@ export const bt = dict(en, { fwSent: "прошивка отправлена — часы установят её и перезагрузятся", installing: (name) => `установка ${name}…`, confirmOnWatch: "сопряжение — подтвердите на часах", + pairingDropped: "часы отключились раньше, чем сопряжение подтвердили", + pairingTimeout: "сопряжение не подтвердили вовремя", authenticating: "авторизация…", noWebBluetooth: "Web Bluetooth здесь недоступен — откройте страницу в Chrome или Edge, а на iPhone в Bluefy", @@ -151,8 +153,6 @@ export const bt = dict(en, { dialNotInstalled: (id, d) => `циферблат ${id} не установлен (${d})`, notAccepted: (why, kb) => `часы не приняли файл (${why}; ${kb} КБ)`, deleteFailed: (d) => `не удалось удалить циферблат (${d})`, - rescueNoKey: - "в этом браузере нет ключа часов — восстановление не может выполнить сопряжение, для него нужно нажатие на часах", storedNotActivated: "сохранён, но не активирован", refusedReplace: (name) => `часы отказались заменить «${name}» — загрузите ещё раз и выберите другой циферблат для замены`, @@ -222,6 +222,8 @@ export const bt = dict(en, { fwSent: "прошивку надіслано — годинник встановить її та перезапуститься", installing: (name) => `встановлення ${name}…`, confirmOnWatch: "сполучення — підтвердьте на годиннику", + pairingDropped: "годинник від'єднався раніше, ніж сполучення підтвердили", + pairingTimeout: "сполучення не підтвердили вчасно", authenticating: "автентифікація…", noWebBluetooth: "Web Bluetooth тут недоступний — відкрийте сторінку в Chrome чи Edge, а на iPhone у Bluefy", @@ -246,8 +248,6 @@ export const bt = dict(en, { dialNotInstalled: (id, d) => `циферблат ${id} не встановлено (${d})`, notAccepted: (why, kb) => `годинник не прийняв файл (${why}; ${kb} КБ)`, deleteFailed: (d) => `не вдалося видалити циферблат (${d})`, - rescueNoKey: - "у цьому браузері немає ключа годинника — відновлення не може виконати сполучення, для нього потрібне натискання на годиннику", storedNotActivated: "збережено, але не активовано", refusedReplace: (name) => `годинник відмовився замінити «${name}» — завантажте ще раз і виберіть інший циферблат для заміни`, @@ -317,6 +317,8 @@ export const bt = dict(en, { fwSent: "firmware enviado — el reloj lo instala y se reinicia", installing: (name) => `instalando ${name}…`, confirmOnWatch: "emparejando — confirma en el reloj", + pairingDropped: "el reloj se desconectó antes de confirmar el emparejamiento", + pairingTimeout: "no se confirmó el emparejamiento a tiempo", authenticating: "autenticando…", noWebBluetooth: "Web Bluetooth no está disponible aquí — abre esta página en Chrome o Edge, o en Bluefy en un iPhone", @@ -341,8 +343,6 @@ export const bt = dict(en, { dialNotInstalled: (id, d) => `la esfera ${id} no está instalada (${d})`, notAccepted: (why, kb) => `el reloj no aceptó el archivo (${why}; ${kb} KB)`, deleteFailed: (d) => `no se pudo borrar la esfera (${d})`, - rescueNoKey: - "este navegador no tiene la clave del reloj — el rescate no puede emparejar, eso requiere tocar el reloj", storedNotActivated: "guardado pero no activado", refusedReplace: (name) => `el reloj se negó a reemplazar «${name}» — vuelve a enviarla y elige otra esfera para reemplazar`, @@ -414,6 +414,8 @@ export const bt = dict(en, { fwSent: "फ़र्मवेयर भेज दिया — घड़ी इसे इंस्टॉल करके रीस्टार्ट होगी", installing: (name) => `${name} इंस्टॉल हो रहा है…`, confirmOnWatch: "पेयरिंग — घड़ी पर पुष्टि करें", + pairingDropped: "पेयरिंग की पुष्टि से पहले घड़ी डिस्कनेक्ट हो गई", + pairingTimeout: "पेयरिंग की पुष्टि समय पर नहीं हुई", authenticating: "प्रमाणीकरण हो रहा है…", noWebBluetooth: "यहां Web Bluetooth उपलब्ध नहीं है — यह पेज Chrome या Edge में खोलें, या iPhone पर Bluefy में", @@ -438,7 +440,6 @@ export const bt = dict(en, { dialNotInstalled: (id, d) => `फ़ेस ${id} इंस्टॉल नहीं है (${d})`, notAccepted: (why, kb) => `घड़ी ने फ़ाइल स्वीकार नहीं की (${why}; ${kb} KB)`, deleteFailed: (d) => `फ़ेस हटाना विफल रहा (${d})`, - rescueNoKey: "इस ब्राउज़र में घड़ी की key नहीं है — रेस्क्यू पेयर नहीं कर सकता, उसके लिए घड़ी पर टैप चाहिए", storedNotActivated: "सेव हुई पर चालू नहीं हुई", refusedReplace: (name) => `घड़ी ने “${name}” को बदलने से मना किया — फिर से भेजें और बदलने के लिए दूसरा फ़ेस चुनें`, @@ -518,6 +519,8 @@ const RULES: Rule[] = [ lit("fwSent"), [/^installing (.+)…$/, (w, m) => w.installing(m[1])], lit("confirmOnWatch"), + lit("pairingDropped"), + lit("pairingTimeout"), lit("authenticating"), lit("noWebBluetooth"), [/^(.+) timed out — the watch is probably connected/, (w, m) => w.timedOut(m[1])], @@ -544,7 +547,6 @@ const RULES: Rule[] = [ [/^the watch refused to replace “(.+)” — /, (w, m) => w.refusedReplace(m[1])], [/^dial delete failed \((.+)\)$/, (w, m) => w.deleteFailed(m[1])], lit("aodNoPreview"), - lit("rescueNoKey"), [ /^an image is (\d+)×(\d+) px, over the (\d+) px limit/, (w, m) => w.imageOverLimit(m[1], m[2], m[3]), diff --git a/src/lib/modules/device/model/rescue.model.ts b/src/lib/modules/device/model/rescue.model.ts index 7b6d04d..c067524 100644 --- a/src/lib/modules/device/model/rescue.model.ts +++ b/src/lib/modules/device/model/rescue.model.ts @@ -76,9 +76,7 @@ const rescueFx = attach({ for (const id of flashedHere()) if (await w.deleteDial(id, FILLER)) deleted++; return { action, deleted }; } catch (e) { - // no key is no key on every attempt: say it once instead of retrying forever - if (pickerClosed(e) || stopping || (e as Error).message.startsWith("no saved key")) - throw e; + if (pickerClosed(e) || stopping) throw e; logged(`attempt ${attempt} failed: ${(e as Error).message}`); statusChanged(t.rescueRetrying(attempt + 1)); await new Promise((r) => setTimeout(r, RETRY_MS)); diff --git a/tests/ble-pair-timeout.browser.test.ts b/tests/ble-pair-timeout.browser.test.ts new file mode 100644 index 0000000..78e87fd --- /dev/null +++ b/tests/ble-pair-timeout.browser.test.ts @@ -0,0 +1,28 @@ +// A pairing nobody confirms must end, or the rescue page's retry loop stops on it for good. +import { expect, test } from "vitest"; +import { Watch } from "$lib/modules/device/lib/ble"; +import { UUID } from "$lib/modules/device/lib/ble-protocol"; + +const silent = () => { + const w = new Watch(); + + w.chars[UUID.shellWrite] = { + writeValue: async () => {}, + } as unknown as BluetoothRemoteGATTCharacteristic; + return w; +}; + +test("pairing gives up after its timeout", async () => { + await expect(silent().pair(20)).rejects.toThrow(/timeout waiting for the pairing confirmation/); +}); + +test("pairing ends when the watch drops the link", async () => { + const w = silent(); + + w.device = new EventTarget() as unknown as BluetoothDevice; + const pairing = w.pair(); + + await new Promise((r) => setTimeout(r, 20)); + w.device.dispatchEvent(new Event("gattserverdisconnected")); + await expect(pairing).rejects.toThrow(/disconnected before the pairing/); +}); From 79d214f46c96a2298b563b3a778383f39e2446c7 Mon Sep 17 00:00:00 2001 From: Egor Kolesnikov Date: Fri, 20 Nov 2026 22:02:57 +0200 Subject: [PATCH 2/2] Rescue: take a key pasted in from another browser or address The site moved from fmc.freethinkel.dev to fmc.tools, and a browser keeps the watch's pairing key per address, so a key saved on the old one is invisible here. The old address's /rescue now prints it; this page takes that text (or the bare 32 hex digits), saves the key, and merges in the faces that were installed there so "delete faces" has something to delete. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CQSU8Nr9jJ3ALiRfiDuC6m --- src/lib/modules/device/i18n.ts | 30 ++++++++++++++++ src/lib/modules/device/lib/ble.ts | 9 +++++ src/lib/modules/device/lib/catalog-names.ts | 13 +++++++ src/lib/modules/device/model/rescue.model.ts | 29 ++++++++++++++-- src/lib/modules/device/pages/rescue.svelte | 36 ++++++++++++++++---- tests/rescue-retry.browser.test.ts | 20 +++++++++++ 6 files changed, 128 insertions(+), 9 deletions(-) diff --git a/src/lib/modules/device/i18n.ts b/src/lib/modules/device/i18n.ts index cfe3497..6fe8f89 100644 --- a/src/lib/modules/device/i18n.ts +++ b/src/lib/modules/device/i18n.ts @@ -85,6 +85,12 @@ export const t = dict( "Gentler than a reset: only the faces this browser installed go, everything else stays. Not yet confirmed on a stuck watch — if it doesn't help, use the factory reset.", rescueRetrying: (n: number) => `waiting for the watch — attempt ${n}…`, stopRescue: "Stop", + rescueKeyHint: + "Coming from another browser, or from the old address fmc.freethinkel.dev? Open /rescue there, copy what it shows and paste it here.", + rescueKeySave: "Save key", + rescueKeyBad: + "There is no key in this text. It is the line fmc_authkey= followed by 32 characters, 0–9 and a–f.", + rescueKeySaved: "Key saved. Start below: this needs no tap on the watch.", rescueNoKey: "This browser has no saved key for a watch, so rescue has to pair, and pairing waits for a tap on the watch. If you installed the face from another browser, open this page there. Otherwise start anyway: each time the status says “confirm on the watch”, press the crown and tap the screen, even if it stays black. We haven't confirmed that a black screen takes the tap.", sendingReset: "sending factory reset…", @@ -184,6 +190,12 @@ export const t = dict( "Бережнее сброса: уходят только циферблаты, установленные из этого браузера, всё остальное остаётся. На зависших часах ещё не проверено — если не поможет, сделайте сброс до заводских.", rescueRetrying: (n: number) => `ожидание часов — попытка ${n}…`, stopRescue: "Стоп", + rescueKeyHint: + "Ключ остался в другом браузере или на старом адресе fmc.freethinkel.dev? Откройте там /rescue, скопируйте текст и вставьте сюда.", + rescueKeySave: "Сохранить ключ", + rescueKeyBad: + "В этом тексте нет ключа. Это строка fmc_authkey= и 32 символа после неё, 0–9 и a–f.", + rescueKeySaved: "Ключ сохранён. Запускайте ниже: нажатие на часах не понадобится.", rescueNoKey: "В этом браузере нет сохранённого ключа часов, поэтому восстановлению придётся выполнить сопряжение, а его нужно подтвердить нажатием на часах. Если вы ставили циферблат из другого браузера, откройте эту страницу там. Иначе всё равно запускайте: каждый раз, когда статус просит подтвердить на часах, нажмите колёсико и коснитесь экрана, даже если он остаётся чёрным. Мы не проверяли, что чёрный экран принимает нажатие.", sendingReset: "отправка сброса до заводских настроек…", @@ -281,6 +293,12 @@ export const t = dict( "Дбайливіше за скидання: зникають лише циферблати, встановлені з цього браузера, усе інше лишається. На завислому годиннику ще не перевірено — якщо не допоможе, скиньте до заводських налаштувань.", rescueRetrying: (n: number) => `очікування годинника — спроба ${n}…`, stopRescue: "Стоп", + rescueKeyHint: + "Ключ лишився в іншому браузері або на старій адресі fmc.freethinkel.dev? Відкрийте там /rescue, скопіюйте текст і вставте сюди.", + rescueKeySave: "Зберегти ключ", + rescueKeyBad: + "У цьому тексті немає ключа. Це рядок fmc_authkey= і 32 символи після нього, 0–9 та a–f.", + rescueKeySaved: "Ключ збережено. Запускайте нижче: дотик до годинника не знадобиться.", rescueNoKey: "У цьому браузері немає збереженого ключа годинника, тому відновленню доведеться виконати сполучення, а його треба підтвердити дотиком на годиннику. Якщо ви встановлювали циферблат з іншого браузера, відкрийте цю сторінку там. Інакше все одно запускайте: щоразу, коли статус просить підтвердити на годиннику, натисніть коліщатко й торкніться екрана, навіть якщо він лишається чорним. Ми не перевіряли, що чорний екран приймає дотик.", sendingReset: "надсилання скидання до заводських налаштувань…", @@ -379,6 +397,12 @@ export const t = dict( "Más suave que un restablecimiento: solo se van las esferas que instaló este navegador y todo lo demás se queda. Aún sin confirmar en un reloj bloqueado; si no ayuda, restablece los datos de fábrica.", rescueRetrying: (n: number) => `esperando al reloj — intento ${n}…`, stopRescue: "Detener", + rescueKeyHint: + "¿La clave quedó en otro navegador o en la dirección antigua fmc.freethinkel.dev? Abre /rescue allí, copia el texto y pégalo aquí.", + rescueKeySave: "Guardar clave", + rescueKeyBad: + "No hay ninguna clave en este texto. Es la línea fmc_authkey= seguida de 32 caracteres, 0–9 y a–f.", + rescueKeySaved: "Clave guardada. Empieza abajo: no hace falta tocar el reloj.", rescueNoKey: "Este navegador no tiene guardada una clave del reloj, así que el rescate tiene que emparejar, y eso hay que confirmarlo con un toque en el reloj. Si instalaste la esfera desde otro navegador, abre esta página allí. Si no, empieza igualmente: cada vez que el estado pida confirmar en el reloj, pulsa la corona y toca la pantalla, aunque siga en negro. No hemos comprobado que una pantalla en negro acepte el toque.", sendingReset: "enviando restablecimiento de fábrica…", @@ -472,6 +496,12 @@ export const t = dict( "रीसेट से हल्का: सिर्फ़ इस ब्राउज़र से इंस्टॉल किए गए फ़ेस हटते हैं, बाकी सब रहता है। अटकी घड़ी पर अभी पुष्टि नहीं हुई — अगर मदद न मिले, तो फ़ैक्टरी रीसेट करें।", rescueRetrying: (n: number) => `घड़ी का इंतज़ार — प्रयास ${n}…`, stopRescue: "रोकें", + rescueKeyHint: + "key किसी और ब्राउज़र में या पुराने पते fmc.freethinkel.dev पर रह गई है? वहाँ /rescue खोलें, जो टेक्स्ट दिखे उसे कॉपी करें और यहाँ पेस्ट करें।", + rescueKeySave: "key सेव करें", + rescueKeyBad: + "इस टेक्स्ट में key नहीं है। यह fmc_authkey= वाली लाइन है, जिसके बाद 32 अक्षर आते हैं, 0–9 और a–f।", + rescueKeySaved: "key सेव हो गई। नीचे शुरू करें: घड़ी पर टैप की ज़रूरत नहीं पड़ेगी।", rescueNoKey: "इस ब्राउज़र में घड़ी की कोई सेव की हुई key नहीं है, इसलिए रेस्क्यू को पेयरिंग करनी होगी, और उसे घड़ी पर टैप करके पुष्टि करना पड़ता है। अगर आपने फ़ेस किसी और ब्राउज़र से इंस्टॉल किया था, तो यह पेज वहीं खोलें। नहीं तो फिर भी शुरू करें: जब भी स्टेटस घड़ी पर पुष्टि करने को कहे, क्राउन दबाएँ और स्क्रीन पर टैप करें, भले ही वह काली रहे। काली स्क्रीन टैप लेती है या नहीं, यह हमने जाँचा नहीं है।", sendingReset: "फ़ैक्टरी रीसेट भेजा जा रहा है…", diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index 971ff26..d4099f9 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -87,6 +87,15 @@ const saveKey = (k: Uint8Array) => localStorage.setItem(KEY_STORE, toHex(k)); /** Whether this browser holds an auth key: without one, connecting means pairing, which needs a * tap on the watch — what the rescue page can't count on. */ export const hasSavedKey = () => loadKey() !== null; +/** Takes a key copied out of another browser or address, where the watch was paired: the line + * `fmc_authkey=<32 hex>` the old address's /rescue prints, or the bare digits. False if the + * text holds no key. */ +export function importKey(text: string): boolean { + const m = /fmc_authkey=([0-9a-f]{32})\b/i.exec(text) ?? /^\s*([0-9a-f]{32})\s*$/i.exec(text); + + if (m) localStorage.setItem(KEY_STORE, m[1].toLowerCase()); + return Boolean(m); +} // dev hygiene: resets Chrome's device permissions and the local auth key. // ponytail: doesn't fix the lock on the watch side (the bond is held by the firmware, not the browser) — diff --git a/src/lib/modules/device/lib/catalog-names.ts b/src/lib/modules/device/lib/catalog-names.ts index 7ad0541..5a48fbf 100644 --- a/src/lib/modules/device/lib/catalog-names.ts +++ b/src/lib/modules/device/lib/catalog-names.ts @@ -70,6 +70,19 @@ export const unclaimDial = (id: number) => { if (e?.serial) write({ ...flashed(), [id]: { ...e, serial: undefined } }); }; +// the faces another browser or address installed, from the `fmc_dial_names=` line its +// /rescue prints: without them the rescue page has nothing to delete. What this browser already +// knows wins. Text with no such line, or a broken one, changes nothing. +export const importFlashed = (text: string) => { + try { + const theirs = JSON.parse(/^fmc_dial_names=(\{.*\})\s*$/m.exec(text)?.[1] ?? "{}"); + + write({ ...theirs, ...flashed() }); + } catch { + /* not ours to fix */ + } +}; + // every dial this browser has flashed, to any watch — what the rescue page can delete without // reading the watch's own list (a wedged watch may not answer for it) export const flashedHere = () => Object.keys(flashed()).map(Number); diff --git a/src/lib/modules/device/model/rescue.model.ts b/src/lib/modules/device/model/rescue.model.ts index c067524..72dcef0 100644 --- a/src/lib/modules/device/model/rescue.model.ts +++ b/src/lib/modules/device/model/rescue.model.ts @@ -7,8 +7,8 @@ // the user stops it. ponytail: a fixed short pause between attempts — Web Bluetooth can't // watch for the advertisement without a flag, so gatt.connect() itself is the probe. import { attach, createEffect, createEvent, createStore, sample, type StoreValue } from "effector"; -import { Watch } from "../lib/ble"; -import { flashedHere } from "../lib/catalog-names"; +import { hasSavedKey, importKey, Watch } from "../lib/ble"; +import { flashedHere, importFlashed } from "../lib/catalog-names"; import { buildBin, TAG } from "$lib/modules/editor/core/format"; import { dbgListeners } from "../lib/ble-protocol"; import { t } from "../i18n"; @@ -97,6 +97,31 @@ const rescueFx = attach({ export const $busy = rescueFx.pending; +// A key paired somewhere this page can't read — another browser, or the address the site moved +// from — pasted in by hand, with the faces installed there if the text carries them. +export const keyTextChanged = createEvent(); +export const keySubmitted = createEvent(); +export const $keyText = createStore("").on(keyTextChanged, (_, text) => text); +const importKeyFx = createEffect((text: string) => { + if (!importKey(text)) throw new Error("no key in the pasted text"); + importFlashed(text); + return flashedHere().length; +}); + +export const $keyed = createStore(hasSavedKey()).on(importKeyFx.done, () => true); +export const $keyImported = createStore(false).on(importKeyFx.done, () => true); +export const $keyRejected = createStore(false) + .on(importKeyFx.fail, () => true) + .reset(importKeyFx.done, keyTextChanged); +/** How many faces the delete action would ask the watch for. */ +export const $faces = createStore(flashedHere().length).on(importKeyFx.doneData, (_, n) => n); + +sample({ + clock: keySubmitted, + source: $keyText, + target: importKeyFx, +}); + sample({ clock: resetRequested, fn: () => "reset" as const, diff --git a/src/lib/modules/device/pages/rescue.svelte b/src/lib/modules/device/pages/rescue.svelte index e424922..2363041 100644 --- a/src/lib/modules/device/pages/rescue.svelte +++ b/src/lib/modules/device/pages/rescue.svelte @@ -4,8 +4,7 @@ // factory reset. Either keeps reconnecting until it goes through or the user stops it. import { Button } from "$lib/shared/components/button"; import { rescueModel } from "../model"; - import { hasSavedKey } from "../lib/ble"; - import { flashedHere } from "../lib/catalog-names"; + import { Textarea } from "$lib/shared/components/textarea"; import { t } from "../i18n"; const ISSUES = "https://github.com/freethinkel/fmc/issues"; @@ -14,14 +13,19 @@ resetRequested, facesRequested, stopRequested, + keyTextChanged, + keySubmitted, + $keyText: keyText, + $keyed: keyed, + $keyImported: keyImported, + $keyRejected: keyRejected, + $faces: faces, $status: status, $error: error, $done: done, $busy: busy, $log: log, } = rescueModel; - const keyed = hasSavedKey(); - const faces = flashedHere().length; const copy = () => navigator.clipboard.writeText($log.join("\n")).catch(() => {}); @@ -36,13 +40,28 @@

{@html $t.rescueIntro}

{$t.rescueBrowser}

- {#if !keyed}

{$t.rescueNoKey}

{/if} + {#if !$keyed} +

{$t.rescueNoKey}

+

{$t.rescueKeyHint}

+
+