gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf51029abf51029abMerge branch 'sy-sync'mref51029ab/tests/browser.mjs

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

Branches

Latest commits

  • 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
  • c8452453sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre