diff --git a/Makefile b/Makefile index a9e4a8c..09fa438 100644 --- a/Makefile +++ b/Makefile @@ -74,17 +74,34 @@ PLAYWRIGHT_VERSION := 1.48.2 PLAYWRIGHT_IMAGE := mcr.microsoft.com/playwright:v$(PLAYWRIGHT_VERSION)-noble BROWSER_TOOLS := build/browser-tools PLAYWRIGHT := $(BROWSER_TOOLS)/node_modules/playwright/package.json +# Lecture du QR code de la synchro dans une capture d'écran, pour le parcours +# seulement (jamais publié) : jsQR (Apache-2.0) et pngjs (MIT). +JSQR_VERSION := 1.4.0 +PNGJS_VERSION := 7.0.0 +QR_READER := $(BROWSER_TOOLS)/node_modules/jsqr/package.json -$(PLAYWRIGHT): - npm install --silent --no-audit --no-fund --prefix $(BROWSER_TOOLS) playwright@$(PLAYWRIGHT_VERSION) +$(PLAYWRIGHT) $(QR_READER) &: + npm install --silent --no-audit --no-fund --prefix $(BROWSER_TOOLS) playwright@$(PLAYWRIGHT_VERSION) jsqr@$(JSQR_VERSION) pngjs@$(PNGJS_VERSION) +# Le parcours de la synchro (relais, appariement, OAuth) parle au vrai serveur +# (server/main.js), lancé ici avec Node de l'hôte (Node 24, comme en production ; +# celui de l'image Playwright est trop ancien) sur un port libre, avec un +# DATA_DIR temporaire effacé à la fin. Le conteneur partage le réseau de l'hôte +# pour le joindre. .PHONY: test-browser -test-browser: $(PLAYWRIGHT) ## Parcours Playwright de l'app, captures dans build/shots/ (Docker) +test-browser: $(PLAYWRIGHT) $(QR_READER) ## Parcours Playwright de l'app, captures dans build/shots/ (Docker) @mkdir -p build/shots - @docker run --rm --init --ipc=host -u "$$(id -u):$$(id -g)" -e HOME=/tmp \ + @data="$$(mktemp -d)"; \ + port="$$(node -e 'const s=require("node:net").createServer().listen(0,"127.0.0.1",()=>{console.log(s.address().port);s.close()})')"; \ + PORT="$$port" SITE_DIR="$(CURDIR)/$(APP_DIR)" DATA_DIR="$$data" PUBLIC_URL="http://127.0.0.1:$$port" \ + node server/main.js >"$$data.log" 2>&1 & pid=$$!; \ + trap 'kill $$pid 2>/dev/null; rm -rf -- "$$data" "$$data.log"' EXIT; \ + for _ in $$(seq 50); do curl -sf -o /dev/null "http://127.0.0.1:$$port/" && break; sleep 0.1; done; \ + curl -sf -o /dev/null "http://127.0.0.1:$$port/" || { echo "Le serveur ne démarre pas :"; cat "$$data.log"; exit 1; }; \ + docker run --rm --init --ipc=host --network host -u "$$(id -u):$$(id -g)" -e HOME=/tmp \ -v "$(CURDIR)/$(APP_DIR):/app:ro" -v "$(CURDIR)/tests/browser:/tests:ro" \ -v "$(CURDIR)/$(BROWSER_TOOLS):/tools:ro" -v "$(CURDIR)/build/shots:/shots" \ - $(PLAYWRIGHT_IMAGE) node /tests/parcours.cjs /app /shots + $(PLAYWRIGHT_IMAGE) node /tests/parcours.cjs /app /shots "http://127.0.0.1:$$port/" test-site: ## Construit l'image de production en local et vérifie ce qu'elle sert (Docker) @tests/test_site.sh diff --git a/app/main.js b/app/main.js index 3121d98..37d0906 100644 --- a/app/main.js +++ b/app/main.js @@ -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=, 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() }); } }); diff --git a/app/styles/screens.css b/app/styles/screens.css index 6e501d4..ae590ff 100644 --- a/app/styles/screens.css +++ b/app/styles/screens.css @@ -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; } diff --git a/app/ui/connect-model.js b/app/ui/connect-model.js new file mode 100644 index 0000000..764bd5d --- /dev/null +++ b/app/ui/connect-model.js @@ -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} 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} */ + 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} 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} */ +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."; +} diff --git a/app/ui/onboarding.js b/app/ui/onboarding.js index b2bbc2b..3a6b7b8 100644 --- a/app/ui/onboarding.js +++ b/app/ui/onboarding.js @@ -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"))); } diff --git a/app/ui/qr.js b/app/ui/qr.js new file mode 100644 index 0000000..93634b9 --- /dev/null +++ b/app/ui/qr.js @@ -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; +} diff --git a/app/ui/router.js b/app/ui/router.js index 0ebd07b..e09907e 100644 --- a/app/ui/router.js +++ b/app/ui/router.js @@ -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} */ 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", }; /** diff --git a/app/ui/screens/connect-ai.js b/app/ui/screens/connect-ai.js new file mode 100644 index 0000000..19c690b --- /dev/null +++ b/app/ui/screens/connect-ai.js @@ -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)), + }; +} diff --git a/app/ui/screens/home.js b/app/ui/screens/home.js index c302e1d..8d569a1 100644 --- a/app/ui/screens/home.js +++ b/app/ui/screens/home.js @@ -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)); } diff --git a/app/ui/screens/profile.js b/app/ui/screens/profile.js index 38b84e8..899fbd0 100644 --- a/app/ui/screens/profile.js +++ b/app/ui/screens/profile.js @@ -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" }; } diff --git a/app/ui/screens/sync.js b/app/ui/screens/sync.js new file mode 100644 index 0000000..74cbb17 --- /dev/null +++ b/app/ui/screens/sync.js @@ -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)), + }; +} diff --git a/app/ui/store.js b/app/ui/store.js index a332a89..0dadd8d 100644 --- a/app/ui/store.js +++ b/app/ui/store.js @@ -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(); }, diff --git a/app/ui/sync-model.js b/app/ui/sync-model.js new file mode 100644 index 0000000..5934ddc --- /dev/null +++ b/app/ui/sync-model.js @@ -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} */ +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, delayMs?: number, timers?: {setTimeout: typeof setTimeout, clearTimeout: typeof clearTimeout}}} options + */ +export function createSyncScheduler({ run, delayMs = PUSH_DELAY_MS, timers = globalThis }) { + /** @type {ReturnType|null} */ + let timer = null; + /** @type {Promise|null} */ + let running = null; + let again = false; + + /** @returns {Promise} */ + 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= », 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("-"); +} diff --git a/app/ui/sync-service.js b/app/ui/sync-service.js new file mode 100644 index 0000000..cca64f5 --- /dev/null +++ b/app/ui/sync-service.js @@ -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} list + * @property {(events: readonly DomainEvent[]) => Promise} add + * @property {(key: string) => Promise} getMeta + * @property {(key: string, value: unknown) => Promise} 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|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} */ + 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} SyncService */ diff --git a/app/vendor/qrcode-generator/LICENSE b/app/vendor/qrcode-generator/LICENSE new file mode 100644 index 0000000..150770c --- /dev/null +++ b/app/vendor/qrcode-generator/LICENSE @@ -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. diff --git a/app/vendor/qrcode-generator/README.md b/app/vendor/qrcode-generator/README.md new file mode 100644 index 0000000..d93a0cd --- /dev/null +++ b/app/vendor/qrcode-generator/README.md @@ -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`. diff --git a/app/vendor/qrcode-generator/qrcode.d.mts b/app/vendor/qrcode-generator/qrcode.d.mts new file mode 100644 index 0000000..c73176b --- /dev/null +++ b/app/vendor/qrcode-generator/qrcode.d.mts @@ -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 }; diff --git a/app/vendor/qrcode-generator/qrcode.mjs b/app/vendor/qrcode-generator/qrcode.mjs new file mode 100644 index 0000000..4445225 --- /dev/null +++ b/app/vendor/qrcode-generator/qrcode.mjs @@ -0,0 +1,2237 @@ +//--------------------------------------------------------------------- +// +// QR Code Generator for JavaScript +// +// Copyright (c) 2009 Kazuhiko Arase +// +// URL: http://www.d-project.com/ +// +// Licensed under the MIT license: +// http://www.opensource.org/licenses/mit-license.php +// +// The word 'QR Code' is registered trademark of +// DENSO WAVE INCORPORATED +// http://www.denso-wave.com/qrcode/faqpatent-e.html +// +//--------------------------------------------------------------------- + +//--------------------------------------------------------------------- +// qrcode +//--------------------------------------------------------------------- + +/** + * qrcode + * @param typeNumber 1 to 40 + * @param errorCorrectionLevel 'L','M','Q','H' + */ +export const qrcode = function(typeNumber, errorCorrectionLevel) { + + const PAD0 = 0xEC; + const PAD1 = 0x11; + + let _typeNumber = typeNumber; + const _errorCorrectionLevel = QRErrorCorrectionLevel[errorCorrectionLevel]; + let _modules = null; + let _moduleCount = 0; + let _dataCache = null; + const _dataList = []; + + const _this = {}; + + const makeImpl = function(test, maskPattern) { + + _moduleCount = _typeNumber * 4 + 17; + _modules = function(moduleCount) { + const modules = new Array(moduleCount); + for (let row = 0; row < moduleCount; row += 1) { + modules[row] = new Array(moduleCount); + for (let col = 0; col < moduleCount; col += 1) { + modules[row][col] = null; + } + } + return modules; + }(_moduleCount); + + setupPositionProbePattern(0, 0); + setupPositionProbePattern(_moduleCount - 7, 0); + setupPositionProbePattern(0, _moduleCount - 7); + setupPositionAdjustPattern(); + setupTimingPattern(); + setupTypeInfo(test, maskPattern); + + if (_typeNumber >= 7) { + setupTypeNumber(test); + } + + if (_dataCache == null) { + _dataCache = createData(_typeNumber, _errorCorrectionLevel, _dataList); + } + + mapData(_dataCache, maskPattern); + }; + + const setupPositionProbePattern = function(row, col) { + + for (let r = -1; r <= 7; r += 1) { + + if (row + r <= -1 || _moduleCount <= row + r) continue; + + for (let c = -1; c <= 7; c += 1) { + + if (col + c <= -1 || _moduleCount <= col + c) continue; + + if ( (0 <= r && r <= 6 && (c == 0 || c == 6) ) + || (0 <= c && c <= 6 && (r == 0 || r == 6) ) + || (2 <= r && r <= 4 && 2 <= c && c <= 4) ) { + _modules[row + r][col + c] = true; + } else { + _modules[row + r][col + c] = false; + } + } + } + }; + + const getBestMaskPattern = function() { + + let minLostPoint = 0; + let pattern = 0; + + for (let i = 0; i < 8; i += 1) { + + makeImpl(true, i); + + const lostPoint = QRUtil.getLostPoint(_this); + + if (i == 0 || minLostPoint > lostPoint) { + minLostPoint = lostPoint; + pattern = i; + } + } + + return pattern; + }; + + const setupTimingPattern = function() { + + for (let r = 8; r < _moduleCount - 8; r += 1) { + if (_modules[r][6] != null) { + continue; + } + _modules[r][6] = (r % 2 == 0); + } + + for (let c = 8; c < _moduleCount - 8; c += 1) { + if (_modules[6][c] != null) { + continue; + } + _modules[6][c] = (c % 2 == 0); + } + }; + + const setupPositionAdjustPattern = function() { + + const pos = QRUtil.getPatternPosition(_typeNumber); + + for (let i = 0; i < pos.length; i += 1) { + + for (let j = 0; j < pos.length; j += 1) { + + const row = pos[i]; + const col = pos[j]; + + if (_modules[row][col] != null) { + continue; + } + + for (let r = -2; r <= 2; r += 1) { + + for (let c = -2; c <= 2; c += 1) { + + if (r == -2 || r == 2 || c == -2 || c == 2 + || (r == 0 && c == 0) ) { + _modules[row + r][col + c] = true; + } else { + _modules[row + r][col + c] = false; + } + } + } + } + } + }; + + const setupTypeNumber = function(test) { + + const bits = QRUtil.getBCHTypeNumber(_typeNumber); + + for (let i = 0; i < 18; i += 1) { + const mod = (!test && ( (bits >> i) & 1) == 1); + _modules[Math.floor(i / 3)][i % 3 + _moduleCount - 8 - 3] = mod; + } + + for (let i = 0; i < 18; i += 1) { + const mod = (!test && ( (bits >> i) & 1) == 1); + _modules[i % 3 + _moduleCount - 8 - 3][Math.floor(i / 3)] = mod; + } + }; + + const setupTypeInfo = function(test, maskPattern) { + + const data = (_errorCorrectionLevel << 3) | maskPattern; + const bits = QRUtil.getBCHTypeInfo(data); + + // vertical + for (let i = 0; i < 15; i += 1) { + + const mod = (!test && ( (bits >> i) & 1) == 1); + + if (i < 6) { + _modules[i][8] = mod; + } else if (i < 8) { + _modules[i + 1][8] = mod; + } else { + _modules[_moduleCount - 15 + i][8] = mod; + } + } + + // horizontal + for (let i = 0; i < 15; i += 1) { + + const mod = (!test && ( (bits >> i) & 1) == 1); + + if (i < 8) { + _modules[8][_moduleCount - i - 1] = mod; + } else if (i < 9) { + _modules[8][15 - i - 1 + 1] = mod; + } else { + _modules[8][15 - i - 1] = mod; + } + } + + // fixed module + _modules[_moduleCount - 8][8] = (!test); + }; + + const mapData = function(data, maskPattern) { + + let inc = -1; + let row = _moduleCount - 1; + let bitIndex = 7; + let byteIndex = 0; + const maskFunc = QRUtil.getMaskFunction(maskPattern); + + for (let col = _moduleCount - 1; col > 0; col -= 2) { + + if (col == 6) col -= 1; + + while (true) { + + for (let c = 0; c < 2; c += 1) { + + if (_modules[row][col - c] == null) { + + let dark = false; + + if (byteIndex < data.length) { + dark = ( ( (data[byteIndex] >>> bitIndex) & 1) == 1); + } + + const mask = maskFunc(row, col - c); + + if (mask) { + dark = !dark; + } + + _modules[row][col - c] = dark; + bitIndex -= 1; + + if (bitIndex == -1) { + byteIndex += 1; + bitIndex = 7; + } + } + } + + row += inc; + + if (row < 0 || _moduleCount <= row) { + row -= inc; + inc = -inc; + break; + } + } + } + }; + + const createBytes = function(buffer, rsBlocks) { + + let offset = 0; + + let maxDcCount = 0; + let maxEcCount = 0; + + const dcdata = new Array(rsBlocks.length); + const ecdata = new Array(rsBlocks.length); + + for (let r = 0; r < rsBlocks.length; r += 1) { + + const dcCount = rsBlocks[r].dataCount; + const ecCount = rsBlocks[r].totalCount - dcCount; + + maxDcCount = Math.max(maxDcCount, dcCount); + maxEcCount = Math.max(maxEcCount, ecCount); + + dcdata[r] = new Array(dcCount); + + for (let i = 0; i < dcdata[r].length; i += 1) { + dcdata[r][i] = 0xff & buffer.getBuffer()[i + offset]; + } + offset += dcCount; + + const rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount); + const rawPoly = qrPolynomial(dcdata[r], rsPoly.getLength() - 1); + + const modPoly = rawPoly.mod(rsPoly); + ecdata[r] = new Array(rsPoly.getLength() - 1); + for (let i = 0; i < ecdata[r].length; i += 1) { + const modIndex = i + modPoly.getLength() - ecdata[r].length; + ecdata[r][i] = (modIndex >= 0)? modPoly.getAt(modIndex) : 0; + } + } + + let totalCodeCount = 0; + for (let i = 0; i < rsBlocks.length; i += 1) { + totalCodeCount += rsBlocks[i].totalCount; + } + + const data = new Array(totalCodeCount); + let index = 0; + + for (let i = 0; i < maxDcCount; i += 1) { + for (let r = 0; r < rsBlocks.length; r += 1) { + if (i < dcdata[r].length) { + data[index] = dcdata[r][i]; + index += 1; + } + } + } + + for (let i = 0; i < maxEcCount; i += 1) { + for (let r = 0; r < rsBlocks.length; r += 1) { + if (i < ecdata[r].length) { + data[index] = ecdata[r][i]; + index += 1; + } + } + } + + return data; + }; + + const createData = function(typeNumber, errorCorrectionLevel, dataList) { + + const rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectionLevel); + + const buffer = qrBitBuffer(); + + for (let i = 0; i < dataList.length; i += 1) { + const data = dataList[i]; + buffer.put(data.getMode(), 4); + buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber) ); + data.write(buffer); + } + + // calc num max data. + let totalDataCount = 0; + for (let i = 0; i < rsBlocks.length; i += 1) { + totalDataCount += rsBlocks[i].dataCount; + } + + if (buffer.getLengthInBits() > totalDataCount * 8) { + throw 'code length overflow. (' + + buffer.getLengthInBits() + + '>' + + totalDataCount * 8 + + ')'; + } + + // end code + if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) { + buffer.put(0, 4); + } + + // padding + while (buffer.getLengthInBits() % 8 != 0) { + buffer.putBit(false); + } + + // padding + while (true) { + + if (buffer.getLengthInBits() >= totalDataCount * 8) { + break; + } + buffer.put(PAD0, 8); + + if (buffer.getLengthInBits() >= totalDataCount * 8) { + break; + } + buffer.put(PAD1, 8); + } + + return createBytes(buffer, rsBlocks); + }; + + _this.addData = function(data, mode) { + + mode = mode || 'Byte'; + + let newData = null; + + switch(mode) { + case 'Numeric' : + newData = qrNumber(data); + break; + case 'Alphanumeric' : + newData = qrAlphaNum(data); + break; + case 'Byte' : + newData = qr8BitByte(data); + break; + case 'Kanji' : + newData = qrKanji(data); + break; + default : + throw 'mode:' + mode; + } + + _dataList.push(newData); + _dataCache = null; + }; + + _this.isDark = function(row, col) { + if (row < 0 || _moduleCount <= row || col < 0 || _moduleCount <= col) { + throw row + ',' + col; + } + return _modules[row][col]; + }; + + _this.getModuleCount = function() { + return _moduleCount; + }; + + _this.make = function() { + if (_typeNumber < 1) { + let typeNumber = 1; + + for (; typeNumber < 40; typeNumber++) { + const rsBlocks = QRRSBlock.getRSBlocks(typeNumber, _errorCorrectionLevel); + const buffer = qrBitBuffer(); + + for (let i = 0; i < _dataList.length; i++) { + const data = _dataList[i]; + buffer.put(data.getMode(), 4); + buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber) ); + data.write(buffer); + } + + let totalDataCount = 0; + for (let i = 0; i < rsBlocks.length; i++) { + totalDataCount += rsBlocks[i].dataCount; + } + + if (buffer.getLengthInBits() <= totalDataCount * 8) { + break; + } + } + + _typeNumber = typeNumber; + } + + makeImpl(false, getBestMaskPattern() ); + }; + + _this.createTableTag = function(cellSize, margin) { + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + let qrHtml = ''; + + qrHtml += ''; + qrHtml += ''; + + for (let r = 0; r < _this.getModuleCount(); r += 1) { + + qrHtml += ''; + + for (let c = 0; c < _this.getModuleCount(); c += 1) { + qrHtml += ''; + } + + qrHtml += ''; + qrHtml += '
'; + } + + qrHtml += '
'; + + return qrHtml; + }; + + _this.createSvgTag = function(cellSize, margin, alt, title) { + + let opts = {}; + if (typeof arguments[0] == 'object') { + // Called by options. + opts = arguments[0]; + // overwrite cellSize and margin. + cellSize = opts.cellSize; + margin = opts.margin; + alt = opts.alt; + title = opts.title; + } + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + // Compose alt property surrogate + alt = (typeof alt === 'string') ? {text: alt} : alt || {}; + alt.text = alt.text || null; + alt.id = (alt.text) ? alt.id || 'qrcode-description' : null; + + // Compose title property surrogate + title = (typeof title === 'string') ? {text: title} : title || {}; + title.text = title.text || null; + title.id = (title.text) ? title.id || 'qrcode-title' : null; + + const size = _this.getModuleCount() * cellSize + margin * 2; + let c, mc, r, mr, qrSvg='', rect; + + rect = 'l' + cellSize + ',0 0,' + cellSize + + ' -' + cellSize + ',0 0,-' + cellSize + 'z '; + + qrSvg += '' + + escapeXml(title.text) + '' : ''; + qrSvg += (alt.text) ? '' + + escapeXml(alt.text) + '' : ''; + qrSvg += ''; + qrSvg += ''; + qrSvg += ''; + + return qrSvg; + }; + + _this.createDataURL = function(cellSize, margin) { + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + const size = _this.getModuleCount() * cellSize + margin * 2; + const min = margin; + const max = size - margin; + + return createDataURL(size, size, function(x, y) { + if (min <= x && x < max && min <= y && y < max) { + const c = Math.floor( (x - min) / cellSize); + const r = Math.floor( (y - min) / cellSize); + return _this.isDark(r, c)? 0 : 1; + } else { + return 1; + } + } ); + }; + + _this.createImgTag = function(cellSize, margin, alt) { + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + const size = _this.getModuleCount() * cellSize + margin * 2; + + let img = ''; + img += '': escaped += '>'; break; + case '&': escaped += '&'; break; + case '"': escaped += '"'; break; + default : escaped += c; break; + } + } + return escaped; + }; + + const _createHalfASCII = function(margin) { + const cellSize = 1; + margin = (typeof margin == 'undefined')? cellSize * 2 : margin; + + const size = _this.getModuleCount() * cellSize + margin * 2; + const min = margin; + const max = size - margin; + + let y, x, r1, r2, p; + + const blocks = { + '██': '█', + '█ ': '▀', + ' █': '▄', + ' ': ' ' + }; + + const blocksLastLineNoMargin = { + '██': '▀', + '█ ': '▀', + ' █': ' ', + ' ': ' ' + }; + + let ascii = ''; + for (y = 0; y < size; y += 2) { + r1 = Math.floor((y - min) / cellSize); + r2 = Math.floor((y + 1 - min) / cellSize); + for (x = 0; x < size; x += 1) { + p = '█'; + + if (min <= x && x < max && min <= y && y < max && _this.isDark(r1, Math.floor((x - min) / cellSize))) { + p = ' '; + } + + if (min <= x && x < max && min <= y+1 && y+1 < max && _this.isDark(r2, Math.floor((x - min) / cellSize))) { + p += ' '; + } + else { + p += '█'; + } + + // Output 2 characters per pixel, to create full square. 1 character per pixels gives only half width of square. + ascii += (margin < 1 && y+1 >= max) ? blocksLastLineNoMargin[p] : blocks[p]; + } + + ascii += '\n'; + } + + if (size % 2 && margin > 0) { + return ascii.substring(0, ascii.length - size - 1) + Array(size+1).join('▀'); + } + + return ascii.substring(0, ascii.length-1); + }; + + _this.createASCII = function(cellSize, margin) { + cellSize = cellSize || 1; + + if (cellSize < 2) { + return _createHalfASCII(margin); + } + + cellSize -= 1; + margin = (typeof margin == 'undefined')? cellSize * 2 : margin; + + const size = _this.getModuleCount() * cellSize + margin * 2; + const min = margin; + const max = size - margin; + + let y, x, r, p; + + const white = Array(cellSize+1).join('██'); + const black = Array(cellSize+1).join(' '); + + let ascii = ''; + let line = ''; + for (y = 0; y < size; y += 1) { + r = Math.floor( (y - min) / cellSize); + line = ''; + for (x = 0; x < size; x += 1) { + p = 1; + + if (min <= x && x < max && min <= y && y < max && _this.isDark(r, Math.floor((x - min) / cellSize))) { + p = 0; + } + + // Output 2 characters per pixel, to create full square. 1 character per pixels gives only half width of square. + line += p ? white : black; + } + + for (r = 0; r < cellSize; r += 1) { + ascii += line + '\n'; + } + } + + return ascii.substring(0, ascii.length-1); + }; + + _this.renderTo2dContext = function(context, cellSize) { + cellSize = cellSize || 2; + const length = _this.getModuleCount(); + for (let row = 0; row < length; row++) { + for (let col = 0; col < length; col++) { + context.fillStyle = _this.isDark(row, col) ? 'black' : 'white'; + context.fillRect(col * cellSize, row * cellSize, cellSize, cellSize); + } + } + } + + return _this; +}; + +//--------------------------------------------------------------------- +// qrcode.stringToBytes +//--------------------------------------------------------------------- + +qrcode.stringToBytes = function(s) { + const bytes = []; + for (let i = 0; i < s.length; i += 1) { + const c = s.charCodeAt(i); + bytes.push(c & 0xff); + } + return bytes; +}; + +//--------------------------------------------------------------------- +// qrcode.createStringToBytes +//--------------------------------------------------------------------- + +/** + * @param unicodeData base64 string of byte array. + * [16bit Unicode],[16bit Bytes], ... + * @param numChars + */ +qrcode.createStringToBytes = function(unicodeData, numChars) { + + // create conversion map. + + const unicodeMap = function() { + + const bin = base64DecodeInputStream(unicodeData); + const read = function() { + const b = bin.read(); + if (b == -1) throw 'eof'; + return b; + }; + + let count = 0; + const unicodeMap = {}; + while (true) { + const b0 = bin.read(); + if (b0 == -1) break; + const b1 = read(); + const b2 = read(); + const b3 = read(); + const k = String.fromCharCode( (b0 << 8) | b1); + const v = (b2 << 8) | b3; + unicodeMap[k] = v; + count += 1; + } + if (count != numChars) { + throw count + ' != ' + numChars; + } + + return unicodeMap; + }(); + + const unknownChar = '?'.charCodeAt(0); + + return function(s) { + const bytes = []; + for (let i = 0; i < s.length; i += 1) { + const c = s.charCodeAt(i); + if (c < 128) { + bytes.push(c); + } else { + const b = unicodeMap[s.charAt(i)]; + if (typeof b == 'number') { + if ( (b & 0xff) == b) { + // 1byte + bytes.push(b); + } else { + // 2bytes + bytes.push(b >>> 8); + bytes.push(b & 0xff); + } + } else { + bytes.push(unknownChar); + } + } + } + return bytes; + }; +}; + +//--------------------------------------------------------------------- +// QRMode +//--------------------------------------------------------------------- + +const QRMode = { + MODE_NUMBER : 1 << 0, + MODE_ALPHA_NUM : 1 << 1, + MODE_8BIT_BYTE : 1 << 2, + MODE_KANJI : 1 << 3 +}; + +//--------------------------------------------------------------------- +// QRErrorCorrectionLevel +//--------------------------------------------------------------------- + +const QRErrorCorrectionLevel = { + L : 1, + M : 0, + Q : 3, + H : 2 +}; + +//--------------------------------------------------------------------- +// QRMaskPattern +//--------------------------------------------------------------------- + +const QRMaskPattern = { + PATTERN000 : 0, + PATTERN001 : 1, + PATTERN010 : 2, + PATTERN011 : 3, + PATTERN100 : 4, + PATTERN101 : 5, + PATTERN110 : 6, + PATTERN111 : 7 +}; + +//--------------------------------------------------------------------- +// QRUtil +//--------------------------------------------------------------------- + +const QRUtil = function() { + + const PATTERN_POSITION_TABLE = [ + [], + [6, 18], + [6, 22], + [6, 26], + [6, 30], + [6, 34], + [6, 22, 38], + [6, 24, 42], + [6, 26, 46], + [6, 28, 50], + [6, 30, 54], + [6, 32, 58], + [6, 34, 62], + [6, 26, 46, 66], + [6, 26, 48, 70], + [6, 26, 50, 74], + [6, 30, 54, 78], + [6, 30, 56, 82], + [6, 30, 58, 86], + [6, 34, 62, 90], + [6, 28, 50, 72, 94], + [6, 26, 50, 74, 98], + [6, 30, 54, 78, 102], + [6, 28, 54, 80, 106], + [6, 32, 58, 84, 110], + [6, 30, 58, 86, 114], + [6, 34, 62, 90, 118], + [6, 26, 50, 74, 98, 122], + [6, 30, 54, 78, 102, 126], + [6, 26, 52, 78, 104, 130], + [6, 30, 56, 82, 108, 134], + [6, 34, 60, 86, 112, 138], + [6, 30, 58, 86, 114, 142], + [6, 34, 62, 90, 118, 146], + [6, 30, 54, 78, 102, 126, 150], + [6, 24, 50, 76, 102, 128, 154], + [6, 28, 54, 80, 106, 132, 158], + [6, 32, 58, 84, 110, 136, 162], + [6, 26, 54, 82, 110, 138, 166], + [6, 30, 58, 86, 114, 142, 170] + ]; + const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0); + const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0); + const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1); + + const _this = {}; + + const getBCHDigit = function(data) { + let digit = 0; + while (data != 0) { + digit += 1; + data >>>= 1; + } + return digit; + }; + + _this.getBCHTypeInfo = function(data) { + let d = data << 10; + while (getBCHDigit(d) - getBCHDigit(G15) >= 0) { + d ^= (G15 << (getBCHDigit(d) - getBCHDigit(G15) ) ); + } + return ( (data << 10) | d) ^ G15_MASK; + }; + + _this.getBCHTypeNumber = function(data) { + let d = data << 12; + while (getBCHDigit(d) - getBCHDigit(G18) >= 0) { + d ^= (G18 << (getBCHDigit(d) - getBCHDigit(G18) ) ); + } + return (data << 12) | d; + }; + + _this.getPatternPosition = function(typeNumber) { + return PATTERN_POSITION_TABLE[typeNumber - 1]; + }; + + _this.getMaskFunction = function(maskPattern) { + + switch (maskPattern) { + + case QRMaskPattern.PATTERN000 : + return function(i, j) { return (i + j) % 2 == 0; }; + case QRMaskPattern.PATTERN001 : + return function(i, j) { return i % 2 == 0; }; + case QRMaskPattern.PATTERN010 : + return function(i, j) { return j % 3 == 0; }; + case QRMaskPattern.PATTERN011 : + return function(i, j) { return (i + j) % 3 == 0; }; + case QRMaskPattern.PATTERN100 : + return function(i, j) { return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 == 0; }; + case QRMaskPattern.PATTERN101 : + return function(i, j) { return (i * j) % 2 + (i * j) % 3 == 0; }; + case QRMaskPattern.PATTERN110 : + return function(i, j) { return ( (i * j) % 2 + (i * j) % 3) % 2 == 0; }; + case QRMaskPattern.PATTERN111 : + return function(i, j) { return ( (i * j) % 3 + (i + j) % 2) % 2 == 0; }; + + default : + throw 'bad maskPattern:' + maskPattern; + } + }; + + _this.getErrorCorrectPolynomial = function(errorCorrectLength) { + let a = qrPolynomial([1], 0); + for (let i = 0; i < errorCorrectLength; i += 1) { + a = a.multiply(qrPolynomial([1, QRMath.gexp(i)], 0) ); + } + return a; + }; + + _this.getLengthInBits = function(mode, type) { + + if (1 <= type && type < 10) { + + // 1 - 9 + + switch(mode) { + case QRMode.MODE_NUMBER : return 10; + case QRMode.MODE_ALPHA_NUM : return 9; + case QRMode.MODE_8BIT_BYTE : return 8; + case QRMode.MODE_KANJI : return 8; + default : + throw 'mode:' + mode; + } + + } else if (type < 27) { + + // 10 - 26 + + switch(mode) { + case QRMode.MODE_NUMBER : return 12; + case QRMode.MODE_ALPHA_NUM : return 11; + case QRMode.MODE_8BIT_BYTE : return 16; + case QRMode.MODE_KANJI : return 10; + default : + throw 'mode:' + mode; + } + + } else if (type < 41) { + + // 27 - 40 + + switch(mode) { + case QRMode.MODE_NUMBER : return 14; + case QRMode.MODE_ALPHA_NUM : return 13; + case QRMode.MODE_8BIT_BYTE : return 16; + case QRMode.MODE_KANJI : return 12; + default : + throw 'mode:' + mode; + } + + } else { + throw 'type:' + type; + } + }; + + _this.getLostPoint = function(qrcode) { + + const moduleCount = qrcode.getModuleCount(); + + let lostPoint = 0; + + // LEVEL1 + + for (let row = 0; row < moduleCount; row += 1) { + for (let col = 0; col < moduleCount; col += 1) { + + let sameCount = 0; + const dark = qrcode.isDark(row, col); + + for (let r = -1; r <= 1; r += 1) { + + if (row + r < 0 || moduleCount <= row + r) { + continue; + } + + for (let c = -1; c <= 1; c += 1) { + + if (col + c < 0 || moduleCount <= col + c) { + continue; + } + + if (r == 0 && c == 0) { + continue; + } + + if (dark == qrcode.isDark(row + r, col + c) ) { + sameCount += 1; + } + } + } + + if (sameCount > 5) { + lostPoint += (3 + sameCount - 5); + } + } + }; + + // LEVEL2 + + for (let row = 0; row < moduleCount - 1; row += 1) { + for (let col = 0; col < moduleCount - 1; col += 1) { + let count = 0; + if (qrcode.isDark(row, col) ) count += 1; + if (qrcode.isDark(row + 1, col) ) count += 1; + if (qrcode.isDark(row, col + 1) ) count += 1; + if (qrcode.isDark(row + 1, col + 1) ) count += 1; + if (count == 0 || count == 4) { + lostPoint += 3; + } + } + } + + // LEVEL3 + + for (let row = 0; row < moduleCount; row += 1) { + for (let col = 0; col < moduleCount - 6; col += 1) { + if (qrcode.isDark(row, col) + && !qrcode.isDark(row, col + 1) + && qrcode.isDark(row, col + 2) + && qrcode.isDark(row, col + 3) + && qrcode.isDark(row, col + 4) + && !qrcode.isDark(row, col + 5) + && qrcode.isDark(row, col + 6) ) { + lostPoint += 40; + } + } + } + + for (let col = 0; col < moduleCount; col += 1) { + for (let row = 0; row < moduleCount - 6; row += 1) { + if (qrcode.isDark(row, col) + && !qrcode.isDark(row + 1, col) + && qrcode.isDark(row + 2, col) + && qrcode.isDark(row + 3, col) + && qrcode.isDark(row + 4, col) + && !qrcode.isDark(row + 5, col) + && qrcode.isDark(row + 6, col) ) { + lostPoint += 40; + } + } + } + + // LEVEL4 + + let darkCount = 0; + + for (let col = 0; col < moduleCount; col += 1) { + for (let row = 0; row < moduleCount; row += 1) { + if (qrcode.isDark(row, col) ) { + darkCount += 1; + } + } + } + + const ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5; + lostPoint += ratio * 10; + + return lostPoint; + }; + + return _this; +}(); + +//--------------------------------------------------------------------- +// QRMath +//--------------------------------------------------------------------- + +const QRMath = function() { + + const EXP_TABLE = new Array(256); + const LOG_TABLE = new Array(256); + + // initialize tables + for (let i = 0; i < 8; i += 1) { + EXP_TABLE[i] = 1 << i; + } + for (let i = 8; i < 256; i += 1) { + EXP_TABLE[i] = EXP_TABLE[i - 4] + ^ EXP_TABLE[i - 5] + ^ EXP_TABLE[i - 6] + ^ EXP_TABLE[i - 8]; + } + for (let i = 0; i < 255; i += 1) { + LOG_TABLE[EXP_TABLE[i] ] = i; + } + + const _this = {}; + + _this.glog = function(n) { + + if (n < 1) { + throw 'glog(' + n + ')'; + } + + return LOG_TABLE[n]; + }; + + _this.gexp = function(n) { + + while (n < 0) { + n += 255; + } + + while (n >= 256) { + n -= 255; + } + + return EXP_TABLE[n]; + }; + + return _this; +}(); + +//--------------------------------------------------------------------- +// qrPolynomial +//--------------------------------------------------------------------- + +const qrPolynomial = function(num, shift) { + + if (typeof num.length == 'undefined') { + throw num.length + '/' + shift; + } + + const _num = function() { + let offset = 0; + while (offset < num.length && num[offset] == 0) { + offset += 1; + } + const _num = new Array(num.length - offset + shift); + for (let i = 0; i < num.length - offset; i += 1) { + _num[i] = num[i + offset]; + } + return _num; + }(); + + const _this = {}; + + _this.getAt = function(index) { + return _num[index]; + }; + + _this.getLength = function() { + return _num.length; + }; + + _this.multiply = function(e) { + + const num = new Array(_this.getLength() + e.getLength() - 1); + + for (let i = 0; i < _this.getLength(); i += 1) { + for (let j = 0; j < e.getLength(); j += 1) { + num[i + j] ^= QRMath.gexp(QRMath.glog(_this.getAt(i) ) + QRMath.glog(e.getAt(j) ) ); + } + } + + return qrPolynomial(num, 0); + }; + + _this.mod = function(e) { + + if (_this.getLength() - e.getLength() < 0) { + return _this; + } + + const ratio = QRMath.glog(_this.getAt(0) ) - QRMath.glog(e.getAt(0) ); + + const num = new Array(_this.getLength() ); + for (let i = 0; i < _this.getLength(); i += 1) { + num[i] = _this.getAt(i); + } + + for (let i = 0; i < e.getLength(); i += 1) { + num[i] ^= QRMath.gexp(QRMath.glog(e.getAt(i) ) + ratio); + } + + // recursive call + return qrPolynomial(num, 0).mod(e); + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// QRRSBlock +//--------------------------------------------------------------------- + +const QRRSBlock = function() { + + const RS_BLOCK_TABLE = [ + + // L + // M + // Q + // H + + // 1 + [1, 26, 19], + [1, 26, 16], + [1, 26, 13], + [1, 26, 9], + + // 2 + [1, 44, 34], + [1, 44, 28], + [1, 44, 22], + [1, 44, 16], + + // 3 + [1, 70, 55], + [1, 70, 44], + [2, 35, 17], + [2, 35, 13], + + // 4 + [1, 100, 80], + [2, 50, 32], + [2, 50, 24], + [4, 25, 9], + + // 5 + [1, 134, 108], + [2, 67, 43], + [2, 33, 15, 2, 34, 16], + [2, 33, 11, 2, 34, 12], + + // 6 + [2, 86, 68], + [4, 43, 27], + [4, 43, 19], + [4, 43, 15], + + // 7 + [2, 98, 78], + [4, 49, 31], + [2, 32, 14, 4, 33, 15], + [4, 39, 13, 1, 40, 14], + + // 8 + [2, 121, 97], + [2, 60, 38, 2, 61, 39], + [4, 40, 18, 2, 41, 19], + [4, 40, 14, 2, 41, 15], + + // 9 + [2, 146, 116], + [3, 58, 36, 2, 59, 37], + [4, 36, 16, 4, 37, 17], + [4, 36, 12, 4, 37, 13], + + // 10 + [2, 86, 68, 2, 87, 69], + [4, 69, 43, 1, 70, 44], + [6, 43, 19, 2, 44, 20], + [6, 43, 15, 2, 44, 16], + + // 11 + [4, 101, 81], + [1, 80, 50, 4, 81, 51], + [4, 50, 22, 4, 51, 23], + [3, 36, 12, 8, 37, 13], + + // 12 + [2, 116, 92, 2, 117, 93], + [6, 58, 36, 2, 59, 37], + [4, 46, 20, 6, 47, 21], + [7, 42, 14, 4, 43, 15], + + // 13 + [4, 133, 107], + [8, 59, 37, 1, 60, 38], + [8, 44, 20, 4, 45, 21], + [12, 33, 11, 4, 34, 12], + + // 14 + [3, 145, 115, 1, 146, 116], + [4, 64, 40, 5, 65, 41], + [11, 36, 16, 5, 37, 17], + [11, 36, 12, 5, 37, 13], + + // 15 + [5, 109, 87, 1, 110, 88], + [5, 65, 41, 5, 66, 42], + [5, 54, 24, 7, 55, 25], + [11, 36, 12, 7, 37, 13], + + // 16 + [5, 122, 98, 1, 123, 99], + [7, 73, 45, 3, 74, 46], + [15, 43, 19, 2, 44, 20], + [3, 45, 15, 13, 46, 16], + + // 17 + [1, 135, 107, 5, 136, 108], + [10, 74, 46, 1, 75, 47], + [1, 50, 22, 15, 51, 23], + [2, 42, 14, 17, 43, 15], + + // 18 + [5, 150, 120, 1, 151, 121], + [9, 69, 43, 4, 70, 44], + [17, 50, 22, 1, 51, 23], + [2, 42, 14, 19, 43, 15], + + // 19 + [3, 141, 113, 4, 142, 114], + [3, 70, 44, 11, 71, 45], + [17, 47, 21, 4, 48, 22], + [9, 39, 13, 16, 40, 14], + + // 20 + [3, 135, 107, 5, 136, 108], + [3, 67, 41, 13, 68, 42], + [15, 54, 24, 5, 55, 25], + [15, 43, 15, 10, 44, 16], + + // 21 + [4, 144, 116, 4, 145, 117], + [17, 68, 42], + [17, 50, 22, 6, 51, 23], + [19, 46, 16, 6, 47, 17], + + // 22 + [2, 139, 111, 7, 140, 112], + [17, 74, 46], + [7, 54, 24, 16, 55, 25], + [34, 37, 13], + + // 23 + [4, 151, 121, 5, 152, 122], + [4, 75, 47, 14, 76, 48], + [11, 54, 24, 14, 55, 25], + [16, 45, 15, 14, 46, 16], + + // 24 + [6, 147, 117, 4, 148, 118], + [6, 73, 45, 14, 74, 46], + [11, 54, 24, 16, 55, 25], + [30, 46, 16, 2, 47, 17], + + // 25 + [8, 132, 106, 4, 133, 107], + [8, 75, 47, 13, 76, 48], + [7, 54, 24, 22, 55, 25], + [22, 45, 15, 13, 46, 16], + + // 26 + [10, 142, 114, 2, 143, 115], + [19, 74, 46, 4, 75, 47], + [28, 50, 22, 6, 51, 23], + [33, 46, 16, 4, 47, 17], + + // 27 + [8, 152, 122, 4, 153, 123], + [22, 73, 45, 3, 74, 46], + [8, 53, 23, 26, 54, 24], + [12, 45, 15, 28, 46, 16], + + // 28 + [3, 147, 117, 10, 148, 118], + [3, 73, 45, 23, 74, 46], + [4, 54, 24, 31, 55, 25], + [11, 45, 15, 31, 46, 16], + + // 29 + [7, 146, 116, 7, 147, 117], + [21, 73, 45, 7, 74, 46], + [1, 53, 23, 37, 54, 24], + [19, 45, 15, 26, 46, 16], + + // 30 + [5, 145, 115, 10, 146, 116], + [19, 75, 47, 10, 76, 48], + [15, 54, 24, 25, 55, 25], + [23, 45, 15, 25, 46, 16], + + // 31 + [13, 145, 115, 3, 146, 116], + [2, 74, 46, 29, 75, 47], + [42, 54, 24, 1, 55, 25], + [23, 45, 15, 28, 46, 16], + + // 32 + [17, 145, 115], + [10, 74, 46, 23, 75, 47], + [10, 54, 24, 35, 55, 25], + [19, 45, 15, 35, 46, 16], + + // 33 + [17, 145, 115, 1, 146, 116], + [14, 74, 46, 21, 75, 47], + [29, 54, 24, 19, 55, 25], + [11, 45, 15, 46, 46, 16], + + // 34 + [13, 145, 115, 6, 146, 116], + [14, 74, 46, 23, 75, 47], + [44, 54, 24, 7, 55, 25], + [59, 46, 16, 1, 47, 17], + + // 35 + [12, 151, 121, 7, 152, 122], + [12, 75, 47, 26, 76, 48], + [39, 54, 24, 14, 55, 25], + [22, 45, 15, 41, 46, 16], + + // 36 + [6, 151, 121, 14, 152, 122], + [6, 75, 47, 34, 76, 48], + [46, 54, 24, 10, 55, 25], + [2, 45, 15, 64, 46, 16], + + // 37 + [17, 152, 122, 4, 153, 123], + [29, 74, 46, 14, 75, 47], + [49, 54, 24, 10, 55, 25], + [24, 45, 15, 46, 46, 16], + + // 38 + [4, 152, 122, 18, 153, 123], + [13, 74, 46, 32, 75, 47], + [48, 54, 24, 14, 55, 25], + [42, 45, 15, 32, 46, 16], + + // 39 + [20, 147, 117, 4, 148, 118], + [40, 75, 47, 7, 76, 48], + [43, 54, 24, 22, 55, 25], + [10, 45, 15, 67, 46, 16], + + // 40 + [19, 148, 118, 6, 149, 119], + [18, 75, 47, 31, 76, 48], + [34, 54, 24, 34, 55, 25], + [20, 45, 15, 61, 46, 16] + ]; + + const qrRSBlock = function(totalCount, dataCount) { + const _this = {}; + _this.totalCount = totalCount; + _this.dataCount = dataCount; + return _this; + }; + + const _this = {}; + + const getRsBlockTable = function(typeNumber, errorCorrectionLevel) { + + switch(errorCorrectionLevel) { + case QRErrorCorrectionLevel.L : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]; + case QRErrorCorrectionLevel.M : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]; + case QRErrorCorrectionLevel.Q : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]; + case QRErrorCorrectionLevel.H : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]; + default : + return undefined; + } + }; + + _this.getRSBlocks = function(typeNumber, errorCorrectionLevel) { + + const rsBlock = getRsBlockTable(typeNumber, errorCorrectionLevel); + + if (typeof rsBlock == 'undefined') { + throw 'bad rs block @ typeNumber:' + typeNumber + + '/errorCorrectionLevel:' + errorCorrectionLevel; + } + + const length = rsBlock.length / 3; + + const list = []; + + for (let i = 0; i < length; i += 1) { + + const count = rsBlock[i * 3 + 0]; + const totalCount = rsBlock[i * 3 + 1]; + const dataCount = rsBlock[i * 3 + 2]; + + for (let j = 0; j < count; j += 1) { + list.push(qrRSBlock(totalCount, dataCount) ); + } + } + + return list; + }; + + return _this; +}(); + +//--------------------------------------------------------------------- +// qrBitBuffer +//--------------------------------------------------------------------- + +const qrBitBuffer = function() { + + const _buffer = []; + let _length = 0; + + const _this = {}; + + _this.getBuffer = function() { + return _buffer; + }; + + _this.getAt = function(index) { + const bufIndex = Math.floor(index / 8); + return ( (_buffer[bufIndex] >>> (7 - index % 8) ) & 1) == 1; + }; + + _this.put = function(num, length) { + for (let i = 0; i < length; i += 1) { + _this.putBit( ( (num >>> (length - i - 1) ) & 1) == 1); + } + }; + + _this.getLengthInBits = function() { + return _length; + }; + + _this.putBit = function(bit) { + + const bufIndex = Math.floor(_length / 8); + if (_buffer.length <= bufIndex) { + _buffer.push(0); + } + + if (bit) { + _buffer[bufIndex] |= (0x80 >>> (_length % 8) ); + } + + _length += 1; + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// qrNumber +//--------------------------------------------------------------------- + +const qrNumber = function(data) { + + const _mode = QRMode.MODE_NUMBER; + const _data = data; + + const _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return _data.length; + }; + + _this.write = function(buffer) { + + const data = _data; + + let i = 0; + + while (i + 2 < data.length) { + buffer.put(strToNum(data.substring(i, i + 3) ), 10); + i += 3; + } + + if (i < data.length) { + if (data.length - i == 1) { + buffer.put(strToNum(data.substring(i, i + 1) ), 4); + } else if (data.length - i == 2) { + buffer.put(strToNum(data.substring(i, i + 2) ), 7); + } + } + }; + + const strToNum = function(s) { + let num = 0; + for (let i = 0; i < s.length; i += 1) { + num = num * 10 + chatToNum(s.charAt(i) ); + } + return num; + }; + + const chatToNum = function(c) { + if ('0' <= c && c <= '9') { + return c.charCodeAt(0) - '0'.charCodeAt(0); + } + throw 'illegal char :' + c; + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// qrAlphaNum +//--------------------------------------------------------------------- + +const qrAlphaNum = function(data) { + + const _mode = QRMode.MODE_ALPHA_NUM; + const _data = data; + + const _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return _data.length; + }; + + _this.write = function(buffer) { + + const s = _data; + + let i = 0; + + while (i + 1 < s.length) { + buffer.put( + getCode(s.charAt(i) ) * 45 + + getCode(s.charAt(i + 1) ), 11); + i += 2; + } + + if (i < s.length) { + buffer.put(getCode(s.charAt(i) ), 6); + } + }; + + const getCode = function(c) { + + if ('0' <= c && c <= '9') { + return c.charCodeAt(0) - '0'.charCodeAt(0); + } else if ('A' <= c && c <= 'Z') { + return c.charCodeAt(0) - 'A'.charCodeAt(0) + 10; + } else { + switch (c) { + case '\u0020' : return 36; + case '$' : return 37; + case '%' : return 38; + case '*' : return 39; + case '+' : return 40; + case '-' : return 41; + case '.' : return 42; + case '/' : return 43; + case ':' : return 44; + default : + throw 'illegal char :' + c; + } + } + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// qr8BitByte +//--------------------------------------------------------------------- + +const qr8BitByte = function(data) { + + const _mode = QRMode.MODE_8BIT_BYTE; + const _data = data; + const _bytes = qrcode.stringToBytes(data); + + const _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return _bytes.length; + }; + + _this.write = function(buffer) { + for (let i = 0; i < _bytes.length; i += 1) { + buffer.put(_bytes[i], 8); + } + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// qrKanji +//--------------------------------------------------------------------- + +const qrKanji = function(data) { + + const _mode = QRMode.MODE_KANJI; + const _data = data; + + const stringToBytes = qrcode.stringToBytes; + !function(c, code) { + // self test for sjis support. + const test = stringToBytes(c); + if (test.length != 2 || ( (test[0] << 8) | test[1]) != code) { + throw 'sjis not supported.'; + } + }('\u53cb', 0x9746); + + const _bytes = stringToBytes(data); + + const _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return ~~(_bytes.length / 2); + }; + + _this.write = function(buffer) { + + const data = _bytes; + + let i = 0; + + while (i + 1 < data.length) { + + let c = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]); + + if (0x8140 <= c && c <= 0x9FFC) { + c -= 0x8140; + } else if (0xE040 <= c && c <= 0xEBBF) { + c -= 0xC140; + } else { + throw 'illegal char at ' + (i + 1) + '/' + c; + } + + c = ( (c >>> 8) & 0xff) * 0xC0 + (c & 0xff); + + buffer.put(c, 13); + + i += 2; + } + + if (i < data.length) { + throw 'illegal char at ' + (i + 1); + } + }; + + return _this; +}; + +//===================================================================== +// GIF Support etc. +// + +//--------------------------------------------------------------------- +// byteArrayOutputStream +//--------------------------------------------------------------------- + +const byteArrayOutputStream = function() { + + const _bytes = []; + + const _this = {}; + + _this.writeByte = function(b) { + _bytes.push(b & 0xff); + }; + + _this.writeShort = function(i) { + _this.writeByte(i); + _this.writeByte(i >>> 8); + }; + + _this.writeBytes = function(b, off, len) { + off = off || 0; + len = len || b.length; + for (let i = 0; i < len; i += 1) { + _this.writeByte(b[i + off]); + } + }; + + _this.writeString = function(s) { + for (let i = 0; i < s.length; i += 1) { + _this.writeByte(s.charCodeAt(i) ); + } + }; + + _this.toByteArray = function() { + return _bytes; + }; + + _this.toString = function() { + let s = ''; + s += '['; + for (let i = 0; i < _bytes.length; i += 1) { + if (i > 0) { + s += ','; + } + s += _bytes[i]; + } + s += ']'; + return s; + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// base64EncodeOutputStream +//--------------------------------------------------------------------- + +const base64EncodeOutputStream = function() { + + let _buffer = 0; + let _buflen = 0; + let _length = 0; + let _base64 = ''; + + const _this = {}; + + const writeEncoded = function(b) { + _base64 += String.fromCharCode(encode(b & 0x3f) ); + }; + + const encode = function(n) { + if (n < 0) { + throw 'n:' + n; + } else if (n < 26) { + return 0x41 + n; + } else if (n < 52) { + return 0x61 + (n - 26); + } else if (n < 62) { + return 0x30 + (n - 52); + } else if (n == 62) { + return 0x2b; + } else if (n == 63) { + return 0x2f; + } else { + throw 'n:' + n; + } + }; + + _this.writeByte = function(n) { + + _buffer = (_buffer << 8) | (n & 0xff); + _buflen += 8; + _length += 1; + + while (_buflen >= 6) { + writeEncoded(_buffer >>> (_buflen - 6) ); + _buflen -= 6; + } + }; + + _this.flush = function() { + + if (_buflen > 0) { + writeEncoded(_buffer << (6 - _buflen) ); + _buffer = 0; + _buflen = 0; + } + + if (_length % 3 != 0) { + // padding + const padlen = 3 - _length % 3; + for (let i = 0; i < padlen; i += 1) { + _base64 += '='; + } + } + }; + + _this.toString = function() { + return _base64; + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// base64DecodeInputStream +//--------------------------------------------------------------------- + +const base64DecodeInputStream = function(str) { + + const _str = str; + let _pos = 0; + let _buffer = 0; + let _buflen = 0; + + const _this = {}; + + _this.read = function() { + + while (_buflen < 8) { + + if (_pos >= _str.length) { + if (_buflen == 0) { + return -1; + } + throw 'unexpected end of file./' + _buflen; + } + + const c = _str.charAt(_pos); + _pos += 1; + + if (c == '=') { + _buflen = 0; + return -1; + } else if (c.match(/^\s$/) ) { + // ignore if whitespace. + continue; + } + + _buffer = (_buffer << 6) | decode(c.charCodeAt(0) ); + _buflen += 6; + } + + const n = (_buffer >>> (_buflen - 8) ) & 0xff; + _buflen -= 8; + return n; + }; + + const decode = function(c) { + if (0x41 <= c && c <= 0x5a) { + return c - 0x41; + } else if (0x61 <= c && c <= 0x7a) { + return c - 0x61 + 26; + } else if (0x30 <= c && c <= 0x39) { + return c - 0x30 + 52; + } else if (c == 0x2b) { + return 62; + } else if (c == 0x2f) { + return 63; + } else { + throw 'c:' + c; + } + }; + + return _this; +}; + +//--------------------------------------------------------------------- +// gifImage (B/W) +//--------------------------------------------------------------------- + +const gifImage = function(width, height) { + + const _width = width; + const _height = height; + const _data = new Array(width * height); + + const _this = {}; + + _this.setPixel = function(x, y, pixel) { + _data[y * _width + x] = pixel; + }; + + _this.write = function(out) { + + //--------------------------------- + // GIF Signature + + out.writeString('GIF87a'); + + //--------------------------------- + // Screen Descriptor + + out.writeShort(_width); + out.writeShort(_height); + + out.writeByte(0x80); // 2bit + out.writeByte(0); + out.writeByte(0); + + //--------------------------------- + // Global Color Map + + // black + out.writeByte(0x00); + out.writeByte(0x00); + out.writeByte(0x00); + + // white + out.writeByte(0xff); + out.writeByte(0xff); + out.writeByte(0xff); + + //--------------------------------- + // Image Descriptor + + out.writeString(','); + out.writeShort(0); + out.writeShort(0); + out.writeShort(_width); + out.writeShort(_height); + out.writeByte(0); + + //--------------------------------- + // Local Color Map + + //--------------------------------- + // Raster Data + + const lzwMinCodeSize = 2; + const raster = getLZWRaster(lzwMinCodeSize); + + out.writeByte(lzwMinCodeSize); + + let offset = 0; + + while (raster.length - offset > 255) { + out.writeByte(255); + out.writeBytes(raster, offset, 255); + offset += 255; + } + + out.writeByte(raster.length - offset); + out.writeBytes(raster, offset, raster.length - offset); + out.writeByte(0x00); + + //--------------------------------- + // GIF Terminator + out.writeString(';'); + }; + + const bitOutputStream = function(out) { + + const _out = out; + let _bitLength = 0; + let _bitBuffer = 0; + + const _this = {}; + + _this.write = function(data, length) { + + if ( (data >>> length) != 0) { + throw 'length over'; + } + + while (_bitLength + length >= 8) { + _out.writeByte(0xff & ( (data << _bitLength) | _bitBuffer) ); + length -= (8 - _bitLength); + data >>>= (8 - _bitLength); + _bitBuffer = 0; + _bitLength = 0; + } + + _bitBuffer = (data << _bitLength) | _bitBuffer; + _bitLength = _bitLength + length; + }; + + _this.flush = function() { + if (_bitLength > 0) { + _out.writeByte(_bitBuffer); + } + }; + + return _this; + }; + + const getLZWRaster = function(lzwMinCodeSize) { + + const clearCode = 1 << lzwMinCodeSize; + const endCode = (1 << lzwMinCodeSize) + 1; + let bitLength = lzwMinCodeSize + 1; + + // Setup LZWTable + const table = lzwTable(); + + for (let i = 0; i < clearCode; i += 1) { + table.add(String.fromCharCode(i) ); + } + table.add(String.fromCharCode(clearCode) ); + table.add(String.fromCharCode(endCode) ); + + const byteOut = byteArrayOutputStream(); + const bitOut = bitOutputStream(byteOut); + + // clear code + bitOut.write(clearCode, bitLength); + + let dataIndex = 0; + + let s = String.fromCharCode(_data[dataIndex]); + dataIndex += 1; + + while (dataIndex < _data.length) { + + const c = String.fromCharCode(_data[dataIndex]); + dataIndex += 1; + + if (table.contains(s + c) ) { + + s = s + c; + + } else { + + bitOut.write(table.indexOf(s), bitLength); + + if (table.size() < 0xfff) { + + if (table.size() == (1 << bitLength) ) { + bitLength += 1; + } + + table.add(s + c); + } + + s = c; + } + } + + bitOut.write(table.indexOf(s), bitLength); + + // end code + bitOut.write(endCode, bitLength); + + bitOut.flush(); + + return byteOut.toByteArray(); + }; + + const lzwTable = function() { + + const _map = {}; + let _size = 0; + + const _this = {}; + + _this.add = function(key) { + if (_this.contains(key) ) { + throw 'dup key:' + key; + } + _map[key] = _size; + _size += 1; + }; + + _this.size = function() { + return _size; + }; + + _this.indexOf = function(key) { + return _map[key]; + }; + + _this.contains = function(key) { + return typeof _map[key] != 'undefined'; + }; + + return _this; + }; + + return _this; +}; + +const createDataURL = function(width, height, getPixel) { + const gif = gifImage(width, height); + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + gif.setPixel(x, y, getPixel(x, y) ); + } + } + + const b = byteArrayOutputStream(); + gif.write(b); + + const base64 = base64EncodeOutputStream(); + const bytes = b.toByteArray(); + for (let i = 0; i < bytes.length; i += 1) { + base64.writeByte(bytes[i]); + } + base64.flush(); + + return 'data:image/gif;base64,' + base64; +}; + +export default qrcode; + +export const stringToBytes = qrcode.stringToBytes; diff --git a/docs/design.md b/docs/design.md index e126b9a..5ab2dbe 100644 --- a/docs/design.md +++ b/docs/design.md @@ -156,9 +156,37 @@ environ 17 Ko compressés de moins au premier chargement. | `.reward`, `.stamp` (`--record`) | Écran de fin de séance | | `.dialog`, `.toast` | Confirmation (`` natif), message bref (ne bloque jamais les touches) | +## Synchro et IA branchée (lot 2) + +Écrans : `app/ui/screens/sync.js` (Synchro `#/synchro`, confirmation d'appariement +`#/relier`, indicateur de l'en-tête) et `app/ui/screens/connect-ai.js` (page +d'autorisation `#/connecter-ia?…`). Logique pure dans `app/ui/sync-model.js` et +`app/ui/connect-model.js`, branchement dans `app/ui/sync-service.js`. + +| Élément | Traduction | +| --- | --- | +| Indicateur (`.topline`, `.sync-flag`) | Une ligne de marquage en haut à droite, absente tant que la synchro n'est pas activée. Le mot porte l'état (« Synchro à jour », « Synchro… », « Hors ligne », « Synchro en erreur ») ; un carré le répète : plein (à jour), jaune (en cours), pointillé (hors ligne) ; l'erreur passe le mot sur un aplat jaune. Cible de 40 px : exception assumée à la règle des 48 px, l'écran Synchro restant aussi accessible depuis l'accueil (case « Synchro ») et le profil | +| État (`.sync-state`) | Bloc encadré, grand mot condensé (« ✓ Synchro à jour »), une phrase (dernière synchro, ou l'erreur traduite) ; trait pointillé hors ligne, trait de 6 px en erreur | +| La clé (`.sync-keybox`) | Chasse fixe, cadre pointillé, masquée par défaut (seul le dernier groupe reste lisible), « Afficher » et « Copier la clé » dessous. On la montre comme un secret (ADR 0005) | +| QR code (`.qr-frame`, `.qr`) | SVG dessiné par le DOM (`app/ui/qr.js`, aucune image `data:`), **noir sur blanc dans les deux thèmes** (les appareils photo lisent mal un code inversé), marge blanche de 4 modules, 280 px au plus. Bibliothèque chargée à l'ouverture de l'écran seulement | +| Confirmations | « Relier cet appareil ? », « Autoriser » / « Refuser » : l'action principale dans la barre du bas ; ce qui va se passer (fusion des données, IA qui lit et propose) en une ligne chacun | + +Textes : la synchro est présentée par trois faits (« Sans compte », « Chiffré », +« Un secret ») ; les erreurs du relais et d'OAuth sont traduites en une phrase qui dit +quoi faire. Aucune scrutation : la synchro part à l'ouverture, 3 s après une saisie +(regroupée), au retour du réseau et au retour sur l'onglet. + +Poids : le premier chargement gagne les modules de la synchro (écrans, service, +`infra/sync.js`, `domain/sync-crypto.js` : 52 Ko bruts, 20 Ko compressés) ; le générateur +de QR code (`app/vendor/qrcode-generator/`, MIT, 51 Ko bruts, 11 Ko compressés) +n'est chargé qu'à l'ouverture de l'écran Synchro. + ## Vérifier - `make test-browser` : parcours complet dans Chromium (Docker), en sombre puis en - clair, captures 412×915 dans `build/shots/`. + clair, captures 412×915 dans `build/shots/`. Puis la synchro contre le vrai + serveur (`server/main.js`, données temporaires) : activation, QR code décodé dans + la capture, appariement d'un second navigateur, page d'autorisation d'une IA + (captures `synchro-*.png`). - `make test` : tests des modules purs de l'interface, dont la lisibilité du texte posé sur une couleur de séance. diff --git a/tests/browser/parcours.cjs b/tests/browser/parcours.cjs index 43532ee..28554d6 100644 --- a/tests/browser/parcours.cjs +++ b/tests/browser/parcours.cjs @@ -16,10 +16,12 @@ const { chromium } = require("/tools/node_modules/playwright"); const appDir = path.resolve(process.argv[2] ?? "app"); const outDir = path.resolve(process.argv[3] ?? "build/shots"); +/** Le vrai serveur (server/main.js, lancé par make test-browser), pour la synchro. */ +const serverBase = process.argv[4] ?? ""; const START = new Date("2026-11-18T09:00:00"); const TYPES = { - ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", + ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".webmanifest": "application/manifest+json", ".svg": "image/svg+xml", ".woff2": "font/woff2", ".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8", }; @@ -336,6 +338,8 @@ function check(scheme, cond, msg) { ok(errors.length === 0, "aucune erreur dans la console" + (errors.length ? " : " + errors.join(" | ") : "")); await ctx.close(); } + if (serverBase) await syncJourney(browser, serverBase); + else check("synchro", false, "adresse du serveur absente : parcours de la synchro non joué (make test-browser la fournit)"); await browser.close(); server.close(); console.log(failures ? `\n${failures} échec(s).` : "\nParcours : OK"); @@ -345,3 +349,206 @@ function check(scheme, cond, msg) { if (lastPage) await lastPage.screenshot({ path: `${outDir}/erreur.png`, fullPage: true }).catch(() => {}); process.exit(1); }); + +// ---- synchro : relais, QR code, appariement, IA branchée (serveur réel) ------------- +// Trois navigateurs sans rien en commun (contextes séparés) : A active la +// synchro, B s'apparie par le lien du QR code, C (non relié) passe par la page +// d'autorisation. Le serveur est celui de production (server/main.js), avec un +// dossier de données temporaire. + +/** Lit le QR code d'une capture PNG (jsQR, pngjs : outils du parcours seulement). */ +function decodeQr(png) { + const { PNG } = require("/tools/node_modules/pngjs"); + const jsqr = require("/tools/node_modules/jsqr"); + const jsQR = jsqr.default ?? jsqr; + const img = PNG.sync.read(png); + const found = jsQR(new Uint8ClampedArray(img.data.buffer, img.data.byteOffset, img.data.length), img.width, img.height); + return found ? found.data : null; +} + +/** + * Attend qu'une condition devienne vraie (au plus `ms`) : l'état d'un écran + * peut suivre une requête réseau ou un délai de synchro. + */ +async function until(fn, ms = 8000, step = 200) { + const end = Date.now() + ms; + for (;;) { + try { + if (await fn()) return true; + } catch { + // élément pas encore là : on réessaie + } + if (Date.now() > end) return false; + await new Promise((r) => setTimeout(r, step)); + } +} + +async function syncJourney(browser, base) { + const scheme = "synchro"; + const ok = (cond, msg) => check(scheme, cond, msg); + const crypto = require("node:crypto"); + const errors = []; + /** Requêtes refusées exprès (clé inconnue, journal absent) : le navigateur les note en console. */ + const expected = /\/oauth\/authorize|\/api\/journals\//; + const open = async (name) => { + const ctx = await browser.newContext({ + viewport: { width: 412, height: 915 }, colorScheme: "dark", deviceScaleFactor: 1, locale: "fr-FR", + permissions: ["clipboard-read", "clipboard-write"], + }); + const page = await ctx.newPage(); + lastPage = page; + page.on("pageerror", (e) => errors.push(`${name} : ${e}`)); + page.on("console", (m) => { + if (m.type() === "error" && !(m.text().startsWith("Failed to load resource") && expected.test(m.location().url ?? ""))) + errors.push(`${name} : ${m.text()}`); + }); + return { ctx, page }; + }; + const goto = async (page, hash) => { await page.goto(base + hash); await page.waitForSelector("h1"); await page.waitForTimeout(250); }; + const inPage = (page, fn) => page.evaluate(fn); + + // ---- A : un programme, puis la synchro activée ----------------------------------- + const A = await open("A"); + const a = A.page; + await goto(a, "#/"); + ok(await a.locator(".sync-flag").isHidden(), "sans clé : pas d'indicateur de synchro"); + await a.getByRole("button", { name: "Programme d'exemple" }).click(); + await a.getByRole("button", { name: "Adopter" }).click(); + await a.waitForSelector(".hud"); + await a.getByRole("link", { name: /^Synchro/ }).click(); + await a.waitForSelector("text=Comment ça marche"); + ok(await a.getByText("Le serveur ne garde que des blocs chiffrés").isVisible(), "synchro : explication avant activation"); + await a.screenshot({ path: `${outDir}/${scheme}-20-sans-cle.png`, fullPage: true }); + await a.getByRole("button", { name: "Activer la synchro" }).click(); + ok(await until(() => a.locator(".sync-state").getAttribute("data-state").then((s) => s === "ok")), "synchro activée : premier dépôt fait"); + ok(await a.locator(".sync-flag", { hasText: "Synchro à jour" }).isVisible(), "indicateur de l'en-tête : à jour"); + ok(await a.locator(".sync-key").innerText().then((t) => t.startsWith("••••")), "clé masquée par défaut"); + await a.getByRole("button", { name: "Afficher" }).click(); + const key = (await a.locator(".sync-key").innerText()).trim(); + ok(/^[0-9A-Z]{4}(-[0-9A-Z]{4}){5}-[0-9A-Z]{2}$/.test(key), "clé affichée en groupes"); + + // ---- le QR code se lit, et porte le lien d'appariement ---------------------------- + // Le message bref (« Synchro activée. ») recouvrirait le code sur la capture : + // on attend qu'il soit parti. + await a.waitForSelector("svg.qr"); + await a.locator(".toast--on").waitFor({ state: "detached", timeout: 6000 }); + const decoded = decodeQr(await a.locator("svg.qr").screenshot({ path: `${outDir}/${scheme}-qr.png` })); + ok(decoded === `${base}#pair=${key}`, `QR code décodé : ${decoded === null ? "illisible" : decoded.replace(key, "")}`); + + await a.getByRole("button", { name: "Copier la clé" }).click(); + ok(await a.evaluate(() => navigator.clipboard.readText()) === key, "clé copiée"); + ok(await a.locator(".copy-line__text", { hasText: "/mcp" }).innerText() === base + "mcp", "adresse du connecteur MCP affichée"); + await a.getByRole("button", { name: "Masquer" }).click(); + await a.locator(".toast--on").waitFor({ state: "detached", timeout: 5000 }).catch(() => {}); + await a.screenshot({ path: `${outDir}/${scheme}-21-avec-cle.png`, fullPage: true }); + + // ---- B : appariement par le lien du QR code --------------------------------------- + const B = await open("B"); + const b = B.page; + await goto(b, "#pair=" + key); + ok(await b.getByRole("heading", { name: "Relier cet appareil ?" }).isVisible(), "lien d'appariement : confirmation demandée"); + ok(!b.url().includes("pair=") && b.url().endsWith("#/relier"), "la clé a quitté l'adresse"); + await b.screenshot({ path: `${outDir}/${scheme}-22-relier.png` }); + await b.locator(".action-bar").getByRole("button", { name: "Relier" }).click(); + await b.waitForSelector(".hud"); + ok(b.url().endsWith("#/") && !b.url().includes("pair="), "après l'appariement : l'accueil, sans la clé dans l'adresse"); + ok(await inPage(b, async () => (await import("./main.js")).store.getState().program?.name ?? null) !== null, "B a reçu le programme de A"); + + // ---- un événement créé sur B apparaît sur A ----------------------------------------- + await goto(b, "#/poids"); + const before = await inPage(b, async () => (await import("./main.js")).sync.getStatus().lastAt); + await b.getByLabel("Poids (kg)").fill("80,5"); + await b.getByRole("button", { name: "Enregistrer", exact: true }).click(); + const synced = await until(() => b.evaluate(async (prev) => { + const s = (await import("./main.js")).sync.getStatus(); + return s.lastAt !== prev && !s.running && !s.error; + }, before), 10000); + ok(synced, "B : synchro d'elle-même, quelques secondes après la saisie" + (synced ? "" : " : " + JSON.stringify(await inPage(b, async () => (await import("./main.js")).sync.getStatus())) + " avant " + before)); + const weightOnA = () => inPage(a, async () => (await import("./main.js")).store.getState().weights.some((w) => w.kg === 80.5)); + ok(await until(async () => { + // Retour sur l'onglet : déclencheur de la synchro (visibilitychange). + await a.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))); + await a.waitForTimeout(300); + return weightOnA(); + }, 12000, 500), "la pesée saisie sur B apparaît sur A"); + + // ---- page d'autorisation d'une IA (A, relié) ---------------------------------------- + const redirectUri = "https://ia.example/callback"; + const reg = await (await fetch(base + "oauth/register", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ client_name: "IA d'essai", redirect_uris: [redirectUri] }), + })).json(); + const verifier = crypto.randomBytes(32).toString("base64url"); + const challenge = crypto.createHash("sha256").update(verifier).digest("base64url"); + const authorizeUrl = (state) => base + "oauth/authorize?" + new URLSearchParams({ + response_type: "code", client_id: reg.client_id, redirect_uri: redirectUri, state, code_challenge: challenge, code_challenge_method: "S256", + }); + // L'adresse de retour de l'IA n'existe pas : le navigateur s'y arrête. + await A.ctx.route("https://ia.example/**", (route) => route.fulfill({ status: 200, contentType: "text/plain", body: "IA" })); + await a.goto(authorizeUrl("etat-1")); + await a.waitForSelector("h1"); + ok(a.url().includes("#/connecter-ia?"), "GET /oauth/authorize mène à la page de l'app"); + ok(await a.getByRole("heading", { name: "IA d'essai" }).isVisible() && await a.getByText("veut lire ton programme et proposer des changements").isVisible(), "connecter-ia : nom de l'IA et ce qu'elle veut"); + ok(await a.getByText("Retour vers ia.example").isVisible(), "connecter-ia : hôte de l'adresse de retour"); + ok(await a.getByText(/Clé de cet appareil/).isVisible(), "connecter-ia : la clé de l'appareil est reprise"); + await a.screenshot({ path: `${outDir}/${scheme}-23-connecter-ia.png`, fullPage: true }); + await Promise.all([a.waitForURL(/^https:\/\/ia\.example\/callback/), a.locator(".action-bar").getByRole("button", { name: "Autoriser" }).click()]); + const back = new URL(a.url()); + ok(back.searchParams.get("state") === "etat-1" && !!back.searchParams.get("code"), "Autoriser : retour vers l'IA avec un code et l'état"); + const tokens = await (await fetch(base + "oauth/token", { + method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ grant_type: "authorization_code", code: back.searchParams.get("code") ?? "", code_verifier: verifier, client_id: reg.client_id, redirect_uri: redirectUri }), + })).json(); + ok(typeof tokens.access_token === "string", "le code s'échange contre un jeton"); + + // ---- l'IA propose, A le voit à la synchro suivante --------------------------------- + await goto(a, "#/"); + const profile = await inPage(a, async () => (await import("./main.js")).store.getState().profile); + const rpc = await (await fetch(base + "mcp", { + method: "POST", headers: { authorization: "Bearer " + tokens.access_token, "content-type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "propose_profile", arguments: { profile: { ...profile, goal: "Courir un 10 km" }, reason: "Essai du parcours." } } }), + })).json(); + ok(!rpc.error && !rpc.result?.isError, "MCP : proposition enregistrée par l'IA" + (rpc.error ? " : " + JSON.stringify(rpc.error) : "")); + // Retour du réseau : déclencheur de la synchro (online). + await a.evaluate(() => window.dispatchEvent(new Event("online"))); + ok(await until(() => a.getByText("Un programme t'attend").isVisible()), "la proposition de l'IA s'affiche à l'accueil"); + ok(await a.locator(".toast--on", { hasText: "Nouvelle proposition" }).count() === 1, "message : nouvelle proposition"); + await a.screenshot({ path: `${outDir}/${scheme}-24-proposition-ia.png` }); + + // ---- C, non relié : clé invalide, journal inconnu, refus --------------------------- + const C = await open("C"); + const c = C.page; + await C.ctx.route("https://ia.example/**", (route) => route.fulfill({ status: 200, contentType: "text/plain", body: "IA" })); + await c.goto(authorizeUrl("etat-2")); + await c.waitForSelector("h1"); + ok(await c.getByText("Cet appareil n'est pas relié").isVisible(), "connecter-ia sans clé : coller une clé ou activer la synchro"); + await c.getByLabel("Ma clé de synchro").fill("pas une clé"); + await c.locator(".action-bar").getByRole("button", { name: "Autoriser" }).click(); + ok(await c.getByText("Clé de synchro invalide").isVisible(), "clé mal formée : refusée sur place"); + await c.getByLabel("Ma clé de synchro").fill("0000-0000-0000-0000-0000-0000-00"); + await c.locator(".action-bar").getByRole("button", { name: "Autoriser" }).click(); + ok(await until(() => c.getByText("active d'abord la synchro et synchronise une fois").isVisible()), "journal inconnu : message traduit"); + await Promise.all([c.waitForURL(/^https:\/\/ia\.example\/callback/), c.getByRole("button", { name: "Refuser" }).click()]); + const refused = new URL(c.url()); + ok(refused.searchParams.get("error") === "access_denied" && refused.searchParams.get("state") === "etat-2", "Refuser : error=access_denied et l'état"); + + // ---- B : désactiver, puis « J'ai déjà une clé » (faute de frappe, puis la bonne) ---- + await goto(b, "#/synchro"); + await b.getByRole("button", { name: "Désactiver sur cet appareil" }).click(); + await b.locator("dialog[open]").getByRole("button", { name: "Désactiver" }).click(); + ok(await until(() => b.getByRole("button", { name: "Activer la synchro" }).isVisible()), "désactivée sur B"); + ok(await b.locator(".sync-flag").isHidden(), "plus d'indicateur sur B"); + ok(await inPage(b, async () => (await import("./main.js")).store.getEvents().length) > 0, "les données de B restent"); + await b.getByLabel("Ma clé de synchro").fill("ZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZ-Z0"); + await b.getByRole("button", { name: "Relier avec cette clé" }).click(); + ok(await until(() => b.locator("dialog[open]", { hasText: "Aucun journal ne correspond" }).isVisible()), "clé sans journal : faute de frappe probable"); + await b.locator("dialog[open]").getByRole("button", { name: "Corriger la clé" }).click(); + await b.getByLabel("Ma clé de synchro").fill(key.toLowerCase()); + await b.getByRole("button", { name: "Relier avec cette clé" }).click(); + ok(await until(() => b.locator(".sync-state").getAttribute("data-state").then((s) => s === "ok")), "B relié de nouveau avec la clé recopiée"); + ok(await until(() => inPage(b, async () => (await import("./main.js")).store.getState().proposals.length === 1)), "B reçoit la proposition de l'IA"); + await b.screenshot({ path: `${outDir}/${scheme}-25-b-relie.png`, fullPage: true }); + + ok(errors.length === 0, "aucune erreur dans la console" + (errors.length ? " : " + errors.join(" | ") : "")); + for (const x of [A, B, C]) await x.ctx.close(); +} diff --git a/tests/ui/store-order.test.js b/tests/ui/store-order.test.js new file mode 100644 index 0000000..d5a3215 --- /dev/null +++ b/tests/ui/store-order.test.js @@ -0,0 +1,31 @@ +// Deux intentions dans la même milliseconde : la plus récente gagne toujours. +// C'était le flottement de make test-browser (jours de la semaine) : l'horloge +// figée de Playwright avance par paliers, et deux PlanSettingsChanged de même +// date étaient départagés par leur identifiant, tiré au hasard. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createStore } from "../../app/ui/store.js"; + +test("dates strictement croissantes pour les événements de l'appareil", (t) => { + t.mock.method(Date, "now", () => Date.parse("2026-11-18T09:00:00.000Z")); + for (let round = 0; round < 20; round++) { + const store = createStore({ device: "d1" }); + store.dispatch("PlanSettingsChanged", { week: null, days: [0, 2, 4], locks: {} }); + store.dispatch("PlanSettingsChanged", { week: null, days: [0, 2, 4, 5], locks: {} }); + assert.deepEqual(store.getState().planSettings?.days, [0, 2, 4, 5]); + const [a, b] = store.getEvents(); + assert.ok(a.at < b.at, `${a.at} < ${b.at}`); + } +}); + +test("après un rechargement, la suite reste après les événements déjà là", (t) => { + const store = createStore({ device: "d1" }); + const e = store.dispatch("ModeChanged", { mode: "recovery" }); + // Horloge revenue en arrière (réglage de l'appareil) : l'ordre tient quand même. + t.mock.method(Date, "now", () => Date.parse(e.at) - 60_000); + const reloaded = createStore({ device: "d1" }); + reloaded.load([e]); + const next = reloaded.dispatch("ModeChanged", { mode: "progression" }); + assert.ok(next.at > e.at); + assert.equal(reloaded.getState().mode, "progression"); +}); diff --git a/tests/ui/sync-model.test.js b/tests/ui/sync-model.test.js new file mode 100644 index 0000000..5ae6f2b --- /dev/null +++ b/tests/ui/sync-model.test.js @@ -0,0 +1,211 @@ +// Synchro côté interface : état affiché, regroupement des envois, appariement, +// page d'autorisation d'une IA, QR code, routes. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createSyncScheduler, maskKey, pairUrl, readPairFragment, sinceText, syncErrorText, syncView } from "../../app/ui/sync-model.js"; +import { authorizeErrorText, isAcceptableRedirect, parseConnectRequest, refusalUrl } from "../../app/ui/connect-model.js"; +import { QUIET_ZONE, qrMatrix, qrPath } from "../../app/ui/qr.js"; +import { href, parseRoute } from "../../app/ui/router.js"; +import { generateSyncKey } from "../../app/domain/sync-crypto.js"; + +const KEY = "0123-4567-89AB-CDEF-GHJK-MNPQ-R0"; + +/** @param {Partial} s */ +const status = (s) => ({ hasKey: true, online: true, running: false, lastAt: null, error: null, ...s }); +const NOW = new Date("2026-11-18T10:00:00"); + +test("état affiché : désactivée, en cours, hors ligne, erreur, à jour", () => { + assert.equal(syncView(status({ hasKey: false, error: "server" }), NOW).state, "off"); + assert.equal(syncView(status({ running: true, error: "server" }), NOW).state, "syncing"); + assert.equal(syncView(status({ online: false }), NOW).state, "offline"); + assert.equal(syncView(status({ error: "offline" }), NOW).state, "offline", "réseau absent : pas une erreur"); + const err = syncView(status({ error: "forbidden", lastAt: "2026-11-18T09:58:30" }), NOW); + assert.equal(err.state, "error"); + assert.match(err.detail, /refuse cette clé/); + assert.match(err.detail, /Dernière synchro il y a 1 min\./); + const ok = syncView(status({ lastAt: "2026-11-18T09:59:30" }), NOW); + assert.deepEqual([ok.state, ok.label, ok.detail], ["ok", "Synchro à jour", "Dernière synchro à l'instant."]); + assert.equal(syncView(status({}), NOW).detail, "Pas encore synchronisé."); +}); + +test("erreurs de synchro traduites, y compris un code inconnu", () => { + for (const code of ["offline", "forbidden", "journal_full", "rate_limited", "server", "key"]) + assert.doesNotMatch(syncErrorText(code), /impossible pour le moment/, code); + assert.match(syncErrorText("autre"), /impossible pour le moment/); + assert.match(syncErrorText(null), /impossible/); +}); + +test("depuis quand : instant, minutes, heure du jour, date", () => { + assert.equal(sinceText("2026-11-18T09:59:59", NOW), "à l'instant"); + assert.equal(sinceText("2026-11-18T09:15:00", NOW), "il y a 45 min"); + assert.equal(sinceText("2026-11-18T07:05:00", NOW), "à 07:05"); + assert.equal(sinceText("2026-11-12T07:05:00", NOW), "le 12/11"); +}); + +/** Minuterie factice : on avance le temps à la main. */ +function fakeTimers() { + let t = 0; + /** @type {Map void}>} */ + const pending = new Map(); + let id = 0; + return { + timers: { + setTimeout: /** @type {any} */ ((/** @type {() => void} */ fn, /** @type {number} */ ms) => { pending.set(++id, { at: t + ms, fn }); return id; }), + clearTimeout: /** @type {any} */ ((/** @type {number} */ i) => { pending.delete(i); }), + }, + /** @param {number} ms */ + advance(ms) { + t += ms; + for (const [i, p] of [...pending]) if (p.at <= t) { pending.delete(i); p.fn(); } + }, + get count() { return pending.size; }, + }; +} +const tick = () => new Promise((r) => setImmediate(r)); + +test("regroupement : plusieurs saisies rapprochées, une seule synchro au bout du délai", async () => { + const clock = fakeTimers(); + let runs = 0; + const s = createSyncScheduler({ run: async () => ++runs, delayMs: 3000, timers: clock.timers }); + s.later(); + clock.advance(1000); + s.later(); + s.later(); + assert.equal(clock.count, 1, "une seule minuterie"); + clock.advance(1999); + assert.equal(runs, 0); + clock.advance(1); + await tick(); + assert.equal(runs, 1); + assert.equal(s.pending, false); + clock.advance(10_000); + await tick(); + assert.equal(runs, 1, "aucune synchro sans demande (pas de scrutation)"); +}); + +test("regroupement : now() part tout de suite et absorbe la synchro différée", async () => { + const clock = fakeTimers(); + let runs = 0; + const s = createSyncScheduler({ run: async () => ++runs, timers: clock.timers }); + s.later(); + assert.equal(await s.now(), 1); + clock.advance(5000); + await tick(); + assert.equal(runs, 1); +}); + +test("regroupement : une demande pendant une synchro en relance une seule à la fin", async () => { + const clock = fakeTimers(); + let runs = 0; + /** @type {(() => void)[]} */ + const release = []; + const s = createSyncScheduler({ run: () => new Promise((r) => { runs++; release.push(() => r(runs)); }), timers: clock.timers }); + const first = s.now(); + s.later(); + s.later(); + const second = s.now(); + assert.equal(first, second, "même promesse"); + assert.equal(clock.count, 0, "pas de minuterie pendant une synchro"); + release.shift()?.(); + await tick(); + assert.equal(runs, 2, "relancée une fois"); + release.shift()?.(); + assert.equal(await first, 2); +}); + +test("regroupement : une erreur ne bloque pas les synchros suivantes ; cancel() oublie la synchro différée", async () => { + const clock = fakeTimers(); + let runs = 0; + const s = createSyncScheduler({ run: async () => { runs++; throw new Error("réseau"); }, timers: clock.timers }); + assert.equal(await s.now(), undefined); + assert.equal(await s.now(), undefined); + assert.equal(runs, 2); + s.later(); + s.cancel(); + clock.advance(5000); + await tick(); + assert.equal(runs, 2); +}); + +test("appariement : adresse du QR code et lecture du fragment", () => { + const key = generateSyncKey(); + const url = pairUrl("https://ia-fit.sans.pub/", key); + assert.equal(url, `https://ia-fit.sans.pub/#pair=${key}`); + assert.equal(readPairFragment(new URL(url).hash), key); + assert.equal(readPairFragment("#pair=" + key.toLowerCase().replace(/-/g, " ")), key, "clé recopiée à la main"); + assert.equal(readPairFragment("#pair=" + encodeURIComponent(key)), key); + assert.equal(readPairFragment("#pair=XXXX"), null); + assert.equal(readPairFragment("#/synchro"), null); + assert.equal(maskKey(KEY), "••••-••••-••••-••••-••••-••••-R0"); +}); + +test("connecter-ia : paramètres lus dans le fragment", () => { + const q = new URLSearchParams({ + client_id: "abc.def", redirect_uri: "https://claude.ai/api/mcp/auth_callback", response_type: "code", + state: "s t&é", code_challenge: "x".repeat(43), code_challenge_method: "S256", client_name: "Claude", scope: "ia-fit", + }); + const r = parseConnectRequest(`#/connecter-ia?${q}`); + assert.deepEqual(r.missing, []); + assert.equal(r.clientName, "Claude"); + assert.equal(r.redirectHost, "claude.ai"); + assert.equal(r.params.state, "s t&é"); + assert.equal(r.params.client_id, "abc.def"); + assert.equal("client_name" in r.params, false, "le nom n'est pas renvoyé au serveur"); + assert.equal("scope" in r.params, false); + const none = parseConnectRequest("#/connecter-ia"); + assert.deepEqual(none.missing, ["client_id", "redirect_uri", "code_challenge", "code_challenge_method"]); + assert.equal(none.clientName, "Une IA"); + assert.equal(parseConnectRequest("#/connecter-ia?redirect_uri=pas-une-adresse").redirectHost, null); + assert.equal(parseConnectRequest("#/connecter-ia?redirect_uri=" + encodeURIComponent("com.exemple.app:/cb")).redirectHost, "com.exemple.app"); +}); + +test("connecter-ia : refus renvoyé à l'IA avec l'état, jamais vers une adresse douteuse", () => { + const url = refusalUrl({ redirect_uri: "https://claude.ai/cb?x=1", state: "abc" }); + assert.equal(url, "https://claude.ai/cb?x=1&error=access_denied&state=abc"); + assert.equal(refusalUrl({ redirect_uri: "http://localhost:3334/cb" }), "http://localhost:3334/cb?error=access_denied"); + assert.equal(refusalUrl({ redirect_uri: "http://evil.example/cb", state: "a" }), null); + assert.equal(refusalUrl({ redirect_uri: "javascript:alert(1)" }), null); + assert.equal(refusalUrl({ redirect_uri: "https://a.example/cb#frag" }), null); + assert.equal(isAcceptableRedirect("com.exemple.app:/cb"), true); + assert.match(authorizeErrorText("unknown_journal"), /active d'abord la synchro et synchronise une fois/); + assert.match(authorizeErrorText("autre"), /impossible/); +}); + +test("routes : synchro, relier, connecter-ia avec ses paramètres", () => { + assert.deepEqual(parseRoute(href.sync()), { name: "sync" }); + assert.deepEqual(parseRoute(href.pair()), { name: "pair" }); + assert.deepEqual(parseRoute("#/connecter-ia?client_id=a&state=b%2Fc"), { name: "connect-ai", query: "client_id=a&state=b%2Fc" }); + assert.deepEqual(parseRoute("#/connecter-ia"), { name: "connect-ai", query: "" }); + assert.deepEqual(parseRoute("#/profil?x=1"), { name: "profile" }, "les autres écrans ignorent les paramètres"); + assert.deepEqual(parseRoute("#pair=" + KEY), { name: "reserved" }); +}); + +test("QR code : structure (taille, repères de position, marge, chemin)", () => { + const text = pairUrl("https://ia-fit.sans.pub", KEY); + const m = qrMatrix(text); + const n = m.length; + assert.ok(m.every((row) => row.length === n), "carré"); + assert.equal((n - 17) % 4, 0, "taille d'une version QR (17 + 4 × version)"); + const version = (n - 17) / 4; + // 62 octets en mode octet, correction M : version 4 (62 octets au plus). + assert.equal(version, 4); + // Les trois repères de position : carré noir 7 × 7, anneau blanc, cœur 3 × 3. + for (const [r0, c0] of [[0, 0], [0, n - 7], [n - 7, 0]]) { + for (let r = 0; r < 7; r++) + for (let c = 0; c < 7; c++) { + const ring = r === 0 || r === 6 || c === 0 || c === 6; + const core = r >= 2 && r <= 4 && c >= 2 && c <= 4; + assert.equal(m[r0 + r][c0 + c], ring || core, `repère (${r0},${c0}) case ${r},${c}`); + } + } + // Motif de synchronisation : alternance sur la ligne 6. + for (let c = 8; c < n - 8; c++) assert.equal(m[6][c], c % 2 === 0); + // Déterministe, et différent pour une autre clé. + assert.deepEqual(qrMatrix(text), m); + assert.notDeepEqual(qrMatrix(pairUrl("https://ia-fit.sans.pub", generateSyncKey())), m); + // Chemin : autant de modules noirs dessinés que dans la matrice, décalés de la marge. + const d = qrPath(m); + const drawn = [...d.matchAll(/M(\d+) (\d+)h(\d+)/g)].reduce((s, x) => s + Number(x[3]), 0); + assert.equal(drawn, m.flat().filter(Boolean).length); + assert.ok(d.startsWith(`M${QUIET_ZONE} ${QUIET_ZONE}h7`), "premier trait : le haut du repère, après la marge"); +});