// verify-atlas-proxy.mjs — drive the REAL worker export against a mocked runtime
// and assert the properties the proxy exists to guarantee.
//
// The point of routing the Atlas probes through our own worker is that the
// upstreams stop seeing the reader. That is only true if three things hold, and
// each is asserted here rather than asserted in prose:
//   1. nothing the reader typed is ever written to storage,
//   2. no reader header is forwarded upstream,
//   3. it is not a general proxy: the upstream host and path are ours to choose.
//
//   node research/atlas-proxy/verify-atlas-proxy.mjs

import assert from 'node:assert';
import { pathToFileURL } from 'node:url';
import path from 'node:path';

const ROOT = path.resolve(import.meta.dirname, '../..');
let checks = 0;
const ok = (cond, label, detail = '') => {
  checks++;
  assert.ok(cond, `${label}${detail ? ': ' + detail : ''}`);
};

// ── a mock runtime ───────────────────────────────────────────────────────────
const kv = new Map();
const kvWrites = [];           // every key and value the worker ever stored
const upstreamCalls = [];      // every outbound fetch it ever made
let cacheStore = new Map();
let upstreamPayload = [{ display_name: 'Somewhere', lat: '1.5', lon: '2.5' }];
let upstreamStatus = 200;

globalThis.caches = {
  default: {
    async match(req) { return cacheStore.get(req.url) ? cacheStore.get(req.url).clone() : undefined; },
    async put(req, res) { cacheStore.set(req.url, res.clone()); },
  },
};
const realFetch = globalThis.fetch;
globalThis.fetch = async (input, init = {}) => {
  const url = typeof input === 'string' ? input : input.url;
  upstreamCalls.push({ url, headers: init.headers || {} });
  return new Response(JSON.stringify(upstreamPayload), {
    status: upstreamStatus, headers: { 'content-type': 'application/json' },
  });
};

const env = {
  DEPOSITS: {
    async get(k) { return kv.has(k) ? kv.get(k) : null; },
    async put(k, v) { kvWrites.push({ k, v }); kv.set(k, v); },
  },
};
const ctx = { waitUntil(p) { return p; } };

const worker = (await import(pathToFileURL(path.join(ROOT, 'worker.js')).href)).default;

const SECRET = 'Sensitive Place Name 12 Privet Drive';
const call = (url, headers = {}) =>
  worker.fetch(new Request(url, { headers: { 'CF-Connecting-IP': '203.0.113.9', ...headers } }), env, ctx);

const reset = () => { kv.clear(); kvWrites.length = 0; upstreamCalls.length = 0; cacheStore = new Map(); upstreamStatus = 200; };

// ── 1. it works at all ───────────────────────────────────────────────────────
reset();
let res = await call(`https://artwaste.land/api/atlas/place?q=${encodeURIComponent(SECRET)}`);
let body = await res.json();
ok(res.status === 200, 'place lookup returns 200', String(res.status));
ok(body.ok === true && Array.isArray(body.data), 'place lookup returns the upstream array under data');
ok(body.data[0].display_name === 'Somewhere', 'upstream payload reaches the page');

// ── 2. the upstream is the one WE chose, carrying only OUR identity ──────────
ok(upstreamCalls.length === 1, 'exactly one upstream request', String(upstreamCalls.length));
const up = upstreamCalls[0];
ok(up.url.startsWith('https://nominatim.openstreetmap.org/search?'), 'upstream host is Nominatim', up.url.slice(0, 60));
ok(/ArtificialWasteland/.test(up.headers['User-Agent'] || ''), 'identifying User-Agent is sent, as the usage policy requires');
for (const forbidden of ['CF-Connecting-IP', 'Referer', 'Cookie', 'cookie', 'referer']) {
  ok(!(forbidden in up.headers), `no ${forbidden} forwarded upstream`);
}

// ── 3. NOTHING the reader typed is stored ────────────────────────────────────
const stored = JSON.stringify(kvWrites);
ok(kvWrites.length > 0, 'the rate-limit counter did record something');
ok(!stored.includes('Privet'), 'no fragment of the query reaches storage');
ok(!stored.includes('203.0.113.9'), 'no raw reader IP reaches storage');
ok(kvWrites.every((w) => /^arl(-global)?:/.test(w.k)), 'only counter keys are written', stored.slice(0, 120));
ok(kvWrites.every((w) => /^\d+$/.test(w.v)), 'counter values are bare integers');

// ── 4. a repeat lookup never leaves the worker ───────────────────────────────
const before = upstreamCalls.length;
res = await call(`https://artwaste.land/api/atlas/place?q=${encodeURIComponent(SECRET)}`);
ok(res.status === 200, 'cached repeat still answers');
ok(upstreamCalls.length === before, 'a repeated query makes no second upstream request', `${upstreamCalls.length} vs ${before}`);

