Lot 2, interface : synchro, appariement par QR code, page d'autorisation d'une IA
- Écran Synchro (#/synchro) : activer, « J'ai déjà une clé » (pull d'abord, faute de frappe signalée), état, clé masquée, QR code, désactiver, brancher son IA (adresse du connecteur et mode d'emploi). - Appariement #pair=<clé> : la clé quitte l'adresse aussitôt, confirmation, fusion des données locales. - Page #/connecter-ia?… : autoriser (POST /oauth/authorize) ou refuser, erreurs traduites ; le routeur accepte « ? » dans le fragment. - Synchro automatique sans scrutation (ouverture, 3 s après une saisie, online, visibilitychange), indicateur dans l'en-tête. - QR code : qrcode-generator 2.0.4 (MIT) vendorisé, dessiné en SVG par le DOM. - Magasin : dates strictement croissantes pour les événements de l'appareil (cause du flottement de test-browser : deux PlanSettingsChanged de la même milliseconde départagés par leur identifiant aléatoire). - test-browser : parcours de la synchro contre server/main.js (données temporaires), QR décodé par jsQR dans la capture. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
c12e37e215
commit
08cc995eef
+208
-1
@@ -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, "<clé>")}`);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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<import("../../app/ui/sync-model.js").SyncStatus>} 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<number, {at: number, fn: () => 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");
|
||||
});
|
||||
Reference in New Issue
Block a user