layouts
All repositories: gitoria
6.9 KB
import http from 'node:http';import assert from 'node:assert/strict';import { spawn } from 'node:child_process';import { readFile, writeFile } from 'node:fs/promises';import path from 'node:path';import { fileURLToPath } from 'node:url';import { launchBrowser } from '../../../tests/browser/cdp.mjs';const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');const bin = process.env.HL_BIN || path.join(root, 'native/zig-out/bin/hybriel');const work = process.env.TMPDIR;if (!work) throw new Error('set TMPDIR to scratch');const port = Number(process.env.HL_PORT_BASE || 28090);const origin = `http://127.0.0.1:${port}`;const other = `http://127.0.0.1:${port + 1}`;const seen = [];const source = await readFile(path.join(root, 'plugins/fetch/client.js'), 'utf8');function serve(req, res) {let body = '';req.on('data', b => body += b);req.on('end', () => {const entry = { method: req.method, body, headers: req.headers };seen.push({ url: req.url, ...entry });res.setHeader('access-control-allow-origin', '*');res.setHeader('access-control-allow-headers', 'authorization,x-test,content-type');if (req.method === 'OPTIONS') { res.end(); return; }if (req.url === '/client.js') { res.setHeader('content-type', 'text/javascript'); res.end(source); return; }if (req.url === '/') { res.setHeader('content-type', 'text/html'); res.end('<title>Fetch redirect test</title><p>Fetch redirect test</p>'); return; }if (req.url.startsWith('/redirect/')) {const [, , code, destination] = req.url.split('/');const location = destination === 'cross' ? other + '/echo' : destination === 'chain' ? '/redirect/302/cross' : destination === 'loop' ? req.url : '/echo';res.writeHead(Number(code), { location }); res.end(); return;}res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(entry));});}const servers = [http.createServer(serve), http.createServer(serve)];function run(args) { return new Promise((resolve, reject) => {const p = spawn(args[0], args.slice(1), { cwd: root, env: process.env });let out = '', err = '';p.stdout.on('data', s => out += s); p.stderr.on('data', s => err += s);p.on('error', reject); p.on('close', code => code ? reject(new Error(`${code}: ${out}${err}`)) : resolve(out));}); }const headers = { AuThOrIzAtIoN: 'secret', Cookie: 'session=secret', 'Proxy-Authorization': 'proxy-secret', 'X-Test': 'kept' };let browser;let count = 0;try {for (const [i, s] of servers.entries()) await new Promise((r, j) => { s.once('error', j); s.listen(port + i, '127.0.0.1', r); });const js = await import('../server.js');for (const target of ['native', 'server JS']) {async function request(route, opts = {}) {if (target === 'server JS') return js.fetch(origin + route, { headers, ...opts });const fixture = path.join(work, 'redirect-probe.hl');const h = Object.entries({ ...headers, ...opts.headers }).map(([k,v]) => `${JSON.stringify(k)} = ${JSON.stringify(v)}`).join('\n');await writeFile(fixture, `import { fetch } from 'hl:fetch'\nr = fetch('${origin + route}', { method = '${opts.method || 'GET'}' headers = { ${h} } ${opts.body === undefined ? '' : `body = '${opts.body}'`} maxRedirects = ${opts.maxRedirects ?? 5} })\nconsole.log(r.status)\nconsole.log(r.text())\n`);const lines = (await run([bin, fixture])).trim().split('\n');return { status: Number(lines[0]), json() { return JSON.parse(lines[1]); } };}for (const dest of ['same', 'cross', 'chain']) {const r = await request('/redirect/302/' + dest); const got = r.json();assert.equal(got.headers.authorization, dest === 'same' ? 'secret' : undefined);assert.equal(got.headers.cookie, dest === 'same' ? 'session=secret' : undefined);assert.equal(got.headers['proxy-authorization'], dest === 'same' ? 'proxy-secret' : undefined);assert.equal(got.headers['x-test'], 'kept');if (dest === 'chain') assert.equal(seen.filter(s => s.url === '/redirect/302/cross').at(-1).headers.authorization, 'secret');count++;}for (const code of [301, 302, 303, 307, 308]) {const got = (await request(`/redirect/${code}/same`, { method: 'POST', body: 'abc', headers: { ...headers, 'Content-Type': 'text/plain' } })).json();const keep = code >= 307;assert.equal(got.method, keep ? 'POST' : 'GET'); assert.equal(got.body, keep ? 'abc' : '');assert.equal(got.headers['content-type'], keep ? 'text/plain' : undefined);assert.equal(got.headers['content-length'], keep ? '3' : undefined); count++;}assert.equal((await request('/redirect/302/same', { maxRedirects: 0 })).status, 302); count++;await assert.rejects(request('/redirect/302/loop', { maxRedirects: 1 }), /redirects/); count++;console.log(`PASS ${target}: 10 redirect scenarios`);}browser = await launchBrowser();const page = await browser.newPage(); await page.goto(origin);const result = await page.evaluate(`(async () => {const {fetch} = await import('/client.js');const r = await fetch('/redirect/302/same');const post = await fetch('/redirect/303/same', {method:'POST',body:'abc',headers:{'Content-Type':'text/plain'}});const same = await fetch('/redirect/302/same', {headers:{Authorization:'browser-secret'}});const cross = await fetch('/redirect/302/cross', {headers:{Authorization:'browser-secret'}});const zero = await fetch('/redirect/302/same', {maxRedirects:0});return {status:r.status,url:r.url,post:post.json(),same:same.json(),cross:cross.json(),zero:{status:zero.status,body:zero.body,headers:zero.headers}};})()`);assert.equal(result.status, 200); assert.equal(result.url, origin + '/echo');assert.equal(result.same.headers.authorization, 'browser-secret');assert.equal(result.cross.headers.authorization, undefined);assert.equal(result.post.method, 'GET'); assert.equal(result.post.body, '');assert.equal(result.post.headers['content-type'], undefined);assert.deepEqual(result.zero, { status: 0, body: '', headers: {} }); count += 5;if (process.env.HL_FETCH_SCREENSHOTS) {await page.send('Page.bringToFront');for (const [name, width, height] of [['phone',390,844],['tablet',800,1280],['desktop',1440,1000]]) {await page.send('Emulation.setDeviceMetricsOverride', {width,height,deviceScaleFactor:1,mobile:name==='phone'});const {data} = await page.send('Page.captureScreenshot', {format:'png',fromSurface:false,captureBeyondViewport:false});await writeFile(path.join(work, `redirect-${name}.png`), Buffer.from(data, 'base64'));}}console.log(`PASS browser: 5 redirect scenarios; total ${count}`);} finally {if (browser?.owned) await browser.close();else if (browser) {for (const page of browser.pages) await page.close();// This harness exposes the transport for disconnecting an attached browser.browser.conn.close();}for (const s of servers) s.closeAllConnections();await Promise.all(servers.map(s => new Promise(r => s.listening ? s.close(r) : r())));}
Branches
Latest commits
- 44071d2cMerge branch 'hl-standard-5' into mainAtlas
- 5ea64202|||PR Gate: count the new-tab check's console errors tooAtlas
- 2752ceddMerge branch 'hl-standard-4' into mainAtlas
- ac552b81|||PR Gate: keyboard (Tab/Enter/Space) and Back/Forward/reload/new-tab checks (HL-STANDARD F5, F21)Atlas
- 8cddcaa9Merge branch 'hl-standard-2' into mainAtlas
- 2b480a64|||PR Type the route parameter of main-menu build (HL-STANDARD L10)Atlas
- ab54a39dMerge branch 'hl-standard' into mainAtlas
- 04d36fcf|||PR Type function parameters and drop unneeded let (HL-STANDARD L2, L10)Atlas
- 220c8fa4Merge branch 'readme-audit' into mainAtlas
- b78fb85a|||PR README matches the codemre
- 9f351699Preserve comments and nest supported selectors without changing rendered outputmre
- 97110ad9WIP: nest accepted layout selectors; stopped at startup parse failuremre
- ce4a0baeKeep caller slot styles whole so minimal shell apps startmre
- 12cd3992Re-vendor complete Hybriel plugins and runtime to day44mre
- b05c20feBackup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
- 8d9ed0b8Re-vendor complete Hybriel plugins and runtime to day39mre
- ebd00b6cNest caller slot styles in three-panemre
- 009991efNest caller slot styles in list-firstmre
- 494d75d4Nest caller slot styles in app-sidebarmre
- e5571680Align all plugin sources with Hybriel day38bmre