fix(client): durcir le cold-start du shim — ensureRepoOpen(anchor) avant lecture/écriture

Défensif : loadShim/resolveAccount/ensureAccount ouvrent l'anchor (private-store-root)
avant de lire/écrire le compte shim, comme le fait déjà readScopeIndex. Robustesse
same-session si l'anchor est là-mais-pas-encore-souscrit.

NB (vérifié nextgraph-rs) : sur le login broker normal, le bootstrap charge le
private-store dans self.repos AVANT de rendre la session à JS → un wallet FRAIS
retourne 0 rows (pas RepoNotFound) et provisionne. Il n'existe AUCUN primitif JS
pour ouvrir un repo *inconnu* : ce heal n'est pas un remède à un store non
bootstrappé (limite NextGraph), juste une robustesse d'ouverture same-session.

Tests : cold-start-anchor.test.ts (rouge-avant/vert-après unit) ; harness e2e
repro-fresh-wallet (mint un wallet neuf par run — comble le trou "aucun test de
démarrage à froid sur wallet vierge"). Fakes anti-fork/watch-shape honorent
désormais la barrière first-State dont dépend le heal. e2e réel 42/42.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sylvain Duchesne
2026-07-13 15:06:30 +02:00
parent 078d675bbf
commit 3046ead08f
7 changed files with 473 additions and 6 deletions
+66
View File
@@ -140,6 +140,72 @@ export async function launchWalletContext(): Promise<BrowserContext> {
});
}
/**
* Create a BRAND-NEW wallet in a BRAND-NEW profile dir and RETURN the launched
* context, without a `.wallet-ready` marker and WITHOUT tearing the context down.
* Unlike {@link ensureWallet} (which reuses one persistent dedicated wallet across
* runs — so it is always "hot"), this mints a genuinely FRESH wallet each call so
* the cold-start (private-store repo not yet in `self.repos`) can be exercised.
*
* Same headless nextgraph.eu creation + first-login-bootstrap flow as ensureWallet,
* but the context stays OPEN and is returned (with its dir) so the caller can then
* open the SDK page in the SAME profile — i.e. the very first app session over a
* wallet that has never run the app. Caller cleans up ctx + dir.
*/
export async function createFreshWalletContext(): Promise<{
ctx: BrowserContext;
dir: string;
name: string;
}> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ng-eventually-fresh-"));
const name = "ng-fresh-" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
const ctx = await chromium.launchPersistentContext(dir, {
headless: true,
executablePath: resolveChromePath(),
args: LAUNCH_ARGS,
});
const page = ctx.pages()[0] || (await ctx.newPage());
page.on("pageerror", () => {});
await page.goto("https://nextgraph.eu/", { waitUntil: "domcontentloaded", timeout: 30000 });
const createButton = page.getByText("Create Wallet", { exact: true });
await createButton.waitFor({ state: "visible", timeout: 15000 });
await createButton.click();
await page.waitForURL("**/account*", { timeout: 15000 }).catch(() => {});
const acceptButton = page.getByText("I accept", { exact: true });
await acceptButton.waitFor({ state: "visible", timeout: 15000 });
await acceptButton.click();
const usernameInput = page.locator("#username-input");
await usernameInput.waitFor({ state: "visible", timeout: 30000 });
await usernameInput.fill(name);
const passwordInput = page.locator("#password-input");
await passwordInput.waitFor({ state: "visible", timeout: 5000 });
await passwordInput.fill(WALLET_PASSWORD);
const submitButton = page.getByText("create my wallet", { exact: false });
await submitButton.waitFor({ state: "visible", timeout: 5000 });
await submitButton.click();
await page.waitForURL("**/#/wallet/login", { timeout: 30000 });
await page.waitForTimeout(2000);
// First login → bootstrap the verifier repos from the broker (this is what a
// brand-new wallet does on its very first unlock).
const walletLink = page.getByText("Click here to login with your wallet");
if (await walletLink.isVisible({ timeout: 5000 }).catch(() => false)) {
await walletLink.click();
await page.waitForTimeout(1000);
}
const loginPassword = page.locator('input[type="password"]');
await loginPassword.waitFor({ state: "visible", timeout: 10000 });
await loginPassword.fill(WALLET_PASSWORD);
await loginPassword.press("Enter");
await page.waitForTimeout(10000);
await page.close().catch(() => {});
return { ctx, dir, name };
}
/**
* Launch a persistent context on a FRESH, EMPTY profile dir (its own userDataDir).
* Empty local storage ⇒ empty verifier repo cache ⇒ the reconnection cold-start:
+121
View File
@@ -0,0 +1,121 @@
/**
* COLD-START repro — a genuinely FRESH wallet (never ran the app) driving the
* shim's first account resolution/provision.
*
* Unlike `run.ts`, which reuses ONE dedicated wallet (always "hot" — its
* private-store repo is already in the verifier's `self.repos`), this mints a
* BRAND-NEW wallet + fresh profile per run and opens the SDK page over it as the
* very first session. It then, in order:
* 1) probes the RAW anchored shim SELECT on `did:ng:${private_store_id}` — the
* cold-start bug surfaces here as `RepoNotFound` (the private-store repo not
* yet open) rather than a silent 0 rows;
* 2) runs `ensureAccount` (resetRegistryCache first) — the app's first-login
* bootstrap — and asserts it provisions 3 scope docs WITHOUT throwing;
* 3) re-resolves the SAME id from a fresh anchored read and asserts it returns
* the SAME docs (real persistence in the shim).
*
* Expected BEFORE the fix: step 1 throws RepoNotFound; step 2/3 fail to persist.
* Expected AFTER the fix: step 1 may still throw (raw, no open), but step 2/3
* succeed because ensureAccount opens the anchor repo before read/write.
*
* Run: `bun run e2e/repro-fresh-wallet.ts`.
*/
import * as fs from "node:fs";
import type { Frame, Page, BrowserContext } from "playwright";
import { buildBundle, serveHarness, createFreshWalletContext, setupBrokerPage } from "./broker";
type Check = { name: string; ok: boolean; detail?: string };
const results: Check[] = [];
function check(name: string, ok: boolean, detail?: string): void {
results.push({ name, ok, detail });
console.log(` [${ok ? "PASS" : "FAIL"}] ${name}${detail ? " — " + detail : ""}`);
}
function sdk<T>(frame: Frame, method: string, ...args: unknown[]): Promise<T> {
return frame.evaluate(
([m, a]) => (window as any).__sdk[m as string](...(a as unknown[])),
[method, args] as const,
) as Promise<T>;
}
async function main(): Promise<void> {
console.log("[repro] building SDK page bundle...");
buildBundle();
const { url, close: closeServer } = await serveHarness();
console.log(`[repro] harness served at ${url}`);
console.log("[repro] creating a BRAND-NEW wallet (fresh profile)...");
let ctx: BrowserContext | null = null;
let dir: string | null = null;
let page: Page | null = null;
try {
const fresh = await createFreshWalletContext();
ctx = fresh.ctx;
dir = fresh.dir;
console.log(`[repro] fresh wallet: ${fresh.name}`);
page = await ctx.newPage();
page.on("pageerror", (e) => console.error("[iframe error]", e.message));
page.on("console", (m) => {
if (m.type() === "error") console.error("[iframe console]", m.text());
});
console.log("[repro] opening SDK page over the FRESH wallet (first-ever app session)...");
const frame = await setupBrokerPage(page, url);
await frame.waitForFunction(() => (window as any).__sdk !== undefined, { timeout: 30000 });
await frame.waitForFunction(() => (window as any).__sdk.status() === "connected", {
timeout: 60000,
});
console.log("[repro] connected. Driving the cold-start shim resolution...");
// 1) RAW anchored shim probe — the diagnostic. Reports RepoNotFound if the
// private-store repo is not yet open in this fresh session.
const probe = await sdk<any>(frame, "shimAnchorProbe");
console.log(
` [DIAG] raw anchored shim read: threw=${probe.threw} error=${probe.error} rows=${probe.rows}`,
);
// 2) ensureAccount — the real bootstrap. This MUST provision cleanly on a fresh
// wallet (all 3 docs truthy, no throw). This is the load-bearing assertion.
const ensured = await sdk<any>(frame, "coldEnsureAccount", "@cold-user-1");
check(
"fresh wallet: ensureAccount provisions the account without throwing",
!ensured.threw && !!ensured.docPublic && !!ensured.docProtected && !!ensured.docPrivate,
ensured.threw
? `THREW: ${ensured.error}`
: `pub=${String(ensured.docPublic).slice(0, 22)}… prot=${String(ensured.docProtected).slice(0, 22)}`,
);
// 3) Re-resolve from a FRESH anchored read — proves the shim actually persisted.
const verified = await sdk<any>(frame, "verifyShimPersisted", "@cold-user-1");
check(
"fresh wallet: the provisioned account persists (re-resolves the SAME docs, no RepoNotFound)",
!verified.threw &&
verified.docPublic === ensured.docPublic &&
verified.docProtected === ensured.docProtected &&
verified.docPrivate === ensured.docPrivate,
verified.threw
? `THREW: ${verified.error}`
: `same=${verified.docPublic === ensured.docPublic && verified.docProtected === ensured.docProtected}`,
);
} finally {
try { if (page) await page.close(); } catch { /* ignore */ }
try { if (ctx) await ctx.close(); } catch { /* ignore */ }
try { if (dir) fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
closeServer();
}
const passed = results.filter((r) => r.ok).length;
const failed = results.length - passed;
console.log(`\n══ cold-start repro: ${passed} passed, ${failed} failed ══`);
if (failed > 0) {
for (const r of results.filter((x) => !x.ok)) console.log(` - ${r.name}: ${r.detail ?? ""}`);
process.exit(1);
}
}
main().catch((e) => {
console.error("[repro] fatal:", e);
process.exit(1);
});
+61
View File
@@ -571,6 +571,67 @@ const identity = new IdentityStore(
return { priv, prot, pub };
},
/**
* COLD-START anchor probe. Runs the EXACT shim SELECT the registry issues,
* anchored to `did:ng:${private_store_id}` (the shim anchor), as the very first
* thing in a fresh session — BEFORE anything opens that repo. Reports whether the
* raw anchored query threw `RepoNotFound` (the cold-start bug: the private-store
* repo not yet in `self.repos`) or returned rows. Uses the low-level docs
* primitive directly so nothing (open-repo, ensureAccount) opens the repo first.
*/
async shimAnchorProbe() {
const s = session ?? (await sessionReady);
const anchor = `did:ng:${s.private_store_id}`;
const query =
"SELECT ?acc WHERE { GRAPH <" +
anchor +
"> { ?acc a <urn:ng-eventually:shim:Account> } }";
try {
const res: any = await docs.sparqlQuery(s.session_id, query, undefined, anchor);
const rows = Array.isArray(res) ? res.length : (res?.results?.bindings?.length ?? 0);
return { threw: false, error: null, rows, anchor };
} catch (e: any) {
return { threw: true, error: String(e?.message ?? e), rows: -1, anchor };
}
},
/**
* COLD-START account provision. resetRegistryCache then ensureAccount(id) — the
* real bootstrap the app runs on first login. On a fresh wallet, if the anchor
* repo isn't open, resolveAccount's read AND ensureAccount's provision write both
* hit RepoNotFound; the account never persists. Returns the 3 scope docs (all
* truthy iff provisioning succeeded) so the runner can gate on real persistence.
*/
async coldEnsureAccount(id: string) {
storeRegistry.resetRegistryCache();
try {
const rec = await storeRegistry.ensureAccount(id);
return {
threw: false,
error: null,
docPublic: rec.docPublic,
docProtected: rec.docProtected,
docPrivate: rec.docPrivate,
};
} catch (e: any) {
return { threw: true, error: String(e?.message ?? e), docPublic: "", docProtected: "", docPrivate: "" };
}
},
/**
* VERIFY the provisioned account actually PERSISTED to the shim: resetRegistryCache
* then re-resolve the SAME id via a fresh anchored read. Returns whether the read
* threw + the resolved docs. After the fix, on a fresh wallet this returns the SAME
* docs coldEnsureAccount minted (real persistence, no RepoNotFound).
*/
async verifyShimPersisted(id: string) {
storeRegistry.resetRegistryCache();
try {
const rec = await storeRegistry.ensureAccount(id);
return { threw: false, error: null, docPublic: rec.docPublic, docProtected: rec.docProtected, docPrivate: rec.docPrivate };
} catch (e: any) {
return { threw: true, error: String(e?.message ?? e), docPublic: "", docProtected: "", docPrivate: "" };
}
},
// ── watchShape (reactive useQuery-shaped read) ───────────────────────────
// A minimal SHEX-ish ShapeType pinning rdf:type to an e2e class IRI. watchShape
// reads only `.shape`/`.schema[...].predicates[rdf:type].dataTypes[].literals`