// ── 5. it is NOT a general proxy ─────────────────────────────────────────────
reset();
for (const [q, why] of [
  ['', 'empty query refused'],
  ['x'.repeat(200), 'oversized query refused'],
]) {
  const r = await call(`https://artwaste.land/api/atlas/place?q=${encodeURIComponent(q)}`);
  ok(r.status === 400, why, String(r.status));
}
ok(upstreamCalls.length === 0, 'a refused place request makes no upstream call');

for (const [qs, why] of [
  ['kind=evil&lat=1&lng=2', 'unknown kind refused'],
  ['kind=columns&lat=999&lng=2', 'out-of-range latitude refused'],
  ['kind=columns&lat=abc&lng=2', 'non-numeric latitude refused'],
  ['kind=units&col_id=1;DROP', 'non-numeric col_id refused'],
  ['kind=units', 'missing col_id refused'],
]) {
  const r = await call(`https://artwaste.land/api/atlas/rock?${qs}`);
  ok(r.status === 400, why, String(r.status));
}
ok(upstreamCalls.length === 0, 'no refused rock request reached an upstream', String(upstreamCalls.length));

// an injected host in a parameter must not change where we go
reset();
upstreamPayload = { success: { data: [] } };
await call('https://artwaste.land/api/atlas/rock?kind=columns&lat=10&lng=20&host=evil.example');
ok(upstreamCalls.length === 1 && new URL(upstreamCalls[0].url).hostname === 'macrostrat.org',
  'an extra parameter cannot redirect the upstream', upstreamCalls[0]?.url || 'none');
ok(!upstreamCalls[0].url.includes('evil.example'), 'unexpected parameters are dropped, not forwarded');

// ── 6. the rate limit actually fires ─────────────────────────────────────────
reset();
upstreamPayload = [{ display_name: 'S', lat: '1', lon: '2' }];
let limited = null;
for (let i = 0; i < 60 && !limited; i++) {
  const r = await call(`https://artwaste.land/api/atlas/place?q=distinct-${i}`);
  if (r.status === 429) limited = i;
}
ok(limited !== null, 'the per-reader daily cap eventually refuses', `refused at request ${limited}`);
ok(limited <= 45, 'the cap fires near its configured value, not far past it', String(limited));

// ── 7. an upstream failure degrades honestly ─────────────────────────────────
reset();
upstreamStatus = 503;
res = await call('https://artwaste.land/api/atlas/place?q=anywhere');
body = await res.json();
ok(res.status === 502 && body.ok === false, 'an upstream error is reported, not disguised as an empty result', String(res.status));

// ── 8. wrong method ──────────────────────────────────────────────────────────
res = await worker.fetch(new Request('https://artwaste.land/api/atlas/place?q=x', { method: 'POST' }), env, ctx);
ok(res.status === 405, 'POST is refused', String(res.status));

// ── 9. the pages really do call us and not the upstreams ─────────────────────
// ⚠ The first version of this check scanned only URL LITERALS sitting directly
// inside fetch(), getJSON() and getAtlas(). It passed, and it was wrong: the
// ground probe assigned the GPlates endpoint to a variable first, so a fifth
// upstream went unseen. A check keyed to a syntactic form measures the form, not
// the property. So: no absolute URL may appear anywhere in script content at
// all, whatever shape the call takes. Citations live in href attributes, which
// are links a reader may follow rather than requests the page makes.
import { readFileSync } from 'node:fs';
const ALLOWED_IN_SCRIPT = /^https?:\/\/(artwaste\.land|www\.w3\.org|schema\.org)/;
for (const slug of ['the-sky-above-you', 'the-ground-beneath-you']) {
  const html = readFileSync(path.join(ROOT, 'public/strata', slug, 'index.html'), 'utf8');
  const scriptBodies = [...html.matchAll(/<script\b(?![^>]*ld\+json)[^>]*>([\s\S]*?)<\/script>/gi)]
    .map((m) => m[1]).join('\n');
  const urls = [...new Set([...scriptBodies.matchAll(/https?:\/\/[^\s"'`)]+/g)].map((m) => m[0]))]
    .filter((u) => !ALLOWED_IN_SCRIPT.test(u));
  ok(scriptBodies.length > 0, `${slug}: found script content to scan`, String(scriptBodies.length));
  ok(urls.length === 0, `${slug}: no absolute URL anywhere in its script content`, urls.join(', '));
  ok(/\/api\/atlas\//.test(html), `${slug}: routes its lookups through the Atlas proxy`);
  // and the src attributes, which are requests the browser makes on load
  const srcs = [...html.matchAll(/\bsrc\s*=\s*["']([^"']+)["']/g)].map((m) => m[1])
    .filter((u) => /^https?:\/\//.test(u) && !ALLOWED_IN_SCRIPT.test(u));
  ok(srcs.length === 0, `${slug}: no third-party src attribute`, srcs.join(', '));
}

globalThis.fetch = realFetch;
console.log(`PASS ${checks} checks. The upstreams see the worker, not the reader; nothing typed is stored; the proxy is not general.`);
