notes
All repositories: gitoria
8.7 KB
// tests/signin-return.mjs — ident#31: signed out on an INNER page of notes, sign in through the selector's panel (email → code → identity, all in// ident's frame), and the browser is back on THE SAME inner page, signed in. Fails on main: the selector has no `return` attribute there, so the// panel's sign-in comes back to the page that is the current URL, which does not handle ident_code (no session, ident_code left in the URL).// Real Chrome, real clicks and keys; ident is a copy of the branch's code (NOTES_GATE_IDENT_DIR) with a mail sink, never live data.// Ports (defaults): NOTES_SIGNIN_PORT app, +1 ident; Chrome NOTES_SIGNIN_CHROME (default 8715-8719).import { spawn } from 'node:child_process';import { mkdirSync, rmSync, existsSync, writeFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { launchBrowser } from './cdp.mjs';import { startIdent } from './identkit.mjs';if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const BIN = join(APP, 'bin/hybriel');const PORT = Number(process.env.NOTES_SIGNIN_PORT || 8706), BASE = `http://127.0.0.1:${PORT}`;const IDENT_PORT = PORT + 1;const IDENT_DIR = process.env.NOTES_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));const CHROME = (process.env.NOTES_SIGNIN_CHROME || '8715-8719').split('-').map(Number);const INNER = '/note/zzz';const G = join(APP, '.scratch/signin-return');const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));let passed = 0, failed = 0;const check = (name, ok, detail = '') => { if (ok) { passed++; console.log(' ok ' + name); } else { failed++; console.log(' FAIL ' + name + (detail ? ' — ' + detail : '')); } };rmSync(G, { recursive: true, force: true }); mkdirSync(join(G, 'mpackdb'), { recursive: true });let ident, server, browser, page, log = '', APPKEY;const sh = (hostSel, expr) => `(() => { const h = document.querySelector(${J(hostSel)}); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;const worlds = new Map();function trackWorlds(p) {p.conn.onEvent((msg) => {if (msg.sessionId !== p.sessionId) return;const c = msg.params && msg.params.context;if (msg.method === 'Runtime.executionContextCreated' && c && c.auxData && c.auxData.isDefault) worlds.set(c.auxData.frameId, c.id);if (msg.method === 'Runtime.executionContextDestroyed') for (const [f, id] of worlds) if (id === msg.params.executionContextId) worlds.delete(f);if (msg.method === 'Runtime.executionContextsCleared') worlds.clear();});return p.send('Runtime.enable');}async function fEval(p, expr) {const t = await p.send('Page.getFrameTree');const f = (t.frameTree.childFrames || [])[0];if (!f) throw new Error('no frame');const id = worlds.get(f.frame.id);if (!id) throw new Error('no context for the frame');const r = await p.send('Runtime.evaluate', { contextId: id, expression: expr, returnByValue: true, awaitPromise: true });if (r.exceptionDetails) throw new Error('frame evaluate threw: ' + ((r.exceptionDetails.exception && r.exceptionDetails.exception.description) || r.exceptionDetails.text));return r.result.value;}async function fWait(p, expr, label) {const end = Date.now() + 30000; let last;while (Date.now() < end) { try { last = await fEval(p, expr); if (last) return last; } catch (e) { last = e.message; } await sleep(100); }throw new Error('frame waitFor timed out: ' + label + ' (' + last + ')');}async function mouse(p, x, y) {const base = { x: Math.round(x), y: Math.round(y), button: 'left', clickCount: 1 };await p.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...base, buttons: 0 });await p.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base, buttons: 1 });await p.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 });}async function shClick(p, inner) {const box = await p.waitFor(sh('#selector', `(() => { const el = r.querySelector(${J(inner)}); if (!el) return null; el.scrollIntoView({ block: 'center' }); const b = el.getBoundingClientRect(); return b.width ? { x: b.left + b.width / 2, y: b.top + b.height / 2 } : null; })()`), { label: 'selector ' + inner });await mouse(p, box.x, box.y);}async function fClick(p, sel) {await fWait(p, `!!document.querySelector(${J(sel)})`, sel);const b = await fEval(p, `(() => { const r = document.querySelector(${J(sel)}).getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; })()`);const o = await p.evaluate(sh('#selector', `(() => { const b = r.querySelector('iframe#signin').getBoundingClientRect(); return { x: b.left, y: b.top }; })()`));await mouse(p, o.x + b.x, o.y + b.y);}async function fType(p, sel, text) {await fClick(p, sel);for (const ch of text) {await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });}}async function up(url) {for (const end = Date.now() + Number(process.env.NOTES_COLD_MS || 120000); Date.now() < end;) { try { const r = await fetch(url + '/'); if (r.ok) return; } catch {} await sleep(250); }throw new Error('did not come up: ' + url + '\n' + log);}try {ident = await startIdent({ identDir: IDENT_DIR, workDir: G, port: IDENT_PORT });const alice = await ident.signIn('[email protected]'); // her ident account exists (with its default identity); the BROWSER is signed out of identAPPKEY = await ident.registerApp(alice, 'notes (signin gate)', [BASE]);server = spawn(BIN, ['project.hl'], { cwd: APP, env: { ...process.env, NOTES_PORT: String(PORT), NOTES_STORAGE: join(G, 'mpackdb'), NOTES_SESSIONS: join(G, 'sessions') + '/', NOTES_WATCH: '0', NOTES_PUBLIC_URL: BASE, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base }, stdio: ['ignore', 'pipe', 'pipe'] });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);await up(BASE);browser = await launchBrowser({ debugPortRange: CHROME });page = await browser.newPage(); await trackWorlds(page);await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });await page.goto(BASE + INNER);await page.waitFor('!!customElements.get("ident-selector") && !!document.querySelector("#selector") && !!document.querySelector("#selector").shadowRoot', { label: 'the selector' });check('signed out on the inner page ' + INNER, (await page.evaluate('document.querySelector("#selector").classList.contains("out")')) === true && (await page.evaluate('location.pathname')) === INNER);await shClick(page, '#choose');await page.waitFor(sh('#selector', `!!r.querySelector('iframe#signin')`), { label: 'the sign-in frame' });await fWait(page, '!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1 && !!document.querySelector("#email")', 'frame hydrated');await fType(page, '#email', '[email protected]');await fClick(page, '#sendcode');await fWait(page, '!!document.querySelector("#code")', 'code field');await fType(page, '#code', ident.lastCode('[email protected]'));await fClick(page, '#verify');await fWait(page, 'document.querySelectorAll("#chooselist li").length >= 1', 'identity list');await page.evaluate('window.__still = 1');await fClick(page, '#chooselist li:nth-child(1) .choose');await page.waitFor(`!window.__still && document.readyState === 'complete' && location.pathname === ${J(INNER)} && !!document.querySelector('#selector') && document.querySelector('#selector').classList.contains('in')`, { timeout: 30000, label: 'back on the same page, signed in' });check('back on the SAME inner page (' + INNER + '), not the start page', (await page.evaluate('location.pathname')) === INNER, await page.evaluate('location.href'));check('signed in: the selector says so and the one-time code is not left in the URL', (await page.evaluate('document.querySelector("#selector").classList.contains("in") && !/ident_code/.test(location.href)')) === true, await page.evaluate('location.href'));} catch (e) {failed++; console.log(' FAIL the flow threw: ' + e.message.slice(0, 600));try { console.log(' at ' + (await page.evaluate('location.href'))); } catch {}} finally {try { await page.close(); } catch {}try { await browser.close(); } catch {}try { server.kill('SIGTERM'); } catch {}try { await ident.stop(); } catch {}writeFileSync(join(G, 'app.log'), log);}console.log(`\n${passed} passed, ${failed} failed`);process.exit(failed ? 1 : 0);
Branches
Latest commits
- 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
- 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
- 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
- d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
- 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
- d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
- 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
- 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
- e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
- 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
- 71a9538bnotes: B27W report, log linemre
- 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre
- 3de46dacnotes: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 73+5 failing → 78 passedmre
- 5909d458notes: MdEditor from components 59704ce (text on the clipboard always pastes, a file manager copy still attaches; pipe rows without a delimiter row; tickets#49, notes#5)mre
- 98bd6a98N5b: pipe rows without a delimiter row are a table (MdEditor ad4e929, plain copy); gate tests/dashboard-table.mjs; reportmre
- dbf93319N5 report: components gate rerun 613 passed, 0 failedmre
- 3a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre
- c16bd443N5: step 1 report (tables pass locally; his DASHBOARD note has no delimiter row)mre
- 6091320anotes: MdEditor 7437e32 (surface drawn at once when the page is claimed); gate measures claim-to-text on 5 note loads at 1280 and 390mre
- 0aa9277enotes: move each component's styles into its own Style block (shell and header selector in main.hl, list, editor frame and delete question in notes.hl); styles.hl keeps the theme inherit, the accent and the message colour; .gitignore ignores a bin symlink too; tests/shots.mjs for the pixel comparemre