Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201// Two full Ziran runtimes + one relay, driven over their real HTTP APIs:// Alice creates a checklist, goes live, invites Bob; Bob sees the invitation// in his base window state, accepts (download-then-sync), and ops flow both// ways end-to-end encrypted — the relay log stays ciphertext.// Run: deno run -A src/sync/e2e.test.ts
import { join } from '@std/path';import { startRelay } from '../../relay/main.ts';import { DevVerifier } from '../../relay/auth.ts';import { toB64 } from './protocol.ts';
let failures = 0;const check = (label: string, ok: boolean, detail = '') => { console.log(`${ok ? 'PASS' : 'FAIL'} ${label}${detail ? ` — ${detail}` : ''}`); if (!ok) failures++;};const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const enc = (s: string) => new TextEncoder().encode(s);const dec = (b: Uint8Array) => new TextDecoder().decode(b);
const tmp = await Deno.makeTempDir({ prefix: 'ziran-e2e-' });const relayData = join(tmp, 'relay');const relay = await startRelay({ port: 0, dataDir: relayData, verifier: new DevVerifier('e2e-secret') });const relayUrl = `ws://127.0.0.1:${relay.port}/ws`;
interface App { port: number; key: string; child: Deno.ChildProcess;}
async function startApp(name: string, did: string, port: number): Promise<App> { const key = `${name}-key`; const child = new Deno.Command(Deno.execPath(), { args: ['run', '-A', 'main.ts'], env: { ZIRAN_SYNC: 'relay', // these suites exercise the relay stack ZIRAN_DATA_DIR: join(tmp, name), ZIRAN_KEY: key, ZIRAN_PORT: String(port), ZIRAN_DID: did, ZIRAN_HANDLE: `${name}.test`, ZIRAN_RELAY: relayUrl, ZIRAN_RELAY_SECRET: 'e2e-secret', }, stdout: 'null', stderr: 'piped', }).spawn(); // Wait for the API to come up. for (let i = 0; i < 60; i++) { try { const res = await fetch(`http://127.0.0.1:${port}/api/state`, { headers: { 'x-ziran-key': key } }); await res.body?.cancel(); if (res.ok) return { port, key, child }; } catch { // not up yet } await sleep(250); } throw new Error(`${name} did not start`);}
const req = async (app: App, path: string, init?: RequestInit) => { const res = await fetch(`http://127.0.0.1:${app.port}${path}`, { ...init, headers: { 'x-ziran-key': app.key, 'content-type': 'application/json', ...(init?.headers ?? {}) }, }); const data = await res.json(); if (!res.ok) throw new Error(data.error ?? `${path} → ${res.status}`); return data;};
let alice: App | undefined;let bob: App | undefined;try { [alice, bob] = await Promise.all([ startApp('alice', 'did:ziran:e2e-alice', 4901), startApp('bob', 'did:ziran:e2e-bob', 4902), ]); await sleep(1200); // sync managers register with the relay
// 1. Both runtimes report the relay as reachable, with their identities. const aState = await req(alice, '/api/state'); const bState = await req(bob, '/api/state'); check('alice runtime is relay-connected', aState.sync?.relayOk === true); check('bob runtime is relay-connected', bState.sync?.relayOk === true); check('identities honored', aState.sync?.identity?.did === 'did:ziran:e2e-alice');
// 2. Alice creates a checklist from the starter model and goes live. const checklist = aState.models.find((m: { id: string }) => m.id === 'com.berjon.ziran.checklist'); check('starter checklist model seeded', Boolean(checklist)); const opened = await req(alice, '/api/docs/from-model', { method: 'POST', body: JSON.stringify({ modelId: checklist.id }), }); const aDoc = opened.doc.id as string; await req(alice, `/api/docs/${aDoc}/sync/share`, { method: 'POST' }); const aState2 = await req(alice, '/api/state'); check('document is live for alice', Boolean(aState2.sync?.docs?.[aDoc]));
// 3. Alice appends an op pre-invite (this lands in the pre-join epoch; Bob // will get its effect through the snapshot, not the log). const op1 = { op: 'add', id: 'aaaa1111', text: 'pack the telescope' }; await req(alice, `/api/docs/${aDoc}/sync/send`, { method: 'POST', body: JSON.stringify({ b64: toB64(enc(JSON.stringify(op1))) }) }); // Simulate the tile persisting after applying the echo: write items data. const items = JSON.stringify([{ id: 'aaaa1111', text: 'pack the telescope', done: false }]); await fetch(`http://127.0.0.1:${alice.port}/api/docs/${aDoc}/data/items`, { method: 'PUT', headers: { 'x-ziran-key': alice.key }, body: enc(items), }); await sleep(300);
// 4. Invite Bob. const invited = await req(alice, `/api/docs/${aDoc}/sync/invite`, { method: 'POST', body: JSON.stringify({ did: 'did:ziran:e2e-bob', role: 'editor' }), }); check('invite returns a share link', typeof invited.link === 'string' && invited.link.includes('/i/'));
// 5. The landing page renders for the link. const landing = await (await fetch(invited.link)).text(); check('landing page names the document', landing.includes('invited') && landing.includes('ziran://invite/'));
// 6. Bob's runtime received the invitation (inbox → state snapshot). await sleep(500); const bState2 = await req(bob, '/api/state'); const inv = bState2.sync?.invitations?.[0]; check('invitation lands in bob’s base window state', Boolean(inv), JSON.stringify(bState2.sync?.invitations)); check('invitation carries inviter + role', inv?.inviterHandle === 'alice.test' && inv?.role === 'editor'); check('invitation does not leak the MLS welcome', !('payload' in (inv ?? { payload: 1 })));
// 7. Bob accepts: download-then-sync, document opens in a window. const accepted = await req(bob, `/api/invitations/${inv.token}/accept`, { method: 'POST' }); const bDoc = accepted.doc.id as string; check('accept opens a verified document', accepted.doc.damaged === false, accepted.doc.damage); check('accept created a window', Boolean(accepted.win?.id));
// 8. Bob's copy contains alice's pre-invite state (via the snapshot). const bItems = await fetch(`http://127.0.0.1:${bob.port}/api/docs/${bDoc}/data/items`, { headers: { 'x-ziran-key': bob.key }, }); const bItemsText = bItems.ok ? dec(new Uint8Array(await bItems.arrayBuffer())) : ''; check('bob’s download carries the pre-invite item', bItemsText.includes('pack the telescope'));
// 9. Live ops flow alice → bob. const op2 = { op: 'add', id: 'bbbb2222', text: 'find dark skies' }; await req(alice, `/api/docs/${aDoc}/sync/send`, { method: 'POST', body: JSON.stringify({ b64: toB64(enc(JSON.stringify(op2))) }) }); await sleep(400); const bAttach = await req(bob, `/api/docs/${bDoc}/sync/attach`, { method: 'POST' }); check('bob is attached to the live session', bAttach.shared === true); const bGot = (bAttach.buffered ?? []).some((m: { b64: string }) => dec(Uint8Array.from(atob(m.b64.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))).includes('find dark skies')); check('alice’s live op reaches bob decrypted', bGot);
// 10. And bob → alice. const op3 = { op: 'set', id: 'aaaa1111', done: true }; await req(bob, `/api/docs/${bDoc}/sync/send`, { method: 'POST', body: JSON.stringify({ b64: toB64(enc(JSON.stringify(op3))) }) }); await sleep(400); const aAttach = await req(alice, `/api/docs/${aDoc}/sync/attach`, { method: 'POST' }); const aGot = (aAttach.buffered ?? []).some((m: { b64: string; author: string }) => m.author === 'did:ziran:e2e-bob'); check('bob’s op reaches alice, attributed to bob', aGot);
// 11. Roster shows both members on both sides. const aFinal = await req(alice, '/api/state'); const bFinal = await req(bob, '/api/state'); check('alice sees both members', aFinal.sync?.docs?.[aDoc]?.members?.length === 2); check('bob sees both members', bFinal.sync?.docs?.[bDoc]?.members?.length === 2); check('bob’s role is editor', bFinal.sync?.docs?.[bDoc]?.role === 'editor');
// 12. THE INVARIANT: the relay stored only ciphertext. let leaked = false; const plaintexts = ['pack the telescope', 'find dark skies', 'aaaa1111']; for await (const doc of Deno.readDir(join(relayData, 'docs'))) { for (const file of ['log.jsonl', 'snapshot.json']) { try { const raw = await Deno.readTextFile(join(relayData, 'docs', doc.name, file)); // The b64 payloads decode to MLS wire format; check both raw file and // decoded payloads for plaintext. if (plaintexts.some((p) => raw.includes(p) || raw.includes(toB64(enc(p))))) leaked = true; } catch { // file absent } } } check('relay log + snapshot are ciphertext only', !leaked);} finally { try { alice?.child.kill(); bob?.child.kill(); } catch { /* already gone */ } relay.shutdown(); await sleep(200); await Deno.remove(tmp, { recursive: true }).catch(() => {});}
if (failures) { console.error(`\n${failures} failure(s)`); Deno.exit(1);}console.log('\ntwo-runtime E2EE collaboration: all good');