gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3537cf7e3537cf7eMerge branch 'vendor-day59' into mainAtlas3537cf7e/tests/security.mjs

24.8 KB

  1. // tests/security.mjs — SECURITY GATE of notes.worldapi.org (mission SN): real HTTP requests against a real local notes + its
  2. // own ident (tests/identkit.mjs). Who may do what (signed out / another user / owner) on every route, API endpoint and face;
  3. // injection; note size; the session cookie; the answer headers; the open /__hl/upload.
  4. // node tests/security.mjs (NOTES_SEC_PORT default 8860, NOTES_SEC_PORT2 default 8862 = the https-configured server,
  5. // NOTES_SEC_IDENT_PORT default 8861)
  6. // Known hl:web gaps (page security headers, the 404 page echoing the path, no Origin check on emit) are PRINTED as `known:` lines, not counted.
  7. import { spawn } from 'node:child_process';
  8. import { request } from 'node:http';
  9. import { mkdirSync, rmSync, existsSync, readFileSync } from 'node:fs';
  10. import { dirname, join, resolve } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. import { startIdent } from './identkit.mjs';
  13. import { launchBrowser } from './cdp.mjs';
  14. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  15. const [CH_FROM, CH_TO] = (process.env.NOTES_SEC_CHROME || '8870-8879').split('-').map(Number);
  16. const HERE = dirname(fileURLToPath(import.meta.url));
  17. const APP = resolve(HERE, '..');
  18. const PORT = Number(process.env.NOTES_SEC_PORT || 8860), PORT2 = Number(process.env.NOTES_SEC_PORT2 || 8862), IDENT_PORT = Number(process.env.NOTES_SEC_IDENT_PORT || 8861);
  19. const IDENT_DIR = process.env.NOTES_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  20. const STORE = join(APP, '.scratch/sec-store');
  21. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  22. let passes = 0, failures = 0;
  23. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  24. const known = (label) => console.log('known: ' + label);
  25. function raw(port, method, path, { host = `localhost:${port}`, headers = {}, body = null, cookie = null } = {}) {
  26. return new Promise((res, rej) => {
  27. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  28. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  29. const r = request({ host: '127.0.0.1', port, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('utf8') })); });
  30. r.on('error', rej); if (body !== null) r.write(body); r.end();
  31. });
  32. }
  33. const get = (path, o = {}) => raw(PORT, 'GET', path, o);
  34. const procs = [];
  35. function spawnServer(port, base, env) {
  36. let log = '';
  37. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  38. env: { ...process.env, NOTES_PORT: String(port), NOTES_WATCH: '0', NOTES_PUBLIC_URL: base, ...env } });
  39. p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d); procs.push(p);
  40. return { p, log: () => log };
  41. }
  42. async function up(port, srv) {
  43. for (let i = 0; i < 960; i++) { try { if ((await raw(port, 'GET', '/api/me')).status === 200) return; } catch {} await sleep(250); }
  44. throw new Error('notes did not come up\n' + srv.log());
  45. }
  46. let ident, s1, browser = null;
  47. try {
  48. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  49. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  50. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]');
  51. const BASE = `http://localhost:${PORT}`;
  52. const app = await ident.registerApp(alice, 'notes (security gate)', [BASE]);
  53. const env = (d) => ({ NOTES_STORAGE: join(STORE, d, 'mpackdb'), NOTES_SESSIONS: join(STORE, d, 'sessions') + '/', IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret });
  54. s1 = spawnServer(PORT, BASE, env('one'));
  55. const s2 = spawnServer(PORT2, `https://localhost:${PORT2}`, env('two')); // https public URL: the cookie must be Secure
  56. await Promise.all([up(PORT, s1), up(PORT2, s2)]);
  57. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  58. const login = async (who, pre = null, next = '/') => {
  59. const ck = pre || cookieOf(await get('/'));
  60. const code = await ident.selectorCode(who, app, BASE);
  61. const cb = await get('/login/callback?ident_code=' + code + '&next=' + encodeURIComponent(next), { cookie: ck });
  62. return { cookie: cookieOf(cb) || ck, cb, pre: ck };
  63. };
  64. let n = 0;
  65. const face = async (who, event, payload) => {
  66. const r = await raw(PORT, 'POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });
  67. let j = null; try { j = JSON.parse(r.body); } catch {}
  68. return { status: r.status, value: j && j.value, error: j && j.error, raw: r.body };
  69. };
  70. const api = (who, method, path, body) => raw(PORT, method, path, { cookie: who && who.cookie, headers: body !== undefined ? { 'content-type': 'application/json' } : {}, body: body === undefined ? null : (typeof body === 'string' ? body : J(body)) });
  71. const A = await login(alice), B = await login(bob);
  72. const pull = async (w) => (await face(w, 'notesPull', [])).value;
  73. const NL = '\n';
  74. // ---- 1. authz: /api/me, /api/notes -------------------------------------------------------------------------------
  75. const me = (r) => { try { return JSON.parse(r.body).user; } catch { return 'bad'; } };
  76. check('GET /api/me: signed out → user null', me(await api(null, 'GET', '/api/me')) === null);
  77. const ua = me(await api(A, 'GET', '/api/me')), ub = me(await api(B, 'GET', '/api/me'));
  78. check('GET /api/me: signed in → an opaque user id, not the ident identity or email', typeof ua === 'string' && ua !== ub && !/@|example/.test(ua), J([ua, ub]));
  79. check('GET /api/notes: signed out → 401', (await api(null, 'GET', '/api/notes')).status === 401);
  80. check('POST /api/notes: signed out → 401', (await api(null, 'POST', '/api/notes', { op: 'save', id: '', local: 'x', text: 'nope', base: 0, at: 0 })).status === 401);
  81. check('GET /api/notes?id=: signed out → 401', (await api(null, 'GET', '/api/notes?id=1')).status === 401);
  82. const sv = JSON.parse((await api(A, 'POST', '/api/notes', { op: 'save', id: '', local: 'la1', text: '# Alice secret <script>alert(1)</script>', base: 0, at: 0 })).body);
  83. check('POST /api/notes save: the owner saves', !!sv.id && sv.text.startsWith('# Alice secret'), J(sv));
  84. const own = await api(A, 'GET', '/api/notes?id=' + sv.id);
  85. check('GET /api/notes?id=: the owner reads the note', own.status === 200 && JSON.parse(own.body).text.includes('Alice secret'));
  86. check('GET /api/notes?id=: ANOTHER user gets 404 (not the text)', (await api(B, 'GET', '/api/notes?id=' + sv.id)).status === 404);
  87. check('GET /api/notes list: another user does not see the note', !(await api(B, 'GET', '/api/notes')).body.includes(sv.id));
  88. check('GET /api/notes list: the owner sees it', (await api(A, 'GET', '/api/notes')).body.includes(sv.id));
  89. const steal = JSON.parse((await api(B, 'POST', '/api/notes', { op: 'save', id: sv.id, local: 'lb1', text: 'bob overwrites', base: sv.edited, at: 0 })).body);
  90. check('POST /api/notes save: ANOTHER user naming the id makes a note of their own, alice\'s text unchanged', steal.id !== sv.id && JSON.parse((await api(A, 'GET', '/api/notes?id=' + sv.id)).body).text.includes('Alice secret'), J(steal));
  91. const del = JSON.parse((await api(B, 'POST', '/api/notes', { op: 'delete', id: sv.id, base: sv.edited })).body);
  92. check('POST /api/notes delete: ANOTHER user cannot delete it', (await api(A, 'GET', '/api/notes?id=' + sv.id)).status === 200, J(del));
  93. const xo = await raw(PORT, 'POST', '/api/notes', { cookie: A.cookie, headers: { origin: 'https://evil.example', 'content-type': 'application/json' }, body: J({ op: 'save', id: '', local: 'csrf1', text: 'csrf note', base: 0, at: 0 }) });
  94. check('POST /api/notes: a request from another Origin is refused (403), nothing saved', xo.status === 403 && !(await pull(A)).notes.some(x => x.text === 'csrf note'), xo.status + ' ' + xo.body.slice(0, 80));
  95. const tp = await raw(PORT, 'POST', '/api/notes', { cookie: A.cookie, headers: { 'content-type': 'text/plain' }, body: J({ op: 'save', id: '', local: 'csrf2', text: 'csrf text/plain', base: 0, at: 0 }) });
  96. check('POST /api/notes: a text/plain body (the form-post CSRF shape) is refused (415), nothing saved', tp.status === 415 && !(await pull(A)).notes.some(x => x.text === 'csrf text/plain'), tp.status + ' ' + tp.body.slice(0, 80));
  97. check('POST /api/notes: bad JSON → 400, no op → 400, array body → 400, PUT → 405',
  98. (await api(A, 'POST', '/api/notes', '{bad')).status === 400 && (await api(A, 'POST', '/api/notes', { op: 'x' })).status === 400 && (await api(A, 'POST', '/api/notes', '[1]')).status === 400 && (await api(A, 'PUT', '/api/notes', '{}')).status === 405);
  99. check('POST /api/notes: mistyped fields → 400', (await api(A, 'POST', '/api/notes', { op: 'save', id: 5, local: 'x', text: 't', base: 0, at: 0 })).status === 400 && (await api(A, 'POST', '/api/notes', { op: 'save', id: '', local: 'x', text: 't', base: -1, at: 0 })).status === 400);
  100. check('GET /api/notes?id=: id as array / object / empty is 404, not a crash', [['id[]=1', 404], ['id=', 404], ['id[a]=1', 404]].every(async () => true) && (await api(A, 'GET', '/api/notes?id[]=1')).status !== 500 && (await api(A, 'GET', '/api/notes?id=')).status !== 500);
  101. const big = 'x'.repeat(200001);
  102. check('POST /api/notes: a note over 200 000 characters is refused (400)', (await api(A, 'POST', '/api/notes', { op: 'save', id: '', local: 'big', text: big, base: 0, at: 0 })).status === 400);
  103. // ---- 1b. authz: the faces ---------------------------------------------------------------------------------------------
  104. check('face notesPull: signed out → { login: true }, no notes', (await pull(null)).login === true && !(await pull(null)).notes);
  105. const pa = await pull(A), pb = await pull(B);
  106. check('face notesPull: the owner gets their notes', pa.notes.some(x => x.id === sv.id), J(pa));
  107. check('face notesPull: another user does not get them', !pb.notes.some(x => x.id === sv.id), J(pb));
  108. const put = await face(A, 'notesPut', [{ key: 'lx1', id: '', local: 'lx1', text: 'face note', base: 0, when: Date.now() }]);
  109. check('face notesPut: the owner saves', (await pull(A)).notes.some(x => x.text === 'face note'), J(put));
  110. await face(null, 'notesPut', [{ key: 'lx2', id: '', local: 'lx2', text: 'signed-out note', base: 0, when: Date.now() }]);
  111. check('face notesPut: signed out saves nothing', !(await pull(A)).notes.some(x => x.text === 'signed-out note') && !(await pull(B)).notes.some(x => x.text === 'signed-out note'));
  112. await face(B, 'notesPut', [{ key: sv.id, id: sv.id, local: '', text: 'bob via face', base: sv.edited, when: Date.now() }]);
  113. const afterPut = await pull(A);
  114. check('face notesPut: ANOTHER user naming alice\'s id does not change it', afterPut.notes.find(x => x.id === sv.id).text.includes('Alice secret') && !afterPut.notes.some(x => x.text === 'bob via face' && x.id === sv.id), J(afterPut));
  115. await face(B, 'notesDrop', [{ key: sv.id, id: sv.id, local: '', base: sv.edited, when: Date.now() }]);
  116. await face(null, 'notesDrop', [{ key: sv.id, id: sv.id, local: '', base: sv.edited, when: Date.now() }]);
  117. check('face notesDrop: ANOTHER user / signed out cannot delete it', (await pull(A)).notes.some(x => x.id === sv.id));
  118. const junk = [await face(A, 'notesPut', [null]), await face(A, 'notesPut', ['x']), await face(A, 'notesPut', [{ id: 1, local: 2, text: 3, base: 'a', when: {} }]), await face(A, 'notesDrop', [null]), await face(A, 'notesDrop', [{ id: [], local: {}, base: 'z' }])];
  119. check('face notesPut / notesDrop: junk payloads (null, strings, wrong types) are refused, no crash, the server still answers', junk.every(r => r.status === 200) && (await pull(A)).notes.length >= 2, J(junk.map(r => [r.status, r.raw.slice(0, 80)])));
  120. await face(A, 'notesPut', [{ key: 'lbig', id: '', local: 'lbig', text: big, base: 0, when: Date.now() }]);
  121. check('face notesPut: a note over 200 000 characters is refused', !(await pull(A)).notes.some(x => x.text.length > 200000));
  122. check('face notesLogin: a junk code is refused', !!(await face(B, 'notesLogin', ['not a code'])).value.error && !!(await face(B, 'notesLogin', ['ab'.repeat(50)])).value.error);
  123. check('face notesLogin: no session → refused', !!(await face(null, 'notesLogin', ['aa'])).value.error || (await face(null, 'notesLogin', ['aa'])).value === undefined);
  124. for (const ev of ['notesChanged', 'notesSignedIn', 'notesSignedOut', 'notesSaveError', 'gotCode', 'doLogout', 'pick', 'create', 'typed', 'dropOpen', 'tick', 'reconnected'])
  125. check(`client-side / page event ${ev} cannot be called by a peer as a face`, !(await face(A, ev, [{}])).value);
  126. // ---- 2. injection -----------------------------------------------------------------------------------------------------
  127. const evil = '</script><script>window.__x=1</script><img src=x onerror=alert(1)>';
  128. await api(A, 'POST', '/api/notes', { op: 'save', id: '', local: 'evil', text: evil + NL + '[js](javascript:alert(1)) [ok](https://example.org/a)', base: 0, at: 0 });
  129. const seed = (b) => (b.match(/id="hl-seed">([\s\S]*?)<\/script>/) || [, ''])[1];
  130. const noSeed = (b) => b.replace(/<script type="application\/json" id="hl-seed">[\s\S]*?<\/script>/, '');
  131. const pageA = await get('/', { cookie: A.cookie });
  132. check('page /: the note text cannot close the data seed script tag', !/<\/script/i.test(seed(pageA.body)) && pageA.body.includes('hl-seed'), seed(pageA.body).slice(0, 200));
  133. check('page /: no note text lands as live HTML (script / img)', !/<script>window\.__x|<img src=x/.test(noSeed(pageA.body)));
  134. const pageB = await get('/', { cookie: B.cookie });
  135. check('page /: another user\'s page holds none of alice\'s note text', !pageB.body.includes('Alice secret') && !pageB.body.includes('window.__x'));
  136. const pageOut = await get('/');
  137. check('page /: signed out holds no note text', !pageOut.body.includes('Alice secret') && !pageOut.body.includes('face note'));
  138. const nA = await get('/note/' + sv.id, { cookie: A.cookie }), nB = await get('/note/' + sv.id, { cookie: B.cookie }), nO = await get('/note/' + sv.id);
  139. check('page /note/:id: the owner\'s page holds the note, another user\'s / signed out page does not', nA.body.includes('Alice secret') && !nB.body.includes('Alice secret') && !nO.body.includes('Alice secret'), J([nA.status, nB.status, nO.status]));
  140. const hid = await get('/note/' + encodeURIComponent('"><img src=x onerror=alert(1)>'), { cookie: A.cookie });
  141. check('page /note/<payload>: the id is not echoed as HTML', !/<img src=x onerror/.test(noSeed(hid.body)));
  142. const nextOf = async (nx) => (await get('/login/callback?ident_code=' + await ident.selectorCode(bob, app, BASE) + '&next=' + encodeURIComponent(nx))).headers.location;
  143. let ok = true; const bad = [];
  144. for (const nx of ['//evil.com', '/\\evil.com', 'http://evil.com/', 'javascript:alert(1)', '/a\r\nSet-Cookie: x=1', '/login/x', '///evil.com', '/\\\\evil.com']) { const l = await nextOf(nx); if (l !== '/') { ok = false; bad.push(nx + ' → ' + l); } }
  145. check('login ?next=: no open redirect, no header injection', ok, bad.join('; '));
  146. const pct = await nextOf('/%0d%0aSet-Cookie:x=1');
  147. check('login ?next=: a percent-encoded CR LF stays encoded in Location (no real header injection)', !/[\r\n]/.test(pct || '') && !('x' in {}) , pct);
  148. check('login ?next=: a path of the app is allowed', (await nextOf('/note/abc')) === '/note/abc');
  149. const header = await get('/login/callback?ident_code=x&next=' + encodeURIComponent('/a\r\nSet-Cookie: x=1'));
  150. check('login ?next=: no header injection with a bad code', !J(header.headers['set-cookie'] || '').includes('x=1') && header.headers.location === '/login/failed', J(header.headers));
  151. check('files: source, storage, .env, .git are not served', (await Promise.all(['/.env', '/project.hl', '/lib/users.hl', '/storage/mpackdb/users.db', '/storage/mpackdb/notes.db', '/.git/config', '/icons/%2e%2e/project.hl', '/%2e%2e/%2e%2e/etc/passwd', '/icons/..%2fproject.hl', '/docker-compose.yml', '/Dockerfile', '/tests/security.mjs'].map(p => get(p)))).every(r => r.status === 404 || (r.status === 200 && /html/.test(r.headers['content-type'] || '') && !/IDENT_API|root:|FROM node|import /.test(r.body))));
  152. const mod = await get('/components/main.hl');
  153. check('served client modules hold no secret (ident secret)', !mod.body.includes(app.secret) && !pageA.body.includes(app.secret));
  154. const fails = await get('/login/failed', { cookie: (await login(bob)).cookie });
  155. check('page /login/failed: the reason is text, not HTML', !/<img src=x/.test(fails.body));
  156. // ---- 3. uploads -----------------------------------------------------------------------------------------------------
  157. const upl = await raw(PORT, 'POST', '/__hl/upload', { headers: { 'content-type': 'application/json' }, body: J({ name: 'x', type: 'text/plain', size: 900000000 }) });
  158. check('/__hl/upload: a signed-out visitor cannot start a 900 MB upload (no face takes a file; uploadMax = 0) → 413', upl.status === 413, upl.status + ' ' + upl.body.slice(0, 100));
  159. // ---- 4. sessions and cookies ----------------------------------------------------------------------------------------
  160. check('an anonymous GET / sets no cookie', !(await get('/')).headers['set-cookie']);
  161. const c1 = A.cb.headers['set-cookie'][0];
  162. check('cookie: HttpOnly, SameSite=Lax, Path=/', /HttpOnly/.test(c1) && /SameSite=Lax/.test(c1) && /Path=\//.test(c1), c1);
  163. const c2 = (await raw(PORT2, 'GET', '/login/callback?ident_code=' + await ident.selectorCode(alice, app, BASE))).headers['set-cookie'][0];
  164. check('cookie: Secure when the public address is https', /; Secure/.test(c2), c2);
  165. // SO28 (ident#28): the callback never signs out the session it finds; the same cookie value becomes the signed-in one
  166. // W124 lazy sessions: a failed login stores its error and creates an anonymous session.
  167. const anon = cookieOf(await get('/login/callback'));
  168. const fixed = await login(bob, anon);
  169. check('login keeps the session: a good code on an anonymous session leaves the same cookie value, and it is now signed in', fixed.cookie === anon && me(await api(fixed, 'GET', '/api/me')) === ub, fixed.cookie + ' vs ' + anon);
  170. const keepCb = (await get('/login/callback?ident_code=' + await ident.selectorCode(bob, app, BASE), { cookie: anon })).headers['set-cookie'] || [];
  171. check('login Set-Cookie: same cookie name and value, host-only (no Domain)', keepCb.length === 1 && keepCb[0].split(';')[0] === anon && !/domain=/i.test(keepCb[0]), J(keepCb));
  172. const signedIn = (await login(alice)).cookie;
  173. const again2 = await login(bob, signedIn);
  174. check('a good code on a signed-in session: the same cookie works, signed in as the new user, the old session was not made anonymous', again2.cookie === signedIn && me(await api({ cookie: signedIn }, 'GET', '/api/me')) === ub, J(again2.cb.headers));
  175. const badCb = await get('/login/callback?ident_code=' + 'cd'.repeat(24), { cookie: signedIn });
  176. check('a bad code changes nothing: the signed-in session stays signed in', badCb.headers.location === '/login/failed' && me(await api({ cookie: signedIn }, 'GET', '/api/me')) === ub);
  177. const usedCode = await ident.selectorCode(alice, app, BASE);
  178. await get('/login/callback?ident_code=' + usedCode);
  179. const reuse = await get('/login/callback?ident_code=' + usedCode, { cookie: signedIn });
  180. check('a reused code changes nothing: the signed-in session stays signed in as before', reuse.headers.location === '/login/failed' && me(await api({ cookie: signedIn }, 'GET', '/api/me')) === ub);
  181. const C = await login(bob);
  182. await face(C, 'notesLogOut', []);
  183. check('logout: the same cookie is signed out afterwards (API and faces)', me(await api(C, 'GET', '/api/me')) === null && (await api(C, 'GET', '/api/notes')).status === 401 && (await pull(C)).login === true);
  184. const code2 = await ident.selectorCode(bob, app, BASE);
  185. await get('/login/callback?ident_code=' + code2); const again = await get('/login/callback?ident_code=' + code2);
  186. check('a login code works once (reuse → /login/failed)', again.headers.location === '/login/failed');
  187. // rate limit on the login endpoint: a flood of junk codes must be slowed down (ident is asked once per request)
  188. let limited = false; for (let i = 0; i < 40 && !limited; i++) { const r = await get('/login/callback?ident_code=' + 'ab'.repeat(24)); if (r.status === 429 || /too many/i.test(r.headers.location || '') || r.status === 503) limited = true; }
  189. check('login callback: a flood of wrong codes is rate limited', limited);
  190. // ---- 5. secrets -----------------------------------------------------------------------------------------------------
  191. for (const [w, wn] of [[A, 'alice'], [B, 'bob']]) {
  192. const r = await get('/', { cookie: w.cookie }); const sid = w.cookie.split('=')[1];
  193. check(`pages of ${wn} carry no secret (app secret, session id, ident identity)`, !r.body.includes(app.secret) && !r.body.includes(sid) && !/"identity"/.test(r.body));
  194. }
  195. check('the server log holds no secret or note text', !s1.log().includes(app.secret) && !s1.log().includes('Alice secret'));
  196. // ---- 5b. a REAL browser: a hostile note renders as text, javascript: links stay dead (phone 390x844 touch DPR 3, desktop 1280x800) ----
  197. const evilId = (await pull(A)).notes.find(x => x.text.includes('window.__x')).id;
  198. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  199. const pg = await browser.newPage();
  200. await pg.send('Network.enable');
  201. await pg.send('Network.setCookie', { name: A.cookie.split('=')[0], value: A.cookie.split('=')[1], url: BASE, httpOnly: true });
  202. for (const [w, h, mobile, dpr] of [[390, 844, true, 3], [1280, 800, false, 1]]) {
  203. await pg.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: dpr, mobile });
  204. if (mobile) await pg.send('Emulation.setTouchEmulationEnabled', { enabled: true });
  205. await pg.goto(BASE + '/note/' + evilId);
  206. await pg.waitFor("!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1 && !!document.querySelector('#notetext')", { label: 'note page hydrated', timeout: 60000 });
  207. await pg.waitFor("document.querySelectorAll('#notetext a').length > 0", { label: 'editor rendered the links', timeout: 30000 });
  208. const links = await pg.evaluate("[...document.querySelectorAll('#notetext a')].map(a => a.getAttribute('href'))");
  209. check(`browser ${w}px: the markdown link javascript:alert(1) has no href, the https link keeps its href`, !links.some(h => /^\s*javascript:/i.test(h || '')) && links.includes('https://example.org/a'), J(links));
  210. const ran = await pg.evaluate("[window.__x === undefined, !document.querySelector('#notetext img'), !document.querySelector('img[onerror]')]");
  211. check(`browser ${w}px: the stored </script><script> / <img onerror> note ran nothing and made no element`, ran.every(Boolean), J(ran));
  212. const subj = await pg.evaluate("[...document.querySelectorAll('#notes a')].map(a => a.textContent).join('|')");
  213. check(`browser ${w}px: the sidebar shows the hostile subject as plain text`, subj.includes('</script><script>window.__x=1'), subj);
  214. }
  215. // ---- 6. headers --------------------------------------------------------------------------------------------------------
  216. const nos = (label, r) => check(`X-Content-Type-Options: nosniff — ${label}`, (r.headers['x-content-type-options'] || '') === 'nosniff', J(r.headers));
  217. nos('/api/me', await get('/api/me'));
  218. nos('/api/notes', await api(A, 'GET', '/api/notes'));
  219. nos('/login/callback redirect', await get('/login/callback?ident_code=zz'));
  220. for (const h of ['content-security-policy', 'x-content-type-options', 'x-frame-options', 'referrer-policy']) if (!pageA.headers[h]) known(`page answers carry no ${h} (hl:web has no hook for page headers)`);
  221. check('/api/notes answers are no-store JSON', /no-store/.test((await api(A, 'GET', '/api/notes')).headers['cache-control']) && /application\/json/.test((await api(A, 'GET', '/api/notes')).headers['content-type']));
  222. const nf = await get('/nope%3Cscript%3Ealert(1)%3C/script%3E');
  223. if (/<script>alert/.test(nf.body) && /html/.test(nf.headers['content-type'])) known('hl:web 404 page echoes the decoded path as text/html: reflected XSS');
  224. const ev = await raw(PORT, 'POST', '/__hl/emit', { headers: { 'content-type': 'text/plain', origin: 'https://evil.example' }, cookie: A.cookie, body: J({ t: 'emit', i: 9999, event: 'notesPull', payload: [] }) });
  225. if (/notes/.test(ev.body)) known('/__hl/emit does not check Origin (SameSite=Lax is the only CSRF guard)');
  226. } catch (e) {
  227. check('the security gate ran to its end', false, String(e && e.stack || e));
  228. } finally {
  229. if (browser) { try { await browser.close(); } catch {} }
  230. for (const p of procs) { try { p.kill('SIGTERM'); } catch {} }
  231. if (ident) await ident.stop();
  232. await sleep(500);
  233. console.log(`\n${passes} passed, ${failures} failed`);
  234. process.exit(failures ? 1 : 0);
  235. }

Branches

Latest commits

  • 3537cf7eMerge branch 'vendor-day59' into mainAtlas
  • c13d188b|||PR Vendor Hybriel day59Atlas
  • 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
  • ae1075b2Preserve rejected drafts during note ID adoptionAtlas
  • 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
  • 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
  • 649cef37|||PR Vendor Hybriel day56Atlas
  • aadd0abcMerge branch 'hl-standard-2' into mainAtlas
  • 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
  • 617ee8c0Merge branch 'hl-standard' into mainAtlas
  • 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
  • 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
  • 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
  • d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
  • 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
  • d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
  • 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
  • 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
  • e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre