fix: la barrière s'affiche à chaque chargement en page de tête, comme chez Festipod

Notre version décidait d'afficher la barrière sur la présence de l'identifiant.
Festipod décidait sur la session — jamais établie en page de tête, donc l'écran
s'affichait toujours, l'identifiant servant seulement à pré-remplir le champ.

La différence n'est pas ergonomique. L'identifiant est un état qu'on observe ;
le portefeuille, lui, vit dans le stockage d'une autre origine et nous est
illisible. Un écran conditionnel doit donc DEVINER cet état invisible — et
quand il devine « déjà installé » alors que le portefeuille a disparu du
navigateur, il cache les seuls contrôles qui répareraient la situation et
précipite la personne dans une impasse.

Impasse observée sur le site réel : sans portefeuille, la page du broker affiche
un texte statique, zéro bouton, un seul lien vers nextgraph.eu qui NE TRANSPORTE
AUCUN retour vers l'application. Le retour arrière du navigateur est la seule
issue — et il ne sert à rien si la barrière ne reprend pas la personne à
l'arrivée.

Le discriminant devient le cadre, pas l'identifiant : page de tête → toujours,
iframe → on s'efface. C'est le signal que @ng-org/web utilise lui-même et que
Festipod utilisait un étage plus bas.

On ne détecte rien et on ne demande rien. Les trois étapes s'affichent toujours ;
qui possède déjà son portefeuille ignore les deux premières. Aucune case « je
l'ai déjà » : savoir si l'on a importé un portefeuille dans ce navigateur est
une question trop technique pour être posée.

Garde-fou repris de Festipod, qu'on n'avait pas : après un aller-retour vers
l'onglet NextGraph et un retour arrière, la barrière restait figée sur un bouton
mort. Elle recharge désormais sur pageshow persisted — seul moyen de rejouer le
init() qui porte la redirection.

