Lot 2, interface : synchro, appariement par QR code, page d'autorisation d'une IA

- Écran Synchro (#/synchro) : activer, « J'ai déjà une clé » (pull d'abord,
  faute de frappe signalée), état, clé masquée, QR code, désactiver, brancher
  son IA (adresse du connecteur et mode d'emploi).
- Appariement #pair=<clé> : la clé quitte l'adresse aussitôt, confirmation,
  fusion des données locales.
- Page #/connecter-ia?… : autoriser (POST /oauth/authorize) ou refuser,
  erreurs traduites ; le routeur accepte « ? » dans le fragment.
- Synchro automatique sans scrutation (ouverture, 3 s après une saisie,
  online, visibilitychange), indicateur dans l'en-tête.
- QR code : qrcode-generator 2.0.4 (MIT) vendorisé, dessiné en SVG par le DOM.
- Magasin : dates strictement croissantes pour les événements de l'appareil
  (cause du flottement de test-browser : deux PlanSettingsChanged de la même
  milliseconde départagés par leur identifiant aléatoire).
- test-browser : parcours de la synchro contre server/main.js (données
  temporaires), QR décodé par jsQR dans la capture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-18 06:19:15 +01:00
co-authored by Claude Opus 5.5
parent c12e37e215
commit 08cc995eef
22 changed files with 3814 additions and 25 deletions
+38 -4
View File
@@ -1,5 +1,5 @@
// Démarrage de l'app : le journal (IndexedDB), le magasin, le minuteur, le
// routeur et ses écrans.
// Démarrage de l'app : le journal (IndexedDB), le magasin, la synchro, le
// minuteur, le routeur et ses écrans.
import { createStore } from "./ui/store.js";
import { href, startRouter } from "./ui/router.js";
@@ -19,6 +19,11 @@ import { analysisScreen } from "./ui/screens/analysis.js";
import { proposalScreen } from "./ui/proposal-card.js";
import { finishScreen, progressScreen } from "./ui/game.js";
import { applyTheme, getTheme } from "./ui/theme-pref.js";
import { pairScreen, syncIndicator, syncScreen } from "./ui/screens/sync.js";
import { connectAiScreen } from "./ui/screens/connect-ai.js";
import { createSyncService } from "./ui/sync-service.js";
import { readPairFragment } from "./ui/sync-model.js";
import { toast } from "./ui/feedback.js";
import { openEventStore } from "./infra/event-store.js";
import { decodeProposalFragment } from "./domain/link.js";
@@ -30,9 +35,17 @@ applyTheme(getTheme());
// créé y est ajouté (ADR 0006).
const db = await openEventStore();
const device = await db.deviceId();
export const store = createStore({ device, onAppend: (event) => { void db.add([event]); } });
export const store = createStore({ device, onAppend: (event) => { void db.add([event]).then(() => sync.later()); } });
store.load(await db.list());
// Synchro avec le relais (ADR 0005), si une clé est enregistrée : à
// l'ouverture, après chaque saisie, au retour du réseau ou sur l'onglet.
export const sync = createSyncService({
db, store,
onNewProposals: (n) => toast(n > 1 ? `${n} nouvelles propositions : à voir à l'accueil.` : "Nouvelle proposition : à voir à l'accueil."),
});
await sync.start();
/** Écritures en bloc (import, réinitialisation) : IndexedDB puis magasin. */
const journal = {
/** @param {import("./domain/events.js").DomainEvent[]} events */
@@ -44,12 +57,14 @@ const journal = {
const fresh = events.filter((e) => !known.has(e.id) && (known.add(e.id), true));
const added = fresh.length ? await db.add(fresh) : 0;
store.load(await db.list());
if (added) sync.later();
return added;
},
/** @param {import("./domain/events.js").DomainEvent[]} events */
async replace(events) {
await db.replaceAll(events);
store.load(await db.list());
sync.later();
},
};
@@ -75,12 +90,28 @@ async function importFromLink() {
let started = false;
await importFromLink();
window.addEventListener("hashchange", () => { void importFromLink(); });
// Lien d'appariement (#pair=<clé>, QR code d'un autre appareil) : la clé
// quitte aussitôt l'adresse (et l'historique) pour la mémoire, et l'écran de
// confirmation s'affiche. Écouteur posé avant celui du routeur : celui-ci lit
// déjà la nouvelle adresse.
/** @type {string|null} */
let pairKey = null;
function takePairLink() {
if (!location.hash.startsWith("#pair=")) return;
pairKey = readPairFragment(location.hash);
history.replaceState(null, "", pairKey ? href.pair() : href.home());
if (!pairKey) alert("Ce lien d'appariement ne contient pas une clé de synchro valide.");
}
takePairLink();
window.addEventListener("hashchange", takePairLink);
registerServiceWorker();
const timer = createTimer();
document.body.append(timer.node);
const root = /** @type {HTMLElement} */ (document.getElementById("app"));
document.body.insertBefore(syncIndicator(sync), root);
started = true;
startRouter(root, (route, nav) => {
@@ -97,12 +128,15 @@ startRouter(root, (route, nav) => {
case "profile": return profileScreen({ store, nav });
case "analysis": return analysisScreen({ store, nav, today, exercise: route.exercise });
case "proposal": return proposalScreen({ store, nav, id: route.id });
case "sync": return syncScreen({ service: sync, store, nav });
case "pair": return pairScreen({ service: sync, store, nav, key: pairKey });
case "connect-ai": return connectAiScreen({ service: sync, nav, hash: "?" + route.query });
case "not-found":
return {
title: "Page introuvable",
node: h("div", { class: "screen" },
screenHeader({ back: { label: "Accueil", onClick: () => nav.go(href.home()) }, title: "Introuvable", sub: "Cette adresse ne mène à aucun écran." })),
};
default: return homeScreen({ store, nav, today });
default: return homeScreen({ store, nav, today, synced: () => !!sync.getKey() });
}
});
+36
View File
@@ -63,3 +63,39 @@
from { transform: scale(1.35); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
/* ---- synchro ------------------------------------------------------------------------ */
/* Indicateur de l'en-tête : une ligne de marquage, à droite, absente tant que la
synchro n'est pas activée. Le mot porte l'état ; le carré le répète. */
.topline { max-width: var(--max); margin: 0 auto; padding: 0 var(--gutter); display: flex; justify-content: flex-end; }
.sync-flag {
display: inline-flex; align-items: center; gap: var(--space-2); min-height: 40px; padding: 0 0 0 var(--space-2);
font-family: var(--font-mark); font-size: var(--fs-mark); font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em;
color: var(--muted); text-decoration: none;
}
.sync-flag__dot { width: 12px; height: 12px; border: 2px solid var(--ink); background: var(--ink); }
.sync-flag[data-state="syncing"] .sync-flag__dot { background: var(--signal); border-color: var(--signal-edge); }
.sync-flag[data-state="offline"] .sync-flag__dot { background: none; border-style: dashed; border-color: var(--muted); }
.sync-flag[data-state="error"] { color: var(--ink); }
.sync-flag[data-state="error"] .sync-flag__text { background: var(--signal); color: var(--on-signal); padding: 0 4px; }
.sync-flag[data-state="error"] .sync-flag__dot { background: none; }
.sync-state__label { font-family: var(--font-display); font-weight: 700; text-transform: uppercase; font-size: var(--fs-2xl); line-height: 0.9; }
.sync-state[data-state="ok"] .sync-state__label::before { content: "✓ "; }
.sync-state[data-state="error"] { border-width: var(--b-heavy); }
.sync-state[data-state="error"] .sync-state__label::before { content: "! "; }
.sync-state[data-state="offline"] { border-style: dashed; }
.sync-facts .row { min-height: 0; padding: var(--space-3) 0; }
.sync-gap { margin-top: var(--space-3); }
.sync-key { font-family: var(--font-mark); font-weight: 700; letter-spacing: 0.04em; }
/* QR code : noir sur blanc dans les deux thèmes (les lecteurs lisent mal un code
inversé), marge blanche comprise dans le SVG, assez grand pour un appareil
photo à 30 cm. */
.qr-frame { border: var(--b) solid var(--ink); padding: var(--space-3); display: grid; place-items: center; min-height: 120px; }
.qr { width: min(100%, 280px); height: auto; }
/* La grille d'écrans compte un nombre impair de cases : la dernière prend la ligne. */
.grid-nav > .tile:last-child:nth-child(odd) { grid-column: 1 / -1; }
.sync-keybox { display: block; margin-top: var(--space-3); padding: var(--space-3); border: var(--b) dashed var(--ink); font-size: var(--fs-lg); text-align: center; overflow-wrap: anywhere; }
.sync-cmd { font-family: var(--font-mark); font-size: var(--fs-sm); overflow-wrap: anywhere; }
+94
View File
@@ -0,0 +1,94 @@
// Page « Brancher une IA » (#/connecter-ia?…), côté logique : lecture des
// paramètres OAuth que le serveur y transmet (GET /oauth/authorize, voir
// server/app.js), adresse de refus, messages d'erreur. Module pur, testé sous
// Node (tests/ui/connect-model.test.js).
/** Paramètres transmis tels quels à POST /oauth/authorize. */
export const OAUTH_FIELDS = /** @type {const} */ (["client_id", "redirect_uri", "response_type", "state", "code_challenge", "code_challenge_method"]);
/**
* @typedef {object} ConnectRequest
* @property {Record<string, string>} params champs OAuth présents (OAUTH_FIELDS)
* @property {string} clientName nom donné par l'IA, ou « Une IA »
* @property {string|null} redirectHost hôte de l'adresse de retour, null si elle est illisible
* @property {string[]} missing champs obligatoires absents
*/
/**
* Lit « #/connecter-ia?client_id=…&redirect_uri=… ».
* @param {string} hash location.hash
* @returns {ConnectRequest}
*/
export function parseConnectRequest(hash) {
const i = hash.indexOf("?");
const query = new URLSearchParams(i < 0 ? "" : hash.slice(i + 1));
/** @type {Record<string, string>} */
const params = {};
for (const k of OAUTH_FIELDS) {
const v = query.get(k);
if (v !== null) params[k] = v;
}
const missing = ["client_id", "redirect_uri", "code_challenge", "code_challenge_method"].filter((k) => !params[k]);
const name = (query.get("client_name") ?? "").trim().slice(0, 80);
return { params, clientName: name || "Une IA", redirectHost: redirectHost(params.redirect_uri), missing };
}
/** @param {string|undefined} uri */
function redirectHost(uri) {
if (!uri) return null;
try {
const u = new URL(uri);
return u.host || u.protocol.replace(/:$/, "");
} catch {
return null;
}
}
/**
* Adresse de retour vers laquelle on peut renvoyer un refus : les mêmes règles
* que le serveur (server/oauth.js, isAcceptableRedirect). La page peut être
* ouverte par un lien fabriqué : on ne renvoie pas n'importe où.
* @param {string|undefined} uri
*/
export function isAcceptableRedirect(uri) {
if (typeof uri !== "string" || uri.length > 512) return false;
let u;
try {
u = new URL(uri);
} catch {
return false;
}
if (u.hash) return false;
if (u.protocol === "https:") return !!u.hostname;
if (u.protocol === "http:") return ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
return /^[a-z][a-z0-9+-]*(\.[a-z0-9+-]+)+:$/.test(u.protocol);
}
/**
* Adresse de retour d'un refus (RFC 6749, 4.1.2.1), ou null si l'adresse de
* retour n'est pas acceptable.
* @param {Record<string, string>} params
*/
export function refusalUrl(params) {
if (!isAcceptableRedirect(params.redirect_uri)) return null;
const u = new URL(params.redirect_uri);
u.searchParams.set("error", "access_denied");
if (params.state !== undefined) u.searchParams.set("state", params.state);
return u.toString();
}
/** Messages des erreurs de POST /oauth/authorize. @type {Record<string, string>} */
export const AUTHORIZE_ERRORS = {
unknown_journal: "Aucun journal sur le relais pour cette clé : active d'abord la synchro et synchronise une fois.",
invalid_sync_key: "Clé de synchro invalide : 26 caractères, chiffres et lettres.",
invalid_client: "Ce connecteur n'est pas reconnu par IA-Fit : supprime-le puis rajoute-le dans ton IA.",
invalid_request: "Demande incomplète ou adresse de retour inconnue : relance la connexion depuis ton IA.",
unsupported_response_type: "Demande non prise en charge : relance la connexion depuis ton IA.",
rate_limited: "Trop de tentatives : réessaie dans une minute.",
offline: "Serveur injoignable : vérifie ta connexion, puis réessaie.",
};
/** @param {string|null|undefined} code */
export function authorizeErrorText(code) {
return (code && AUTHORIZE_ERRORS[code]) || "Autorisation impossible pour le moment : réessaie plus tard.";
}
+3 -2
View File
@@ -65,9 +65,10 @@ export function onboarding({ store }) {
h("h2", { class: "tape" }, "Ou bien"),
h("div", { class: "btn-stack" },
h("button", { type: "button", class: "btn btn--block", on: { click: startFromExample } }, "Programme d'exemple"),
h("a", { class: "btn btn--block btn--ghost", href: href.data() }, "Restaurer une sauvegarde")),
h("a", { class: "btn btn--block btn--ghost", href: href.data() }, "Restaurer une sauvegarde"),
h("a", { class: "btn btn--block btn--ghost", href: href.sync() }, "Relier à un autre appareil")),
h("p", { class: "foot" }, "Rien ne part sur un serveur. Ce que tu colles dans ton IA, c'est toi qui le choisis."),
h("p", { class: "foot" }, "Rien ne part sur un serveur sans toi : la synchro est à activer, et chiffrée. Ce que tu colles dans ton IA, c'est toi qui le choisis."),
actionBar(h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: copyBrief } }, "Créer mon programme")));
}
+75
View File
@@ -0,0 +1,75 @@
// QR code de l'appariement (ADR 0005, point 4), dessiné en SVG par le DOM :
// ni innerHTML, ni image data:, compatible avec la CSP stricte.
//
// Le calcul des modules est confié à qrcode-generator (Kazuhiko Arase, MIT),
// vendorisé tel quel dans app/vendor/qrcode-generator/. Ce module n'est chargé
// qu'à l'ouverture de l'écran Synchro (import dynamique) : il ne pèse rien au
// premier chargement.
import qrcode from "../vendor/qrcode-generator/qrcode.mjs";
/** Marge blanche autour du code, en modules : 4 selon la norme. */
export const QUIET_ZONE = 4;
/**
* Modules d'un QR code (true = noir). Correction d'erreur M (15 %), version
* choisie au plus petit. Fonction pure, testée sous Node.
* @param {string} text
* @returns {boolean[][]} lignes de modules, carré
*/
export function qrMatrix(text) {
const qr = qrcode(0, "M");
qr.addData(text, "Byte");
qr.make();
const n = qr.getModuleCount();
return Array.from({ length: n }, (_, r) => Array.from({ length: n }, (_, c) => !!qr.isDark(r, c)));
}
/**
* Chemin SVG des modules noirs, décalés de la marge : un carré 1 × 1 par
* module, regroupés par plages horizontales.
* @param {boolean[][]} matrix
* @param {number} [margin]
*/
export function qrPath(matrix, margin = QUIET_ZONE) {
let d = "";
matrix.forEach((row, r) => {
for (let c = 0; c < row.length; c++) {
if (!row[c]) continue;
let end = c;
while (end + 1 < row.length && row[end + 1]) end++;
d += `M${c + margin} ${r + margin}h${end - c + 1}v1h-${end - c + 1}z`;
c = end;
}
});
return d;
}
const SVG = "http://www.w3.org/2000/svg";
/**
* Le QR code en SVG : noir sur blanc quel que soit le thème (les lecteurs
* lisent mal un code inversé), marge comprise.
* @param {string} text
* @param {string} label description pour les lecteurs d'écran
* @returns {SVGSVGElement}
*/
export function qrSvg(text, label) {
const matrix = qrMatrix(text);
const size = matrix.length + 2 * QUIET_ZONE;
const svg = document.createElementNS(SVG, "svg");
svg.setAttribute("viewBox", `0 0 ${size} ${size}`);
svg.setAttribute("role", "img");
svg.setAttribute("aria-label", label);
svg.setAttribute("shape-rendering", "crispEdges");
svg.setAttribute("class", "qr");
const bg = document.createElementNS(SVG, "rect");
bg.setAttribute("width", String(size));
bg.setAttribute("height", String(size));
bg.setAttribute("fill", "#FFFFFF");
const dark = document.createElementNS(SVG, "path");
dark.setAttribute("d", qrPath(matrix));
dark.setAttribute("fill", "#000000");
svg.append(bg, dark);
return svg;
}
+16 -4
View File
@@ -2,8 +2,12 @@
// et le bouton retour du navigateur fonctionne.
//
// Les fragments #import= (lien d'une IA, ADR 0005 point 7) et #pair=
// (appariement, lot 2) sont réservés : le routeur ne les interprète pas et ne
// les réécrit pas : main.js lit #import= (link.js) ; #pair= attend le lot 2.
// (appariement, point 4) sont réservés : le routeur ne les interprète pas et ne
// les réécrit pas : main.js les lit (link.js, sync-model.js), puis remplace
// l'adresse.
//
// Une adresse peut porter des paramètres après « ? » (#/connecter-ia?…, page
// d'autorisation d'une IA) : seul cet écran les lit, les autres les ignorent.
/**
* @typedef {{name: "home"}
@@ -19,6 +23,9 @@
* | {name: "profile"}
* | {name: "analysis", exercise: string|null}
* | {name: "proposal", id: string}
* | {name: "sync"}
* | {name: "pair"}
* | {name: "connect-ai", query: string}
* | {name: "reserved"}
* | {name: "not-found"}} Route
*/
@@ -33,7 +40,9 @@ export const RESERVED = ["#import=", "#pair="];
*/
export function parseRoute(hash) {
if (RESERVED.some((p) => hash.startsWith(p))) return { name: "reserved" };
const path = hash.replace(/^#\/?/, "").replace(/\/+$/, "");
const q = hash.indexOf("?");
const query = q < 0 ? "" : hash.slice(q + 1);
const path = (q < 0 ? hash : hash.slice(0, q)).replace(/^#\/?/, "").replace(/\/+$/, "");
if (path === "") return { name: "home" };
const parts = path.split("/").map((p) => {
try { return decodeURIComponent(p); } catch { return p; }
@@ -45,6 +54,7 @@ export function parseRoute(hash) {
if (head === "analyses" && parts.length === 1) return { name: "analysis", exercise: null };
if (head === "analyses" && parts.length === 2 && arg) return { name: "analysis", exercise: arg };
if (head === "proposition" && parts.length === 2 && arg) return { name: "proposal", id: arg };
if (head === "connecter-ia" && parts.length === 1) return { name: "connect-ai", query };
if (parts.length === 1 && SIMPLE[head]) return /** @type {Route} */ ({ name: SIMPLE[head] });
return { name: "not-found" };
}
@@ -52,7 +62,7 @@ export function parseRoute(hash) {
/** Écrans sans paramètre : adresse → nom. @type {Record<string, string>} */
const SIMPLE = {
bravo: "finish", progression: "progress", historique: "history", semaine: "week", activites: "activities",
poids: "weight", donnees: "data", profil: "profile",
poids: "weight", donnees: "data", profil: "profile", synchro: "sync", relier: "pair",
};
const enc = encodeURIComponent;
@@ -72,6 +82,8 @@ export const href = {
profile: () => "#/profil",
analysis: (/** @type {string|null} */ exercise = null) => "#/analyses" + (exercise ? "/" + enc(exercise) : ""),
proposal: (/** @type {string} */ id) => "#/proposition/" + enc(id),
sync: () => "#/synchro",
pair: () => "#/relier",
};
/**
+111
View File
@@ -0,0 +1,111 @@
// Brancher une IA (ADR 0005, point 5) : la page d'autorisation OAuth, servie
// par l'app. Le serveur y redirige GET /oauth/authorize après avoir vérifié le
// client (#/connecter-ia?client_id=…&client_name=…) ; la page envoie la clé de
// synchro à POST /oauth/authorize, puis suit l'adresse de retour avec le code.
import { h } from "../dom.js";
import { screenHeader, actionBar } from "../layout.js";
import { href } from "../router.js";
import { authorizeErrorText, parseConnectRequest, refusalUrl } from "../connect-model.js";
import { maskKey } from "../sync-model.js";
import { fact } from "./sync.js";
import { normalizeSyncKey } from "../../domain/sync-crypto.js";
/**
* @param {{service: import("../sync-service.js").SyncService, nav: import("../router.js").Navigation, hash: string, leave?: (url: string) => void}} ctx
* leave : quitter l'app vers l'adresse de retour de l'IA (location.assign par défaut)
* @returns {import("../router.js").Screen}
*/
export function connectAiScreen({ service, nav, hash, leave = (url) => location.assign(url) }) {
const req = parseConnectRequest(hash);
const back = { label: "Accueil", onClick: () => nav.go(href.home()) };
if (req.missing.length) {
return {
title: "Brancher une IA",
node: h("div", { class: "screen" },
screenHeader({ back, kicker: "Brancher une IA", title: "Demande incomplète", sub: "Il manque des informations à cette demande d'accès. Relance la connexion depuis ton IA." }),
h("p", { class: "mono-list" }, "Manque : ", req.missing.join(", "))),
};
}
const key = service.getKey();
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
const input = key ? null : h("input", {
id: "connect-key", class: "field__input field__input--mono", type: "text", autocomplete: "off", autocapitalize: "characters",
spellcheck: "false", placeholder: "XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XX",
});
/** @param {string} text */
const fail = (text) => {
status.className = "status status--err";
status.textContent = text;
allow.disabled = false;
};
const authorize = async () => {
const syncKey = key ?? normalizeSyncKey(input?.value ?? "");
if (!syncKey) {
input?.setAttribute("aria-invalid", "true");
return fail(authorizeErrorText("invalid_sync_key"));
}
input?.removeAttribute("aria-invalid");
allow.disabled = true;
status.className = "status";
status.textContent = "Autorisation…";
// Sur un appareil relié, le journal doit être sur le relais : une synchro
// d'abord (sans effet si tout y est déjà).
if (key) await service.syncNow();
let res;
try {
res = await fetch("/oauth/authorize", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ ...req.params, sync_key: syncKey }),
});
} catch {
return fail(authorizeErrorText("offline"));
}
const body = await res.json().catch(() => ({}));
if (res.ok && typeof body.redirect === "string") {
status.className = "status status--ok";
status.textContent = "Autorisé : retour vers ton IA…";
leave(body.redirect);
return;
}
fail(authorizeErrorText(res.status === 429 ? "rate_limited" : body.error));
};
const refuse = () => {
const url = refusalUrl(req.params);
if (url) leave(url);
else {
status.className = "status status--ok";
status.textContent = "Accès refusé. Tu peux fermer cette page.";
allow.disabled = true;
}
};
const allow = h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: () => void authorize() } }, "Autoriser");
return {
title: "Brancher une IA",
node: h("div", { class: "screen" },
screenHeader({ back, kicker: "Brancher une IA", title: req.clientName, sub: "veut lire ton programme et proposer des changements." }),
h("p", { class: "mark" }, "Retour vers ", req.redirectHost ?? "adresse illisible"),
h("h2", { class: "tape" }, "Ce qu'elle pourra faire"),
h("ul", { class: "rows sync-facts" },
fact("Lire", "Ton programme, tes séances, ton poids et ton profil."),
fact("Proposer", "Des changements de programme. Chaque proposition se valide dans l'app, avec un aperçu : rien ne change sans toi."),
fact("Ce qu'elle voit", "Tes données en clair, le temps de chaque requête. Son fournisseur les garde selon ses propres règles.")),
h("h2", { class: "tape" }, "Ta clé"),
key
? h("p", null, "Clé de cet appareil : ", h("code", { class: "sync-key" }, maskKey(key)))
: [
h("p", { class: "muted" }, "Cet appareil n'est pas relié. Colle la clé d'un appareil relié (écran Synchro), ou active la synchro ici."),
h("div", { class: "field sync-gap" }, h("label", { class: "field__label", for: "connect-key" }, "Ma clé de synchro"), input),
h("a", { class: "btn btn--ghost btn--block", href: href.sync() }, "Activer la synchro sur cet appareil"),
],
status,
h("button", { type: "button", class: "btn btn--block sync-gap", on: { click: refuse } }, "Refuser"),
actionBar(allow)),
};
}
+9 -6
View File
@@ -28,12 +28,13 @@ import { toast } from "../feedback.js";
export const hasProgram = (state) => !!state.program && state.programVersions.length > 0;
/**
* @param {{store: Store, nav: import("../router.js").Navigation, today: () => string}} ctx
* @param {{store: Store, nav: import("../router.js").Navigation, today: () => string, synced?: () => boolean}} ctx
* synced : la synchro est-elle activée sur cet appareil ?
* @returns {import("../router.js").Screen}
*/
export function homeScreen({ store, nav, today }) {
export function homeScreen({ store, nav, today, synced = () => false }) {
const node = h("div", { class: "screen screen--home" });
const paint = () => node.replaceChildren(homeContent(store, nav, today()));
const paint = () => node.replaceChildren(homeContent(store, nav, today(), synced()));
paint();
return { node, title: "", destroy: store.subscribe(paintWhenIdle(node, paint)) };
}
@@ -55,9 +56,10 @@ export function plaque(key, color, cls = "plaque") {
* @param {Store} store
* @param {import("../router.js").Navigation} nav
* @param {string} today
* @param {boolean} synced
* @returns {Node}
*/
function homeContent(store, nav, today) {
function homeContent(store, nav, today, synced) {
const state = store.getState();
if (state.proposals.length) {
const [first, ...others] = state.proposals;
@@ -180,9 +182,10 @@ function homeContent(store, nav, today) {
tile(href.progress(), "Succès", "niveau, records"),
tile(href.activities(), "Activités", plural(program.activities?.length ?? 0, "activité")),
tile(href.profile(), "Profil", "objectif, mode"),
tile(href.data(), "Données", "sauvegarde, IA")),
tile(href.data(), "Données", "sauvegarde, IA"),
tile(href.sync(), "Synchro", synced ? "appareils, IA · activée" : "appareils, IA")),
h("p", { class: "foot" }, `${program.name} · tes données restent sur cet appareil.`),
h("p", { class: "foot" }, `${program.name} · `, synced ? "synchronisé, chiffré." : "tes données restent sur cet appareil."),
primary && actionBar(primary));
}
+4 -1
View File
@@ -116,6 +116,9 @@ export function profileScreen({ store, nav }) {
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: save } }, "Enregistrer le profil"),
h("h2", { class: "tape" }, "Affichage"),
h("div", { class: "segmented", role: "group", "aria-label": "Thème" }, themeBtns),
h("p", { class: "muted" }, "Sombre par défaut : un écran OLED noir consomme moins."));
h("p", { class: "muted" }, "Sombre par défaut : un écran OLED noir consomme moins."),
h("h2", { class: "tape" }, "Appareils et IA"),
h("p", { class: "muted" }, "Relier ton téléphone et ton PC, brancher ton IA : sans compte, par une clé de synchro."),
h("a", { class: "btn btn--block sync-gap", href: href.sync() }, "Synchro et IA"));
return { node, title: "Profil" };
}
+304
View File
@@ -0,0 +1,304 @@
// Synchro (ADR 0005, points 2 à 5) : activer la clé, la retrouver, apparier un
// autre appareil par QR code, brancher une IA. Plus l'indicateur de l'en-tête
// et l'écran de confirmation d'un lien d'appariement (#pair=).
import { h, paintWhenIdle, replace } from "../dom.js";
import { screenHeader, actionBar } from "../layout.js";
import { href } from "../router.js";
import { confirmDialog, toast } from "../feedback.js";
import { copyText } from "../files.js";
import { plural } from "../format.js";
import { maskKey, pairUrl, syncView } from "../sync-model.js";
import { generateSyncKey, normalizeSyncKey } from "../../domain/sync-crypto.js";
/** @typedef {import("../sync-service.js").SyncService} SyncService */
/** Adresse du connecteur MCP, sur la même origine que l'app (docs/mcp.md). */
export const mcpUrl = () => `${location.origin}/mcp`;
/**
* Indicateur discret de l'en-tête : absent tant que la synchro n'est pas
* activée, puis « à jour », « en cours », « hors ligne » ou « en erreur ».
* @param {SyncService} service
*/
export function syncIndicator(service) {
const text = h("span", { class: "sync-flag__text" });
const link = h("a", { class: "sync-flag", href: href.sync() }, h("span", { class: "sync-flag__dot", "aria-hidden": "true" }), text);
const bar = h("div", { class: "topline" }, link);
const paint = () => {
const v = syncView(service.getStatus(), new Date());
bar.hidden = v.state === "off";
link.dataset.state = v.state;
text.textContent = v.label;
link.setAttribute("aria-label", `${v.label} : ouvrir l'écran Synchro`);
};
service.subscribe(paint);
paint();
return bar;
}
/**
* @param {{service: SyncService, store: import("../store.js").Store, nav: import("../router.js").Navigation}} ctx
* @returns {import("../router.js").Screen}
*/
export function syncScreen({ service, store, nav }) {
const zone = h("div");
let hasKey = !!service.getKey();
/** @type {(() => void)[]} */
let cleanups = [];
const clean = () => { cleanups.forEach((fn) => fn()); cleanups = []; };
const paint = () => {
clean();
hasKey = !!service.getKey();
replace(zone, hasKey ? withKey(service, store, cleanups) : withoutKey(service));
};
paint();
// On ne repeint tout que si la clé change ; l'état seul se met à jour dans
// son bloc (statusBlock).
const repaint = paintWhenIdle(zone, paint);
const unsubscribe = service.subscribe(() => { if (!!service.getKey() !== hasKey) repaint(); });
const node = h("div", { class: "screen" },
screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Sans compte", title: "Synchro", sub: "Tes appareils et ton IA partagent ton journal, chiffré." }),
zone);
return { node, title: "Synchro", destroy: () => { unsubscribe(); clean(); } };
}
/** @param {SyncService} service */
function withoutKey(service) {
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
const busy = (/** @type {HTMLButtonElement} */ b, /** @type {boolean} */ on) => { b.disabled = on; };
const activate = async () => {
busy(start, true);
const s = await service.enable(generateSyncKey());
toast(s.error && s.error !== "offline" ? "Synchro activée, mais pas encore faite." : "Synchro activée.");
};
const start = h("button", { type: "button", class: "btn btn--primary btn--block btn--lg", on: { click: () => void activate() } }, "Activer la synchro");
const input = h("input", {
id: "sync-key", class: "field__input field__input--mono", type: "text", autocomplete: "off", autocapitalize: "characters",
spellcheck: "false", placeholder: "XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XX",
});
const link = async () => {
const key = normalizeSyncKey(input.value);
if (!key) {
input.setAttribute("aria-invalid", "true");
status.className = "status status--err";
status.textContent = "Clé invalide : 26 caractères, chiffres et lettres (sans I, L, O ni U).";
return;
}
input.removeAttribute("aria-invalid");
status.className = "status";
status.textContent = "Lecture du relais…";
busy(join, true);
let found;
try {
found = await service.probe(key);
} catch (e) {
busy(join, false);
status.className = "status status--err";
status.textContent = e instanceof Error ? e.message : String(e);
return;
}
if (!found.exists) {
const ok = await confirmDialog({
title: "Clé inconnue",
lines: ["Aucun journal ne correspond à cette clé sur le relais : une faute de frappe est probable.",
"Vérifie-la. Sinon, un nouveau journal sera créé avec cette clé et les données de cet appareil."],
confirm: "Créer un nouveau journal", cancel: "Corriger la clé",
});
if (!ok) {
busy(join, false);
status.textContent = "";
input.focus();
return;
}
}
await service.enable(key);
toast(found.added ? `Appareil relié : ${plural(found.added, "événement")} reçu${found.added > 1 ? "s" : ""}.` : "Appareil relié.");
};
const join = h("button", { type: "button", class: "btn btn--block", on: { click: () => void link() } }, "Relier avec cette clé");
return h("div", null,
h("h2", { class: "tape" }, "Comment ça marche"),
h("ul", { class: "rows sync-facts" },
fact("Sans compte", "Une clé tirée au hasard relie tes appareils et ton IA. Ni e-mail, ni mot de passe."),
fact("Chiffré", "Le serveur ne garde que des blocs chiffrés avec ta clé : il ne peut pas les lire."),
fact("Un secret", "Qui a la clé a tout : garde-la comme un mot de passe.")),
h("p", { class: "muted sync-gap" }, "Sans synchro, tout reste sur cet appareil : l'app marche aussi bien hors ligne."),
h("h2", { class: "tape" }, "J'ai déjà une clé"),
h("p", { class: "muted" }, "Celle d'un autre appareil : écran Synchro, « Afficher » puis « Copier ». Ou scanne son QR code."),
h("div", { class: "field sync-gap" }, h("label", { class: "field__label", for: "sync-key" }, "Ma clé de synchro"), input),
join,
status,
aiSection(false),
actionBar(start));
}
/**
* @param {SyncService} service
* @param {import("../store.js").Store} store
* @param {(() => void)[]} cleanups désabonnements, appelés quand la zone est repeinte
*/
function withKey(service, store, cleanups) {
const key = /** @type {string} */ (service.getKey());
// ---- état ---------------------------------------------------------------------
const state = h("p", { class: "sync-state__label" });
const detail = h("p", { class: "muted" });
const now = h("button", { type: "button", class: "btn btn--block", on: { click: () => void syncNow() } }, "Synchroniser maintenant");
const block = h("section", { class: "block sync-state", "aria-label": "État de la synchro", "aria-live": "polite" }, state, detail, now);
const paintState = () => {
const s = service.getStatus();
const v = syncView(s, new Date());
block.dataset.state = v.state;
state.textContent = v.label;
detail.textContent = v.detail;
now.disabled = s.running;
};
const syncNow = async () => {
const s = await service.syncNow();
if (!s.error) toast("Synchro faite.");
};
cleanups.push(service.subscribe(paintState));
paintState();
// ---- la clé -------------------------------------------------------------------
let shown = false;
const keyText = h("code", { class: "sync-key sync-keybox", "aria-label": "Clé de synchro, masquée" }, maskKey(key));
const show = h("button", { type: "button", class: "btn btn--block", "aria-pressed": "false" }, "Afficher");
show.addEventListener("click", () => {
shown = !shown;
keyText.textContent = shown ? key : maskKey(key);
keyText.setAttribute("aria-label", shown ? "Clé de synchro" : "Clé de synchro, masquée");
show.textContent = shown ? "Masquer" : "Afficher";
show.setAttribute("aria-pressed", String(shown));
});
const fallback = h("div", { class: "manual-copy", hidden: true });
const copy = h("button", { type: "button", class: "btn btn--block", on: { click: async () => {
if (await copyText(key, fallback, "Clé de synchro")) toast("Clé copiée. Garde-la secrète.");
} } }, "Copier la clé");
// ---- QR code (module chargé à la demande) -------------------------------------
const link = pairUrl(location.origin, key);
const qr = h("div", { class: "qr-frame" }, h("p", { class: "muted" }, "QR code…"));
import("../qr.js")
.then((m) => qr.replaceChildren(m.qrSvg(link, "QR code d'appariement : il ouvre IA-Fit et relie l'appareil à ton journal")))
.catch(() => qr.replaceChildren(h("p", { class: "status status--err" }, "QR code indisponible : recopie la clé à la main.")));
// ---- désactiver ---------------------------------------------------------------
const disable = async () => {
const ok = await confirmDialog({
title: "Désactiver ici ?",
lines: ["Cet appareil oublie la clé et ne se synchronise plus.",
`Ses données restent ici (${plural(store.getEvents().length, "événement")}), et le journal chiffré reste sur le relais pour tes autres appareils et ton IA.`,
"Note la clé avant si tu veux relier l'appareil plus tard."],
confirm: "Désactiver", cancel: "Garder la synchro", danger: true,
});
if (!ok) return;
await service.disable();
toast("Synchro désactivée sur cet appareil.");
};
return h("div", null,
block,
h("h2", { class: "tape" }, "Ta clé"),
h("p", { class: "muted" }, "Qui a la clé a tout : ne la donne qu'à tes appareils."),
keyText,
h("div", { class: "btn-row sync-gap" }, show, copy),
fallback,
h("h2", { class: "tape" }, "Autre appareil"),
qr,
h("p", { class: "sync-gap" }, h("strong", null, "Scanne-le avec l'appareil photo de ton téléphone."), " Le lien ouvre IA-Fit et relie le téléphone à ton journal."),
h("p", { class: "muted" }, "Sans appareil photo : ouvre IA-Fit sur l'autre appareil, écran Synchro, « J'ai déjà une clé »."),
aiSection(true),
h("h2", { class: "tape" }, "Cet appareil"),
h("button", { type: "button", class: "btn btn--danger btn--block", on: { click: () => void disable() } }, "Désactiver sur cet appareil"));
}
/** Une ligne « titre : explication ». @param {string} title @param {string} text */
export function fact(title, text) {
return h("li", { class: "row" }, h("span", { class: "row__main" }, h("span", { class: "row__title" }, title), h("span", { class: "row__meta" }, text)));
}
/**
* « Brancher mon IA » : l'adresse du connecteur et le mode d'emploi (docs/mcp.md).
* @param {boolean} ready la synchro est activée
*/
function aiSection(ready) {
const url = mcpUrl();
const fallback = h("div", { class: "manual-copy", hidden: true });
const copy = h("button", { type: "button", class: "btn btn--sm", on: { click: async () => {
if (await copyText(url, fallback, "Adresse du connecteur")) toast("Adresse copiée.");
} } }, "Copier");
/** @param {string} who @param {string} how */
const step = (who, how) => h("li", { class: "how__step" }, h("span", null, h("strong", null, who), " : ", how));
return [
h("h2", { class: "tape" }, "Brancher mon IA"),
h("p", { class: "muted" }, ready
? "Ton IA lit ton programme et propose des changements ; chaque proposition se valide ici."
: "Active d'abord la synchro : ton IA lit le journal chiffré du relais."),
h("div", { class: "copy-line sync-gap" }, h("code", { class: "copy-line__text" }, url), copy),
fallback,
h("ol", { class: "how sync-gap" },
step("Claude", "Réglages → Connecteurs → Ajouter un connecteur personnalisé, colle l'adresse."),
step("ChatGPT", "Réglages → Applications et connecteurs → Paramètres avancés → mode développeur, puis « Créer » : l'adresse, authentification OAuth."),
h("li", { class: "how__step" }, h("span", null, h("strong", null, "Claude Code"), " : ",
h("code", { class: "sync-cmd" }, `claude mcp add --transport http ia-fit ${url}`), ", puis /mcp."))),
h("p", { class: "muted sync-gap" }, "Ton IA ouvre ensuite une page d'IA-Fit : touche « Autoriser »."),
];
}
/**
* Lien d'appariement ouvert (#pair=) : la clé a déjà quitté l'adresse
* (main.js), elle arrive ici en mémoire.
* @param {{service: SyncService, store: import("../store.js").Store, nav: import("../router.js").Navigation, key: string|null}} ctx
* @returns {import("../router.js").Screen}
*/
export function pairScreen({ service, store, nav, key }) {
const home = () => nav.go(href.home(), { replace: true });
const head = (/** @type {string|null} */ sub) => screenHeader({ kicker: "Synchro", title: "Relier cet appareil ?", sub });
if (!key) {
return {
title: "Relier",
node: h("div", { class: "screen" }, head("Ce lien d'appariement n'est plus valable ici (page rechargée ?). Scanne de nouveau le QR code."),
h("a", { class: "btn btn--block", href: href.home() }, "Accueil")),
};
}
const current = service.getKey();
if (current === key) {
return {
title: "Relier",
node: h("div", { class: "screen" }, head("Cet appareil est déjà relié à ce journal."),
h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: home } }, "Accueil")),
};
}
const n = store.getEvents().length;
const status = h("p", { class: "status", role: "status", "aria-live": "polite" });
const go = h("button", { type: "button", class: "btn btn--primary btn--block btn--lg" }, "Relier");
go.addEventListener("click", async () => {
go.disabled = true;
status.className = "status";
status.textContent = "Synchro…";
const s = await service.enable(key);
if (s.error && s.error !== "offline") {
// La clé est gardée : la synchro réessaiera ; l'écran Synchro dit pourquoi.
toast("Appareil relié, mais la synchro a échoué : voir l'écran Synchro.");
} else toast(s.error ? "Appareil relié : la synchro se fera au retour du réseau." : "Appareil relié à ton journal.");
home();
});
return {
title: "Relier",
node: h("div", { class: "screen" },
head("Relier cet appareil à ton journal ? Il recevra ton programme et tes séances, et ce que tu saisis ici rejoindra tes autres appareils."),
h("p", { class: "mark" }, "Clé ", maskKey(key)),
current && h("p", { class: "coach-note coach-note--plain sync-gap" },
`Cet appareil est relié à un autre journal (clé ${maskKey(current)}) : il passera à celui-ci, et ses données y seront recopiées.`),
n > 0 && h("p", { class: "coach-note coach-note--plain sync-gap" },
`Cet appareil a déjà des données (${plural(n, "événement")}) : elles seront fusionnées avec le journal. Rien n'est effacé.`),
h("p", { class: "muted sync-gap" }, "Qui a la clé a tout : ne relie que tes propres appareils."),
status,
h("button", { type: "button", class: "btn btn--ghost btn--block sync-gap", on: { click: home } }, "Annuler"),
actionBar(go)),
};
}
+18 -1
View File
@@ -39,12 +39,28 @@ export function createStore(options = {}) {
const listeners = new Set();
const notify = () => { for (const fn of [...listeners]) fn(state); };
// Les événements de cet appareil reçoivent des dates strictement croissantes.
// Le journal se replie dans l'ordre (date, appareil, identifiant) : deux
// intentions de la même milliseconde (deux touches rapides, une horloge
// arrondie par le navigateur) seraient sinon départagées par leur
// identifiant, tiré au hasard, et la plus récente pourrait passer avant.
let lastAt = 0;
/** @param {readonly DomainEvent[]} list */
const noteOwn = (list) => {
for (const e of list) if (e.device === device) lastAt = Math.max(lastAt, Date.parse(e.at) || 0);
};
noteOwn(events);
const nextAt = () => {
lastAt = Math.max(Date.now(), lastAt + 1);
return new Date(lastAt).toISOString();
};
return {
device,
getState: () => state,
getEvents: () => events,
dispatch(type, data) {
const event = createEvent(type, /** @type {any} */ (data), { device });
const event = createEvent(type, /** @type {any} */ (data), { device, at: nextAt() });
events = [...events, event];
state = foldEvents(events);
options.onAppend?.(event);
@@ -53,6 +69,7 @@ export function createStore(options = {}) {
},
load(list) {
events = [...list];
noteOwn(events);
state = foldEvents(events);
notify();
},
+163
View File
@@ -0,0 +1,163 @@
// Synchro, côté interface : ce qui s'affiche et quand on synchronise. Modules
// purs, sans DOM ni réseau, testés sous Node (tests/ui/sync-model.test.js).
// Le branchement sur le navigateur est dans sync-service.js.
import { normalizeSyncKey } from "../domain/sync-crypto.js";
/** Délai entre une saisie et la synchro qu'elle déclenche (sync.js : 2 à 5 s). */
export const PUSH_DELAY_MS = 3000;
/** @typedef {"off"|"ok"|"syncing"|"offline"|"error"} SyncState */
/**
* @typedef {object} SyncStatus
* @property {boolean} hasKey
* @property {boolean} online navigator.onLine
* @property {boolean} running une synchro est en cours
* @property {string|null} lastAt fin de la dernière synchro réussie (ISO)
* @property {string|null} error code de la dernière erreur (SyncError.code), effacé au succès
*/
/** Messages des erreurs de synchro (SyncError.code, app/infra/sync.js). @type {Record<string, string>} */
export const SYNC_ERRORS = {
offline: "Hors ligne : la synchro reprendra au retour du réseau.",
forbidden: "Le relais refuse cette clé : son journal est protégé par une autre clé d'accès. Vérifie la clé, ou désactive puis réactive la synchro.",
journal_full: "Ton journal a atteint la taille maximale sur le relais. Exporte une sauvegarde (écran Données).",
rate_limited: "Trop de synchros d'affilée : nouvel essai dans une minute.",
server: "Le relais a répondu par une erreur : nouvel essai plus tard.",
key: "Clé de synchro illisible sur cet appareil : désactive puis relie de nouveau l'appareil.",
};
/** @param {string|null|undefined} code */
export function syncErrorText(code) {
return (code && SYNC_ERRORS[code]) || "Synchro impossible pour le moment : nouvel essai plus tard.";
}
/**
* « il y a 3 min », « à 14:05 », « le 12/11 »…
* @param {string} iso
* @param {Date} now
*/
export function sinceText(iso, now) {
const at = new Date(iso);
const s = Math.round((now.getTime() - at.getTime()) / 1000);
if (!Number.isFinite(s)) return "";
if (s < 60) return "à l'instant";
if (s < 3600) return `il y a ${Math.floor(s / 60)} min`;
const pad = (/** @type {number} */ n) => String(n).padStart(2, "0");
if (at.toDateString() === now.toDateString()) return `à ${pad(at.getHours())}:${pad(at.getMinutes())}`;
return `le ${pad(at.getDate())}/${pad(at.getMonth() + 1)}`;
}
/**
* Ce que montrent l'indicateur de l'en-tête et l'écran Synchro.
* @param {SyncStatus} s
* @param {Date} now
* @returns {{state: SyncState, label: string, detail: string}}
* label : court (indicateur) ; detail : une phrase (écran Synchro)
*/
export function syncView(s, now) {
const last = s.lastAt ? `Dernière synchro ${sinceText(s.lastAt, now)}.` : "Pas encore synchronisé.";
if (!s.hasKey) return { state: "off", label: "Synchro désactivée", detail: "Les données restent sur cet appareil." };
if (s.running) return { state: "syncing", label: "Synchro…", detail: "Synchro en cours." };
if (!s.online || s.error === "offline") return { state: "offline", label: "Hors ligne", detail: `${SYNC_ERRORS.offline} ${last}` };
if (s.error) return { state: "error", label: "Synchro en erreur", detail: `${syncErrorText(s.error)} ${last}` };
return { state: "ok", label: "Synchro à jour", detail: last };
}
/**
* Regroupe les demandes de synchro : `later()` (après une saisie) lance une
* synchro au bout de `delayMs`, une seule pour toutes les saisies de cet
* intervalle ; `now()` (ouverture, retour du réseau, retour sur l'onglet) la
* lance tout de suite. Une demande pendant une synchro en relance une, une
* seule, à sa fin : un événement créé pendant l'envoi n'attend pas la saisie
* suivante. Aucune minuterie ne tourne en dehors d'une demande (pas de
* scrutation).
* @template T
* @param {{run: () => Promise<T>, delayMs?: number, timers?: {setTimeout: typeof setTimeout, clearTimeout: typeof clearTimeout}}} options
*/
export function createSyncScheduler({ run, delayMs = PUSH_DELAY_MS, timers = globalThis }) {
/** @type {ReturnType<typeof setTimeout>|null} */
let timer = null;
/** @type {Promise<T|undefined>|null} */
let running = null;
let again = false;
/** @returns {Promise<T|undefined>} */
function now() {
if (timer !== null) {
timers.clearTimeout(timer);
timer = null;
}
if (running) {
again = true;
return running;
}
running = (async () => {
let result;
try {
do {
again = false;
result = await run().catch(() => undefined);
} while (again);
} finally {
running = null;
}
return result;
})();
return running;
}
function later() {
if (running) {
again = true;
return;
}
if (timer === null) timer = timers.setTimeout(() => { timer = null; void now(); }, delayMs);
}
return {
now,
later,
/** Une synchro attend son délai ? (tests) */
get pending() { return timer !== null; },
/** Plus de synchro différée (clé effacée). */
cancel() {
if (timer !== null) timers.clearTimeout(timer);
timer = null;
again = false;
},
};
}
/**
* Adresse d'appariement portée par le QR code (ADR 0005, point 4). La clé est
* après « # » : le navigateur ne l'envoie jamais au serveur.
* @param {string} origin https://ia-fit.sans.pub
* @param {string} syncKey
*/
export function pairUrl(origin, syncKey) {
return `${origin.replace(/\/+$/, "")}/#pair=${syncKey}`;
}
/**
* Clé d'un fragment « #pair=<clé> », normalisée ; null si le fragment n'en est
* pas un ou si la clé est invalide.
* @param {string} hash
*/
export function readPairFragment(hash) {
const m = /^#pair=(.*)$/.exec(hash);
if (!m) return null;
let raw = m[1];
try { raw = decodeURIComponent(raw); } catch { /* laissée telle quelle */ }
return normalizeSyncKey(raw);
}
/**
* La clé masquée : seul son dernier groupe reste lisible, pour la reconnaître.
* @param {string} syncKey au format affiché
*/
export function maskKey(syncKey) {
const groups = syncKey.split("-");
return groups.map((g, i) => (i === groups.length - 1 ? g : "•".repeat(g.length))).join("-");
}
+165
View File
@@ -0,0 +1,165 @@
// La synchro branchée sur l'app (mode d'emploi en tête de app/infra/sync.js) :
// la clé de l'appareil, quand synchroniser, l'état affiché.
//
// Quand : à l'ouverture (si une clé existe), après chaque événement local
// (délai de 3 s, regroupé), au retour du réseau (`online`) et au retour sur
// l'onglet (`visibilitychange`). Jamais de scrutation : sans saisie ni retour,
// aucune requête ne part.
//
// Gardé dans le magasin `meta` d'IndexedDB :
// - « syncKey » : la clé de synchro de l'appareil (null une fois désactivée) ;
// - « syncLastAt » : fin de la dernière synchro réussie (ISO).
import { createSync, SyncError } from "../infra/sync.js";
import { createSyncScheduler } from "./sync-model.js";
/** @typedef {import("./sync-model.js").SyncStatus} SyncStatus */
/** @typedef {import("../domain/events.js").DomainEvent} DomainEvent */
/**
* @typedef {object} MetaStore ce que le service utilise de openEventStore()
* @property {() => Promise<DomainEvent[]>} list
* @property {(events: readonly DomainEvent[]) => Promise<number>} add
* @property {(key: string) => Promise<unknown>} getMeta
* @property {(key: string, value: unknown) => Promise<void>} setMeta
*/
/** @param {unknown} e */
const errorCode = (e) => (e instanceof SyncError ? e.code : e instanceof Error && e.name === "SyncCryptoError" ? "key" : "server");
/**
* @param {{db: MetaStore, store: import("./store.js").Store, onNewProposals?: (count: number) => void}} options
* onNewProposals : des propositions sont arrivées par la synchro (de l'IA, d'un autre appareil)
*/
export function createSyncService({ db, store, onNewProposals }) {
/** @type {string|null} */
let key = null;
/** @type {ReturnType<typeof createSync>|null} */
let sync = null;
/** @type {SyncStatus} */
const status = { hasKey: false, online: navigator.onLine, running: false, lastAt: null, error: null };
/** @type {Set<() => void>} */
const listeners = new Set();
const notify = () => { for (const fn of [...listeners]) fn(); };
/** Relit le journal après des événements reçus ; signale les nouvelles propositions. */
async function reload() {
const before = new Set(store.getState().proposals.map((p) => p.id));
store.load(await db.list());
const fresh = store.getState().proposals.filter((p) => !before.has(p.id)).length;
if (fresh) onNewProposals?.(fresh);
}
async function run() {
const current = sync;
if (!current) return null;
status.running = true;
notify();
try {
const result = await current.sync();
if (current !== sync) return result; // clé changée pendant la synchro
status.error = null;
status.lastAt = new Date().toISOString();
await db.setMeta("syncLastAt", status.lastAt);
if (result.pulled) await reload();
return result;
} catch (e) {
if (current === sync) status.error = errorCode(e);
throw e;
} finally {
status.running = false;
notify();
}
}
const scheduler = createSyncScheduler({ run });
/** @param {string|null} next */
async function setKey(next) {
scheduler.cancel();
key = next;
sync = next ? createSync({ store: db, syncKey: next }) : null;
status.hasKey = !!next;
status.error = null;
await db.setMeta("syncKey", next);
notify();
}
return {
/** Lit la clé enregistrée et branche les déclencheurs. */
async start() {
const saved = await db.getMeta("syncKey");
const last = await db.getMeta("syncLastAt");
status.lastAt = typeof last === "string" ? last : null;
if (typeof saved === "string" && saved) {
key = saved;
sync = createSync({ store: db, syncKey: saved });
status.hasKey = true;
}
window.addEventListener("online", () => {
status.online = true;
notify();
if (sync) void scheduler.now();
});
window.addEventListener("offline", () => {
status.online = false;
notify();
});
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible" && sync) void scheduler.now();
});
if (sync) void scheduler.now();
},
getKey: () => key,
/** @returns {Readonly<SyncStatus>} */
getStatus: () => status,
/** @param {() => void} fn @returns {() => void} */
subscribe(fn) {
listeners.add(fn);
return () => { listeners.delete(fn); };
},
/** Synchronise tout de suite ; renvoie l'état ensuite. */
async syncNow() {
await scheduler.now();
return status;
},
/** Un événement local vient d'être écrit : synchro dans 3 s, regroupée. */
later() {
if (sync) scheduler.later();
},
/**
* Lit le relais avec une clé, avant de l'adopter (« J'ai déjà une clé ») :
* les événements trouvés rejoignent le journal local.
* @param {string} candidate clé normalisée
* @returns {Promise<{exists: boolean, added: number}>} lève une SyncError
*/
async probe(candidate) {
const { exists, added } = await createSync({ store: db, syncKey: candidate }).pull();
if (added) await reload();
return { exists, added };
},
/**
* Adopte une clé (nouvelle, collée ou appariée) puis synchronise : les
* événements du relais rejoignent le journal local, et les événements
* locaux partent vers le relais.
* @param {string} next clé normalisée
*/
async enable(next) {
await setKey(next);
await scheduler.now();
return status;
},
/** Oublie la clé sur cet appareil ; le journal local et le relais restent. */
async disable() {
await setKey(null);
},
};
}
/** @typedef {ReturnType<typeof createSyncService>} SyncService */
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2009 Kazuhiko Arase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1
View File
@@ -0,0 +1 @@
`qrcode.mjs` : qrcode-generator 2.0.4 de Kazuhiko Arase (registre npm, `dist/qrcode.mjs`, sha256 ea91d711…b7c0), licence MIT (`LICENSE`), non modifié ; `qrcode.d.mts` : ses types réduits, pour `make lint`.
+18
View File
@@ -0,0 +1,18 @@
// Types de qrcode.mjs, pour la vérification JSDoc (make lint) : ce qu'IA-Fit
// en utilise, repris de qrcode.d.ts du même paquet (MIT, Kazuhiko Arase). Sans
// ce fichier, tsc vérifierait le code vendorisé lui-même.
type ErrorCorrectionLevel = "L" | "M" | "Q" | "H";
type Mode = "Numeric" | "Alphanumeric" | "Byte" | "Kanji";
export interface QRCode {
addData(data: string, mode?: Mode): void;
make(): void;
getModuleCount(): number;
isDark(row: number, col: number): boolean;
}
/** typeNumber : 0 (automatique) à 40. */
declare function qrcode(typeNumber: number, errorCorrectionLevel: ErrorCorrectionLevel): QRCode;
export default qrcode;
export { qrcode };
File diff suppressed because it is too large Load Diff