gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit81f10e4e81f10e4eident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre81f10e4e/tests/browser.mjs

162.7 KB

  1. // tests/browser.mjs — THE GATE of tickets.worldapi.org: its own server on its own
  2. // storage, the import command, the JSON API, and TWO real headless Chromes (two
  3. // viewers) for the live push. Everything is checked in the browser's DOM, not in
  4. // curl output. Ticket #10 added: the strict API table (unknown / missing / empty /
  5. // wrong-type fields → 400 naming the field, nothing written), Vienna local time (checked
  6. // against node's Intl, also tests/localtime.hl's DST edges), and the paragraph import
  7. // (a CRLF fixture in .scratch/gate-import → #7, rendered with a blank line between).
  8. // Ticket #15 added: `author` required on every POST (missing/empty → 400 naming author),
  9. // invalid JSON → 400 { error } without source paths (jsoncheck.hl), the web forms have no
  10. // name field (author 'creator'), and list lines kept by the import (.scratch/gate-import-lists → hybriel #3).
  11. // Ticket #38 (mission 008) added: UUID keys + storage in <store>/mpackdb, per-project
  12. // numbers and URLs /<slug>/<number> (ticket #25; was /projects/<slug>/<number>). The gate FIRST writes an old-format store
  13. // (tests/oldstore.hl: 5 tickets, old #1–#5 in projects alpha / beta.example.org), migrates
  14. // it TWICE with tools/migrate-008.hl (the second run must write nothing), and runs the
  15. // server on the migrated tables: old numbers answer on /api/tickets/<n>, /tickets/<n>
  16. // redirects (301) to the new URL, the per-project API, live pushes carrying the new hrefs.
  17. // Ticket #7 (mission 011) added LOGIN VIA IDENT: the gate runs its OWN ident (a copy of
  18. // ident's code without .env / storage — codes go to a mail sink, never real mail; tests/identkit.mjs)
  19. // on :8353, registers tickets there (origin = this gate's server), and then: every API write
  20. // needs `Authorization: Bearer <token>` (401 otherwise, checked before the body; `author` in a
  21. // body → 400), a machine user "gate" logs in through the login button's server half
  22. // (/login/callback) and makes its token over the face; the FIRST server runs without
  23. // TICKETS_CREATOR_IDENTITY (nobody may confirm/reject → 403), the second with alice's per-app id.
  24. // In the browsers: signed out = reading only; A (alice, the creator) logs in with the identity
  25. // SELECTOR, B (bob) with ident's /login link (no header button since 2026-10-24); both get the display-name prompt; writes show the
  26. // user as author; bob cannot confirm/reject, alice can; bob's token on /you: shown once → API
  27. // write as bob → revoke → 401; forged face sessions (#31) are refused; old events keep their
  28. // authors; logout resets the selector.
  29. // Ticket #12 (mission 024) added THE MARKDOWN EDITOR; since mission 016 every Markdown field is the Hybriel MdEditor
  30. // (components/md-editor/) and the comments are the shared Comments block (components/comments/, layouts#2): typed with
  31. // real keys, Ctrl+Enter sends; "m016:" checks edit (the earlier version folds out), delete (asks first), like (toggle),
  32. // Edit / Delete only on your own comments, comments in place between the other history entries, a non-member reads
  33. // only and the server refuses them (faces + API), the comment API. The blocks' own gate: components.hybriel.worldapi.org.
  34. //
  35. // node tests/browser.mjs (TICKETS_GATE_PORT to move the server, default 8352;
  36. // TICKETS_GATE_IDENT_PORT the gate's ident, default 8353;
  37. // TICKETS_GATE_IDENT_DIR ident's code, default ../ident.worldapi.org)
  38. //
  39. // Debug ports: 8620-8629 (browser A) and 8630-8639 (browser B) — TICKETS_GATE_CHROME_A /
  40. // TICKETS_GATE_CHROME_B ("8810-8814") move them (mission 017: parallel workers get disjoint
  41. // port ranges); browser C (mission 046, the installable app / offline part at the end) 8640-8649,
  42. // TICKETS_GATE_CHROME_C. Screenshots at 390px
  43. // and 1280px land in .scratch/gate-*.png — LOOK at them. The whole server log is kept in
  44. // .scratch/gate-server.log. Every process started here (server, import runs, Chromes)
  45. // is stopped by PID in `finally`.
  46. import { spawn, spawnSync } from 'node:child_process';
  47. import http from 'node:http';
  48. import { rmSync, mkdirSync, writeFileSync, existsSync, readdirSync, copyFileSync, readFileSync } from 'node:fs';
  49. import { dirname, join, resolve } from 'node:path';
  50. import { fileURLToPath } from 'node:url';
  51. import zlib from 'node:zlib';
  52. import { launchBrowser } from './cdp.mjs';
  53. import { startIdent } from './identkit.mjs';
  54. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  55. const HERE = dirname(fileURLToPath(import.meta.url));
  56. const APP = resolve(HERE, '..');
  57. const BIN = join(APP, 'bin/hybriel');
  58. const PORT = Number(process.env.TICKETS_GATE_PORT || 8352);
  59. const BASE = `http://127.0.0.1:${PORT}`;
  60. const SCRATCH = join(APP, '.scratch');
  61. const STORE = join(SCRATCH, 'gate-store');
  62. const IDENT_PORT = Number(process.env.TICKETS_GATE_IDENT_PORT || 8353);
  63. // ident's CODE (read only — copied without .env/storage by identkit): the sibling folder,
  64. // or the Loreana path when the gate runs in a copy (.scratch/dev…)
  65. const IDENT_DIR = process.env.TICKETS_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  66. rmSync(STORE, { recursive: true, force: true });
  67. mkdirSync(join(STORE, 'mpackdb'), { recursive: true });
  68. // IW (creator 2026-10-24, "you removed the ident widget from all sites"): ident's <ident-selector> stands in the header, VISIBLE, top right — signed
  69. // out and signed in, on the phone and on the desktop. Returns 'ok' or what is wrong (hidden by an ancestor, no box, outside the viewport, not in the
  70. // header, not on the right, covered by something else).
  71. const SELECTOR_IN_HEADER = `(() => { const s = document.querySelector('application-header ident-selector'); if (!s) return 'no ident-selector in the header';
  72. for (let e = s; e && e !== document.documentElement; e = e.parentElement) { const c = getComputedStyle(e); if (c.display === 'none') return 'display:none on ' + e.tagName; if (c.visibility === 'hidden') return 'visibility:hidden on ' + e.tagName; if (+c.opacity === 0) return 'opacity 0 on ' + e.tagName; }
  73. const b = s.getBoundingClientRect(), h = document.querySelector('application-header').getBoundingClientRect();
  74. if (b.width < 40 || b.height < 30) return 'no box ' + b.width + 'x' + b.height;
  75. if (b.left < 0 || b.top < 0 || b.right > innerWidth + 0.5 || b.bottom > innerHeight) return 'outside the viewport ' + JSON.stringify([b.left, b.top, b.right, b.bottom]);
  76. if (b.top < h.top - 1 || b.bottom > h.bottom + 1) return 'not inside the header row ' + JSON.stringify([b.top, b.bottom, h.top, h.bottom]);
  77. if (b.left + b.width / 2 < innerWidth / 2) return 'not at the top right ' + b.left;
  78. const top = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2); if (!top || !top.closest('ident-selector')) return 'covered by ' + (top && top.tagName);
  79. return 'ok'; })()`;
  80. let failures = 0, passes = 0;
  81. function check(label, ok, detail = '') {
  82. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  83. if (ok) passes++; else failures++;
  84. }
  85. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  86. const J = JSON.stringify;
  87. // a re-vendored Hybriel compiles each entry at its first start (cold ~20 s on Loreana, hybriel#148; then ~1 s from
  88. // ~/.hybriel/cache/run): every start of a .hl program waits up to COLD_MS (TICKETS_COLD_MS, default 120 s)
  89. const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);
  90. // ---- the legacy fixture (ticket #20): a store from before projects were own data; the server's migrate.hl
  91. // turns it into projects with ids, members and the new states at its first start ----------------------
  92. const hl = (script, env) => { const r = spawnSync(BIN, [script], { cwd: APP, env: { ...process.env, ...env }, encoding: 'utf8', timeout: COLD_MS }); return (r.stdout || '') + (r.stderr || ''); };
  93. const fixture = hl('tests/oldstore.hl', { TICKETS_STORAGE: join(STORE, 'mpackdb') });
  94. check('migrate: the pre-#20 fixture is written (2 projects, 5 tickets, 8 events)', /oldstore: 2 projects, 5 tickets, 8 events/.test(fixture), fixture);
  95. // ---- the servers: our own ident, then tickets (twice: without and with a creator) ----------
  96. let log = '';
  97. let server = null;
  98. let ident = null;
  99. // ticket #9 (mission 012): the exchanges ident RECEIVES from tickets, counted by a small proxy
  100. // between the two (tickets' IDENT_EXCHANGE_URL → here → our ident)
  101. const EXCH_PORT = Number(process.env.TICKETS_GATE_EXCHANGE_PORT || 8357);
  102. const exchanges = [];
  103. const exchProxy = http.createServer((req, res) => {
  104. let body = '';
  105. req.on('data', d => body += d);
  106. req.on('end', async () => {
  107. try {
  108. const r = await fetch(`http://127.0.0.1:${IDENT_PORT}${req.url}`, { method: req.method, headers: { 'content-type': req.headers['content-type'] || 'application/json' }, body: req.method === 'GET' ? undefined : body });
  109. const t = await r.text();
  110. let code = ''; try { code = JSON.parse(body).code || ''; } catch {}
  111. exchanges.push({ path: req.url, code, status: r.status });
  112. res.writeHead(r.status, { 'content-type': r.headers.get('content-type') || 'application/json' });
  113. res.end(t);
  114. } catch (e) { req.socket.destroy(); } // ident stopped: tickets must see NO answer, like a direct connection
  115. });
  116. });
  117. await new Promise((ok, bad) => { exchProxy.once('error', bad); exchProxy.listen(EXCH_PORT, '127.0.0.1', ok); });
  118. let APPKEY = null;
  119. function startTickets(extraEnv) {
  120. log += `\n==== tickets server start ${J(Object.keys(extraEnv))}\n`;
  121. server = spawn(BIN, ['project.hl'], {
  122. cwd: APP,
  123. env: { ...process.env, TICKETS_PORT: String(PORT), TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'),
  124. IDENT_URL: `http://127.0.0.1:${IDENT_PORT}`, IDENT_EXCHANGE_URL: `http://127.0.0.1:${EXCH_PORT}`, TICKETS_PUBLIC_URL: BASE, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret,
  125. TICKETS_CREATOR_IDENTITY: '', TICKETS_WATCH: '0', ...extraEnv },
  126. stdio: ['ignore', 'pipe', 'pipe'],
  127. });
  128. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  129. }
  130. async function stopTickets() {
  131. if (!server) return;
  132. const s = server;
  133. try { s.kill('SIGTERM'); } catch {}
  134. await new Promise(r => { if (s.exitCode !== null || s.signalCode !== null) return r(); s.once('exit', r); setTimeout(r, 3000); });
  135. }
  136. async function ticketsUp() {
  137. for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { const r = await fetch(BASE + '/'); if (r.ok) return; } catch {} await sleep(250); }
  138. throw new Error(`server did not come up within ${COLD_MS} ms\n` + log);
  139. }
  140. // THE API: reads never carry a token (reading is public); writes carry the gate user's
  141. // token unless another (or none: null) is given
  142. let TOKEN = null;
  143. const api = async (method, path, body, token = TOKEN) => {
  144. const headers = body ? { 'content-type': 'application/json' } : {};
  145. if (method !== 'GET' && token) headers.authorization = 'Bearer ' + token;
  146. const r = await fetch(BASE + path, { method, headers, body: body ? J(body) : undefined });
  147. let json = null; try { json = await r.json(); } catch {}
  148. return { status: r.status, json };
  149. };
  150. const runImport = (token = TOKEN) => {
  151. const r = spawnSync(BIN, ['tools/import.hl'], { cwd: APP, env: { ...process.env, TICKETS_URL: BASE, TICKETS_TOKEN: token || '' }, encoding: 'utf8', timeout: COLD_MS });
  152. return (r.stdout || '') + (r.stderr || '');
  153. };
  154. // a face over the REST carrier (POST /__hl/emit) with a cookie (or none)
  155. let emitI = 0;
  156. // hybriel#16 (mission 036): hl:web itself refuses an emit with one argument too many — the ack is
  157. // ok:false "… the `session` parameter is filled by the server, never by the peer"; the face never runs.
  158. const framework_refused = (raw) => { try { const j = JSON.parse(raw); return j.ok === false && /the `session` parameter is filled by the server/.test(j.error || ''); } catch { return false; } };
  159. const temit = async (event, payload, cookie) => {
  160. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });
  161. const raw = await r.text();
  162. let j = null; try { j = JSON.parse(raw); } catch {}
  163. return { status: r.status, value: j ? j.value : undefined, raw };
  164. };
  165. const cookieOf = (r) => (r.headers.get('set-cookie') || '').split(';')[0];
  166. const texts = (page, sel) => page.evaluate(`Array.from(document.querySelectorAll(${J(sel)})).map(e => e.textContent.trim())`);
  167. // MISSION 016: the history as rows. A run of comments is ONE Comments block (components/comments/) in the history: each of its
  168. // comments is a row { kind 'comment', id, author, text (its Markdown, the block's hidden field), drawn (what the browser drew) };
  169. // every other entry a row { kind (the li's class), author, head, text (its event-text) }.
  170. const hist = (page) => page.evaluate(`[...document.querySelectorAll('#events > li')].flatMap(li => li.classList.contains('comments') ? [...li.querySelectorAll('li.comment')].map(c => ({ kind: 'comment', id: c.dataset.id, author: c.querySelector('.comment-author').textContent, text: (c.querySelector('md-editor[data-readonly="true"] input.value') || {}).value ?? '', drawn: (c.querySelector('md-editor[data-readonly="true"] article') || {}).textContent ?? '' })) : [{ kind: li.className, author: (li.querySelector('event-head strong') || {}).textContent ?? '', head: li.querySelector('event-head').textContent.replace(/\\s+/g, ' ').trim(), text: (li.querySelector('event-text:not(.edit)') || {}).textContent ?? '' }])`);
  171. // REAL keys: characters, '\n' = Enter; Shift+Enter (a line break in the MdEditor), Ctrl+Enter (sends the form), End
  172. const realKeys = async (page, text) => {
  173. for (const ch of text) {
  174. if (ch === '\n') {
  175. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  176. await page.send('Input.dispatchKeyEvent', { type: 'char', key: 'Enter', text: '\r' });
  177. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  178. } else {
  179. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  180. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  181. }
  182. }
  183. };
  184. const modKey = async (page, key, modifiers, vk, text) => {
  185. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key, code: key, windowsVirtualKeyCode: vk, modifiers });
  186. if (text) await page.send('Input.dispatchKeyEvent', { type: 'char', key, text, modifiers });
  187. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code: key, windowsVirtualKeyCode: vk, modifiers });
  188. };
  189. const ctrlEnter = (page) => modKey(page, 'Enter', 2, 13);
  190. const shiftEnter = (page) => modKey(page, 'Enter', 8, 13, '\r');
  191. const endKey = (page) => modKey(page, 'End', 0, 35);
  192. // an MdEditor builds its content once the page is live (a CSS animation hands it over): wait until it shows `text`
  193. // a real click lands at the coordinates the element had when they were measured: a push re-draws the comments (the read-only
  194. // MdEditors build their text a moment later and move the buttons below them), and a press at the old spot hits nothing —
  195. // the server never saw the click (mission 019, "B: unliked"). So wait until the element has not moved for half a second.
  196. const calmClick = async (page, sel) => {
  197. await page.waitFor(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return false; const r = e.getBoundingClientRect(), k = r.left + ',' + r.top + ',' + r.width + ',' + r.height, w = window.__calm || (window.__calm = { k: '', n: 0 }); w.n = w.k === k ? w.n + 1 : 0; w.k = k; return w.n >= 8; })()`, { label: 'calm: ' + sel, interval: 60 });
  198. await page.evaluate('delete window.__calm');
  199. await page.click(sel);
  200. };
  201. const mdShows = (page, sel, text, label) => page.waitFor(`(() => { const a = document.querySelector(${J(sel)}); return !!a && a.textContent === ${J(text)}; })()`, { label });
  202. const type = (page, sel, value) => page.evaluate(`(() => { const i = document.querySelector(${J(sel)}); i.value = ${J(value)}; i.dispatchEvent(new Event("input", { bubbles: true })); })()`);
  203. const choose = (page, sel, value) => page.evaluate(`(() => { const i = document.querySelector(${J(sel)}); i.value = ${J(value)}; i.dispatchEvent(new Event("change", { bubbles: true })); })()`);
  204. // CONNECTED = the server has READ the tab's `hello` (its mounts), not just an open socket: a push the server sends
  205. // before that reaches no component (mission 046: "inbox follows the state change live" failed ~1 in 5 when the API
  206. // write overtook the hello). A `ping` sent after the hello on the same socket is answered after it — its pong proves it.
  207. const helloRead = `new Promise((ok) => { const s = window.__hl.socket; const h = (ev) => { let f = null; try { f = JSON.parse(ev.data); } catch {} if (f && f.t === 'pong') { s.removeEventListener('message', h); ok(true); } }; s.addEventListener('message', h); s.send(JSON.stringify({ t: 'ping' })); setTimeout(() => ok(false), 10000); })`;
  208. const connected = async (page, label) => {
  209. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label });
  210. if (!(await page.evaluate(helloRead))) throw new Error('no pong after the hello: ' + label);
  211. };
  212. // a client-side navigation by a REAL click, then the socket announced the new mounts
  213. const clickNav = async (page, sel, cond, label) => { await page.click(sel); await page.waitFor(cond, { label }); await sleep(300); };
  214. async function viewport(page, width, height) {
  215. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  216. await sleep(250);
  217. }
  218. async function shot(page, name) {
  219. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  220. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  221. }
  222. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  223. // INSIDE ident's selector (shadow DOM): an expression over its root `r`, and a REAL click
  224. const sh = (expr) => `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  225. async function shClick(page, inner, name = null) {
  226. const find = `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; const el = ${name === null ? `r.querySelector(${J(inner)})` : `[...r.querySelectorAll(${J(inner)})].find(b => b.textContent === ${J(name)})`}; if (!el) return null; el.scrollIntoView({ block: 'center' }); const b = el.getBoundingClientRect(); if (!b.width) return null; return { x: b.left + b.width / 2, y: b.top + b.height / 2 }; })()`;
  227. const box = await page.waitFor(find, { label: 'selector ' + inner + ' ' + (name || '') });
  228. const at = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  229. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...at, buttons: 0 });
  230. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...at, buttons: 1 });
  231. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, buttons: 0 });
  232. }
  233. const connectedIdent = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'ident page hydrated' });
  234. // sign in to OUR ident on ident's own page (email → code from the sink → skip the names)
  235. async function identSignIn(page, email) {
  236. await page.goto(ident.base + '/');
  237. await page.waitForSelector('#email');
  238. await connectedIdent(page);
  239. await page.type('#email', email);
  240. await page.click('#sendcode');
  241. // ident#20: a sent code NAVIGATES to ident's /code page; type only once that page is hydrated
  242. await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });
  243. await connectedIdent(page);
  244. await page.type('#code', ident.lastCode(email));
  245. await page.click('#verify');
  246. await page.waitForSelector('#signout, #menusignout', { timeout: 10000 });
  247. }
  248. // TICKET #11 (mission 014): the gate must stay green while other browsers load the machine.
  249. // Every wait of a page (waitFor / waitForSelector / click / goto) gets SLOW× its timeout
  250. // (TICKETS_GATE_SLOW, default 3: 10 s → 30 s) — a wait that succeeds returns at once, so a green
  251. // run costs nothing; only a real failure waits longer before it says so.
  252. const SLOW = Number(process.env.TICKETS_GATE_SLOW || 3);
  253. function patient(page) {
  254. const waitFor = page.waitFor.bind(page);
  255. page.waitFor = (expr, o = {}) => waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });
  256. const goto = page.goto.bind(page);
  257. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });
  258. return page;
  259. }
  260. let A, B, C;
  261. const range = (v, dflt) => (v || dflt).split('-').map(Number);
  262. try {
  263. // ---- ticket #7: our own ident, tickets registered in it ----------------------------------
  264. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  265. const alice = await ident.signIn('[email protected]');
  266. const bob = await ident.signIn('[email protected]');
  267. const gateAcct = await ident.signIn('[email protected]');
  268. APPKEY = await ident.registerApp(alice, 'tickets (gate)', [BASE]);
  269. check('ident: our own ident runs (a copy without .env), tickets is registered (key + secret)', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && /^sk_[0-9a-f]{48}$/.test(APPKEY.secret) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  270. // alice's per-app id — what the architect puts into TICKETS_CREATOR_IDENTITY
  271. const ALICE_ID = await ident.exchange(APPKEY, await ident.selectorCode(alice, APPKEY, BASE));
  272. const GATE_ID = await ident.exchange(APPKEY, await ident.selectorCode(gateAcct, APPKEY, BASE));
  273. check('ident: one identity id per identity (a short id, or the old 32 hex)', /^[0-9a-z]{5,64}$/.test(ALICE_ID) && /^[0-9a-z]{5,64}$/.test(GATE_ID) && ALICE_ID !== GATE_ID, ALICE_ID + ' ' + GATE_ID);
  274. // ---- server #1: NO creator configured ---------------------------------------------------
  275. startTickets({});
  276. await ticketsUp();
  277. // the machine user "gate": the login button's SERVER half (ident → /login/callback?ident_code=)
  278. const first = await fetch(BASE + '/');
  279. let GATE_COOKIE = cookieOf(first);
  280. check('login: a page visit gets the tickets session cookie (hlsid)', /^hlsid=[0-9a-f]+$/.test(GATE_COOKIE), GATE_COOKIE);
  281. const noCode = await fetch(BASE + '/login/callback', { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  282. check('login: /login/callback without a code → 400 page, no redirect', noCode.status === 400 && !noCode.headers.get('location') && /no login code/.test(await noCode.text()));
  283. const badCode = await fetch(BASE + '/login/callback?ident_code=' + 'ab'.repeat(24), { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  284. check('login: an unknown code → 400 "ident refused the login", no redirect', badCode.status === 400 && !badCode.headers.get('location') && /ident refused the login \(400/.test(await badCode.text()));
  285. const gateCode = await ident.selectorCode(gateAcct, APPKEY, BASE);
  286. const cb = await fetch(BASE + '/login/callback?ident_code=' + gateCode, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  287. check('login: /login/callback exchanges the code → 302 to /', cb.status === 302 && cb.headers.get('location') === '/', cb.status + ' ' + cb.headers.get('location'));
  288. // mission ST: a login gets a NEW session id (fixation): the cookie the browser brought is logged out, the answer sets the new one
  289. const rotated = cookieOf(cb);
  290. check('login (ST): the login sets a NEW session cookie; the one the browser brought is no longer signed in', /^hlsid=[0-9a-f]+$/.test(rotated) && rotated !== GATE_COOKIE && !(await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } }).then(r => r.text())).includes('class="in"'), rotated + ' vs ' + GATE_COOKIE);
  291. GATE_COOKIE = rotated;
  292. const again = await fetch(BASE + '/login/callback?ident_code=' + gateCode, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  293. check('login: the same code again → 400 (single use)', again.status === 400 && /already used/.test(await again.text()));
  294. // ticket #10: the button's return URL carries ?next=<page> (login.js); /login/callback follows
  295. // only a same-origin PATH, anything else → /
  296. for (const [next, want] of [
  297. ['/projects/alpha/2', '/projects/alpha/2'], ['/project/alpha/state/open?x=1&y=2', '/project/alpha/state/open?x=1&y=2'], ['/inbox', '/inbox'],
  298. ['/%2F%2Fevil.example', '/%2F%2Fevil.example'],
  299. ['//evil.example/x', '/'], ['https://evil.example/', '/'], ['http:/evil.example', '/'], ['/\\evil.example', '/'], ['javascript:alert(1)', '/'],
  300. ['evil.example', '/'], ['/a b', '/'], ['/x\r\nSet-Cookie: a=b', '/'], ['/x"><script>', '/'], ['/login/callback', '/'], ['/' + 'a'.repeat(500), '/'], ['', '/'],
  301. ]) {
  302. const c = await ident.selectorCode(gateAcct, APPKEY, BASE);
  303. const r = await fetch(BASE + '/login/callback?next=' + encodeURIComponent(next) + '&ident_code=' + c, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  304. check(`return (#10): next=${J(next.length > 40 ? next.slice(0, 20) + '…(' + next.length + ')' : next)} → 302 ${want}`, r.status === 302 && r.headers.get('location') === want, r.status + ' ' + r.headers.get('location'));
  305. if (r.status === 302) GATE_COOKIE = cookieOf(r);
  306. }
  307. let html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();
  308. check('login: first login → the page asks for a display name, no write form yet', html.includes('id="nameform"') && !html.includes('id="newticketform"') && html.includes('class="in"'));
  309. check('login: the page never carries the identity id (only /you does)', !html.includes(GATE_ID));
  310. let f = await temit('commentOn', ['x', 'before the name'], GATE_COOKIE);
  311. check('login: no writing before a display name', f.value && /display name first/.test(f.value.error), f.raw);
  312. f = await temit('saveDisplayName', [' '], GATE_COOKIE);
  313. check('name: an empty display name is refused', f.value && /must not be empty/.test(f.value.error), f.raw);
  314. f = await temit('saveDisplayName', ['x'.repeat(61)], GATE_COOKIE);
  315. check('name: 61 characters are refused', f.value && /too long/.test(f.value.error), f.raw);
  316. f = await temit('saveDisplayName', ['gate'], GATE_COOKIE);
  317. check('name: "gate" saved (answer: name, named — no identity id)', f.value && f.value.name === 'gate' && f.value.named === true && !f.raw.includes(GATE_ID), f.raw);
  318. f = await temit('saveDisplayName', ['gate2'], GATE_COOKIE);
  319. check('name: asked once — a second name is refused', f.value && /already set/.test(f.value.error), f.raw);
  320. html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();
  321. check('name: afterwards no prompt; no role yet → no ticket form, a role hint (ticket #20)', !html.includes('id="nameform"') && !html.includes('id="newticketform"') && html.includes('id="rolehint"'));
  322. f = await temit('tokenCreate', ['gate machine'], GATE_COOKIE);
  323. TOKEN = f.value && f.value.token;
  324. check('token: created over the face — tkt_ + 48 hex, listed with its label', /^tkt_[0-9a-f]{48}$/.test(TOKEN || '') && f.value.tokens.length === 1 && f.value.tokens[0].label === 'gate machine' && !J(f.value.tokens).includes(TOKEN), f.raw);
  325. const you0 = await (await fetch(BASE + '/you', { headers: { cookie: GATE_COOKIE } })).text();
  326. check('/you shows the user its own ident id and "not a member of any project yet"', you0.includes(GATE_ID) && /not a member of any project yet/.test(you0) && !you0.includes(TOKEN));
  327. // ticket #20: the legacy projects have NO admin yet (no creator configured) and the gate user is no member: every write is refused
  328. const nm1 = await api('POST', '/api/tickets/1/comments', { text: 'not a member' });
  329. const nm2 = await api('POST', '/api/projects/alpha/tickets/1/state', { state: 'review' });
  330. const nm3 = await api('POST', '/api/projects/alpha/tickets', { subject: 'not a member' });
  331. check('roles: a non-member cannot comment / change the state / open a ticket → 403, nothing written', nm1.status === 403 && nm2.status === 403 && nm3.status === 403 && (await api('GET', '/api/tickets/1')).json.events.length === 3, J([nm1, nm2, nm3]) + J([(await api('GET', '/api/projects/alpha')).status, (await api('GET', '/api/tickets/1')).status]) + log.slice(-900) + log.slice(-600));
  332. check('migration: at the first start the log says what was migrated', /migrated: 2 project\(s\) turned into records/.test(log) && /migrated: 5 ticket\(s\) linked to their project by id/.test(log), log.slice(0, 400));
  333. await stopTickets();
  334. // ---- server #2: the gate user is the creator → admin of the legacy projects (its session + token survive) --
  335. startTickets({ TICKETS_CREATOR_IDENTITY: GATE_ID });
  336. await ticketsUp();
  337. html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();
  338. check('restart: the gate user is still logged in (session on disk)', /id="whoami"[^>]*>gate</.test(html), html.slice(0, 200));
  339. // ---- the migrated legacy tickets: old numbers still answer (ticket #38) ---------------
  340. const PT = (slug, n) => `/api/projects/${slug}/tickets/${n}`;
  341. const old1 = await api('GET', '/api/tickets/1');
  342. check('legacy: GET /api/tickets/1 (old number) answers alpha #1 with project, number, href, oldNumber',
  343. old1.status === 200 && old1.json.ticket.project === 'alpha' && old1.json.ticket.number === 1 && old1.json.ticket.ref === '#1' && old1.json.ticket.oldNumber === 1
  344. && old1.json.ticket.href === '/alpha/1' && old1.json.ticket.apiHref === PT('alpha', 1) && /^[0-9a-z]{8,}$/.test(old1.json.ticket.id), J(old1.json).slice(0, 500));
  345. check('legacy: history kept in order with authors, texts and times (same ms → old order)',
  346. J(old1.json.events.map(e => [e.seq, e.kind, e.author, e.text, e.to, e.createdMs])) === J([[1, 'created', 'creator', '', '', 1790000000000], [2, 'comment', 'worker', 'legacy comment on one', '', 1790000300000], [3, 'state', 'worker', 'started', 'progress', 1790000300000]]), J(old1.json.events));
  347. check('legacy: state, subject, times and event count kept', old1.json.ticket.state === 'progress' && old1.json.ticket.subject === 'Legacy alpha one' && old1.json.ticket.createdMs === 1790000000000 && old1.json.ticket.updatedMs === 1790000300000 && old1.json.ticket.events === 3, J(old1.json.ticket));
  348. const a2 = await api('GET', PT('alpha', 2));
  349. check('legacy: GET /api/projects/alpha/tickets/2 is old #3 (per-project form)', a2.status === 200 && a2.json.ticket.oldNumber === 3 && a2.json.ticket.subject === 'Question: legacy alpha two' && J(a2.json.events.map(e => e.kind)) === J(['created', 'comment']), J(a2.json).slice(0, 300));
  350. check('legacy: old #4 is alpha #3, old #5 is beta.example.org #2', (await api('GET', '/api/tickets/4')).json.ticket.href === '/alpha/3' && (await api('GET', '/api/tickets/5')).json.ticket.href === '/beta.example.org/2');
  351. const byUuid = await api('GET', '/api/tickets/' + old1.json.ticket.id);
  352. check('legacy: /api/tickets/<uuid> answers the same ticket', byUuid.status === 200 && byUuid.json.ticket.href === '/alpha/1');
  353. check('legacy: unknown old number / number / project → 404', (await api('GET', '/api/tickets/6')).status === 404 && (await api('GET', PT('alpha', 4))).status === 404 && (await api('GET', PT('nope', 1))).status === 404 && (await api('GET', '/api/projects/nope/tickets')).status === 404);
  354. const oldCmt = await api('POST', '/api/tickets/4/comments', { text: 'via the old number' });
  355. check('legacy: POST /api/tickets/4/comments (old number, gate token) → 201, lands on alpha #3, author = the token\'s user', oldCmt.status === 201 && oldCmt.json.event.author === 'gate' && oldCmt.json.ticket.href === '/alpha/3' && oldCmt.json.ticket.oldNumber === 4 && oldCmt.json.event.seq === 2 && oldCmt.json.event.number === 3 && oldCmt.json.event.project === 'alpha', J(oldCmt.json));
  356. const newCmt = await api('POST', PT('alpha', 3) + '/comments', { text: 'via the project number' });
  357. check('legacy: POST /api/projects/alpha/tickets/3/comments → 201 on the same ticket', newCmt.status === 201 && newCmt.json.ticket.id === oldCmt.json.ticket.id && newCmt.json.ticket.events === 3);
  358. const newSt = await api('POST', PT('beta.example.org', 2) + '/state', { state: 'on-hold', text: 'parked' });
  359. check('legacy: POST /api/projects/beta.example.org/tickets/2/state → 201', newSt.status === 201 && newSt.json.ticket.state === 'pending' && (await api('GET', '/api/tickets/5')).json.ticket.state === 'pending', J(newSt.json));
  360. const a4 = await api('POST', '/api/projects/alpha/tickets', { subject: 'New alpha after the migration' });
  361. check('numbers: POST /api/projects/alpha/tickets → alpha #4, no old number', a4.status === 201 && a4.json.ticket.number === 4 && a4.json.ticket.href === '/alpha/4' && !('oldNumber' in a4.json.ticket) && a4.json.ticket.hasOld === false, J(a4.json));
  362. for (const t of ['gamma', 'antcolony', 'tickets.worldapi.org', 'ident.worldapi.org', 'gitoria.worldapi.org']) await api('POST', '/api/projects', { title: t, slug: t });
  363. const g1 = await api('POST', '/api/tickets', { project: 'gamma', subject: 'first of a new project' });
  364. check('numbers: a new project starts at 1 (POST /api/tickets)', g1.status === 201 && g1.json.ticket.project === 'gamma' && g1.json.ticket.number === 1 && g1.json.ticket.href === '/gamma/1', J(g1.json));
  365. const g2 = await api('POST', '/api/tickets', { project: 'gamma', subject: 'second of gamma' });
  366. check('numbers: … and counts on (gamma #2)', g2.json.ticket.number === 2 && (await api('GET', PT('gamma', 2))).json.ticket.subject === 'second of gamma');
  367. check('numbers: the per-project POST refuses a project field (strict)', (await api('POST', '/api/projects/alpha/tickets', { subject: 's', project: 'alpha' })).json.field === 'project');
  368. const redir = await fetch(BASE + '/tickets/3', { redirect: 'manual' });
  369. check('legacy: GET /tickets/3 (old page URL) → 301 Location /alpha/2', redir.status === 301 && redir.headers.get('location') === '/alpha/2', redir.status + ' ' + redir.headers.get('location'));
  370. check('legacy: GET /tickets/99 → 404', (await fetch(BASE + '/tickets/99', { redirect: 'manual' })).status === 404);
  371. const LEGACY = (await api('GET', '/api/tickets')).json.tickets.length; // 5 migrated + alpha #4 + gamma #1, #2
  372. // ---- import: the five AntColony ticket files, twice ----------------------------------
  373. const imp0 = runImport(null);
  374. check('import: without TICKETS_TOKEN every file is refused (401), nothing written', /import: 0 new, 0 already there, 5 failed/.test(imp0) && /FAIL .*: 401/.test(imp0) && (await api('GET', '/api/tickets')).json.tickets.length === LEGACY, imp0);
  375. const imp1 = runImport();
  376. check('import: first run creates all five', /import: 5 new, 0 already there, 0 failed/.test(imp1), imp1);
  377. check('import: numbered per project (antcolony #1, #2)', /NEW 0004-scheduler\.md → antcolony #1/.test(imp1) && /NEW 0005-agent\.md → antcolony #2/.test(imp1) && /NEW 0001-tickets-app\.md → tickets\.worldapi\.org #1/.test(imp1), imp1);
  378. const imp2 = runImport();
  379. check('import: second run is idempotent (0 new, 5 already there)', /import: 0 new, 5 already there, 0 failed/.test(imp2), imp2);
  380. let list = await api('GET', '/api/tickets');
  381. const TOTAL = LEGACY + 5;
  382. check('api: GET /api/tickets lists five more after two imports', list.status === 200 && list.json.tickets.length === TOTAL && list.json.tickets.filter(t => t.source).length === 5, J(list).slice(0, 300));
  383. let one = await api('GET', PT('tickets.worldapi.org', 1));
  384. check('api: tickets.worldapi.org #1 is the first file (project, subject, summary, a created event)',
  385. one.status === 200 && one.json.ticket.project === 'tickets.worldapi.org' && one.json.ticket.subject === 'Build the World Ticket System in Hybriel'
  386. && one.json.ticket.summary.startsWith('Everyone can write everyone a ticket. This is the only state store of AntColony, so it comes first. Minimal scope:')
  387. && one.json.events.length === 1 && one.json.events[0].kind === 'created' && one.json.events[0].text === 'imported from 0001-tickets-app.md' && one.json.events[0].author === 'gate', J(one.json).slice(0, 400));
  388. check('api: antcolony #1 is the scheduler file', (await api('GET', PT('antcolony', 1))).json.ticket.source === '0004-scheduler.md');
  389. check('api: unknown ticket is a 404', (await api('GET', '/api/tickets/99')).status === 404 && (await api('GET', PT('antcolony', 99))).status === 404);
  390. check('api: a ticket without subject is refused (400)', (await api('POST', '/api/tickets', { project: 'x' })).status === 400);
  391. check('api: an unknown state is refused (400)', (await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'nope' })).status === 400);
  392. check('api: an empty comment is refused (400)', (await api('POST', PT('ident.worldapi.org', 1) + '/comments', { text: ' ' })).status === 400);
  393. check('api: filter by project', (await api('GET', '/api/tickets?project=antcolony')).json.tickets.length === 2 && (await api('GET', '/api/projects/antcolony/tickets')).json.tickets.length === 2);
  394. check('api: filter by project + state on the per-project list', (await api('GET', '/api/projects/alpha/tickets?state=in-progress')).json.tickets.map(t => t.number).join() === '1');
  395. const projects = await api('GET', '/api/projects');
  396. const imported = (await api('GET', '/api/tickets')).json.tickets.filter(t => t.source);
  397. check('import: hard-wrapped lines are joined (no line break left in the five)', imported.length === 5 && imported.every(t => !t.summary.includes('\n')));
  398. check('api: projects (creation order) and states', J(projects.json.projects) === J(['alpha', 'beta.example.org', 'gamma', 'antcolony', 'tickets.worldapi.org', 'ident.worldapi.org', 'gitoria.worldapi.org']) && projects.json.states.length === 7, J(projects.json));
  399. // ---- the API is strict (ticket #10): every refused body writes NOTHING ----------------
  400. const rawPost = async (path, raw, auth = 'Bearer ' + TOKEN) => {
  401. const r = await fetch(BASE + path, { method: 'POST', headers: { 'content-type': 'application/json', ...(auth ? { authorization: auth } : {}) }, body: raw });
  402. let json = null; try { json = await r.clone().json(); } catch {}
  403. return { status: r.status, json, text: json ? '' : await r.text() };
  404. };
  405. const strictCases = [
  406. // [path, raw body, expected status, expected `field` (null = none), error must include]
  407. ['/api/tickets', J({ project: 'x', subject: 's', bogus: '1' }), 400, 'bogus', "unknown field 'bogus'"],
  408. ['/api/tickets', J({ project: 'x', subject: 's', Subject: 't' }), 400, 'Subject', "unknown field 'Subject'"],
  409. ['/api/tickets', J({ project: 'x' }), 400, 'subject', "field 'subject' is required"],
  410. ['/api/tickets', J({ subject: 's' }), 400, 'project', "field 'project' is required"],
  411. ['/api/tickets', J({ project: 'x', subject: ' ' }), 400, 'subject', "field 'subject' must not be empty"],
  412. ['/api/tickets', J({ project: '', subject: 's' }), 400, 'project', "field 'project' must not be empty"],
  413. ['/api/tickets', J({ project: 'x', subject: 5 }), 400, 'subject', "field 'subject' must be a string"],
  414. ['/api/tickets', J({ project: 'x', subject: 's', summary: null }), 400, 'summary', "field 'summary' must be a string"],
  415. ['/api/tickets', J({ project: 'a b', subject: 's' }), 400, 'project', 'no such project'],
  416. // ticket #7: NO free author any more — the author is the token's user; a body naming one is refused
  417. ['/api/tickets', J({ project: 'x', subject: 's', author: ['a'] }), 400, 'author', "no field 'author' any more"],
  418. ['/api/tickets', J({ project: 'x', subject: 's', author: 'gate' }), 400, 'author', "no field 'author' any more: the author is the user of your API token"],
  419. ['/api/tickets', J({ project: 'x', subject: 's', summary: 'y', author: ' ' }), 400, 'author', "no field 'author' any more"],
  420. ['/api/tickets/2/comments', J({ text: 'x', author: 'creator' }), 400, 'author', "no field 'author' any more"],
  421. ['/api/tickets/2/comments', J({ text: 'x', author: '' }), 400, 'author', "no field 'author' any more"],
  422. ['/api/tickets/2/state', J({ state: 'in progress', author: 'creator' }), 400, 'author', "no field 'author' any more"],
  423. ['/api/tickets/2/state', J({ state: 'confirmed', text: 'n', author: ' ' }), 400, 'author', "no field 'author' any more"],
  424. ['/api/tickets', J([1, 2]), 400, '', 'must be a JSON object'],
  425. ['/api/tickets', J('text'), 400, '', 'must be a JSON object'],
  426. ['/api/tickets', '', 400, '', 'must be a JSON object'],
  427. ['/api/tickets/2/comments', J({ text: 'hi', state: 'open' }), 400, 'state', "unknown field 'state'"],
  428. ['/api/tickets/2/comments', J({}), 400, 'text', "field 'text' is required"],
  429. ['/api/tickets/2/comments', J({ text: ' ' }), 400, 'text', "field 'text' must not be empty"],
  430. ['/api/tickets/2/comments', J({ text: { a: 1 } }), 400, 'text', "field 'text' must be a string"],
  431. ['/api/tickets/2/comments', J({ text: true }), 400, 'text', "field 'text' must be a string"],
  432. ['/api/tickets/2/comments', J({ text: 'x', author: 7 }), 400, 'author', "no field 'author' any more"],
  433. ['/api/tickets/2/state', J({ state: 'open', note: 'x' }), 400, 'note', "unknown field 'note'"],
  434. ['/api/tickets/2/state', J({ text: 'x' }), 400, 'state', "field 'state' is required"],
  435. ['/api/tickets/2/state', J({ state: '' }), 400, 'state', "field 'state' must not be empty"],
  436. ['/api/tickets/2/state', J({ state: 3 }), 400, 'state', "field 'state' must be a string"],
  437. ['/api/tickets/2/state', J({ state: 'nope' }), 400, 'state', 'unknown state'],
  438. ['/api/tickets/2/state', J({ state: 'open' }), 400, 'state', 'already open'],
  439. ['/api/tickets/99/comments', J({ text: 'x' }), 404, null, 'no such ticket'],
  440. // ticket #38: the slug is the project name, so a new name must be URL-safe; the per-project form is as strict
  441. ['/api/tickets', J({ project: 'a#b', subject: 's' }), 400, 'project', 'no such project'],
  442. ['/api/tickets', J({ project: 'ä', subject: 's' }), 400, 'project', 'no such project'],
  443. ['/api/projects/beta.example.org/tickets/1/comments', J({ text: 'x', author: 'a' }), 400, 'author', "no field 'author' any more"],
  444. ['/api/projects/beta.example.org/tickets/1/comments', J({ text: 'x', bogus: '1' }), 400, 'bogus', "unknown field 'bogus'"],
  445. ['/api/projects/beta.example.org/tickets/1/state', J({ state: 'open' }), 400, 'state', 'already open'],
  446. ['/api/projects/beta.example.org/tickets/1/state', J({ state: 5 }), 400, 'state', "field 'state' must be a string"],
  447. ['/api/projects/beta.example.org/tickets', J({ subject: 's', author: 'a' }), 400, 'author', "no field 'author' any more"],
  448. ['/api/projects/beta.example.org/tickets/9/comments', J({ text: 'x' }), 404, null, 'no such ticket'],
  449. ['/api/projects/beta.example.org/tickets/x/comments', J({ text: 'x' }), 404, null, 'no such ticket'],
  450. ];
  451. for (const [path, raw, want, field, says] of strictCases) {
  452. const r = await rawPost(path, raw);
  453. const ok = r.status === want && r.json && typeof r.json.error === 'string' && r.json.error.includes(says) && (field === null || r.json.field === field);
  454. check(`strict: POST ${path} ${raw || '(empty)'} → ${want}${field ? ' naming ' + field : ''}`, ok, r.status + ' ' + J(r.json) + r.text);
  455. }
  456. // invalid JSON (ticket #15): refused by jsoncheck.hl BEFORE JSON.parse → 400 { error },
  457. // no source path (workaround for hybriel #12: an uncaught JSON.parse answered 500 + api.hl:31:9)
  458. const badJsonCases = [
  459. ['/api/tickets', '{"project":"x",', 15], ['/api/tickets', '{bad', 1], ['/api/tickets', "{'project':'x'}", 1],
  460. ['/api/tickets', '{"project":"x","subject":"s","summary":"a",}', 43], ['/api/tickets', '[1 2]', 3],
  461. ['/api/tickets/2/comments', '{"text":"x","n":"a"} trailing', 21], ['/api/tickets/2/comments', '{"text":"\\x","n":"a"}', 10],
  462. ['/api/tickets/2/state', '{"state":01}', 10], ['/api/tickets/2/state', '['.repeat(70), 64], ['/api/tickets/2/state', ' ', 3],
  463. // LONE \u surrogate escapes: hl's JSON.parse still refuses them (would be a 500) → refused by the check
  464. // (a valid pair parses since hybriel#15, mission 036: see the two checks below)
  465. ['/api/tickets/2/comments', '{"text":"\\ud800"}', 10], ['/api/tickets/2/comments', '{"text":"\\udc00"}', 10],
  466. ['/api/tickets/2/comments', '{"text":"\\ud83dx"}', 10], ['/api/tickets/2/comments', '{"text":"\\ud83d\\u0041"}', 10],
  467. ];
  468. for (const [path, raw, at] of badJsonCases) {
  469. const r = await rawPost(path, raw);
  470. const ok = r.status === 400 && r.json && J(Object.keys(r.json)) === J(['error']) && r.json.error === 'invalid JSON at character ' + at && !/\.hl|\//.test(r.json.error);
  471. check(`strict: invalid JSON POST ${path} ${raw.length > 40 ? raw.slice(0, 40) + '…' : raw} → 400 at ${at}, no source path`, ok, r.status + ' ' + J(r.json) + r.text);
  472. }
  473. // valid but unusual JSON is NOT mistaken for invalid (escapes, unicode, numbers, nesting) → normal field errors
  474. const oddValid = await rawPost('/api/tickets/2/comments', '{ "text" : "q\\"b\\\\s\\/\\u00e9\\n", "n": [-1.5e+3, 0, true, null, {"x":[]}] }');
  475. check('strict: valid unusual JSON passes the check (→ unknown field n, not invalid JSON)', oddValid.status === 400 && oddValid.json && oddValid.json.field === 'n', oddValid.status + ' ' + J(oddValid.json) + oddValid.text);
  476. const pairOnly = await rawPost('/api/tickets/2/comments', '{"text":"\\ud83d\\ude00","n":"a"}');
  477. check('strict: a valid \\u surrogate pair passes the check (hybriel#15 → unknown field n, not invalid JSON)', pairOnly.status === 400 && pairOnly.json && pairOnly.json.field === 'n', pairOnly.status + ' ' + J(pairOnly.json) + pairOnly.text);
  478. const escaped = await rawPost('/api/tickets/3/comments', '{"text":"q\\"b\\\\s\\/\\u00e9 \u{1F600} end \\ud83d\\ude00"}');
  479. check('strict: a comment with JSON escapes (\\" \\\\ \\/ \\u00e9 \\ud83d\\ude00) and a raw emoji is stored decoded (201)', escaped.status === 201 && escaped.json.event.text === 'q"b\\s/\u00e9 \u{1F600} end \u{1F600}', escaped.status + ' ' + J(escaped.json) + escaped.text);
  480. const afterStrict = await api('GET', '/api/tickets');
  481. check('strict: the refused requests wrote nothing (same ticket count, old #2 = beta.example.org #1 has one event)', afterStrict.json.tickets.length === TOTAL && (await api('GET', '/api/tickets/2')).json.events.length === 1 && (await api('GET', PT('beta.example.org', 1))).json.events.length === 1, J(afterStrict.json.tickets.map(t => t.ref)));
  482. check('strict: GET /api/inbox refuses POST (405)', (await rawPost('/api/inbox', '{}')).status === 405);
  483. // ---- ticket #7: API writes need a valid token — 401 BEFORE the body is looked at ----------
  484. const before401 = J((await api('GET', '/api/tickets')).json.tickets.map(t => [t.ref, t.events]));
  485. const authCases = [
  486. // [path, raw body, Authorization header (null = none), label]
  487. ['/api/tickets', J({ project: 'x', subject: 's' }), null, 'no token'],
  488. ['/api/projects/alpha/tickets', J({ subject: 's' }), null, 'no token'],
  489. ['/api/tickets/2/comments', J({ text: 'x' }), null, 'no token'],
  490. ['/api/projects/alpha/tickets/1/comments', J({ text: 'x' }), null, 'no token'],
  491. ['/api/tickets/2/state', J({ state: 'in progress' }), null, 'no token'],
  492. ['/api/projects/alpha/tickets/1/state', J({ state: 'on hold' }), null, 'no token'],
  493. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer tkt_' + '0'.repeat(48), 'an unknown token'],
  494. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ' + TOKEN + '0', 'a token with one character more'],
  495. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ' + TOKEN.slice(0, -1), 'a token with one character less'],
  496. ['/api/tickets/2/comments', J({ text: 'x' }), TOKEN, 'the token without "Bearer"'],
  497. ['/api/tickets/2/comments', J({ text: 'x' }), 'Basic ' + TOKEN, 'Basic instead of Bearer'],
  498. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ', 'an empty Bearer'],
  499. ['/api/tickets/2/comments', '{bad', null, 'no token + invalid JSON (auth first)'],
  500. ['/api/tickets/2/comments', J({ text: 'x', author: 'creator' }), null, 'no token + an author field (auth first)'],
  501. ];
  502. for (const [path, raw, auth, label] of authCases) {
  503. const r = await rawPost(path, raw, auth);
  504. check(`auth: POST ${path} with ${label} → 401`, r.status === 401 && r.json && /Authorization: Bearer/.test(r.json.error), r.status + ' ' + J(r.json) + r.text);
  505. }
  506. check('auth: the refused writes wrote nothing', J((await api('GET', '/api/tickets')).json.tickets.map(t => [t.ref, t.events])) === before401);
  507. const anonRead = await fetch(BASE + '/api/tickets/1');
  508. check('auth: reading needs no token (GET without Authorization → 200)', anonRead.status === 200);
  509. // ---- local time (ticket #10): Europe/Vienna, storage stays epoch ms -----------------------
  510. const vienna = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Europe/Vienna', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
  511. const lt = spawnSync(BIN, ['tests/localtime.hl'], { cwd: APP, encoding: 'utf8', timeout: COLD_MS });
  512. const ltLines = (lt.stdout || '').trim().split('\n').filter(Boolean);
  513. const ltBad = ltLines.filter(l => { const [ms, ...rest] = l.split(' '); return vienna.format(new Date(Number(ms))) !== rest.join(' '); });
  514. check('time: localtime.hl matches Intl Europe/Vienna on DST edges 2000–2100', ltLines.length === 11 && ltBad.length === 0, J(ltBad) + (lt.stderr || ''));
  515. const t2 = (await api('GET', PT('ident.worldapi.org', 1))).json;
  516. check('time: API rows render updatedMs / createdMs in Vienna time', t2.ticket.updated === vienna.format(new Date(t2.ticket.updatedMs)) && t2.events[0].when === vienna.format(new Date(t2.events[0].createdMs)), J([t2.ticket.updated, t2.ticket.updatedMs, t2.events[0].when]));
  517. // ---- two viewers ------------------------------------------------------------------
  518. A = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_A, '8620-8629') });
  519. B = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_B, '8630-8639') });
  520. const a = patient(await A.newPage());
  521. const b = patient(await B.newPage());
  522. // SSR of the list
  523. await a.goto(BASE + '/');
  524. await a.waitForSelector('#tickets li');
  525. await connected(a, 'A connected');
  526. check('list: SSR shows every ticket (migrated + new + imported)', (await texts(a, '#tickets li')).length === TOTAL, J(await texts(a, '#tickets li')));
  527. check('list: every row has a state badge, a #ref link and its project', await a.evaluate(`Array.from(document.querySelectorAll('#tickets li')).every(li => li.querySelector('ticket-state') && /^#\\d+/.test(li.querySelector('a.subject').textContent) && li.querySelector('ticket-meta a'))`));
  528. check('list: every ticket link is /<project>/<number> of its row (ticket #25)', await a.evaluate(`Array.from(document.querySelectorAll('#tickets li')).every(li => li.querySelector('a.subject').getAttribute('href') === '/' + li.querySelector('ticket-meta a').textContent + '/' + li.querySelector('ticket-ref').textContent.slice(1))`));
  529. check('list: the project filter offers all seven projects', (await texts(a, '#projectfilter a')).length === 8, J(await texts(a, '#projectfilter a')));
  530. check('list: palette — accent is purple #c586c0, danger #f44747; the brand is the theme\'s white title (mission 022: it was the accent)', await a.evaluate(`(() => { const cs = getComputedStyle(document.documentElement); return cs.getPropertyValue('--color-accent').trim() === '#c586c0' && getComputedStyle(document.querySelector('.brand')).color === 'rgb(245, 250, 255)' && getComputedStyle(document.body).backgroundColor === 'rgb(25, 30, 35)'; })()`), await a.evaluate(`getComputedStyle(document.querySelector('.brand')).color + ' ' + getComputedStyle(document.body).backgroundColor`));
  531. check('list: danger token resolves to #f44747', await a.evaluate(`(() => { const s = document.createElement('span'); s.style.color = 'var(--color-danger)'; document.body.append(s); const c = getComputedStyle(s).color; s.remove(); return c; })()`) === 'rgb(244, 71, 71)');
  532. // filters by real clicks (client-side navigation)
  533. await clickNav(a, '#projectfilter a[href="/project/antcolony"]', 'location.pathname === "/project/antcolony" && document.querySelectorAll("#tickets li").length === 2', 'project filter');
  534. check('filter: project antcolony shows its two tickets', J(await texts(a, '#tickets ticket-meta a')) === J(['antcolony', 'antcolony']), J(await texts(a, '#tickets ticket-meta a')));
  535. check('filter: the chosen project is marked selected', (await a.text('#projectfilter a.selected')) === 'antcolony');
  536. await clickNav(a, '#statefilter a[href="/project/antcolony/state/progress"]', 'location.pathname === "/project/antcolony/state/progress" && !!document.querySelector("#empty")', 'state filter');
  537. check('filter: project + state "progress" is empty (nothing in progress yet)', (await texts(a, '#tickets li')).length === 0);
  538. await clickNav(a, '#statefilter a[href="/project/antcolony"]', 'document.querySelectorAll("#tickets li").length === 2', 'state filter cleared');
  539. check('filter: clearing the state keeps the project', (await a.evaluate('location.pathname')) === '/project/antcolony');
  540. await a.goto(BASE + '/state/open');
  541. await a.waitForSelector('#tickets li');
  542. const OPEN = (await api('GET', '/api/tickets?state=open')).json.tickets.length;
  543. check('filter: /state/open by URL (SSR) shows every open ticket', (await texts(a, '#tickets li')).length === OPEN, OPEN);
  544. // ---- a migrated ticket in the browser: the old URL redirects, a real click opens the new one
  545. await a.goto(BASE + '/tickets/4');
  546. await a.waitForSelector('#subject');
  547. check('legacy: the old URL /tickets/4 lands on /alpha/3 (redirect in the browser)', (await a.evaluate('location.pathname')) === '/alpha/3' && (await a.text('#subject')) === 'Legacy alpha three' && (await a.text('#ref')) === '#3', await a.evaluate('location.href'));
  548. check('legacy: the page says "formerly #4"', (await a.text('#oldref')) === 'formerly #4', await a.text('#oldref'));
  549. await a.waitFor('document.querySelectorAll("#events li.comment").length === 2', { label: 'legacy: both API comments in the block' });
  550. const legacyH = await hist(a);
  551. check('legacy: its history holds the created event and both API comments, in order', J(legacyH.map(h => h.kind + ':' + h.text)) === J(['created:', 'comment:via the old number', 'comment:via the project number']), J(legacyH));
  552. await a.goto(BASE + '/project/alpha');
  553. await a.waitForSelector('#tickets li');
  554. await connected(a, 'A on alpha');
  555. await clickNav(a, '#tickets a.subject[href="/alpha/1"]', 'location.pathname === "/alpha/1" && !!document.querySelector("#events li.comment")', 'click alpha #1');
  556. const legacy1 = await hist(a);
  557. check('legacy: a real click on a list row opens /alpha/1 (old #1, history in order)', (await a.text('#subject')) === 'Legacy alpha one' && (await a.text('#oldref')) === 'formerly #1' && J(legacy1.filter(h => h.text).map(h => h.text)) === J(['legacy comment on one', 'started']), J(legacy1));
  558. await a.goto(BASE + '/gamma/1');
  559. await a.waitForSelector('#subject');
  560. check('numbers: a new ticket has no "formerly"', (await a.text('#ref')) === '#1' && !(await a.evaluate('!!document.querySelector("#oldref")')));
  561. await a.goto(BASE + '/alpha/99');
  562. await a.waitForSelector('#gone');
  563. check('numbers: an unknown number shows "no such ticket"', (await a.text('#gone')).includes('no such ticket'));
  564. await a.goto(BASE + '/gamma');
  565. await a.waitForSelector('#tickets li');
  566. check('numbers: /<slug> lists that project', (await texts(a, '#tickets li')).length === 2 && (await a.text('#heading')) === 'gamma');
  567. // ---- ticket #25: short URLs /<slug>, /<slug>/<number>; every old page URL answers 301; hl:web's own urls stay its own
  568. const SHORT_SSR = [['/gamma', 'id="heading">gamma<'], ['/gamma/1', 'first of a new project'], ['/beta.example.org/2', 'Legacy beta two'], ['/alpha/3', 'Legacy alpha three']];
  569. for (const [path, want] of SHORT_SSR) {
  570. const r = await fetch(BASE + path, { redirect: 'manual' });
  571. const body = await r.text();
  572. check(`short (#25): GET ${path} → 200, the page itself (SSR)`, r.status === 200 && body.includes(want), r.status + ' ' + body.slice(0, 200));
  573. }
  574. for (const [from, to] of [['/projects/gamma', '/gamma'], ['/projects/gamma/1', '/gamma/1'], ['/projects/gamma/tickets/2', '/gamma/2'], ['/projects/beta.example.org/tickets/2', '/beta.example.org/2'], ['/projects/alpha/3', '/alpha/3'], ['/tickets/5', '/beta.example.org/2']]) {
  575. const r = await fetch(BASE + from, { redirect: 'manual' });
  576. check(`short (#25): old ${from} → 301 Location ${to}`, r.status === 301 && r.headers.get('location') === to, r.status + ' ' + r.headers.get('location'));
  577. }
  578. for (const from of ['/projects/nope', '/projects/nope/1', '/projects/gamma/99', '/projects/gamma/tickets/99', '/projects/gamma/tickets/x', '/projects/gamma/%0d%0aSet-Cookie:x']) {
  579. const r = await fetch(BASE + from, { redirect: 'manual' });
  580. check(`short (#25): old ${from} names nothing → 404, no Location`, r.status === 404 && !r.headers.get('location'), r.status + ' ' + r.headers.get('location'));
  581. }
  582. const ssrNope = await (await fetch(BASE + '/nope')).text();
  583. check('short (#25): /nope (no such project) → the page says so', /no such project|nope/i.test(ssrNope) && ssrNope.includes('id="heading">nope<'), ssrNope.slice(0, 200));
  584. // hl:web appends its own urls AFTER the app's routes; /:projectSlug/:ticketNumber must not answer them (project.hl moves it last)
  585. for (const [path, type] of [['/__hl/app.css', 'text/css'], ['/__hl/hl-runtime.js', 'text/javascript'], ['/__hl/sw.js', 'text/javascript'], ['/__hl/manifest.webmanifest', 'application/manifest+json'], ['/__hl/web/client.js', 'text/javascript'], ['/components/ticket.hl', 'text/javascript'], ['/components/ticket_list.hl', 'text/javascript'], ['/components/main.hl', 'text/javascript']]) {
  586. const r = await fetch(BASE + path);
  587. const body = await r.text();
  588. check(`short (#25): hl:web's ${path} is still its own (${type}, no page)`, r.status === 200 && (r.headers.get('content-type') || '').startsWith(type) && !body.startsWith('<!doctype'), r.status + ' ' + r.headers.get('content-type'));
  589. }
  590. const em = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'nosuchface', payload: [] }) });
  591. check('short (#25): POST /__hl/emit is still hl:web\'s carrier (JSON ack)', em.status === 200 && /"ok":false/.test(await em.text()));
  592. // in the browser: an old link lands on the short URL; the project link on the ticket page is a CLIENT navigation to /<slug>
  593. await a.goto(BASE + '/projects/gamma/tickets/1');
  594. await a.waitForSelector('#subject');
  595. check('short (#25): Chrome on /projects/gamma/tickets/1 lands on /gamma/1', (await a.evaluate('location.pathname')) === '/gamma/1' && (await a.text('#subject')) === 'first of a new project', await a.evaluate('location.href'));
  596. await connected(a, 'A on /gamma/1');
  597. await a.evaluate('window.__w083 = 1');
  598. check('short (#25): the ticket page links its project as /gamma', (await a.evaluate('document.querySelector("#project").getAttribute("href")')) === '/gamma');
  599. await clickNav(a, '#project', 'location.pathname === "/gamma" && document.querySelectorAll("#tickets li").length === 2', 'click the project');
  600. check('short (#25): a click on the project → /gamma, its list, without a reload', (await a.evaluate('window.__w083')) === 1 && (await a.text('#heading')) === 'gamma');
  601. await clickNav(a, '#tickets a.subject[href="/gamma/2"]', 'location.pathname === "/gamma/2" && !!document.querySelector("#subject")', 'click gamma #2');
  602. check('short (#25): … and a click on a row → /gamma/2, without a reload', (await a.evaluate('window.__w083')) === 1 && (await a.text('#subject')) === 'second of gamma');
  603. // reserved slugs: no project may be named like a path the app answers itself
  604. for (const slug of ['api', 'Inbox', '__hl', 'components', 'projects', 'tickets', 'login.js', 'my', 'assets', 'sign-in']) {
  605. const r = await api('POST', '/api/projects', { title: 'Reserved ' + slug, slug });
  606. check(`short (#25): a new project with the slug ${slug} → 400 reserved`, r.status === 400 && r.json.field === 'slug' && /reserved/.test(r.json.error), J(r));
  607. }
  608. const toRes = await api('POST', '/api/projects/gamma', { slug: 'inbox' });
  609. check('short (#25): changing a slug to a reserved one → 400, gamma keeps its slug', toRes.status === 400 && /reserved/.test(toRes.json.error) && (await api('GET', '/api/projects/gamma')).json.project.slug === 'gamma', J(toRes));
  610. check('short (#25): no project was made by the refusals', !(await api('GET', '/api/projects')).json.projects.some(p => /reserved|^api$|^inbox$/i.test(p)));
  611. // every first segment a route of project.hl answers is a reserved slug (a new route must add its name)
  612. const routeHeads = [...readFileSync(join(APP, 'project.hl'), 'utf8').matchAll(/pattern = "\/([^/":]+)/g)].map(m => m[1]);
  613. const reservedSrc = readFileSync(join(APP, 'lib/projects.hl'), 'utf8').match(/static reservedSlugs = \[([^\]]*)\]/);
  614. const reserved = reservedSrc ? [...reservedSrc[1].matchAll(/'([^']*)'/g)].map(m => m[1]) : [];
  615. const missingHeads = [...new Set([...routeHeads, '__hl', 'components'])].filter(h => !reserved.includes(h));
  616. check(`short (#25): every first path segment of project.hl's routes (${new Set(routeHeads).size}) + __hl + components is reserved`, routeHeads.length > 10 && missingHeads.length === 0, J(missingHeads));
  617. // ---- old events keep their authors (ticket #7) --------------------------------------------
  618. await a.goto(BASE + '/projects/alpha/1');
  619. await a.waitForSelector('#events li.comment');
  620. check('legacy: old events show their stored authors (creator, worker, worker)', J((await hist(a)).map(h => h.author)) === J(['creator', 'worker', 'worker']), J(await hist(a)));
  621. // ---- signed out: reading only (ticket #7) --------------------------------------------------
  622. const IDENT1 = '/projects/ident.worldapi.org/1';
  623. await a.goto(BASE + IDENT1);
  624. await a.waitForSelector('#events li');
  625. await connected(a, 'A on ident #1 (signed out)');
  626. check('signed out: the ticket page shows the history, a login hint and NO write forms', (await hist(a)).length === 1 && !!(await a.evaluate('!!document.querySelector("#loginhint")')) && !(await a.evaluate('!!document.querySelector("#commentform") || !!document.querySelector("#stateform")')));
  627. check('signed out: top right the selector ("choose ident") and NOTHING beside it — no second "Log in with ident" button (creator 2026-10-24)', await a.evaluate(`(() => { const s = document.querySelector('#selector'); const r = s && s.shadowRoot; const hb = document.querySelector('application-header').getBoundingClientRect(); const sb = s.getBoundingClientRect(); return !!r && /choose/.test(r.querySelector('#choose').textContent) && !s.hasAttribute('logged-in') && sb.right > hb.right - 400 && !document.querySelector('#loginbutton') && !document.querySelector('a[href*="/login?key="]'); })()`));
  628. check('signed out: the selector is restyled to tickets\' accent (purple)', await a.evaluate(sh('getComputedStyle(r.querySelector("#choose")).backgroundColor')) === 'rgb(197, 134, 192)');
  629. let anonCookie = (await a.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];
  630. const anonTry = await temit('commentOn', [(await api('GET', PT('ident.worldapi.org', 1))).json.ticket.id, 'anonymous'], anonCookie);
  631. check('signed out: a web write (the face, with the browser\'s own cookie) is refused', anonTry.value && /log in with ident/.test(anonTry.value.error), anonTry.raw);
  632. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  633. await viewport(a, w, h);
  634. check(`layout ${name} ${w}px: signed-out header (the selector) has no horizontal overflow`, await noOverflow(a));
  635. check(`IW ${name} ${w}px signed out: ident's selector stands visible at the top right of the header`, (await a.evaluate(SELECTOR_IN_HEADER)) === 'ok', await a.evaluate(SELECTOR_IN_HEADER));
  636. await shot(a, `${name}-signedout`);
  637. }
  638. await viewport(a, 1280, 900);
  639. // ---- A = alice (the creator): sign in to ident, then the SELECTOR on tickets ---------------
  640. await identSignIn(a, '[email protected]');
  641. await a.goto(BASE + IDENT1);
  642. await a.waitForSelector('#events li');
  643. await connected(a, 'A on ident #1');
  644. await a.evaluate('window.__loginMarker = 1');
  645. await shClick(a, '#choose');
  646. await a.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'selector list' });
  647. check('selector: lists alice\'s identity', J(await a.evaluate(sh(`[...r.querySelectorAll('[part~="identity"]')].map(b => b.textContent)`))) === J(['Default']));
  648. await shClick(a, '[part~="identity"]', 'Default');
  649. await a.waitForSelector('#nameform', { timeout: 10000 });
  650. check('selector login: no reload, the host set logged-in, the name prompt appears', (await a.evaluate('window.__loginMarker')) === 1 && await a.evaluate('document.querySelector("#selector").hasAttribute("logged-in") && document.querySelector("#selector").loggedIn === true') && /logged in with/.test(await a.evaluate(sh('r.querySelector("#status").textContent'))));
  651. check('selector login: still no write forms before the name', !(await a.evaluate('!!document.querySelector("#commentform")')));
  652. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  653. await viewport(a, w, h);
  654. check(`layout ${name} ${w}px: name prompt has no horizontal overflow`, await noOverflow(a));
  655. await shot(a, `${name}-name`);
  656. }
  657. await viewport(a, 1280, 900);
  658. await a.type('#displayname', 'alice');
  659. await a.click('#namesave');
  660. await a.waitFor('!document.querySelector("#nameform") && !!document.querySelector("#memberhint")', { label: 'A named, no role yet: a member hint, no forms' });
  661. check('name: saved; no role yet → a role hint, no comment form; top right shows "alice"', (await a.evaluate('window.__loginMarker')) === 1 && (await a.text('#whoami')) === 'alice' && !(await a.evaluate('!!document.querySelector("#commentform")')));
  662. // ticket #20: the admin (the gate user, the creator) gives alice a role in every project; the page follows live
  663. const grant = async (name, role) => { for (const slug of (await api('GET', '/api/projects')).json.projects) { const g = await api('POST', `/api/projects/${slug}/members`, { user: name, role }); if (g.status !== 200 && g.status !== 201) throw new Error('grant failed ' + slug + ' ' + J(g)); } };
  664. await grant('alice', 'admin');
  665. await a.goto(BASE + IDENT1);
  666. await a.waitFor('!!document.querySelector("#commentform")', { label: 'A: the forms appear after alice got a role' });
  667. await connected(a, 'A on ident #1 with a role');
  668. await a.evaluate('window.__loginMarker = 1');
  669. check('roles: alice made admin → the comment form appears (page reloaded), no member hint', !(await a.evaluate('!!document.querySelector("#memberhint")')));
  670. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  671. await viewport(a, w, h);
  672. check(`layout ${name} ${w}px: logged-in header has no horizontal overflow`, await noOverflow(a));
  673. check(`IW ${name} ${w}px signed in: ident's selector stands visible at the top right of the header and shows the chosen identity`, (await a.evaluate(SELECTOR_IN_HEADER)) === 'ok' && /logged in with/.test(await a.evaluate(sh('r.querySelector("#status").textContent'))), await a.evaluate(SELECTOR_IN_HEADER));
  674. check(`IW ${name} ${w}px signed in: Log out is still reachable (the user menu opens by a real click and shows it, 44 px high)`, await (async () => { await a.click('button.user-toggle'); await a.waitFor('document.querySelector("#user-menu").matches(":popover-open")', { label: 'user menu' }); const r = await a.evaluate('(() => { const b = document.querySelector("#logout").getBoundingClientRect(); return b.width > 0 && b.height >= 44 && b.bottom <= innerHeight && b.right <= innerWidth; })()'); await a.evaluate('document.querySelector("#user-menu").hidePopover()'); return r; })());
  675. await shot(a, `${name}-loggedin`);
  676. }
  677. await viewport(a, 1280, 900);
  678. const aliceCookie = (await a.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];
  679. const aliceHtml = await (await fetch(BASE + '/', { headers: { cookie: aliceCookie } })).text();
  680. const ALICE_UID = (/\\?"user\\?":\{\\?"id\\?":\\?"([0-9a-z]{12})/.exec(aliceHtml) || [])[1];
  681. check('session: the page knows alice\'s tickets user id, NEVER her identity id', /^[0-9a-z]{12}$/.test(ALICE_UID || '') && !aliceHtml.includes(ALICE_ID), ALICE_UID);
  682. // ---- B = bob: sign in to ident, then the plain LOGIN LINK (ident /login, no button in the header any more) ---------------------------------------
  683. await identSignIn(b, '[email protected]');
  684. await b.goto(BASE + '/');
  685. await b.waitForSelector('#selector');
  686. await connected(b, 'B on / signed out');
  687. // the header has no login button any more; the old way (ident's /login with the app key and the callback) is still served — open it as the button's link did
  688. await b.goto(`${ident.base}/login?key=${APPKEY.key}&return=${encodeURIComponent(BASE + '/login/callback')}`);
  689. await b.waitForSelector('#chooselist', { timeout: 10000 });
  690. check('button: tickets → ident /signin/<rid> (choose an identity)', (await b.evaluate('location.href')).startsWith(ident.base + '/signin/'));
  691. await connectedIdent(b);
  692. await b.click('#chooselist li:nth-child(1) .choose');
  693. await b.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector('#nameform')`, { timeout: 10000, label: 'B back with the name prompt' });
  694. check('button: back on tickets (/login/callback → /), logged in, asked for a name', await b.evaluate('document.querySelector("#selector").classList.contains("in")') && !(await b.evaluate('!!document.querySelector("#newticket")')));
  695. await connected(b, 'B on / after the button login');
  696. await b.type('#displayname', 'bob');
  697. await b.click('#namesave');
  698. await b.waitFor('!document.querySelector("#nameform") && !!document.querySelector("#rolehint")', { label: 'B named' });
  699. check('button: bob named (no role yet: a role hint, no new-ticket form)', (await b.text('#whoami')) === 'bob' && !(await b.evaluate('!!document.querySelector("#newticket")')));
  700. await grant('bob', 'edit');
  701. await b.goto(BASE + '/');
  702. await b.waitFor('!!document.querySelector("#newticket")', { label: 'B: the new-ticket form appears with the role edit' });
  703. await connected(b, 'B on / with a role');
  704. check('roles: bob made edit → the new-ticket form appears', (await b.text('#whoami')) === 'bob');
  705. const bobCookie = (await b.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];
  706. // ---- the ticket page, two viewers ---------------------------------------------------
  707. await b.goto(BASE + IDENT1);
  708. await b.waitForSelector('#events li');
  709. await connected(b, 'B on ident #1');
  710. await sleep(300);
  711. check('ticket: subject, ref, project, state', (await a.text('#subject')) === 'Rebuild ident in Hybriel: email OTP login' && (await a.text('#ref')) === '#1' && (await a.text('#project')) === 'ident.worldapi.org' && (await a.text('#state')) === 'open', [await a.text('#subject'), await a.text('#ref'), await a.text('#project'), await a.text('#state')].join(' | '));
  712. check('ticket: the imported summary is one paragraph (hard wraps joined)', await a.evaluate(`!document.querySelector('#summary').textContent.includes('\\n') && document.querySelector('#summary').textContent.startsWith('Login for all worldapi apps (tickets, gitoria, …). Only email one-time codes, no passwords. Built on hl:webex;')`), await a.text('#summary'));
  713. check('time: the ticket page shows Vienna time (opened / updated / history)', await a.evaluate(`[document.querySelector('ticket-view header time').textContent, document.querySelector('#updated').textContent, document.querySelector('#events li time').textContent]`).then(v => J(v) === J([t2.ticket.created, t2.ticket.updated, t2.events[0].when]) && t2.ticket.created === vienna.format(new Date(t2.events[0].createdMs))), J(t2.ticket));
  714. check('ticket: history starts with the import event (by the token\'s user "gate")', (await hist(a)).length === 1 && (await a.text('#events > li')).includes('gate opened the ticket'), await a.text('#events > li'));
  715. // A comments (real typing into the form, real click) → B sees it without reload
  716. check('ticket: no author field (ticket #7: the author is the logged-in user)', await a.evaluate('!document.querySelector("#author") && !document.querySelector("input[name=author]")'));
  717. // mission 016: the form is the Comments block's (an MdEditor): REAL keys into it, a line break with Shift+Enter, sent with Ctrl+Enter
  718. await mdShows(a, '#commentform md-editor article', '', 'A: the comment editor is live');
  719. await a.click('#commentform md-editor article');
  720. await realKeys(a, 'first comment from A');
  721. await shiftEnter(a);
  722. await realKeys(a, 'second line');
  723. await ctrlEnter(a);
  724. await a.waitFor('document.querySelectorAll("#events li.comment").length === 1', { label: 'A sees its comment' });
  725. const firstA = (await hist(a)).pop();
  726. check('comment: typed with real keys, sent with Ctrl+Enter — appended in the writing browser as a Comments block row, author = the login (alice)', firstA.kind === 'comment' && firstA.author === 'alice' && firstA.text === 'first comment from A\nsecond line', J(firstA));
  727. check('comment: the block\'s form starts empty again', await a.evaluate('document.querySelector("#commentform md-editor input.value").value === ""'));
  728. await b.waitFor('document.querySelectorAll("#events li.comment").length === 1', { label: 'B got the comment live' });
  729. check('live: B sees A\'s comment without a reload', (await hist(b)).pop().text === 'first comment from A\nsecond line');
  730. await mdShows(b, '#events li.comment md-editor[data-readonly="true"] article', 'first comment from Asecond line', 'B draws the comment (a line break, no paragraph)');
  731. // hybriel 64527baa+: a face taking `session` answers with a sync of the session-derived members — a list must
  732. // not get the new row twice (gitoria's keys/tokens did). Settle, then count.
  733. await sleep(600);
  734. for (const [p, who] of [[a, 'A'], [b, 'B']]) { const h = await hist(p); check(`once: ${who} shows A's comment exactly once (2 history rows)`, h.length === 2 && h.filter(r => r.text === 'first comment from A\nsecond line').length === 1, J(h)); }
  735. check('live: B did not reload (no navigation entry)', await b.evaluate('performance.getEntriesByType("navigation").length === 1 && performance.getEntriesByType("navigation")[0].type === "navigate"'));
  736. await b.evaluate('window.__gateMarker = 42'); // survives only if B never reloads
  737. // ---- mission 013: GitHub pipe tables in a comment (lib/markdown.hl) — typed with REAL keys into the comment editor's
  738. // Markdown source view (a real click on its "Markdown source" button), sent by a real click; B gets it live -----------
  739. const LONGCELL = 'averyveryverylongwordthatcannotwrapanywhereatallsothetablemustscrollinsideitsbox';
  740. const TABLE_MD = 'Table check:\n| Item | Qty | Note \\| x |\n|:---|:---:|---:|\n| **milk** | `2` | a\\|b |\n| bread | 1 | <script>window.__tablePwned = 1</script> [x](javascript:alert(1)) |\n|' + LONGCELL + '|3\n\na | b stays text\n\nafter the table';
  741. const keys = async (page, text) => {
  742. for (const ch of text) {
  743. if (ch === '\n') {
  744. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  745. await page.send('Input.dispatchKeyEvent', { type: 'char', key: 'Enter', text: '\r' });
  746. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  747. } else {
  748. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  749. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  750. }
  751. }
  752. };
  753. // mission 016: the comment form is the block's MdEditor — its "Markdown source" button (a real click), then real keys
  754. await a.click('#commentform md-editor button.source-switch');
  755. await a.waitFor(`(() => { const t = document.querySelector('#commentform md-editor textarea'); return !!t && t.offsetParent !== null; })()`, { label: 'A: the comment editor shows its Markdown source' });
  756. await a.click('#commentform md-editor textarea');
  757. await keys(a, TABLE_MD);
  758. check('tables: the typed keys reached the comment field as Markdown', (await a.evaluate('document.querySelector("#commentform md-editor input.value").value')) === TABLE_MD, await a.evaluate('document.querySelector("#commentform md-editor input.value").value'));
  759. await a.click('#commentform button.comment-post');
  760. const LASTC = `[...document.querySelectorAll('#events li.comment')].pop()`;
  761. await a.waitFor(`document.querySelectorAll("#events li.comment").length === 2 && !!${LASTC}.querySelector('md-editor[data-readonly="true"] article table')`, { label: 'A sees its table comment' });
  762. const TABLE_PROBE = `(() => { const t = ${LASTC}.querySelector('md-editor[data-readonly="true"] article'); const tb = t.querySelectorAll('table'); const tab = tb[0]; if (!tab) return null;
  763. const cell = (c) => ({ text: c.textContent, align: c.getAttribute('data-align'), css: getComputedStyle(c).textAlign, strong: [...c.querySelectorAll('strong')].map(e => e.textContent), code: [...c.querySelectorAll('code')].map(e => e.textContent), links: c.querySelectorAll('a').length });
  764. return { tables: tb.length, inBox: getComputedStyle(tab).display + ' ' + getComputedStyle(tab).overflowX, head: [...tab.querySelectorAll('thead th')].map(cell), rows: [...tab.querySelectorAll('tbody tr')].map(r => [...r.children].map(c => c.tagName.toLowerCase() + ':' + c.textContent)),
  765. cells: [...tab.querySelectorAll('tbody td')].map(cell), paras: [...t.querySelectorAll(':scope > p')].map(p => p.textContent).filter(x => x !== ''), scripts: t.querySelectorAll('script').length, pwned: window.__tablePwned === 1,
  766. border: getComputedStyle(tab.querySelector('th')).borderTopColor, borderW: getComputedStyle(tab.querySelector('th')).borderTopWidth }; })()`;
  767. const tA = await a.evaluate(TABLE_PROBE);
  768. check('tables: a comment with a pipe table renders ONE <table> (the block draws it with MdEditor: the table is its own scrolling box)', !!tA && tA.tables === 1 && tA.inBox === 'block auto', J(tA));
  769. check('tables: header cells, `\\|` is a pipe in a cell, alignment from |:---|:---:|---:| (data-align + the computed text-align)', !!tA && J(tA.head.map(c => [c.text, c.align, c.css])) === J([['Item', 'left', 'left'], ['Qty', 'center', 'center'], ['Note | x', 'right', 'right']]), J(tA && tA.head));
  770. check('tables: body rows — inline Markdown in cells (**milk** strong, `2` code, a\\|b), a short row padded, raw HTML / javascript: stay text', !!tA && J(tA.rows) === J([['td:milk', 'td:2', 'td:a|b'], ['td:bread', 'td:1', 'td:<script>window.__tablePwned = 1</script> [x](javascript:alert(1))'], ['td:' + LONGCELL, 'td:3', 'td:']]) && J(tA.cells[0].strong) === J(['milk']) && J(tA.cells[1].code) === J(['2']) && tA.cells.every(c => c.links === 0) && tA.scripts === 0 && !tA.pwned, J(tA && [tA.rows, tA.cells.slice(0, 2), tA.scripts]));
  771. check('tables: the paragraph before stays, "a | b stays text" (pipes, no delimiter row) stays a paragraph', !!tA && J(tA.paras) === J(['Table check:', 'a | b stays text', 'after the table']), J(tA && tA.paras));
  772. check('tables: thin grey lines (1px, the palette\'s border grey: no hue — channels within 12)', !!tA && tA.borderW === '1px' && (() => { const m = /rgba?\((\d+), (\d+), (\d+)/.exec(tA.border); if (!m) return false; const v = [m[1], m[2], m[3]].map(Number); return Math.max(...v) - Math.min(...v) <= 12; })(), J(tA && [tA.border, tA.borderW]));
  773. await b.waitFor(`!!${LASTC} && !!${LASTC}.querySelector('md-editor[data-readonly="true"] article table')`, { label: 'B got the table comment live' });
  774. const tB = await b.evaluate(TABLE_PROBE);
  775. check('tables: live — B shows the same table without a reload', J(tB) === J(tA) && (await b.evaluate('window.__gateMarker')) === 42, J(tB));
  776. // mission 016: the block draws a comment in the browser — the server's HTML carries its Markdown in the block's hidden field, escaped
  777. const tSsr = (await (await fetch(BASE + IDENT1)).text());
  778. check('tables: the server-rendered page carries the comment\'s Markdown escaped in the block (no live <script> from it)', tSsr.includes('&lt;script&gt;window.__tablePwned') && !tSsr.includes('<script>window.__tablePwned') && /<comments-block/.test(tSsr), (tSsr.match(/&lt;script&gt;window.__tablePwned.{0,80}/) || ['not found'])[0]);
  779. const tJson = await api('GET', PT('ident.worldapi.org', 1));
  780. const tMdView = await (await fetch(BASE + PT('ident.worldapi.org', 1), { headers: { accept: 'text/markdown' } })).text();
  781. check('tables: the API keeps the raw Markdown (JSON text byte for byte; Accept: text/markdown shows the typed lines)', tJson.json.events[tJson.json.events.length - 1].text === TABLE_MD && tMdView.includes(TABLE_MD), J(tJson.json.events[tJson.json.events.length - 1]).slice(0, 300));
  782. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  783. await viewport(a, w, h);
  784. await a.evaluate(`${LASTC}.querySelector('md-editor[data-readonly="true"] article table').scrollIntoView({ block: "center" })`);
  785. const box = await a.evaluate(`(() => { const m = ${LASTC}.querySelector('md-editor[data-readonly="true"] article table'); const t = m; return { boxW: m.clientWidth, scrollW: m.scrollWidth, tableW: m.scrollWidth, right: m.getBoundingClientRect().right, tableRight: m.getBoundingClientRect().right, overflowX: getComputedStyle(m).overflowX }; })()`);
  786. check(`tables ${name} ${w}px: the table stays inside its box (wider than the box: the box scrolls; else its right line is inside), phone: it scrolls, the page does not scroll sideways`, (await noOverflow(a)) && box.overflowX === 'auto' && (box.tableW > box.boxW ? box.scrollW > box.boxW : box.scrollW <= box.boxW) /* mission 022: the old else-branch compared an element with itself (never true); with the theme's wider column (72rem, was 60rem) the fixture table fits the box on desktop: then nothing scrolls */ && (w > 600 || box.scrollW > box.boxW) && box.right <= w, J(box));
  787. await shot(a, `${name}-table`);
  788. }
  789. await viewport(a, 1280, 900);
  790. // ---- ticket #20: the new states, the roles, projects with members, the inbox (browser + API) ------------------
  791. // A (alice, admin) moves ident #1 to "review": B follows live; the ticket is assigned to the project's first admin (the gate user)
  792. check('shell: no inbox count yet (nothing assigned to bob)', (await b.text('application-header main-menu')).replace(/\s+/g, ' ').trim() === 'All ticketsInbox' && (await b.evaluate('document.querySelectorAll("application-header main-menu span.count").length')) === 0); // mission 023: the count is a badge; none while nothing is assigned
  793. check('state: the choices are the new state names', J((await texts(a, '#newstate option')).sort()) === J(['canceled', 'done', 'pending', 'progress', 'reopened', 'review']), J(await texts(a, '#newstate option')));
  794. await choose(a, '#newstate', 'review');
  795. // ==== m021 START — tickets#29: the editor's LOOK on the ticket page (the creator: "why did the md wysiwyg editor's layout change?")
  796. const LOOK = (sel) => `(() => { const m = document.querySelector(${J(sel)}); const c = getComputedStyle(m); const art = m.querySelector('article'); const f = m.querySelector('nav button.file'); const bs = [...m.querySelectorAll('nav button')].filter(x => getComputedStyle(x).display !== 'none').map(x => x.getBoundingClientRect()); return { cls: m.className, border: c.borderTopWidth + ' ' + c.borderTopStyle, pad: c.paddingTop, h: Math.round(m.getBoundingClientRect().height), art: Math.round(art.getBoundingClientRect().height), file: !!f && getComputedStyle(f).display !== 'none', rows: new Set(bs.map(r => Math.round(r.top))).size, minTap: Math.round(Math.min(...bs.map(r => Math.min(r.width, r.height)))) }; })()`;
  797. const noteLook = await a.evaluate(LOOK('#statenote md-editor'));
  798. check('m021: the empty state note has no dashed frame / padding (the host `.empty` rule is for "No tickets" paragraphs only) and is about one line (art < 60 px)', noteLook.border.startsWith('0px') && noteLook.pad === '0px' && !noteLook.cls.split(' ').includes('empty') && noteLook.art < 60, J(noteLook));
  799. check('m021: no File button where the host has no upload (the toolbar has 10 buttons, not 11)', !noteLook.file && !(await a.evaluate(LOOK('#commentform md-editor'))).file, J(noteLook));
  800. const cmLook = await a.evaluate(LOOK('#commentform md-editor'));
  801. check('m021: the comment form is ~3 lines tall (art 70-110 px), no frame', cmLook.art >= 70 && cmLook.art <= 110 && cmLook.border.startsWith('0px') && cmLook.pad === '0px', J(cmLook));
  802. // F4: under the tickets theme (`:focus-visible` and `textarea:focus` rules) the focused editor shows ONE ring (its own frame), never a second one on the surface / source textarea; the toolbar holds icons
  803. await a.click('#commentform md-editor article'); await sleep(250);
  804. const f4a = await a.evaluate(`(() => { const m = document.querySelector('#commentform md-editor'); const x = m.querySelector('article'); const c = getComputedStyle(x), r = getComputedStyle(m); const bs = [...m.querySelectorAll('nav button')].filter(b => getComputedStyle(b).display !== 'none'); return { focused: document.activeElement === x, art: c.outlineStyle + '/' + c.outlineWidth, root: r.outlineStyle + '/' + r.outlineWidth, buttons: bs.length, svgs: bs.filter(b => b.querySelector('svg path') && b.textContent.trim() === '' && b.getAttribute('aria-label') === b.title).length }; })()`);
  805. check('F4: the focused comment editor under the tickets theme: the surface has no outline of its own, the frame one 2 px ring; every toolbar button is an icon with title + aria-label', f4a.focused && f4a.art.startsWith('none/') && f4a.root === 'solid/2px' && f4a.buttons === 10 && f4a.svgs === 10, J(f4a));
  806. await a.click('#commentform md-editor footer button.source-switch'); await sleep(300);
  807. await a.click('#commentform md-editor textarea'); await sleep(250);
  808. const f4b = await a.evaluate(`(() => { const m = document.querySelector('#commentform md-editor'); const t = m.querySelector('textarea'); const c = getComputedStyle(t), r = getComputedStyle(m); return { focused: document.activeElement === t, ta: c.outlineStyle + '/' + c.outlineWidth, root: r.outlineStyle + '/' + r.outlineWidth }; })()`);
  809. check('F4: the focused source textarea under the tickets theme has no outline of its own (the frame keeps its ring)', f4b.focused && f4b.ta.startsWith('none/') && f4b.root === 'solid/2px', J(f4b));
  810. await a.click('#commentform md-editor footer button.source-switch'); await sleep(300);
  811. await a.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  812. await sleep(400);
  813. const noteLook390 = await a.evaluate(LOOK('#statenote md-editor'));
  814. check('m021 / E2: at 390 px the toolbar is two even rows (5 + 5, no swipe) and every button is a 44 px target', noteLook390.rows === 2 && noteLook390.minTap >= 44, J(noteLook390));
  815. await a.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  816. // ==== m021 END
  817. await type(a, '#statenote md-editor input.value', 'please test');
  818. await a.click('#statesend');
  819. await a.waitFor('document.querySelector("#state").textContent === "review"', { label: 'A state changed' });
  820. check('state: A shows the new state and a state event with the note', (await a.text('#events > li:nth-last-child(2)')).includes('alice changed the state') && (await a.text('#events > li:nth-last-child(2) ticket-state')) === 'review' && (await a.text('#events > li:nth-last-child(2) event-text')) === 'please test' && (await a.text('#events > li:last-child')).includes('assigned the ticket to gate'), await a.text('#events > li:last-child'));
  821. await sleep(600);
  822. check('once: A shows the state change exactly once', (await texts(a, '#events > li')).filter(t => t.includes('alice changed the state')).length === 1, J(await texts(a, '#events > li')));
  823. await b.waitFor('document.querySelector("#state").textContent === "review"', { label: 'B state live' });
  824. check('live: B\'s state badge followed, no reload', (await b.evaluate('document.querySelector("#state").className')) === 'review' && (await b.evaluate('window.__gateMarker')) === 42);
  825. const inboxOf = async (tok) => { const r = await fetch(BASE + '/api/inbox', { headers: { authorization: 'Bearer ' + tok } }); let json = null; try { json = await r.json(); } catch {} return { status: r.status, json }; };
  826. const inbox0 = await inboxOf(TOKEN);
  827. check('inbox: the gate user (first admin) has ident #1 in review, only tickets assigned to them', inbox0.status === 200 && inbox0.json.review.some(t => t.subject === 'Rebuild ident in Hybriel: email OTP login') && [...inbox0.json.review, ...inbox0.json.pending].every(t => t.assignee === 'gate'), J(inbox0.json).slice(0, 400));
  828. const oldNames = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'awaiting creator' });
  829. check('states: the old name "awaiting creator" is an alias of review (already there → 400 "already")', oldNames.status === 400 && /already review/.test(oldNames.json.error), J(oldNames));
  830. const aliasBack = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'in progress' });
  831. check('states: "in progress" is an alias of progress (201)', aliasBack.status === 201 && aliasBack.json.ticket.state === 'progress', J(aliasBack).slice(0, 300));
  832. await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'open' });
  833. // roles: bob = use → comment + open ⇄ review, nothing else (web and API)
  834. let aliceTok0 = null;
  835. const bobTok = (await temit('tokenCreate', ['bob gate'], bobCookie)).value.token;
  836. await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'use' });
  837. await b.goto(BASE + IDENT1);
  838. await b.waitForSelector('#stateform');
  839. await connected(b, 'B on ident #1 as use');
  840. check('roles: bob (use) sees only review in the state choices (ticket is open)', J(await texts(b, '#newstate option')) === J(['review']), J(await texts(b, '#newstate option')));
  841. const useDone = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'done' }, bobTok);
  842. const useReview = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'review' }, bobTok);
  843. const useNew = await api('POST', '/api/projects/ident.worldapi.org/tickets', { subject: 'use may not' }, bobTok);
  844. const useSettings = await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'admin' }, bobTok);
  845. const useComment = await api('POST', PT('ident.worldapi.org', 1) + '/comments', { text: 'a use member comments' }, bobTok);
  846. check('roles: use → done 403, review 201, new ticket 403, members 403, comment 201', [useDone.status, useReview.status, useNew.status, useSettings.status, useComment.status].join() === '403,201,403,403,201', J([useDone, useNew, useSettings]).slice(0, 500));
  847. await b.goto(BASE + '/projects/ident.worldapi.org/settings');
  848. await b.waitForSelector('#notadmin');
  849. check('roles: the settings page of a non-admin says so and has no forms', !(await b.evaluate('!!document.querySelector("#detailsform")')));
  850. await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'edit' });
  851. const editAssign = await api('POST', PT('ident.worldapi.org', 1) + '/assign', { assignee: 'bob' }, bobTok);
  852. check('roles: edit may assign (201) and move to any state', editAssign.status === 201 || editAssign.status === 200, J(editAssign).slice(0, 300));
  853. const editPending = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'pending' }, bobTok);
  854. check('roles: edit → pending 201; "on hold" is an alias of pending', editPending.status === 201 && editPending.json.ticket.state === 'pending', J(editPending).slice(0, 300));
  855. // the inbox page of bob: pending and review, only what is assigned to him
  856. await b.goto(BASE + '/inbox');
  857. await b.waitForSelector('#pendingbox');
  858. await connected(b, 'B inbox');
  859. check('inbox: bob has ident #1 under pending, review is empty', (await texts(b, '#pending li a.subject')).length === 1 && (await b.text('#pending li a.subject')).includes('Rebuild ident') && !!(await b.evaluate('!!document.querySelector("#reviewempty")')), J(await texts(b, '#pendingbox')));
  860. await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'review' }, bobTok);
  861. await b.waitFor('document.querySelectorAll("#review li").length === 1 && document.querySelectorAll("#pending li").length === 0', { label: 'inbox follows the state change live' });
  862. check('inbox: the ticket moved from pending to review live, header count 1', (await b.text('application-header main-menu')).replace(/\s+/g, ' ').trim() === 'All ticketsInbox1'); // mission 023: the badge's own element after the plain label
  863. {
  864. // mission 023: the Inbox count is a badge (its own span.count), the label stays plain; `current` / aria-current marks the page's item
  865. const menuInfo = () => b.evaluate(`(() => { const m = document.querySelector('application-header main-menu'); return [...m.querySelectorAll('a')].map(a => ({ href: a.getAttribute('href'), aria: a.getAttribute('aria-current'), cls: a.className, label: a.firstChild && a.firstChild.nodeValue, badge: [...a.querySelectorAll('span.count')].map(x => x.textContent) })); })()`);
  866. const marked = async (href, label) => { await b.waitFor(`(() => { const a = document.querySelector('application-header main-menu a[href="${href}"]'); return !!a && a.getAttribute('aria-current') === 'page'; })()`, { label }).catch(() => {}); const m = await menuInfo(); return m.filter(x => x.aria === 'page').map(x => x.href).join() === href && m.filter(x => x.cls === 'current').length === 1; };
  867. const mi = await menuInfo();
  868. check('menu badge: the Inbox count is its own span.count (1), the label is the plain text "Inbox"', mi.length === 2 && J(mi[1].badge) === '["1"]' && mi[1].label === 'Inbox' && mi[0].badge.length === 0, J(mi));
  869. check('menu current: on /inbox the Inbox item has aria-current="page" and the class current, All tickets has not', await marked('/inbox', 'inbox marked'), J(await menuInfo()));
  870. await b.goto(`${BASE}/`); await b.waitForSelector('#tickets li');
  871. check('menu current: on the ticket list All tickets has aria-current="page", the Inbox has not', await marked('/', 'list marked'), J(await menuInfo()));
  872. const tHref = await b.evaluate(`(() => { const a = document.querySelector('#tickets li a.subject'); return a ? a.getAttribute('href') : ''; })()`);
  873. await b.goto(`${BASE}${tHref}`); await b.waitForSelector('#subject');
  874. check(`menu current: on a ticket page (${tHref}, no item's path) All tickets has aria-current="page"`, tHref !== '' && await marked('/', 'ticket marked'), J(await menuInfo()));
  875. await b.goto(`${BASE}/inbox`); await b.waitForSelector('#pendingbox'); await connected(b, 'B inbox again');
  876. check('menu current: back on /inbox the marker moved to the Inbox', await marked('/inbox', 'inbox marked again'), J(await menuInfo()));
  877. // mission 024 (hybriel#197): the marker is in the SERVER's HTML (a plain fetch, no browser, no script): in the first paint, no flicker
  878. {
  879. const ssr = async path => { const h = await (await fetch(BASE + path)).text(); const tags = [...h.matchAll(/<a\b[^>]*>/g)].map(m => m[0]).filter(t => /href="\/(inbox)?"/.test(t) && /aria-current=/.test(t)); return tags.map(t => (t.match(/href="([^"]*)"/) || [])[1] + (/aria-current="page"/.test(t) ? '*' : '')); };
  880. const proj = '/' + tHref.split('/')[1];
  881. for (const [path, want] of [['/', '/*,/inbox'], ['/inbox', '/,/inbox*'], [proj, '/*,/inbox'], [tHref, '/*,/inbox']]) {
  882. const got = await ssr(path); const uniq = [...new Set(got)].join();
  883. check(`menu current in the server's HTML (plain fetch of ${path}): ${want}`, uniq === want, J(got));
  884. }
  885. }
  886. }
  887. aliceTok0 = (await temit('tokenCreate', ['alice #20'], aliceCookie)).value.token;
  888. check('inbox: alice (admin, nothing assigned) has an empty inbox', (await inboxOf(aliceTok0)).json.review.length === 0);
  889. // ---- mission 016 (layouts#2): THE COMMENTS BLOCK — edit (author), delete (author, asks first), like (members, toggle), in place
  890. // in the history between the other events; a non-member reads only, and the server refuses them too (faces + API) ----------------
  891. const cbProj = await api('POST', '/api/projects', { title: 'Comments block' });
  892. const CB = cbProj.json && cbProj.json.project ? cbProj.json.project.slug : 'comments-block';
  893. await api('POST', `/api/projects/${CB}/members`, { user: 'alice', role: 'admin' });
  894. const cbT = (await api('POST', `/api/projects/${CB}/tickets`, { subject: 'Comments in place' })).json.ticket;
  895. const cbGate = (await api('POST', PT(CB, 1) + '/comments', { text: 'the **gate** writes first' })).json.event;
  896. await api('POST', PT(CB, 1) + '/state', { state: 'progress', text: 'working on it' });
  897. check('m016: the fixture — a project bob is not in, a ticket with created / gate\'s comment / a state change', cbProj.status === 201 && !!cbT && !!cbGate && cbGate.kind === 'comment', J(cbProj).slice(0, 300));
  898. const CBURL = '/' + CB + '/1';
  899. // B = bob, NOT a member: reads the comments in the block, in place; no form, no Edit / Delete; the like does nothing
  900. await b.goto(BASE + CBURL);
  901. await b.waitForSelector('#events li.comment');
  902. await connected(b, 'B on the comments ticket (no member)');
  903. await mdShows(b, `li.comment[data-id="${cbGate.id}"] md-editor[data-readonly="true"] article`, 'the gate writes first', 'B draws gate\'s comment');
  904. const nmH = await hist(b);
  905. check('m016: in place — created, gate\'s comment (a Comments block row, Markdown drawn), then the state change', J(nmH.map(h => h.kind)) === J(['created', 'comment', 'state']) && nmH[1].author === 'gate' && nmH[1].text === 'the **gate** writes first' && (await b.evaluate(`document.querySelector('li.comment[data-id="${cbGate.id}"] article strong').textContent`)) === 'gate', J(nmH));
  906. check('m016: the block\'s count line and form are not shown inside the history (one visible comment form at most)', await b.evaluate(`[...document.querySelectorAll('#events h2.comments-count, #events form.comment-form')].every(e => e.offsetParent === null)`));
  907. check('m016: non-member — no comment form, the member hint, no Edit / Delete anywhere', await b.evaluate('!document.querySelector("#commentform") && !!document.querySelector("#memberhint") && !document.querySelector(".comment-edit-start, .comment-delete")'));
  908. await calmClick(b, `li.comment[data-id="${cbGate.id}"] button.comment-like`);
  909. await sleep(700);
  910. check('m016: non-member — pressing the like changes nothing (page and store)', (await b.evaluate(`document.querySelector('li.comment[data-id="${cbGate.id}"] button.comment-like').getAttribute('aria-pressed')`)) === 'false' && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id).likes === undefined);
  911. // the server refuses a non-member too: the faces with bob's own session, and the API with bob's token
  912. const nmFaces = [await temit('commentOn', [cbT.id, 'bob is no member'], bobCookie), await temit('ticketCommentLike', [cbT.id, cbGate.id], bobCookie), await temit('ticketCommentEdit', [cbT.id, cbGate.id, 'bob edits'], bobCookie), await temit('ticketCommentDelete', [cbT.id, cbGate.id], bobCookie)];
  913. check('m016: non-member — the faces (post, like, edit, delete with bob\'s own session) are refused', nmFaces.every(f => f.value && /member/.test(f.value.error || '')), J(nmFaces.map(f => f.raw)));
  914. const nmApi = [await api('POST', PT(CB, 1) + `/comments/${cbGate.id}/like`, null, bobTok), await api('POST', `/api/tickets/${cbT.id}/comments/${cbGate.id}/edit`, { text: 'bob edits' }, bobTok), await api('POST', PT(CB, 1) + `/comments/${cbGate.id}/delete`, {}, bobTok)];
  915. const afterNm = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id);
  916. check('m016: non-member — the API answers 403 to like / edit / delete, the comment is untouched', J(nmApi.map(r => r.status)) === J([403, 403, 403]) && afterNm.text === 'the **gate** writes first' && afterNm.likes === undefined && afterNm.edited === undefined && afterNm.deleted === undefined, J(nmApi));
  917. // bob becomes a member (use): after a reload he has the form
  918. await api('POST', `/api/projects/${CB}/members`, { user: 'bob', role: 'use' });
  919. await b.goto(BASE + CBURL);
  920. await b.waitForSelector('#commentform form.comment-form');
  921. await connected(b, 'B on the comments ticket (use)');
  922. await b.evaluate('window.__m016 = 1');
  923. // A = alice posts by REAL keys + Ctrl+Enter: a NEW block after the state change; both browsers
  924. await a.goto(BASE + CBURL);
  925. await a.waitForSelector('#commentform form.comment-form');
  926. await connected(a, 'A on the comments ticket');
  927. await mdShows(a, '#commentform md-editor article', '', 'A: the comment editor is live');
  928. await a.click('#commentform md-editor article');
  929. await realKeys(a, 'alice writes **later** now');
  930. await ctrlEnter(a);
  931. await a.waitFor('document.querySelectorAll("#events li.comment").length === 2', { label: 'A: its comment' });
  932. await b.waitFor('document.querySelectorAll("#events li.comment").length === 2', { label: 'B: alice\'s comment live' });
  933. const cbStored = (await api('GET', PT(CB, 1))).json.events;
  934. const aliceC = cbStored[cbStored.length - 1];
  935. const hA = await hist(a), hB = await hist(b);
  936. check('m016: post — stored once as alice\'s comment (the visual editor wrote **later**), in a new block after the state change, A and B', aliceC.kind === 'comment' && aliceC.author === 'alice' && aliceC.text === 'alice writes **later** now' && cbStored.filter(e => e.kind === 'comment').length === 2 && J(hA.map(h => h.kind)) === J(['created', 'comment', 'state', 'comment']) && J(hB.map(h => h.kind + ':' + h.text)) === J(hA.map(h => h.kind + ':' + h.text)) && (await b.evaluate('document.querySelectorAll("#events > li.comments").length')) === 2, J([aliceC, hA, hB]));
  937. check('m016: Edit / Delete only on your own comment — A on alice\'s yes, on gate\'s no; B (bob) on neither', await a.evaluate(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] .comment-edit-start') && !!document.querySelector('li.comment[data-id="${aliceC.id}"] .comment-delete') && !document.querySelector('li.comment[data-id="${cbGate.id}"] .comment-edit-start')`) && await b.evaluate('!document.querySelector(".comment-edit-start, .comment-delete")'));
  938. // EDIT: a real click on Edit, real keys at the end, Save → both browsers show the new text and "edited"; the earlier version folds out
  939. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-edit-start`);
  940. await mdShows(a, `li.comment[data-id="${aliceC.id}"] form.comment-edit md-editor article`, 'alice writes later now', 'A: the edit editor holds the comment');
  941. await a.click(`li.comment[data-id="${aliceC.id}"] form.comment-edit md-editor article`);
  942. await endKey(a);
  943. await realKeys(a, ' and edits');
  944. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-save`);
  945. await a.waitFor(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history')`, { label: 'A: edited' });
  946. await b.waitFor(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history')`, { label: 'B: the edit live' });
  947. const edApi = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id);
  948. check('m016: edit — stored as the new text, the earlier one kept (API: edited, editedWhen, earlier)', edApi.text === 'alice writes **later** now and edits' && edApi.edited === true && /^\d{4}-\d\d-\d\d \d\d:\d\d$/.test(edApi.editedWhen) && J(edApi.earlier.map(v => v.text)) === J(['alice writes **later** now']), J(edApi));
  949. await mdShows(b, `li.comment[data-id="${aliceC.id}"] md-editor[data-readonly="true"] article`, 'alice writes later now and edits', 'B draws the edited text');
  950. check('m016: edit — B shows the new text and "edited" without a reload', (await b.evaluate('window.__m016')) === 1 && (await b.text(`li.comment[data-id="${aliceC.id}"] details.comment-history summary`)) === 'edited');
  951. await b.click(`li.comment[data-id="${aliceC.id}"] details.comment-history summary`);
  952. await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history').open`, { label: 'B: history open' });
  953. check('m016: edit — a click on "edited" folds out the earlier version ("Edited once", its Markdown)', (await b.text(`li.comment[data-id="${aliceC.id}"] .comment-history-title`)) === 'Edited once' && J(await texts(b, `li.comment[data-id="${aliceC.id}"] details.comment-history li pre`)) === J(['alice writes **later** now']));
  954. // K1: the theme's framed foldable must not show: "edited" is a quiet label beside the time; the bubble hugs its content (the readonly editor had an inline min-height of 9em)
  955. const k1 = await b.evaluate(`(() => { const li = document.querySelector('li.comment[data-id="${aliceC.id}"]'); const d = li.querySelector('details.comment-history'); const s = d.querySelector('summary'); const t = li.querySelector('comment-meta time').getBoundingClientRect(); const sr = s.getBoundingClientRect(); const cs = getComputedStyle(d), ss = getComputedStyle(s); const bu = li.querySelector('comment-bubble'); const last = [...bu.children].filter(c => c.getBoundingClientRect().height > 0).pop().getBoundingClientRect(); return { box: cs.borderTopStyle, bg: ss.backgroundColor, sb: ss.borderBottomStyle, pad: ss.paddingTop, sameLine: Math.abs(sr.top - t.top) < 14 && sr.left > t.right - 1, h: Math.round(sr.height), slack: Math.round(bu.getBoundingClientRect().bottom - last.bottom - parseFloat(getComputedStyle(bu).paddingBottom)), inline: li.querySelector('md-editor article').style.minHeight }; })()`);
  956. check('k1: "edited" is a quiet label on the time\'s line (no frame, no header strip, its padding only the 44 px hit area, sync MC) and the bubble hugs its content', k1.box === 'none' && k1.bg === 'rgba(0, 0, 0, 0)' && k1.sb === 'none' && parseFloat(k1.pad) <= 14 && k1.sameLine && k1.h <= 48 && k1.slack <= 3 && k1.inline === '', J(k1));
  957. // sync of components.hybriel 4922f9c (SY): like / Edit / Delete and the "edited" label are 44 px targets
  958. const k1t = await b.evaluate(`[...document.querySelectorAll('comments-block button, comments-block summary')].filter(e => e.getBoundingClientRect().width > 0 && e.closest('md-editor') == null).map(e => { const r = e.getBoundingClientRect(); return (e.textContent || e.className).trim().slice(0, 10) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); }).filter(t => Number(t.split(' ').pop().split('x')[1]) < 43.5 || Number(t.split(' ').pop().split('x')[0]) < 43.5)`);
  959. check('sy: every like / Edit / Delete button and the "edited" label of the thread is a 44 px target', k1t.length === 0, J(k1t));
  960. // LIKE: bob likes alice's comment (toggle), alice sees the count live
  961. await calmClick(b, `li.comment[data-id="${aliceC.id}"] button.comment-like`);
  962. await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').getAttribute('aria-pressed') === 'true'`, { label: 'B: liked' });
  963. await a.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').textContent === '♡ 1'`, { label: 'A: the count live' });
  964. check('m016: like — B pressed: ♥ 1 (pressed), A sees ♡ 1 (not hers), the API says likes 1', (await b.text(`li.comment[data-id="${aliceC.id}"] button.comment-like`)) === '♥ 1' && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).likes === 1);
  965. await calmClick(b, `li.comment[data-id="${aliceC.id}"] button.comment-like`);
  966. await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').getAttribute('aria-pressed') === 'false'`, { label: 'B: unliked' });
  967. await a.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').textContent === '♡ 0'`, { label: 'A: back to 0' });
  968. check('m016: like — pressed again takes it back (♡ 0, no likes key in the API)', (await b.text(`li.comment[data-id="${aliceC.id}"] button.comment-like`)) === '♡ 0' && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).likes === undefined);
  969. // another user's comment: bob (a member now) may not edit / delete it — faces and API refused
  970. const otherFaces = [await temit('ticketCommentEdit', [cbT.id, aliceC.id, 'bob edits alice'], bobCookie), await temit('ticketCommentDelete', [cbT.id, aliceC.id], bobCookie)];
  971. const otherApi = [await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/edit`, { text: 'bob edits alice' }, bobTok), await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/delete`, null, bobTok)];
  972. check('m016: another user\'s comment — bob\'s edit / delete refused (faces: "only its author", API 403), nothing changed', otherFaces.every(f => f.value && /only its author/.test(f.value.error || '')) && J(otherApi.map(r => r.status)) === J([403, 403]) && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).text === 'alice writes **later** now and edits', J([otherFaces.map(f => f.raw), otherApi]));
  973. // DELETE asks first: Keep takes it back, Delete removes it from both browsers; one line stays in its place
  974. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete`);
  975. await a.waitForSelector(`li.comment[data-id="${aliceC.id}"] comment-ask`);
  976. check('m016: delete — asks first ("Delete this comment?" Delete / Keep)', (await a.text(`li.comment[data-id="${aliceC.id}"] comment-ask span`)) === 'Delete this comment?' && !!(await a.evaluate(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] .comment-delete-keep')`)));
  977. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete-keep`);
  978. await sleep(600);
  979. check('m016: delete — Keep: nothing deleted', !(await a.evaluate(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] comment-ask')`)) && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).deleted === undefined);
  980. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete`);
  981. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete-yes`);
  982. await a.waitFor(`!document.querySelector('li.comment[data-id="${aliceC.id}"]')`, { label: 'A: the comment is gone' });
  983. await b.waitFor(`!document.querySelector('li.comment[data-id="${aliceC.id}"]')`, { label: 'B: gone live' });
  984. const delApi = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id);
  985. const hDel = await hist(b);
  986. check('m016: delete — gone from A and B; ONE line stays in its place ("alice commented (deleted …)"); the API: deleted, no text', delApi.deleted === true && delApi.text === '' && delApi.hasText === false && delApi.earlier === undefined && J(hDel.map(h => h.kind)) === J(['created', 'comment', 'state', 'comment deleted']) && /^alice commented \(deleted \d{4}-\d\d-\d\d \d\d:\d\d\)/.test(hDel[3].head) && (await b.evaluate('window.__m016')) === 1, J([delApi, hDel]));
  987. const delMd = await (await fetch(BASE + PT(CB, 1), { headers: { accept: 'text/markdown' } })).text();
  988. check('m016: delete — the Markdown view keeps the line, not the text', /· alice commented \(deleted /.test(delMd) && !delMd.includes('alice writes'), delMd.slice(-400));
  989. const delAgain = [await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/edit`, { text: 'again' }, aliceTok0), await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/like`, null, aliceTok0)];
  990. check('m016: a deleted comment can be neither edited nor liked (400)', J(delAgain.map(r => r.status)) === J([400, 400]), J(delAgain));
  991. // THE API for programs: both URL forms, the token's user, refusals; an untouched comment keeps exactly its old keys
  992. const apiPost = (await api('POST', PT(CB, 1) + '/comments', { text: 'gate via API' })).json.event;
  993. const apiEdit = await api('POST', `/api/tickets/${cbT.id}/comments/${apiPost.id}/edit`, { text: 'gate via API, edited' });
  994. const apiLike = await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/like`, null);
  995. const apiUnlike = await api('POST', `/api/tickets/${cbT.id}/comments/${apiPost.id}/like`, {});
  996. check('m016: API — edit 200 (edited, earlier), like 200 liked:true likes 1, again 200 liked:false (no likes key)', apiEdit.status === 200 && apiEdit.json.event.text === 'gate via API, edited' && apiEdit.json.event.edited === true && apiLike.status === 200 && apiLike.json.liked === true && apiLike.json.event.likes === 1 && apiUnlike.status === 200 && apiUnlike.json.liked === false && apiUnlike.json.event.likes === undefined, J([apiEdit, apiLike, apiUnlike]).slice(0, 600));
  997. const apiRef = [await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: 'x' }, null), await api('POST', PT(CB, 1) + '/comments/zzzzzzzzzzzz/like', null), await api('POST', PT(CB, 1) + `/comments/${cbStored[0].id}/like`, null), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: 'gate via API, edited' }), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: ' ' }), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: 'x', author: 'me' }), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/delete`, { why: 'x' }), await api('POST', PT(CB, 1) + '/comments/' + cbGate.id + '/edit', { text: 'x' }, aliceTok0)];
  998. check('m016: API refusals — no token 401, unknown comment 404, a non-comment entry 400, same text 400, empty 400, author 400, unknown field 400, alice on gate\'s 403', J(apiRef.map(r => r.status)) === J([401, 404, 400, 400, 400, 400, 400, 403]), J(apiRef.map(r => [r.status, r.json])));
  999. const keysOf = (e) => Object.keys(e).sort().join(',');
  1000. const plainC = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id);
  1001. check('m016: an untouched comment has exactly the keys it had (as when it was written)', keysOf(plainC) === keysOf(cbGate) && plainC.text === cbGate.text, keysOf(plainC) + ' vs ' + keysOf(cbGate));
  1002. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  1003. await viewport(b, w, h);
  1004. check(`m016 layout ${name} ${w}px: the history with the comment blocks has no horizontal overflow`, await noOverflow(b));
  1005. await shot(b, `${name}-comments`);
  1006. }
  1007. await viewport(b, 1280, 900);
  1008. // ---- mission 017 (tickets#27): ATTACHMENTS — pictures and files with a comment. The "Respond" block's form sits in the shared
  1009. // FilesUpload (pick mode); the API takes multipart/form-data. REAL input: the chooser's file input (DOM.setFileInputFiles), a real
  1010. // Ctrl+V of an image INTO the comment editor, real keys + Ctrl+Enter, real clicks. Checked: two chosen + one pasted picture go with
  1011. // one comment, a second user (B) sees the three thumbnails live and opens one full size; a file over 10 MB is refused (page: in its row;
  1012. // API: 413); a file that claims to be a PNG but is not is refused; a non-member cannot fetch an attachment (401 / 403) and sees no
  1013. // thumbnail; the API post of a PNG (multipart) and its download (Content-Type, nosniff, the same bytes); an edit keeps the files,
  1014. // a delete drops them (404, the bytes leave storage); the Markdown view lists them; 390 px: 44 px targets, no overflow.
  1015. // Null-safe: on the old code every check here FAILS instead of ending the gate.
  1016. {
  1017. const crc = (buf) => { let c, t = []; for (let n = 0; n < 256; n++) { c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } let x = 0xffffffff; for (const v of buf) x = t[(x ^ v) & 0xff] ^ (x >>> 8); return (x ^ 0xffffffff) >>> 0; };
  1018. const png = (w, h, rgb) => {
  1019. const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
  1020. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
  1021. const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set([(rgb[0] + x) & 255, (rgb[1] + y) & 255, rgb[2]], y * (w * 3 + 1) + 1 + x * 3);
  1022. return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
  1023. };
  1024. const FD = join(SCRATCH, 'gate-files');
  1025. rmSync(FD, { recursive: true, force: true });
  1026. mkdirSync(FD, { recursive: true });
  1027. const F = (n) => join(FD, n);
  1028. writeFileSync(F('phone-390.png'), png(390, 640, [30, 90, 160]));
  1029. writeFileSync(F('desktop-1280.png'), png(1280, 720, [160, 60, 30]));
  1030. writeFileSync(F('api-shot.png'), png(200, 120, [10, 200, 90]));
  1031. writeFileSync(F('huge.bin'), Buffer.alloc(11 * 1048576, 3));
  1032. const ATT_DIR = join(STORE, 'attachments');
  1033. const storedFiles = () => existsSync(ATT_DIR) ? readdirSync(ATT_DIR).filter(n => !n.startsWith('.')).length : 0;
  1034. // the API with a multipart body (what a conductor's script does: curl -F / fetch FormData)
  1035. const apiFiles = async (path, text, files, token = TOKEN) => {
  1036. const fd = new FormData();
  1037. if (text !== null) fd.append('text', text);
  1038. for (const [name, buf, type] of files) fd.append('file', new Blob([buf], { type: type || 'application/octet-stream' }), name);
  1039. const r = await fetch(BASE + path, { method: 'POST', headers: token ? { authorization: 'Bearer ' + token } : {}, body: fd });
  1040. let json = null; try { json = await r.json(); } catch {}
  1041. return { status: r.status, json };
  1042. };
  1043. const getFile = async (url, headers = {}) => { const r = await fetch(BASE + url, { headers }); return { status: r.status, type: r.headers.get('content-type'), nosniff: r.headers.get('x-content-type-options'), csp: r.headers.get('content-security-policy') || '', disp: r.headers.get('content-disposition') || '', buf: Buffer.from(await r.arrayBuffer()) }; };
  1044. const atT = await api('POST', `/api/projects/${CB}/tickets`, { subject: 'Screenshots for the review' });
  1045. const AT = atT.json && atT.json.ticket ? atT.json.ticket : {};
  1046. const ATURL = '/' + CB + '/' + (AT.number || 2);
  1047. const ATP = PT(CB, AT.number || 2);
  1048. // 1. THE API: a PNG through multipart, as a conductor posts a screenshot
  1049. const stored0 = storedFiles();
  1050. const viaApi = await apiFiles(ATP + '/comments', 'The phone view, from a script', [['api-shot.png', readFileSync(F('api-shot.png')), 'image/png']]);
  1051. const apiAtt = viaApi.json && viaApi.json.event && viaApi.json.event.attachments ? viaApi.json.event.attachments : [];
  1052. check('m017: API — POST …/comments as multipart (text + a PNG) → 201; the event lists the attachment { id, name, type image/png, size, image, url }', viaApi.status === 201 && apiAtt.length === 1 && apiAtt[0].name === 'api-shot.png' && apiAtt[0].type === 'image/png' && apiAtt[0].image === true && apiAtt[0].size === readFileSync(F('api-shot.png')).length && /^\/api\/attachments\/\w+$/.test(apiAtt[0].url || '') && viaApi.json.event.text === 'The phone view, from a script' && storedFiles() === stored0 + 1, J(viaApi).slice(0, 500));
  1053. const apiUrl = apiAtt.length ? apiAtt[0].url : '/api/attachments/none';
  1054. const dl = await getFile(apiUrl, { authorization: 'Bearer ' + TOKEN });
  1055. check('m017: API — GET the attachment with the token: 200, Content-Type image/png (from its content), nosniff, a sandbox policy, inline, the same bytes', dl.status === 200 && dl.type === 'image/png' && dl.nosniff === 'nosniff' && /sandbox/.test(dl.csp) && /^inline; filename="api-shot.png"/.test(dl.disp) && dl.buf.equals(readFileSync(F('api-shot.png'))), J([dl.status, dl.type, dl.nosniff, dl.csp, dl.disp, dl.buf.length]));
  1056. const getAgain = (await api('GET', ATP)).json;
  1057. const apiEv = getAgain && getAgain.events ? getAgain.events.find(e => e.id === (viaApi.json && viaApi.json.event ? viaApi.json.event.id : '')) : null;
  1058. check('m017: API — GET the ticket returns the attachment list with its URL', !!apiEv && J(apiEv.attachments) === J(apiAtt), J(apiEv).slice(0, 400));
  1059. // refusals: a fake PNG, a file over 10 MB, more than 25 MB together, a bad field, a files-only post is fine
  1060. const fake = await apiFiles(ATP + '/comments', 'not a picture', [['fake.png', Buffer.from('this is text, not a PNG'), 'image/png']]);
  1061. const huge = await apiFiles(ATP + '/comments', 'too big', [['huge.bin', readFileSync(F('huge.bin'))]]);
  1062. const nine = Buffer.alloc(9 * 1048576, 5);
  1063. const tooMuch = await apiFiles(ATP + '/comments', 'three times 9 MB', [['a.bin', nine], ['b.bin', nine], ['c.bin', nine]]);
  1064. const badField = await (async () => { const fd = new FormData(); fd.append('text', 'x'); fd.append('subject', 'no'); const r = await fetch(BASE + ATP + '/comments', { method: 'POST', headers: { authorization: 'Bearer ' + TOKEN }, body: fd }); return { status: r.status, json: await r.json().catch(() => null) }; })();
  1065. const noTokenFiles = await apiFiles(ATP + '/comments', 'x', [['api-shot.png', readFileSync(F('api-shot.png')), 'image/png']], null);
  1066. check('m017: API refusals — a fake PNG 400 ("is not a PNG…"), 11 MB 413, 27 MB together 413, an unknown field 400, no token 401; nothing stored', fake.status === 400 && /fake\.png is not a PNG, JPEG, GIF or WebP picture/.test((fake.json || {}).error || '') && huge.status === 413 && tooMuch.status === 413 && badField.status === 400 && (badField.json || {}).field === 'subject' && noTokenFiles.status === 401 && storedFiles() === stored0 + 1, J([fake, huge, tooMuch, badField, noTokenFiles].map(r => [r.status, r.json])).slice(0, 700));
  1067. const onlyFile = await apiFiles(ATP + '/comments', null, [['notes.txt', Buffer.from('plain words\n')]]);
  1068. check('m017: API — a post with a file and no text is fine (201): a text file, served as a download (text/plain, attachment)', onlyFile.status === 201 && onlyFile.json.event.hasText === false && onlyFile.json.event.attachments[0].image === false && /^text\/plain/.test((await getFile(onlyFile.json.event.attachments[0].url, { authorization: 'Bearer ' + TOKEN })).type) && /^attachment;/.test((await getFile(onlyFile.json.event.attachments[0].url, { authorization: 'Bearer ' + TOKEN })).disp), J(onlyFile).slice(0, 400));
  1069. const jsonStill = await api('POST', ATP + '/comments', { text: 'a JSON comment as before' });
  1070. check('m017: API — a JSON comment works as before and carries no attachments key', jsonStill.status === 201 && jsonStill.json.event.attachments === undefined && jsonStill.json.event.text === 'a JSON comment as before', J(jsonStill).slice(0, 300));
  1071. // 2. THE PAGE: A (alice) chooses two pictures, pastes a third into the editor (real Ctrl+V), types, Ctrl+Enter; B (bob) watches
  1072. await A.conn.send('Browser.grantPermissions', { origin: BASE, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'] }).catch(() => {});
  1073. await b.goto(BASE + ATURL);
  1074. await b.waitForSelector('#events li.comment');
  1075. await connected(b, 'B on the attachments ticket');
  1076. await b.evaluate('window.__m017 = 1');
  1077. await a.goto(BASE + ATURL);
  1078. await a.waitForSelector('#commentform form.comment-form');
  1079. await connected(a, 'A on the attachments ticket');
  1080. await a.waitFor(`[...document.querySelectorAll('#events ul.comment-files img')].length >= 1 && [...document.querySelectorAll('#events ul.comment-files img')].every(i => i.complete && i.naturalWidth > 0)`, { label: 'A: the API picture drawn' }).catch(() => {});
  1081. check('m017: page — the API\'s picture shows as a drawn thumbnail (200 px) for a member, the text file as a row', (await a.evaluate(`(() => { const i = document.querySelector('#events ul.comment-files img'); return i ? i.naturalWidth : 0; })()`)) === 200 && (await a.evaluate(`[...document.querySelectorAll('#events a.comment-file .name')].map(n => n.textContent).join()`)) === 'notes.txt');
  1082. const chooseOn = async (page, names) => {
  1083. const { root } = await page.send('DOM.getDocument');
  1084. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: '#commentform files-upload label.choose input[type=file]' });
  1085. try { await page.send('DOM.setFileInputFiles', { files: names.map(F), nodeId }); } catch {}
  1086. };
  1087. const pickedOn = (page) => page.evaluate(`[...document.querySelectorAll('#commentform files-upload li.picked')].map(li => li.querySelector('.name').textContent + ':' + (li.querySelector('img.thumb') ? li.querySelector('img.thumb').naturalWidth : 'kind'))`);
  1088. await chooseOn(a, ['phone-390.png', 'desktop-1280.png']);
  1089. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 2 && [...document.querySelectorAll('#commentform files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { label: 'A: two chosen' }).catch(() => {});
  1090. await mdShows(a, '#commentform md-editor article', '', 'A: the comment editor is live').catch(() => {});
  1091. await a.click('#commentform md-editor article').catch(() => {});
  1092. await realKeys(a, 'Review shots: phone, desktop and a paste');
  1093. const put = await a.evaluate(`(async () => { try { const c = document.createElement('canvas'); c.width = 160; c.height = 100; const x = c.getContext('2d'); x.fillStyle = '#246'; x.fillRect(0, 0, 160, 100); const bl = await new Promise(r => c.toBlob(r, 'image/png')); await navigator.clipboard.write([new ClipboardItem({ 'image/png': bl })]); return 'ok'; } catch (e) { return 'ERR ' + e.message; } })()`);
  1094. await a.send('Page.bringToFront');
  1095. await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, commands: ['paste'] });
  1096. await a.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86 });
  1097. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 3 && [...document.querySelectorAll('#commentform files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { label: 'A: pasted' }).catch(() => {});
  1098. const pk = await pickedOn(a);
  1099. check('m017: page — two chosen pictures + a real Ctrl+V into the comment editor wait as three drawn thumbnails; the editor holds only the text', put === 'ok' && J(pk) === J(['phone-390.png:390', 'desktop-1280.png:1280', 'image.png:160']) && (await a.evaluate(`document.querySelector('#commentform md-editor input.value').value`)) === 'Review shots: phone, desktop and a paste', put + ' ' + J(pk));
  1100. // a file over 10 MB is refused in its own row before anything is sent
  1101. await chooseOn(a, ['huge.bin']);
  1102. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.refused').length === 1`, { label: 'A: refused' }).catch(() => {});
  1103. check('m017: page — an 11 MB file is refused in its row ("Too big — at most 10.0 MB"), the three pictures stay', (await a.evaluate(`[...document.querySelectorAll('#commentform files-upload li.refused .state')].map(s => s.textContent).join()`)) === 'Too big — at most 10.0 MB' && (await pickedOn(a)).length === 3);
  1104. const before = storedFiles();
  1105. await a.click('#commentform md-editor article').catch(() => {});
  1106. await ctrlEnter(a);
  1107. await a.waitFor(`document.querySelectorAll('#commentform files-upload li').length === 0 && [...document.querySelectorAll('#events li.comment')].some(li => li.querySelectorAll('ul.comment-files img').length === 3)`, { timeout: 30000, label: 'A: posted with three' }).catch(() => {});
  1108. const st = (await api('GET', ATP)).json;
  1109. const shotC = st && st.events ? st.events.filter(e => e.kind === 'comment').pop() : null;
  1110. check('m017: page — Ctrl+Enter sends text + the three pictures as ONE comment of alice; stored in order (390, 1280, the paste), the form empty again', !!shotC && shotC.author === 'alice' && shotC.text === 'Review shots: phone, desktop and a paste' && J((shotC.attachments || []).map(x => [x.name, x.type])) === J([['phone-390.png', 'image/png'], ['desktop-1280.png', 'image/png'], ['image.png', 'image/png']]) && storedFiles() === before + 3 && (await a.evaluate(`document.querySelectorAll('#commentform files-upload li').length`)) === 0, J(shotC).slice(0, 500));
  1111. // B sees them live (no reload) and opens one full size
  1112. await b.waitFor(`!!document.querySelector('li.comment[data-id="${shotC ? shotC.id : 'x'}"]') && document.querySelectorAll('li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files img').length === 3 && [...document.querySelectorAll('li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files img')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 20000, label: 'B: three thumbnails live' }).catch(() => {});
  1113. const bThumbs = await b.evaluate(`[...document.querySelectorAll('li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files img')].map(i => i.naturalWidth)`);
  1114. check('m017: B (a second user) sees the three thumbnails live, drawn (390, 1280, 160 px wide), without a reload', (await b.evaluate('window.__m017')) === 1 && J(bThumbs) === J([390, 1280, 160]), J(bThumbs));
  1115. const firstUrl = shotC && shotC.attachments ? shotC.attachments[1].url : '/none';
  1116. const tabs0 = (await B.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length;
  1117. await b.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files li:nth-child(2) a.comment-thumb`).catch(() => {});
  1118. let opened = null;
  1119. for (let i = 0; i < 40 && !opened; i++) { await sleep(250); opened = (await B.conn.send('Target.getTargets')).targetInfos.find(t => t.type === 'page' && t.url === BASE + firstUrl); }
  1120. check('m017: B — a click on a thumbnail opens the full picture in a new tab', !!opened && (await B.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length === tabs0 + 1, J(opened));
  1121. if (opened) await B.conn.send('Target.closeTarget', { targetId: opened.targetId }).catch(() => {});
  1122. const bobFull = await getFile(firstUrl, { cookie: bobCookie });
  1123. check('m017: B — the full picture (bob\'s session, a member): 200 image/png, the 1280 × 720 file byte for byte', bobFull.status === 200 && bobFull.type === 'image/png' && bobFull.buf.equals(readFileSync(F('desktop-1280.png'))), J([bobFull.status, bobFull.type, bobFull.buf.length]));
  1124. // 3. A NON-MEMBER cannot fetch: a project bob is not in, a picture posted there
  1125. const prv = await api('POST', '/api/projects', { title: 'Attachments private' });
  1126. const PRV = prv.json && prv.json.project ? prv.json.project.slug : 'attachments-private';
  1127. await api('POST', `/api/projects/${PRV}/tickets`, { subject: 'Members only' });
  1128. const prvPost = await apiFiles(PT(PRV, 1) + '/comments', 'a private screenshot', [['private.png', readFileSync(F('api-shot.png')), 'image/png']]);
  1129. const prvUrl = prvPost.json && prvPost.json.event && prvPost.json.event.attachments ? prvPost.json.event.attachments[0].url : '/api/attachments/none';
  1130. const nm = [await getFile(prvUrl), await getFile(prvUrl, { cookie: bobCookie }), await getFile(prvUrl, { authorization: 'Bearer ' + bobTok }), await getFile(prvUrl, { authorization: 'Bearer ' + TOKEN }), await getFile('/api/attachments/zzzzzzzzzzzz', { authorization: 'Bearer ' + TOKEN })];
  1131. check('m017: a non-member cannot fetch an attachment — no login 401, bob\'s session 403, bob\'s token 403; a member 200; unknown 404', prvPost.status === 201 && J(nm.map(r => r.status)) === J([401, 403, 403, 200, 404]) && !nm[1].buf.includes(Buffer.from([137, 80, 78, 71])), J(nm.map(r => [r.status, r.type])));
  1132. await b.goto(BASE + '/' + PRV + '/1');
  1133. await b.waitForSelector('#events li.comment');
  1134. await connected(b, 'B on the private ticket');
  1135. await sleep(500);
  1136. check('m017: a non-member\'s page shows the file\'s name and size but no thumbnail and no link', (await b.evaluate(`!document.querySelector('#events ul.comment-files img') && !document.querySelector('#events ul.comment-files a') && document.querySelector('#events ul.comment-files span.comment-file .name').textContent === 'private.png'`)), await b.evaluate(`(document.querySelector('#events ul.comment-files') || {}).outerHTML`));
  1137. const nmFace = await temit('commentWithFiles', [AT.id || '', 'x', []], bobCookie);
  1138. const prvT = (await api('GET', PT(PRV, 1))).json.ticket;
  1139. const nmFace2 = await temit('commentWithFiles', [prvT ? prvT.id : '', 'bob is no member', []], bobCookie);
  1140. check('m017: the face commentWithFiles refuses a non-member (bob\'s own session)', !!nmFace2.value && /member/.test(nmFace2.value.error || ''), J([nmFace.raw, nmFace2.raw]));
  1141. // 4. EDIT keeps the files, DELETE drops them
  1142. const edit = await api('POST', `${ATP}/comments/${viaApi.json && viaApi.json.event ? viaApi.json.event.id : 'x'}/edit`, { text: 'The phone view, from a script (edited)' });
  1143. check('m017: an edit keeps the attachments (same list, the file still served)', edit.status === 200 && J(edit.json.event.attachments) === J(apiAtt) && (await getFile(apiUrl, { authorization: 'Bearer ' + TOKEN })).status === 200, J(edit).slice(0, 300));
  1144. const n0 = storedFiles();
  1145. await sleep(1000);
  1146. await a.waitForSelector(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete`).catch(() => {});
  1147. await a.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete`).catch(() => {});
  1148. await a.waitForSelector(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete-yes`).catch(() => {});
  1149. await a.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete-yes`).catch(() => {});
  1150. await a.waitFor(`!document.querySelector('li.comment[data-id="${shotC ? shotC.id : 'x'}"]')`, { label: 'A: deleted' }).catch(() => {});
  1151. const goneEv = (await api('GET', ATP)).json.events.find(e => e.id === (shotC ? shotC.id : ''));
  1152. check('m017: a delete drops the files: no attachments in the API, the addresses answer 404, the three files left storage', !!goneEv && goneEv.deleted === true && goneEv.attachments === undefined && (await getFile(firstUrl, { cookie: aliceCookie })).status === 404 && storedFiles() === n0 - 3, J([goneEv, storedFiles(), n0]).slice(0, 300));
  1153. const md = await (await fetch(BASE + ATP, { headers: { accept: 'text/markdown' } })).text();
  1154. check('m017: the Markdown view lists a comment\'s files with their addresses', md.includes('Attachments:') && md.includes(`- [api-shot.png](${BASE}${apiUrl}) · image/png · `) && !md.includes('phone-390.png'), md.slice(-600));
  1155. // 5. 390 px: the form with picked files and the thumbnails; touch targets ≥ 44 px, nothing wider than the screen
  1156. await b.goto(BASE + ATURL);
  1157. await b.waitForSelector('#commentform form.comment-form');
  1158. await connected(b, 'B on the attachments ticket again');
  1159. await b.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1160. await b.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  1161. await sleep(300);
  1162. await chooseOn(b, ['phone-390.png', 'huge.bin']);
  1163. await b.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 1 && document.querySelectorAll('#commentform files-upload li.refused').length === 1`, { label: 'B phone picked' }).catch(() => {});
  1164. await sleep(400);
  1165. const targets = await b.evaluate(`[...document.querySelectorAll('#events a.comment-thumb, #events a.comment-file, #commentform files-upload label.choose, #commentform files-upload label.camera, #commentform files-upload button.remove, #commentform button.comment-post')].map(el => { const r = el.getBoundingClientRect(); return el.className + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); })`);
  1166. check('m017 390px: every attachment target is at least 44 × 44 px (thumbnails, file rows, Choose files, Camera, ✕, Comment)', targets.length >= 7 && targets.every(t => { const [w, h] = t.split(' ').pop().split('x').map(Number); return w >= 44 && h >= 44; }), J(targets));
  1167. check('m017 390px: no horizontal overflow with thumbnails, picked files and a refused row', await noOverflow(b) && (await b.evaluate(`[...document.querySelectorAll('#events ul.comment-files li, #commentform files-upload li')].every(li => li.getBoundingClientRect().right <= window.innerWidth)`)));
  1168. await shot(b, 'phone-attachments');
  1169. await b.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  1170. await viewport(b, 1280, 900);
  1171. await shot(b, 'desktop-attachments');
  1172. check('m017: no console errors on the attachment pages (A and B)', [a, b].every(p => p.problems().filter(m => !/favicon/.test(m.text)).length === 0), a.dumpConsole().slice(-600) + ' | ' + b.dumpConsole().slice(-600));
  1173. }
  1174. // a new project by hand: title → slug proposed, admin can change it; old slugs keep working
  1175. await a.goto(BASE + '/new-project');
  1176. await a.waitForSelector('#projectform');
  1177. await connected(a, 'A on /new-project');
  1178. await type(a, '#projecttitle', 'My Project');
  1179. await a.waitFor('document.querySelector("#projectslug").value === "my-project"', { label: 'slug proposed' });
  1180. check('project: the slug my-project is proposed from the title', (await a.evaluate('document.querySelector("#projectslug").value')) === 'my-project');
  1181. await a.click('#projectcreate');
  1182. await a.waitForSelector('#created');
  1183. const mp = await api('GET', '/api/projects/my-project');
  1184. check('project: created; alice is its first admin; it has no tickets', mp.status === 200 && mp.json.project.title === 'My Project' && J(mp.json.members.map(m => [m.name, m.role])) === J([['alice', 'admin']]), J(mp.json).slice(0, 400));
  1185. await a.goto(BASE + '/projects/my-project/settings');
  1186. await a.waitForSelector('#detailsform');
  1187. await connected(a, 'A on settings');
  1188. await type(a, '#setslug', 'my-proj');
  1189. await type(a, '#setdescription md-editor input.value', 'The **first** project.');
  1190. await a.click('#detailssave');
  1191. await a.waitFor('!!document.querySelector("#savemessage") && document.querySelector("#savemessage").textContent.length > 0', { label: 'saved' });
  1192. const mp2 = await api('GET', '/api/projects/my-proj');
  1193. const mpOld = await api('GET', '/api/projects/my-project');
  1194. check('project: the slug changed, the description is kept, the old slug still resolves', mp2.status === 200 && mp2.json.project.description === 'The **first** project.' && mpOld.status === 200 && mpOld.json.project.slug === 'my-proj', J([mp2.json.project, mpOld.status]).slice(0, 400));
  1195. const oldSlugMoved = await fetch(BASE + '/projects/my-project', { redirect: 'manual' });
  1196. check('short (#25): /projects/<old slug> → 301 to /<current slug>', oldSlugMoved.status === 301 && oldSlugMoved.headers.get('location') === '/my-proj', oldSlugMoved.status + ' ' + oldSlugMoved.headers.get('location'));
  1197. await a.goto(BASE + '/my-project');
  1198. await a.waitForSelector('#heading');
  1199. check('project: the old address still opens the project page', (await a.text('#heading')) === 'My Project' || (await a.text('#heading')).includes('My Project'), await a.text('#heading'));
  1200. // members in the settings page: add bob as use; remove; the last admin cannot go
  1201. await a.goto(BASE + '/projects/my-proj/settings');
  1202. await a.waitForSelector('#addform');
  1203. await connected(a, 'A on settings again');
  1204. await type(a, '#addref', 'bob');
  1205. await choose(a, '#addrole', 'use');
  1206. await a.click('#addsave');
  1207. await a.waitFor('document.querySelectorAll("#members li").length === 2', { label: 'bob added' });
  1208. await sleep(600);
  1209. check('once: the settings page lists bob exactly once (2 members)', (await texts(a, '#members li')).length === 2 && (await texts(a, '#members li .membername')).filter(t => t === 'bob').length === 1, J(await texts(a, '#members li')));
  1210. check('members: bob added as use in the settings page', J((await api('GET', '/api/projects/my-proj')).json.members.map(m => [m.name, m.role])) === J([['alice', 'admin'], ['bob', 'use']]));
  1211. const lastAdmin = await api('POST', '/api/projects/my-proj/members', { user: 'alice', role: 'use' }, aliceTok0);
  1212. check('members: the last admin cannot be demoted (400)', lastAdmin.status === 400 && /at least one admin/.test(lastAdmin.json.error), J(lastAdmin));
  1213. const badRole = await api('POST', '/api/projects/my-proj/members', { user: 'bob', role: 'boss' }, aliceTok0);
  1214. check('members: an unknown role is refused (400)', badRole.status === 400 && badRole.json.field === 'role', J(badRole));
  1215. const rm = await api('POST', '/api/projects/my-proj/members/remove', { user: 'bob' }, aliceTok0);
  1216. check('members: an admin removes a member (200)', rm.status === 200 && rm.json.members.length === 1, J(rm).slice(0, 300));
  1217. // an invite link through ident
  1218. const inv = await api('POST', '/api/projects/my-proj/invites', { role: 'use' }, aliceTok0);
  1219. check('invite: an admin gets an ident invite link for the role use', inv.status === 201 && /^https?:\/\//.test(inv.json.url || ''), J(inv).slice(0, 400));
  1220. // carol opens the link, chooses her identity at ident → ident sends her back to tickets with the invite id → she is a member
  1221. const carol = await ident.signIn('[email protected]');
  1222. const invPage = await fetch(inv.json.url, { redirect: 'manual' });
  1223. const rid = (invPage.headers.get('location') || '').split('/').pop();
  1224. const chosen = await ident.emit('chooseIdentity', [rid, carol.identities[0].id], carol.cookie);
  1225. const back = chosen.value && chosen.value.url ? await fetch(chosen.value.url.replace(/^https?:\/\/[^/]+/, BASE), { redirect: 'manual' }) : { status: 0, headers: new Headers() };
  1226. const carolCookie = (back.headers.get('set-cookie') || '').split(';')[0];
  1227. const carolFace = await temit('saveDisplayName', ['carol'], carolCookie);
  1228. const mp3 = (await api('GET', '/api/projects/my-proj')).json;
  1229. check('invite: carol follows the link, picks an identity at ident, is sent back → member with the role use', invPage.status === 302 && back.status === 302 && J(mp3.members.map(m => [m.name, m.role]).filter(x => x[0] === 'carol' || x[1] === 'use')) === J([['carol', 'use']]), J([invPage.status, chosen.raw.slice(0, 200), back.status, mp3.members]).slice(0, 600));
  1230. const invBob = await api('POST', '/api/projects/my-proj/invites', { role: 'use' }, bobTok);
  1231. check('invite: a non-admin gets 403', invBob.status === 403, J(invBob).slice(0, 200));
  1232. // the new pages fit the screen (phone and desktop), with the project's data on them
  1233. for (const [path, sel, name] of [['/projects/my-proj/settings', '#addform', 'settings'], ['/new-project', '#projectform', 'new-project'], ['/my-proj', '#heading', 'project']]) {
  1234. await a.goto(BASE + path);
  1235. await a.waitForSelector(sel);
  1236. await connected(a, 'A on ' + path);
  1237. for (const [w, h, dev] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  1238. await viewport(a, w, h);
  1239. check(`layout ${dev} ${w}px: ${name} page has no horizontal overflow`, await noOverflow(a));
  1240. await shot(a, `${dev}-${name}`);
  1241. }
  1242. }
  1243. await viewport(a, 1280, 900);
  1244. await b.goto(BASE + '/inbox');
  1245. await b.waitForSelector('#pendingbox');
  1246. for (const [w, h, dev] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  1247. await viewport(b, w, h);
  1248. check(`layout ${dev} ${w}px: inbox page has no horizontal overflow`, await noOverflow(b));
  1249. }
  1250. await viewport(b, 1280, 900);
  1251. // ---- ticket #25 (mission 012): /api/projects/<project id>/… answers as /api/projects/<slug>/… (every route under it);
  1252. // tickets stay under their project, there is no new global /api/tickets/<x>
  1253. const rawGet = async (path, md = false) => { const r = await fetch(BASE + path, { headers: md ? { accept: 'text/markdown' } : {} }); return r.status + ' ' + (r.headers.get('content-type') || '') + '\n' + await r.text(); };
  1254. const idOf = async (slug) => (await api('GET', '/api/projects')).json.details.find(p => p.slug === slug).id;
  1255. const gammaId = await idOf('gamma');
  1256. check(`ids (#25): a project's id is its 12-character record id (gamma = ${gammaId})`, /^[0-9a-z]{12}$/.test(gammaId || ''), J(gammaId));
  1257. for (const [byId, bySlug, md] of [[`/api/projects/${gammaId}`, '/api/projects/gamma', false], [`/api/projects/${gammaId}/tickets`, '/api/projects/gamma/tickets', false], [`/api/projects/${gammaId}/tickets`, '/api/projects/gamma/tickets', true], [`/api/projects/${gammaId}/tickets?state=open`, '/api/projects/gamma/tickets?state=open', false], [`/api/projects/${gammaId}/tickets?state=bogus`, '/api/projects/gamma/tickets?state=bogus', false], [`/api/projects/${gammaId}/tickets/1`, '/api/projects/gamma/tickets/1', false], [`/api/projects/${gammaId}/tickets/1`, '/api/projects/gamma/tickets/1', true], [`/api/projects/${gammaId}/tickets/99`, '/api/projects/gamma/tickets/99', false], [`/api/projects/${gammaId}/connections`, '/api/projects/gamma/connections', false]]) {
  1258. const [x, y] = [await rawGet(byId, md), await rawGet(bySlug, md)];
  1259. check(`ids (#25): GET ${byId.replace(gammaId, '<id>')}${md ? ' (Markdown)' : ''} answers byte for byte as the slug form`, x === y && /^(200|404|400) /.test(x), J([x.slice(0, 200), y.slice(0, 200)]));
  1260. }
  1261. for (const p of ['/api/projects/0zzzzzzzzzzz', '/api/projects/0zzzzzzzzzzz/tickets', '/api/projects/0zzzzzzzzzzz/tickets/1', '/api/projects/0zzzzzzzzzzz/connections']) {
  1262. const r = await api('GET', p);
  1263. check(`ids (#25): GET ${p} (no such id) → 404`, r.status === 404, J(r));
  1264. }
  1265. const glob = await api('GET', '/api/tickets/' + gammaId);
  1266. check('ids (#25): no global /api/tickets/<project id> (→ 404, as before)', glob.status === 404, J(glob).slice(0, 200));
  1267. // every write route under /api/projects/<id>/… on a project of its own
  1268. const dp = await api('POST', '/api/projects', { title: 'Delta by id', slug: 'delta' });
  1269. const did = dp.json && dp.json.project ? dp.json.project.id : null;
  1270. const P = (rest) => `/api/projects/${did}${rest}`;
  1271. const dt = await api('POST', P('/tickets'), { subject: 'made by id' });
  1272. check('ids (#25): POST /api/projects/<id>/tickets → 201 in that project, #1', dp.status === 201 && dt.status === 201 && dt.json.ticket.project === 'delta' && dt.json.ticket.number === 1, J([dp.status, dt]).slice(0, 300));
  1273. const dWrites = [
  1274. ['comments', await api('POST', P('/tickets/1/comments'), { text: 'comment by id' })],
  1275. ['state', await api('POST', P('/tickets/1/state'), { state: 'progress' })],
  1276. ['edit', await api('POST', P('/tickets/1/edit'), { subject: 'made by id, edited' })],
  1277. ['assign', await api('POST', P('/tickets/1/assign'), { assignee: 'gate' })],
  1278. ['parent', await api('POST', P('/tickets/1/parent'), { parent: 'gamma#1' })],
  1279. ['blocked-by', await api('POST', P('/tickets/1/blocked-by'), { add: 'gamma#2' })],
  1280. ];
  1281. check('ids (#25): POST /api/projects/<id>/tickets/1/{comments,state,edit,assign,parent,blocked-by} → 201 each', dWrites.every(([, r]) => r.status === 201), J(dWrites.map(([k, r]) => [k, r.status, r.json && r.json.error])));
  1282. const dRead = (await api('GET', '/api/projects/delta/tickets/1')).json;
  1283. check('ids (#25): … and the slug form reads what they wrote', dRead.ticket.subject === 'made by id, edited' && dRead.ticket.state === 'progress' && dRead.ticket.assignee === 'gate' && dRead.ticket.parent && dRead.ticket.parent.key === 'gamma#1' && dRead.ticket.blockedBy.length === 1 && dRead.events.some(e => e.text === 'comment by id'), J(dRead.ticket).slice(0, 500));
  1284. const dDesc = await api('POST', P(''), { description: 'set by id' });
  1285. const dMem = await api('POST', P('/members'), { user: 'bob', role: 'use' });
  1286. const dRm = await api('POST', P('/members/remove'), { user: 'bob' });
  1287. const dInv = await api('POST', P('/invites'), { role: 'boss' });
  1288. const dDis = await api('POST', P('/connections/remove'), { id: 'nope' });
  1289. check('ids (#25): POST /api/projects/<id> (200), /members (200), /members/remove (200); /invites with a bad role and /connections/remove of an unknown key are refused by the PROJECT\'s checks (400, not 404)', dDesc.status === 200 && dDesc.json.project.description === 'set by id' && dMem.status === 200 && dRm.status === 200 && dInv.status === 400 && dInv.json.field === 'role' && dDis.status === 400, J([dDesc.status, dMem.status, dRm.status, dInv, dDis]).slice(0, 500));
  1290. const zz = await api('POST', '/api/projects/0zzzzzzzzzzz/tickets', { subject: 'nowhere' });
  1291. check('ids (#25): POST to an unknown id → refused, nothing made', zz.status >= 400 && zz.status < 500, J(zz));
  1292. // the id survives a slug change; the old slug, the new one and the id answer the same
  1293. await api('POST', P(''), { slug: 'delta2' });
  1294. const [vId, vNew, vOld] = [await rawGet(P('/tickets/1')), await rawGet('/api/projects/delta2/tickets/1'), await rawGet('/api/projects/delta/tickets/1')];
  1295. check('ids (#25): after a slug change the id, the new slug and the old slug answer the same ticket', vId === vNew && vNew === vOld && vId.startsWith('200 ') && vId.includes('"project":"delta2"'), J([vId.slice(0, 120), vOld.slice(0, 120)]));
  1296. check('ids (#25): GET /api/projects/<id> after the slug change → the project with its current slug', (await api('GET', P(''))).json.project.slug === 'delta2');
  1297. // ---- the browsers said nothing bad (checked BEFORE ident goes down, ticket #11) ------------------
  1298. const problems = [...a.problems(), ...b.problems()].map(m => m.text).filter(t => !/favicon/.test(t));
  1299. check('console: no errors or warnings in either browser', problems.length === 0, J(problems).slice(0, 800));
  1300. // ---- ident down: a login fails politely, the server keeps serving ----------------------------
  1301. // TICKET #11: no page may be loading while ident stops (a tickets page loads ident's
  1302. // selector.js → ERR_CONNECTION_REFUSED in the console). Both browsers park on about:blank
  1303. // first and stay there; the phase is checked with fetch only, and the console again after.
  1304. for (const p of [a, b]) { await p.goto('about:blank'); }
  1305. await sleep(300);
  1306. const quietBefore = [...a.problems(), ...b.problems()].length;
  1307. await ident.stop();
  1308. const down = await fetch(BASE + '/login/callback?ident_code=' + 'cd'.repeat(24), { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  1309. const downText = await down.text();
  1310. const downFace = await temit('identLogin', ['cd'.repeat(24)], GATE_COOKIE);
  1311. check('ident down: /login/callback → 400 "ident did not answer" (no 500, no source path)', down.status === 400 && /ident did not answer/.test(downText) && !/\.hl/.test(downText), down.status + ' ' + downText.slice(0, 300));
  1312. check('ident down: the selector face answers "ident did not answer", the server keeps serving', downFace.value && downFace.value.error === 'ident did not answer' && (await fetch(BASE + '/')).status === 200, downFace.raw);
  1313. const lateProblems = [...a.problems(), ...b.problems()].slice(quietBefore).map(m => m.text);
  1314. check('console: nothing new while ident was down (the browsers were parked, #11)', lateProblems.length === 0, J(lateProblems).slice(0, 800));
  1315. // ---- THE INSTALLABLE APP (mission 046): manifest, icons, service worker, offline shell ----------------
  1316. // Its own fresh Chrome C (no worker from A/B), at the END because it stops the server: the offline reload must
  1317. // not reach the server even through the service worker (the CDP offline emulation is the page's, and it is what
  1318. // makes navigator.onLine false for the shell's note). ident is already down here (its selector.js fails to load).
  1319. const home = await (await fetch(BASE + '/')).text();
  1320. const mhref = (home.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1321. check('pwa: the page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header darker)', !!mhref && /<link rel="apple-touch-icon" href="\/icons\/apple-touch-icon.png">/.test(home) && /<link rel="icon" href="\/icons\/icon.svg">/.test(home) && /<meta name="theme-color" content="rgb\(15, 20, 25\)">/.test(home), J([mhref, (home.match(/<link rel="(icon|apple-touch-icon)"[^>]*>|<meta name="theme-color"[^>]*>/g) || [])]));
  1322. const mres = await fetch(BASE + (mhref || '/__hl/manifest.webmanifest'));
  1323. let man = {}; try { man = await mres.json(); } catch {}
  1324. check('pwa: the manifest is served as a web manifest: name tickets, start_url /, display standalone, theme rgb(15, 20, 25)', /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'tickets' && man.start_url === '/' && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man).slice(0, 400));
  1325. const pngSize = async (src) => { const r = await fetch(BASE + src); const buf = Buffer.from(await r.arrayBuffer()); return r.ok && /image\/png/.test(r.headers.get('content-type') || '') && buf.readUInt32BE(0) === 0x89504e47 ? buf.readUInt32BE(16) : 0; };
  1326. const iconOk = [];
  1327. for (const ic of man.icons || []) iconOk.push(ic.type === 'image/png' && await pngSize(ic.src) === Number(ic.sizes.split('x')[0]));
  1328. check('pwa: every manifest icon is a real PNG of its declared size (192 and 512, any and maskable)', iconOk.length === 4 && iconOk.every(Boolean) && ['any', 'maskable'].every(p => (man.icons || []).some(i => i.sizes === '512x512' && i.purpose === p)), J(man.icons));
  1329. const fav = await fetch(BASE + '/favicon.ico');
  1330. const favBuf = Buffer.from(await fav.arrayBuffer());
  1331. const svg = await fetch(BASE + '/icons/icon.svg');
  1332. check('pwa: apple-touch-icon is a 180px PNG, /favicon.ico an icon file, /icons/icon.svg an SVG', await pngSize('/icons/apple-touch-icon.png') === 180 && fav.ok && /icon/.test(fav.headers.get('content-type') || '') && favBuf.readUInt32LE(0) === 0x00010000 && svg.ok && /svg/.test(svg.headers.get('content-type') || '') && /<svg/.test(await svg.text()));
  1333. // ---- mission MT (mobile audit 2026-10-23): what a designer sees at 390 px. Each check below FAILED on the code before the fix
  1334. // (the ticket number wrapped to "# / 2 / 6", two chip rows filled half the screen, fields stood beside their captions at their own
  1335. // width, the Edit button was a centred slab, 500 rows drawn at once, member names broke mid-word, relation links were 24 px high)
  1336. const bulkP = await api('POST', '/api/projects', { title: 'Bulk', slug: 'bulk-mt' }, aliceTok0);
  1337. for (let i = 1; i <= 60; i++) await api('POST', '/api/projects/bulk-mt/tickets', { subject: i === 60 ? 'Bulk ticket 60 with a very long subject ' + 'unbrokenwords'.repeat(8) : 'Bulk ticket ' + i }, aliceTok0);
  1338. check('mt: the bulk project has 60 tickets (setup)', bulkP.status === 201 && (await api('GET', '/api/projects/bulk-mt/tickets', undefined, aliceTok0)).json.tickets.length === 60, J(bulkP).slice(0, 200));
  1339. await viewport(a, 390, 844);
  1340. await a.goto(BASE + '/bulk-mt');
  1341. await a.waitForSelector('#tickets li');
  1342. await connected(a, 'A on /bulk-mt');
  1343. const mtRows = await a.evaluate(`document.querySelectorAll('#tickets li').length`);
  1344. check('mt (paging): the list draws the newest 50 of 60 tickets and a "Show 50 more (10 left)" button', mtRows === 50 && /Show 50 more \(10 left\)/.test(await a.text('#moretickets')), mtRows + ' ' + await a.evaluate(`(document.querySelector('#moretickets') || {}).textContent`));
  1345. const mtOrder = await a.evaluate(`[...document.querySelectorAll('#tickets li a.subject')].map(x => x.textContent.replace(/^#\\d+/, '').slice(0, 14))`);
  1346. check('mt (paging): the 50 rows are the NEWEST 50, newest first (Bulk ticket 60 … Bulk ticket 11)', mtOrder[0] === 'Bulk ticket 60' && mtOrder[1] === 'Bulk ticket 59' && mtOrder[49] === 'Bulk ticket 11', J([mtOrder[0], mtOrder[1], mtOrder[49]]));
  1347. const mtRefs = await a.evaluate(`[...document.querySelectorAll('#tickets li a.subject ticket-ref')].map(r => Math.round(r.getBoundingClientRect().height))`);
  1348. check('mt (list row): the ticket number stands on ONE line in front of the subject (never "# / 5 / 0" stacked) — 390 px, ≤ 30 px high', mtRefs.length === 50 && mtRefs.every(h => h <= 30), J(mtRefs));
  1349. const mtFilter = await a.evaluate(`(() => { const n = document.querySelector('#projectfilter'), s = document.querySelector('#statefilter'); const tops = (e) => new Set([...e.querySelectorAll('a')].map(x => Math.round(x.getBoundingClientRect().top))).size; return [tops(n), tops(s), Math.round(n.getBoundingClientRect().height), Math.round(s.getBoundingClientRect().height)]; })()`);
  1350. check('mt (filters): the project chips and the state chips are ONE row each at 390 px (they scroll inside their row, not wrap over half the screen)', mtFilter[0] === 1 && mtFilter[1] === 1 && mtFilter[2] <= 64 && mtFilter[3] <= 64, J(mtFilter));
  1351. const mtAct = await a.evaluate(`(() => { const x = document.querySelector('#newprojectlink'); return x ? getComputedStyle(x).backgroundColor : 'none'; })()`);
  1352. check('mt (actions): "New project" is a button with its own background, not loose text', !!mtAct && mtAct !== 'rgba(0, 0, 0, 0)' && mtAct !== 'none', mtAct);
  1353. await shot(a, 'mt-phone-bulk');
  1354. await a.click('#moretickets').catch(() => {});
  1355. await a.waitFor(`document.querySelectorAll('#tickets li').length === 60`, { label: 'all 60 rows after the click' }).catch(() => {});
  1356. check('mt (paging): a real click on "Show more" draws the other 10 (60 rows) and the button goes', (await a.evaluate(`document.querySelectorAll('#tickets li').length`)) === 60 && !(await a.evaluate(`!!document.querySelector('#moretickets')`)));
  1357. check('mt (long subject): a subject of unbroken words does not widen the phone page', await noOverflow(a));
  1358. const mtNew = await api('POST', '/api/projects/bulk-mt/tickets', { subject: 'Bulk ticket 61, arrives live' }, aliceTok0);
  1359. await a.waitFor(`document.querySelectorAll('#tickets li').length === 61`, { label: 'live row' }).catch(() => {});
  1360. check('mt (paging): with everything shown a new ticket arrives live at the top (61 rows, none cut off)', mtNew.status === 201 && (await a.evaluate(`document.querySelectorAll('#tickets li').length`)) === 61 && /Bulk ticket 61/.test(await a.evaluate(`document.querySelector('#tickets li a.subject').textContent`)));
  1361. // fields: the caption above, the field the full width of its form — settings (admin), the ticket's manage forms, new ticket, /you
  1362. const fullW = (sels) => `(() => { const out = []; for (const s of ${J(sels)}) { const e = document.querySelector(s); if (!e) { out.push(s + ' missing'); continue; } const fe = e.closest('form'), cs = getComputedStyle(fe), f = fe.getBoundingClientRect(), r = e.getBoundingClientRect(), inner = f.width - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight); if (r.width < inner - 2) out.push(s + ' ' + Math.round(r.width) + ' of ' + Math.round(f.width)); } return out; })()`;
  1363. await a.goto(BASE + '/projects/my-proj/settings');
  1364. await a.waitForSelector('#addform');
  1365. await connected(a, 'A on settings');
  1366. const mtSet = await a.evaluate(fullW(['#settitle', '#setslug', '#addref', '#addrole', '#inviterole', '#inviteuses', '#invitedays', '#inviteemail']));
  1367. check('mt (settings): every field is as wide as its form at 390 px (caption above, not beside it)', mtSet.length === 0, J(mtSet));
  1368. const mtNames = await a.evaluate(`[...document.querySelectorAll('#members .membername')].map(e => [e.textContent, Math.round(e.getBoundingClientRect().height), Math.round(e.getBoundingClientRect().width), Math.round(e.parentElement.getBoundingClientRect().width)])`);
  1369. check('mt (settings): a member name has the whole first line of its row, unbroken (no mid-word break "AntColonySche / duler")', mtNames.length > 0 && mtNames.every(([, h, w, lw]) => h <= 30 && w >= lw - 40), J(mtNames));
  1370. await shot(a, 'mt-phone-settings');
  1371. await a.goto(BASE + '/you');
  1372. await a.waitForSelector('#tokenform');
  1373. await connected(a, 'A on /you');
  1374. check('mt (you): the token label field is as wide as its form', (await a.evaluate(fullW(['#tokenlabel']))).length === 0, J(await a.evaluate(fullW(['#tokenlabel']))));
  1375. const mtPar = await api('POST', '/api/projects/bulk-mt/tickets/2/parent', { parent: 'bulk-mt#1' }, aliceTok0);
  1376. await a.goto(BASE + '/bulk-mt/2');
  1377. await a.waitForSelector('#subject');
  1378. await connected(a, 'A on the MT child ticket');
  1379. await a.waitFor(`!!document.querySelector('#parentkey') && !!document.querySelector('#parent a')`, { label: 'manage forms and the parent link' }).catch(() => {});
  1380. const mtMan = await a.evaluate(fullW(['#assignselect', '#parentkey', '#blockerkey', '#newstate']));
  1381. check('mt (ticket): the manage and state fields are as wide as their forms at 390 px', mtMan.length === 0, J(mtMan));
  1382. const mtEdit = await a.evaluate(`(() => { const e = document.querySelector('#editbutton'); return e ? Math.round(e.getBoundingClientRect().width) : -1; })()`);
  1383. check('mt (ticket): "Edit" is a normal button, not a slab across the whole page (≤ 160 px wide at 390)', mtEdit > 0 && mtEdit <= 160, String(mtEdit));
  1384. const mtRel = await a.evaluate(`[...document.querySelectorAll('#parent a, .refs a')].map(x => Math.round(x.getBoundingClientRect().height))`);
  1385. check('mt (relations): the links to the parent / children / blockers are 44 px targets', mtRel.length > 0 && mtRel.every(h => h >= 44), J(mtRel));
  1386. await shot(a, 'mt-phone-ticket');
  1387. await a.goto(BASE + '/bulk-mt');
  1388. await a.waitForSelector('#newticket');
  1389. await connected(a, 'A on bulk new ticket');
  1390. await a.click('#newticket summary');
  1391. await sleep(500);
  1392. const mtNewF = await a.evaluate(fullW(['#newproject', '#newsubject']));
  1393. check('mt (new ticket): project and subject fields are as wide as the form', mtNewF.length === 0, J(mtNewF));
  1394. await viewport(a, 1280, 900);
  1395. C = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_C, '8640-8649') });
  1396. const c = patient(await C.newPage());
  1397. await viewport(c, 390, 844);
  1398. await c.goto(BASE + '/');
  1399. await c.waitForSelector('#tickets li');
  1400. await connected(c, 'C connected');
  1401. await c.waitFor('navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))', { label: 'service worker active' });
  1402. await c.waitFor('!!navigator.serviceWorker.controller', { label: 'the worker controls the page' });
  1403. check('pwa: a service worker is registered for the whole app and controls the page', await c.evaluate(`navigator.serviceWorker.getRegistration().then(r => !!r && new URL(r.scope).pathname === '/' && /\\/__hl\\/sw\\.js/.test(r.active.scriptURL))`));
  1404. const inst = await c.send('Page.getInstallabilityErrors');
  1405. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  1406. // the list holds TOTAL + the one ticket made through /api/projects/<id>/tickets (mission 012) + mission 016's comments ticket + mission 017's attachments ticket + the 'Members only' ticket (reading a ticket is public; only its files are members-only)
  1407. const LISTED = Math.min(50, TOTAL + 4 + 61); // mission MT: the list draws 50 rows (+ "Show more") — the bulk project of the phone checks adds 61
  1408. const online = await c.evaluate(`[!!document.querySelector('#offline'), document.querySelectorAll('#tickets li').length]`);
  1409. check('pwa: online the shell shows no offline note', online[0] === false && online[1] === LISTED, J(online) + " expected " + LISTED + " TOTAL " + TOTAL);
  1410. const cProblems = c.problems().map(m => m.text).filter(t => !/favicon/.test(t) && !t.includes(':' + IDENT_PORT) && !/Failed to load resource/.test(t));
  1411. check('pwa: no console errors in the installed app (ident is down: its selector.js is not counted)', cProblems.length === 0, J(cProblems).slice(0, 600));
  1412. await sleep(1500);
  1413. await shot(c, 'pwa-phone-online');
  1414. // OFFLINE: the network of the page is cut AND the server is gone; `/` reloads from the worker's cache
  1415. await stopTickets();
  1416. await c.setOffline(true);
  1417. await c.goto(BASE + '/');
  1418. await c.waitForSelector('#tickets li');
  1419. await c.waitFor('!!document.querySelector("#offline")', { label: 'the offline note' });
  1420. const off = await c.evaluate(`[document.querySelector('application-header .brand').textContent, document.querySelector('#offline').textContent, document.querySelectorAll('#tickets li').length, getComputedStyle(document.querySelector('#offline')).display]`);
  1421. check('pwa: offline reload of / shows the shell (header), the last loaded list and says it is offline', off[0] === 'tickets' && /You are offline/.test(off[1]) && off[2] === LISTED && off[3] !== 'none', J(off));
  1422. await sleep(300);
  1423. await shot(c, 'pwa-phone-offline');
  1424. check('layout phone 390px: the offline shell has no horizontal overflow', await noOverflow(c));
  1425. await c.goto(BASE + '/inbox');
  1426. await c.waitForSelector('main[data-hl-offline]');
  1427. check('pwa: offline a page that is not kept (/inbox) gets "Unavailable offline"', /Unavailable offline/.test(await c.text('main')), await c.text('main'));
  1428. await c.goto(BASE + '/');
  1429. await c.waitForSelector('#offline');
  1430. await c.setOffline(false);
  1431. await c.waitFor('!document.querySelector("#offline")', { label: 'the note goes when the network is back' });
  1432. check('pwa: the offline note goes when the browser is online again', true);
  1433. } catch (e) {
  1434. check('gate ran to the end', false, e.stack || String(e));
  1435. } finally {
  1436. for (const br of [A, B, C]) { if (br) { try { await br.close(); } catch {} } }
  1437. await stopTickets();
  1438. if (ident) { await ident.stop(); writeFileSync(join(SCRATCH, 'gate-ident.log'), ident.log()); }
  1439. exchProxy.close();
  1440. writeFileSync(join(SCRATCH, 'gate-server.log'), log);
  1441. }
  1442. console.log(`\n${passes} passed, ${failures} failed`);
  1443. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 81f10e4eident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • f51029abMerge branch 'sy-sync'mre
  • eae6e8c7sync components.hybriel 4922f9c: comments like / Edit / Delete / 'edited' are 44 px targets; gate: 'edited' hit-area padding, thread targets check (SY)mre
  • 0de4750btheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 4eeb7bfeST2 report wordingmre
  • 2558f56cst2-sec: keep the hlsid session cookie name (no one is signed out), Secure flag only; gate: a cookie issued by main stays signed in; ident stub serves selector.js; security.mjs in deploy GATESmre
  • ea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmre
  • 7c8c2282sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b6277497report MT-mobile, LOGmre
  • 6709398blist paging: the newest rows come first (the sorted array was not used); filter rows hide their scrollbar; gate checks the ordermre
  • 31736a80gate: member-name check fails on the old row layout toomre
  • e03ae537gate: the phone checks run on without the Show more button (so old code reports every failed check)mre
  • adf7f132gate: 390 px checks for the mobile audit fixes (row number, filters, field widths, Edit, member names, relation taps, paging)mre
  • 28e9c938ticket list: draw the newest 50 rows and a Show more button (500 rows were a 2-4 s first paint, 740 KB, a 90 000 px phone page)mre
  • ccebb0c7mobile: ticket number stays on one line, filter chips one scrolling row, fields full width under their caption, Edit/action buttons, member names whole, 44 px relation linksmre
  • f2dc7741gate: the phone toolbar is two even rows (E2)mre
  • 20f7c33async components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
  • d74a5482sync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
  • 9d02c540sync components.hybriel 6b0936a: the 'edited' foldable drops the theme's border and marginmre
  • 22751914sync components.hybriel 8d79ff7: bubble hugs its content, quiet 'edited' label; gate checksmre