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
40 changes: 35 additions & 5 deletions src/lib/modules/device/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,14 @@ 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. 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",
Expand Down Expand Up @@ -184,8 +190,14 @@ 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: "отправка сброса до заводских настроек…",
rescueTitle: "Восстановление — FMC",
rescue: "Восстановление",
Expand Down Expand Up @@ -281,8 +293,14 @@ 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: "надсилання скидання до заводських налаштувань…",
rescueTitle: "Відновлення — FMC",
rescue: "Відновлення",
Expand Down Expand Up @@ -379,8 +397,14 @@ 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. 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",
Expand Down Expand Up @@ -472,8 +496,14 @@ 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 नहीं है। इसके बिना कनेक्ट करने का मतलब पेयरिंग है, जिसे घड़ी पर पुष्टि करना पड़ता है। यह पेज उसी ब्राउज़र में खोलें जिससे आपने फ़ेस इंस्टॉल किया था।",
"इस ब्राउज़र में घड़ी की कोई सेव की हुई key नहीं है, इसलिए रेस्क्यू को पेयरिंग करनी होगी, और उसे घड़ी पर टैप करके पुष्टि करना पड़ता है। अगर आपने फ़ेस किसी और ब्राउज़र से इंस्टॉल किया था, तो यह पेज वहीं खोलें। नहीं तो फिर भी शुरू करें: जब भी स्टेटस घड़ी पर पुष्टि करने को कहे, क्राउन दबाएँ और स्क्रीन पर टैप करें, भले ही वह काली रहे। काली स्क्रीन टैप लेती है या नहीं, यह हमने जाँचा नहीं है।",
sendingReset: "फ़ैक्टरी रीसेट भेजा जा रहा है…",
rescueTitle: "रेस्क्यू — FMC",
rescue: "रेस्क्यू",
Expand Down
72 changes: 50 additions & 22 deletions src/lib/modules/device/lib/ble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -85,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) —
Expand Down Expand Up @@ -325,27 +336,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]) {
Expand All @@ -355,9 +365,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:
Expand Down Expand Up @@ -897,7 +907,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,
Expand All @@ -908,10 +919,27 @@ export class Watch {
}
this.status("pairing — confirm on the watch");
await this.codec.setKey(null);
const gotSecret = new Promise<string>((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<string>((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));
Expand Down
13 changes: 13 additions & 0 deletions src/lib/modules/device/lib/catalog-names.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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=<json>` 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);
Expand Down
Loading
Loading