Vérifié sur navigateur : cliquer « Import a Wallet File » ouvre un sélecteur sur
place, sans navigation ni changement d'onglet, et notre onglet ne reçoit AUCUN
signal quand l'import réussit. Détecter le retour est donc impossible, pas
seulement fragile.
This commit is contained in:
Sylvain Duchesne
2026-08-12 14:59:10 +02:00
parent c5b4703687
commit f5a3adc385
9 changed files with 621 additions and 65 deletions
+249 -22
View File
@@ -25,17 +25,43 @@ function fakeStorage(initial: Record<string, string> = {}) {
};
}
/** Put the page in a given URL + storage state, as the browser would. */
function inPage(search: string, storage: ReturnType<typeof fakeStorage>) {
/**
* Which side of the broker frontier a page is on — the thing that decides whether the
* barrier shows at all, so no page double may leave it unsaid.
*/
type Side = "top-level" | "in the broker iframe";
/**
* The `window` a page of that side presents.
*
* `window.self !== window.top` is the signal the gate reads, and it is the one
* `@ng-org/web`'s `init()` reads to decide whether to hand the page over. A double that
* omitted `window` would silently be a top-level page — and every framed assertion here
* would be quietly testing the other context.
*/
function fakeWindow(side: Side, onEvent?: (type: string, fn: (e: unknown) => void) => void) {
const self = {};
return {
self,
top: side === "top-level" ? self : {},
addEventListener: (type: string, fn: (e: unknown) => void): void => onEvent?.(type, fn),
};
}
/** Put the page in a given URL + storage state, on a given side, as the browser would. */
function inPage(search: string, storage: ReturnType<typeof fakeStorage>, side: Side) {
const location = { search, href: "https://app.example" + search };
(globalThis as any).location = location;
(globalThis as any).localStorage = storage;
(globalThis as any).history = { replaceState: () => {} };
Object.assign(globalThis, {
location,
localStorage: storage,
history: { replaceState: (): void => {} },
window: fakeWindow(side),
});
return { location };
}
/** Everything a page installs on the global object, so nothing leaks into the next test. */
const PAGE_GLOBALS = ["location", "localStorage", "history", "document"] as const;
const PAGE_GLOBALS = ["location", "localStorage", "history", "document", "window"] as const;
afterEach(() => {
setCurrentUser(null);
@@ -57,8 +83,10 @@ function configured() {
}
test("an identity already set is left alone — the gate never re-asks", async () => {
// The escape hatch: a caller that took charge of the identity itself is not a person
// arriving at a page, so there is nobody to show a barrier to — top-level or not.
configured();
inPage("", fakeStorage());
inPage("", fakeStorage(), "top-level");
setCurrentUser("alice");
await ensureIdentity();
expect(getCurrentUser()).toBe("alice");
@@ -70,7 +98,7 @@ test("the URL parameter WINS over storage — it is the only thing that crosses
// round-trip; storage does not. If storage won here, a user entering a second
// identifier would keep being sent back to the first one's space.
configured();
inPage("?ng-id=fromurl", fakeStorage({ [KEY]: "fromstorage" }));
inPage("?ng-id=fromurl", fakeStorage({ [KEY]: "fromstorage" }), "in the broker iframe");
await ensureIdentity();
expect(getCurrentUser()).toBe("fromurl");
});
@@ -78,14 +106,16 @@ test("the URL parameter WINS over storage — it is the only thing that crosses
test("the URL parameter is copied into THIS partition, so a plain reload still knows", async () => {
configured();
const storage = fakeStorage();
inPage("?ng-id=carol", storage);
inPage("?ng-id=carol", storage, "in the broker iframe");
await ensureIdentity();
expect(storage.getItem(KEY)).toBe("carol");
});
test("with no parameter, storage answers — a reload does not re-ask", async () => {
test("inside the iframe, with no parameter, storage answers — the barrier stays away", async () => {
// The round-trip is behind us here, so a known identifier settles the question outright.
// Top-level it does not, and the pair below says so.
configured();
inPage("", fakeStorage({ [KEY]: "dana" }));
inPage("", fakeStorage({ [KEY]: "dana" }), "in the broker iframe");
await ensureIdentity();
expect(getCurrentUser()).toBe("dana");
});
@@ -94,13 +124,13 @@ test("nothing known and no DOM to ask on → it refuses loudly", async () => {
// Continuing silently would provision an anonymous virtual space, which is the failure
// this module exists to prevent. The error names what the caller must do.
configured();
inPage("", fakeStorage());
inPage("", fakeStorage(), "top-level");
await expect(ensureIdentity()).rejects.toThrow(/no DOM to ask on/i);
});
test("no shared wallet configured → it refuses, rather than inventing a space", async () => {
configure({ ng: {} as never, useShape: (() => {}) as never });
inPage("", fakeStorage());
inPage("", fakeStorage(), "top-level");
await expect(ensureIdentity()).rejects.toThrow(/no shared wallet configured/i);
});
@@ -110,14 +140,14 @@ test("the URL value is NORMALIZED on the way in — `@Erin` and `erin` are one s
// a link with `?ng-id=@Erin` keyed onto a different virtual user than the same person
// typing `erin`. One normalizer — the injected one — for all three entry paths.
configured();
inPage("?ng-id=@Erin", fakeStorage());
inPage("?ng-id=@Erin", fakeStorage(), "in the broker iframe");
await ensureIdentity();
expect(getCurrentUser()).toBe("erin");
});
test("a stored value is normalized too — an old entry cannot key onto a second space", async () => {
configured();
inPage("", fakeStorage({ [KEY]: "@Frank" }));
inPage("", fakeStorage({ [KEY]: "@Frank" }), "in the broker iframe");
await ensureIdentity();
expect(getCurrentUser()).toBe("frank");
});
@@ -147,12 +177,13 @@ function fakeElement() {
return {
value: "",
disabled: false,
textContent: "",
addEventListener(type: string, fn: (e: unknown) => void): void {
handlers.set(type, [...(handlers.get(type) ?? []), fn]);
},
focus(): void {},
fire(type: string): void {
for (const fn of handlers.get(type) ?? []) fn({});
fire(type: string, event: unknown = {}): void {
for (const fn of handlers.get(type) ?? []) fn(event);
},
};
}
@@ -186,12 +217,28 @@ function fakeDom() {
get shown(): boolean {
return mounted > 0;
},
/** What the field holds before anyone touches it — the prefill, seen as a user sees it. */
get prefilled(): string {
return input.value;
},
/** The button's label and whether it can be pressed — the frozen state, once entered. */
get button(): { label: string; disabled: boolean } {
return { label: go.textContent, disabled: go.disabled };
},
/** What a user does at the gate: type an identifier, then press Entrer. */
submit(id: string): void {
input.value = id;
input.fire("input");
go.fire("click");
},
/** What a returning user does: press Entrer on the field as they found it. */
confirm(): void {
go.fire("click");
},
/** A press of Enter in the field — which a real one still takes once the button is dead. */
pressEnter(): void {
input.fire("keydown", { key: "Enter" });
},
};
}
@@ -203,26 +250,48 @@ function fakeDom() {
* `href` — as a real browser does, and as `init()` relies on when it reads the address bar
* afterwards. A fake whose `replaceState` did nothing would let a broken gate pass.
*/
function inBrowser(opts: { url: string; storage?: ReturnType<typeof fakeStorage> }) {
function inBrowser(opts: { url: string; storage?: ReturnType<typeof fakeStorage>; side?: Side }) {
const storage = opts.storage ?? fakeStorage();
const dom = fakeDom();
const side = opts.side ?? "top-level";
let href = opts.url;
let reloads = 0;
const location = {
get href(): string { return href; },
set href(next: string) { href = next; },
get search(): string { return new URL(href).search; },
reload: (): void => void (reloads += 1),
};
const history = {
replaceState: (_state: unknown, _title: string, next: string): void => void (href = next),
};
// The page-level listeners the gate installs, kept so a test can play the browser event
// that fires them. `pageshow` is the only one, and it cannot be simulated any other way.
const listeners = new Map<string, ((e: unknown) => void)[]>();
Object.assign(globalThis, {
location,
history,
localStorage: storage,
document: dom.document,
window: fakeWindow(side, (type, fn) => listeners.set(type, [...(listeners.get(type) ?? []), fn])),
});
return { location, storage, dom };
return {
location,
storage,
dom,
/** How many times the page asked the browser to reload it. */
get reloads(): number { return reloads; },
/** Is anything listening for the browser restoring this page from its cache? */
get armed(): boolean { return (listeners.get("pageshow") ?? []).length > 0; },
/**
* The browser restoring this page — from its back/forward cache (`persisted`) or
* loading it afresh. Only the first is a return from a hand-over that did not complete.
*/
pageshow(persisted: boolean): void {
for (const fn of listeners.get("pageshow") ?? []) fn({ persisted });
},
};
}
test("settled at the GATE: the address bar carries the identifier `init()` will hand over", async () => {
@@ -231,6 +300,9 @@ test("settled at the GATE: the address bar carries the identifier `init()` will
const settled = ensureIdentity();
expect(page.dom.shown).toBe(true);
// A first access knows nothing, so the field is bare — the prefill below has to be able
// to fail, and it cannot if the field is filled whatever happened.
expect(page.dom.prefilled).toBe("");
page.dom.submit("Gina");
expect(await settled).toBe("gina");
@@ -243,18 +315,30 @@ test("settled from STORAGE: the address bar gains the identifier — the silent
// broker iframe read different localStorage partitions. A returning user is recognised
// from storage and the URL stays bare, so unless the parameter is written HERE the
// round-trip leaves without it and the user lands in a second, empty virtual space.
//
// Top-level, being recognised is not the same as being let through: the barrier shows,
// with the field already filled, and the identifier reaches the address bar when the
// person confirms it.
configured();
const page = inBrowser({ url: APP, storage: fakeStorage({ [KEY]: "dana" }) });
expect(await ensureIdentity()).toBe("dana");
const settled = ensureIdentity();
expect(page.dom.prefilled).toBe("dana");
page.dom.confirm();
expect(await settled).toBe("dana");
expect(page.location.href).toBe(APP + "?ng-id=dana");
});
test("settled from the URL: the parameter is rewritten NORMALIZED, not as the link spelled it", async () => {
// `@Erin` and `erin` must be one virtual space, and it is the address bar that survives
// the round-trip — so it is the normalized form that has to be in it, not the raw one.
// The field shows the normalized form too: it is the identifier, not the spelling of the
// link, that names the space they are about to enter.
configured();
const page = inBrowser({ url: APP + "?ng-id=@Erin" });
expect(await ensureIdentity()).toBe("erin");
const settled = ensureIdentity();
expect(page.dom.prefilled).toBe("erin");
page.dom.confirm();
expect(await settled).toBe("erin");
expect(page.location.href).toBe(APP + "?ng-id=erin");
});
@@ -266,6 +350,147 @@ test("settled by the CALLER: an identity set before the call still reaches the a
expect(page.location.href).toBe(APP + "?ng-id=alice");
});
// ── Which side of the frontier decides whether the barrier shows ───────────
//
// Not whether the identity is known. A top-level page is one redirect away from the
// broker, and someone whose browser has lost the wallet — or never had it, the identifier
// having reached them by link — lands there on a static dead end with no way back but the
// browser's own Back button. The barrier is the only screen that hands the wallet out, so
// it shows on every top-level load and stands aside only past the round-trip, inside the
// iframe. Keying it on identity presence is what made it skip itself, silently, for
// exactly the people who needed it.
test("TOP-LEVEL, a known identifier fills the field — it does not skip the barrier", async () => {
// The regression this pair exists for. `dana` is known from storage, and the barrier
// shows anyway, prefilled: one click, no typing, and the wallet still on offer above it.
configured();
const page = inBrowser({ url: APP, storage: fakeStorage({ [KEY]: "dana" }) });
const settled = ensureIdentity();
expect(page.dom.shown).toBe(true);
expect(page.dom.prefilled).toBe("dana");
page.dom.confirm();
expect(await settled).toBe("dana");
});
test("INSIDE THE IFRAME, the same known identifier stands the barrier down", async () => {
// The other half, and what makes the one above an assertion rather than a tautology:
// same identity, same storage, a DOM perfectly able to show a barrier — and no barrier,
// because the round-trip is behind us. A returning user asked to confirm again on the
// far side would be answering the same question twice for nothing.
configured();
const page = inBrowser({
url: APP + "?ng-id=dana",
storage: fakeStorage({ [KEY]: "dana" }),
side: "in the broker iframe",
});
expect(await ensureIdentity()).toBe("dana");
expect(page.dom.shown).toBe(false);
});
test("inside the iframe, a page that knows NOBODY still asks — the safe failure", async () => {
// The last resort, and it must stay: an iframe reached without the parameter has no
// identity to act as, and continuing would provision an anonymous virtual space that
// looks like a working application. Asking is the honest outcome.
configured();
const page = inBrowser({ url: APP, side: "in the broker iframe" });
const settled = ensureIdentity();
expect(page.dom.shown).toBe(true);
page.dom.submit("Hana");
expect(await settled).toBe("hana");
});
// ── Coming BACK from a hand-over that dead-ended ──────────────────────────
//
// The broker sends a walletless visitor to a static page with no return path. Back is
// their only way out, and it restores this document from the browser's cache exactly as
// it left — barrier frozen, button dead, `init()` already delegated and never redirecting
// again. Without a reset there is nothing on that page left to press.
test("a top-level page that has been handed over holds its barrier, frozen", async () => {
configured();
const page = inBrowser({ url: APP });
const settled = ensureIdentity();
page.dom.submit("Gina");
await settled;
// Not removed: the hand-over is a navigation, and a bare page is what the person would
// come back to. This is also the state the reset below un-sticks.
expect(page.dom.shown).toBe(true);
expect(page.dom.button).toEqual({ label: "Accès en cours…", disabled: true });
expect(page.armed).toBe(true);
});
test("restored from the browser's cache, it reloads — the button comes back to life", async () => {
configured();
const page = inBrowser({ url: APP });
const settled = ensureIdentity();
page.dom.submit("Gina");
await settled;
page.pageshow(true);
// A reload re-runs `init()`, which settles again and puts the barrier back up prefilled
// from the address bar — the only reset available, since the redirect belongs to the
// level below and has already happened.
expect(page.reloads).toBe(1);
});
test("a barrier already answered ignores a second Enter — one return listener, one reload", async () => {
// The button is dead by then, and a dead button dispatches no click — but the field
// still takes the key. Twice armed would be twice reloaded on the way back.
configured();
const page = inBrowser({ url: APP });
const settled = ensureIdentity();
page.dom.submit("Gina");
await settled;
page.dom.pressEnter();
page.pageshow(true);
expect(page.reloads).toBe(1);
});
test("an ordinary load is not a return — it must not reload", async () => {
// `pageshow` fires on every load, cached or not. Reloading on the plain one would loop
// the page forever, which is a worse failure than the one being fixed.
configured();
const page = inBrowser({ url: APP });
const settled = ensureIdentity();
page.dom.submit("Gina");
await settled;
page.pageshow(false);
expect(page.reloads).toBe(0);
});
test("someone still AT the barrier is not reset — what they typed survives", async () => {
// Armed on the way OUT, not at load: a person who wandered off before confirming comes
// back to the page they left, not to a reloaded one that lost their identifier. So the
// arming has to straddle the confirmation, and this pins both sides of it.
configured();
const page = inBrowser({ url: APP });
const settled = ensureIdentity();
expect(page.armed).toBe(false);
// A barrier left unanswered would hold the settling in flight and every later test would
// JOIN it instead of raising its own — so answer it, always.
page.dom.submit("Gina");
await settled;
expect(page.armed).toBe(true);
});
test("inside the iframe nothing is armed — there was no hand-over to come back from", async () => {
configured();
const page = inBrowser({ url: APP, side: "in the broker iframe" });
const settled = ensureIdentity();
page.dom.submit("Hana");
await settled;
// And the barrier IS removed here: the application renders behind it.
expect(page.dom.shown).toBe(false);
expect(page.armed).toBe(false);
});
test("a storage that refuses writes does not cost the round-trip its parameter", async () => {
// Private mode, quota, a sandboxed document: `setItem` throws. Storage is only
// same-partition convenience — the address bar is what crosses the frontier — so the two
@@ -300,7 +525,9 @@ test("an address bar that cannot be rewritten fails safely — the gate asks aga
},
},
});
expect(await ensureIdentity()).toBe("dana");
const settled = ensureIdentity();
page.dom.confirm();
expect(await settled).toBe("dana");
expect(page.storage.getItem(KEY)).toBe("dana");
expect(page.location.href).toBe(APP);
});
+34 -8
View File
@@ -33,22 +33,32 @@ function fakeStorage(initial: Record<string, string> = {}) {
};
}
/**
* Which side of the broker frontier the page is on. It decides whether the barrier shows
* at all — top-level it always does, past the round-trip it never does — so no page here
* may leave it unsaid: `window.self !== window.top` is what the gate reads, and a double
* without a `window` would silently be top-level.
*/
type Side = "top-level" | "in the broker iframe";
/**
* A browser page, faithful in the one way these assertions depend on: `location.search`
* tracks `href`, and `history.replaceState` MOVES `href` — as a real browser does, and as
* the real `init()` relies on when it reads the address bar. A double whose `replaceState`
* did nothing would let a broken `init()` pass.
*/
function inBrowser(url: string, storage: ReturnType<typeof fakeStorage>) {
function inBrowser(url: string, storage: ReturnType<typeof fakeStorage>, side: Side) {
let href = url;
const location = {
get href(): string { return href; },
get search(): string { return new URL(href).search; },
};
const self = {};
Object.assign(globalThis, {
location,
history: { replaceState: (_s: unknown, _t: string, next: string): void => void (href = next) },
localStorage: storage,
window: { self, top: side === "top-level" ? self : {}, addEventListener: (): void => {} },
});
return { location };
}
@@ -99,10 +109,14 @@ function fakeDom() {
input.fire("input");
go.fire("click");
},
/** What a returning user does: press Entrer on the field as they found it, prefilled. */
confirm(): void {
go.fire("click");
},
};
}
const PAGE_GLOBALS = ["location", "localStorage", "history", "document"] as const;
const PAGE_GLOBALS = ["location", "localStorage", "history", "document", "window"] as const;
afterEach(() => {
setCurrentUser(null);
@@ -170,11 +184,20 @@ test("the injected `init` finds the identifier ALREADY in the address bar", asyn
// wrapper that delegated first and settled after would satisfy any ordering check and
// still send the round-trip off bare. Identity from storage is the case that bites —
// storage does not cross the broker's partition, the URL does.
//
// Top-level, which is the only side that hands over at all, so Hana meets the barrier
// with her identifier already in the field and confirms it. What must be true when the
// delegate is finally called is unchanged: the address bar already carries her.
const wiring = consumerWiring();
configured(wiring);
inBrowser(APP, fakeStorage({ [KEY]: "hana" }));
inBrowser(APP, fakeStorage({ [KEY]: "hana" }), "top-level");
const dom = fakeDom();
Object.assign(globalThis, { document: dom.document });
await within(init(() => {}, true, []));
const delegated = init(() => {}, true, []);
await Promise.resolve();
dom.confirm();
await within(delegated);
expect(wiring.calls.length).toBe(1);
expect(wiring.calls[0]!.href).toBe(APP + "?ng-id=hana");
@@ -186,9 +209,12 @@ test("it resolves though the session exists only AFTER it delegates — the cycl
// `session()` → the consumer's thunk → a promise only `init()`'s callback resolves. Await
// that here and nothing ever runs: `init` is never called, so the session never arrives,
// so the wait never ends. `init()` therefore awaits the SESSION-FREE half only.
//
// Inside the iframe, which is where the cycle actually closes: the identifier arrived in
// the URL, the barrier stands aside, and delegating is what opens the session.
const wiring = consumerWiring();
configured(wiring);
inBrowser(APP + "?ng-id=iris", fakeStorage());
inBrowser(APP + "?ng-id=iris", fakeStorage(), "in the broker iframe");
await within(init(() => {}, true, []));
@@ -204,7 +230,7 @@ test("a settling failure rejects — the page is not handed to the broker withou
// is still visible.
const wiring = consumerWiring();
configured(wiring, { sharedWallet: false });
inBrowser(APP, fakeStorage());
inBrowser(APP, fakeStorage(), "top-level");
await expect(init(() => {}, true, [])).rejects.toThrow(/no shared wallet configured/i);
expect(wiring.calls.length).toBe(0);
@@ -218,7 +244,7 @@ test("`init` and `ensureIdentity` in the same tick raise ONE barrier, not two",
// it never hands the page to the broker — the application hangs before it ever loads.
const wiring = consumerWiring();
configured(wiring);
inBrowser(APP, fakeStorage());
inBrowser(APP, fakeStorage(), "top-level");
const dom = fakeDom();
Object.assign(globalThis, { document: dom.document });
@@ -239,7 +265,7 @@ test("arguments and return value pass through untouched — it is still a forwar
// would be a difference the application has to unlearn at migration.
const wiring = consumerWiring();
configured(wiring);
inBrowser(APP, fakeStorage());
inBrowser(APP, fakeStorage(), "top-level");
setCurrentUser("juno");
const callback = (): void => {};
@@ -40,8 +40,16 @@ function fakeStorage() {
};
}
/** A page whose address bar MOVES on `replaceState`, as the gate and `init()` both rely on. */
function inBrowser(url: string): void {
/**
* A page whose address bar MOVES on `replaceState`, as the gate and `init()` both rely on.
*
* INSIDE THE BROKER IFRAME (`window.self !== window.top`), and that is not decoration: it
* is the side of the frontier this whole file describes. The identifier has already crossed
* in the URL, so the barrier stands aside; and the session exists only here, opened by the
* callback `init()` is given. Top-level, `init()` navigates away and no session is ever
* established, so the deadlock pinned below could not even be reached.
*/
function inBrokerIframe(url: string): void {
let href = url;
Object.assign(globalThis, {
location: {
@@ -50,10 +58,11 @@ function inBrowser(url: string): void {
},
history: { replaceState: (_s: unknown, _t: string, next: string): void => void (href = next) },
localStorage: fakeStorage(),
window: { self: {}, top: {}, addEventListener: (): void => {} },
});
}
const PAGE_GLOBALS = ["location", "localStorage", "history", "document"] as const;
const PAGE_GLOBALS = ["location", "localStorage", "history", "document", "window"] as const;
afterEach(() => {
setCurrentUser(null);
@@ -108,7 +117,7 @@ function bootTheApplication(identifier: string) {
sharedWallet: { fileUrl: "/w.ngw", password: "pw" },
});
inBrowser(`${APP}?ng-id=${encodeURIComponent(identifier)}`);
inBrokerIframe(`${APP}?ng-id=${encodeURIComponent(identifier)}`);
let delegated!: Promise<unknown>;
sessionReady = new Promise<RegistrySession>((resolve) => {