// Run with Node.js, then open http://127.0.0.1:8787 in a browser.
import { createServer } from 'node:http';
import assert from 'node:assert/strict';
import { Script } from 'node:vm';

const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWOQLNgNAAHqAUWXoD3FAAAAAElFTkSuQmCC', 'base64');
const html = `<!doctype html><html lang="en"><meta charset="utf-8"><title>Image CORS experiment</title>
<h1>Image CORS experiment</h1><button id="run">Run all three cases</button><pre id="result" aria-live="polite"></pre>
<script type="module">
document.querySelector('#run').onclick = async () => {
  const results = [];
  for (const [name, cors, url] of [
    ['No crossorigin: export is blocked', false, '/image.png'],
    ['crossorigin without server permission: load is blocked', true, '/image.png'],
    ['crossorigin with server permission: export succeeds', true, '/image.png?cors=1']
  ]) {
    const image = new Image();
    if (cors) image.crossOrigin = 'anonymous';
    image.src = 'http://127.0.0.1:8788' + url;
    try {
      await image.decode();
      const canvas = document.createElement('canvas');
      canvas.width = canvas.height = 1;
      canvas.getContext('2d').drawImage(image, 0, 0);
      canvas.toDataURL('image/png');
      results.push(name + ': exported');
    } catch (error) {
      results.push(name + ': ' + error.name + ': ' + error.message);
    }
  }
  document.querySelector('#result').textContent = results.join('\\n');
};
</script></html>`;

const page = createServer((_req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
  res.end(html);
});
const images = createServer((req, res) => {
  if (req.url === '/image.png?cors=1') res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:8787');
  res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-store' });
  res.end(png);
});

page.listen(8787, '127.0.0.1');
images.listen(8788, '127.0.0.1');
if (process.argv.includes('--check')) {
  try {
    new Script(html.match(/<script type="module">([\s\S]*?)<\/script>/)[1]);
    for (const suffix of ['', '?cors=1']) {
      const response = await fetch('http://127.0.0.1:8788/image.png' + suffix);
      assert.equal(response.status, 200);
      assert.equal(response.headers.get('access-control-allow-origin'), suffix ? 'http://127.0.0.1:8787' : null);
      assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
    }
    assert((await (await fetch('http://127.0.0.1:8787')).text()).includes('image.crossOrigin'));
    console.log('Two-origin HTTP checks passed; run in a browser to observe canvas enforcement');
  } finally {
    page.close(); images.close();
  }
} else {
  console.log('Open http://127.0.0.1:8787 and press Run all three cases. Ctrl+C stops both servers.');
}
