import { panelConfig, panelPage } from './panel.mjs';

// Attach as a Route in front of an EXISTING origin, not a Custom Domain.
// Change these two values and the route pattern together; see README.md.
const PROTECTED_HOST = 'shop.example.com';
const PROTECTED_PATH = '/api/checkout';
const EVALUATE_URL = 'https://maskbreak.com/v1/evaluate';
const MAX_BYTES = 64 * 1024; // Each request/evaluation response, including chunked bodies.
const CHECK_TIMEOUT_MS = 3000;
const ORIGIN_TIMEOUT_MS = 10000; // Until response headers; the origin body is streamed.

function noStore(response) {
  const result = new Response(response.body, response);
  result.headers.set('Cache-Control', 'private, no-store');
  result.headers.set('CDN-Cache-Control', 'no-store');
  result.headers.set('Cloudflare-CDN-Cache-Control', 'no-store');
  return result;
}

function deny(status, error) {
  return noStore(Response.json({ error }, { status }));
}

function protectionResponse(request, env, decision, captcha = false) {
  const config = panelConfig({
    brand: env.SCREEN_BRAND, blockTitle: env.SCREEN_BLOCK_TITLE,
    blockMessage: env.SCREEN_BLOCK_MESSAGE, reviewTitle: env.SCREEN_REVIEW_TITLE,
    reviewMessage: env.SCREEN_REVIEW_MESSAGE, accent: env.SCREEN_ACCENT,
    supportUrl: env.SCREEN_SUPPORT_URL,
  });
  const status = decision === 'block' ? 403 : 409;
  const response = (request.headers.get('Accept') || '').includes('text/html')
    ? new Response(panelPage(decision, config), { status, headers: {
      'Content-Type': 'text/html; charset=utf-8',
      'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
      'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer',
    } })
    : Response.json({ error: decision === 'block' ? 'Request blocked' : 'Additional verification required',
      maskbreak: { version: 1, decision, screen: config,
        ...(captcha ? { challenge: { type: 'turnstile', sitekey: env.TURNSTILE_SITE_KEY, action: 'maskbreak_review' } } : {}) },
    }, { status });
  return noStore(response);
}

async function passedChallenge(request, env, protectedHost) {
  const token = request.headers.get('X-Maskbreak-Challenge');
  if (!token || token.length > 2048 || /\s/.test(token)) return false;
  return withTimeout(CHECK_TIMEOUT_MS, async signal => {
    const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ secret: env.TURNSTILE_SECRET, response: token,
        ...(request.headers.get('CF-Connecting-IP') ? { remoteip: request.headers.get('CF-Connecting-IP') } : {}) }),
      redirect: 'error', cache: 'no-store', signal,
    });
    if (!response.ok || !(response.headers.get('Content-Type') || '').toLowerCase().startsWith('application/json')) {
      if (response.body) await response.body.cancel();
      return false;
    }
    const result = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await readBytes(response, signal)));
    // A client claim, an expired/replayed token, another site's token or
    // another action's token never releases this protected request.
    return result.success === true && result.hostname === protectedHost
      && result.action === 'maskbreak_review';
  });
}

async function withTimeout(ms, work) {
  const controller = new AbortController();
  let timer;
  const deadline = new Promise((_, reject) => {
    timer = setTimeout(() => {
      reject(new Error('Deadline exceeded'));
      controller.abort();
    }, ms);
  });
  try {
    return await Promise.race([work(controller.signal), deadline]);
  } catch (error) {
    controller.abort();
    throw error;
  } finally {
    clearTimeout(timer);
  }
}

// Read the original stream once, then reconstruct it from these bounded bytes.
// Cloning/teeing an arbitrary upload can buffer an unbounded second branch.
async function readBytes(message, signal) {
  if (Number(message.headers.get('Content-Length')) > MAX_BYTES) {
    throw deny(413, 'Body too large');
  }
  if (!message.body) return new Uint8Array();
  const reader = message.body.getReader();
  const bytes = new Uint8Array(MAX_BYTES);
  let length = 0;
  let cancellation;
  const cancel = () => { cancellation = reader.cancel().catch(() => {}); };
  signal.addEventListener('abort', cancel, { once: true });
  try {
    for (;;) {
      signal.throwIfAborted();
      const { done, value } = await reader.read();
      signal.throwIfAborted();
      if (done) return bytes.subarray(0, length);
      if (length + value.byteLength > MAX_BYTES) throw deny(413, 'Body too large');
      bytes.set(value, length);
      length += value.byteLength;
    }
  } finally {
    signal.removeEventListener('abort', cancel);
    await (cancellation || reader.cancel().catch(() => {}));
    reader.releaseLock();
  }
}

const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);

// A used-up month: HTTP 429 whose JSON body carries the code
// monthly_quota_exceeded. Any other 429 (the per-address ceiling, the
// invalid-key lockout) fails closed like every other error.
async function monthlyAllowanceUsed(response, signal) {
  if ((response.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase() !== 'application/json') return false;
  const body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await readBytes(response, signal)));
  return object(body) && body.code === 'monthly_quota_exceeded';
}
const booleans = (value, keys) => object(value) && keys.every(key => typeof value[key] === 'boolean');
const liveFlags = value => ['test', 'sample', 'sandbox', 'degraded'].every(
  key => value[key] === undefined || value[key] === false
);

function liveVerdict(value) {
  return object(value) && liveFlags(value) && value.status === 'success'
    && ['allow', 'review', 'block'].includes(value.decision)
    && Number.isFinite(value.risk_score) && value.risk_score >= 0 && value.risk_score <= 100
    && [value.details, value.network, value.device, value.deviceIntel].every(
      part => part === undefined || (object(part) && liveFlags(part))
    );
}

function complete(value) {
  // /v1/evaluate omits device when the device event lookup failed. An allow
  // alone does not prove either layer ran. No invented "complete" API flag.
  return typeof value.ip === 'string' && value.ip.trim() !== '' && value.ip !== 'unknown'
    && booleans(value.network, ['vpn', 'proxy', 'datacenter', 'anonymous', 'tor', 'residential'])
    && booleans(value.device, ['antidetect', 'automation', 'emulator', 'virtual_machine',
      'incognito', 'privacy_mode', 'ip_blocklisted', 'high_activity'])
    && Number.isFinite(value.device.tampering_score);
}

function browserTokens(bytes, type) {
  const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
  let fields;
  if (type === 'application/json') {
    fields = JSON.parse(text);
    if (!object(fields)) throw deny(400, 'Expected a JSON object');
  } else {
    const form = new URLSearchParams(text);
    if (form.getAll('monocle').length !== 1 || form.getAll('sentinel_fp').length !== 1) {
      throw deny(403, 'Browser verification required');
    }
    fields = Object.fromEntries(form);
  }
  const token = fields.monocle;
  const fingerprintEventId = fields.sentinel_fp;
  if (!validToken(token, 32768) || !validToken(fingerprintEventId, 256)) {
    throw deny(403, 'Browser verification required');
  }
  // Send only verification inputs, never passwords, cookies, or form fields.
  return { token, fingerprintEventId };
}

function validToken(value, max) {
  return typeof value === 'string' && value.length > 0 && value.length <= max
    && value.trim() === value && !/\s/.test(value) && !/^(test|sample|sandbox)(?:_|$)/i.test(value);
}

// Rollout switch, the same one as the dashboard snippets and integrate.md:
// MASKBREAK_MODE, a plain Worker variable (not a secret).
//   'watch' (the default; also any value other than 'enforce'): run every check
//     below, write one log line with what enforce would have returned, then
//     forward the request to the origin anyway. A missing token, a missing key,
//     an error or a Maskbreak outage never locks a real customer out. The one
//     exception is a body the Worker had to stop reading (over 64 KiB without a
//     Content-Length, or a stalled upload): it cannot forward bytes it no
//     longer has, so that request gets the same refusal in both modes.
//   'enforce': the gate. Only a complete live allow, or a complete review that
//     passed a server-verified Turnstile challenge, reaches the origin. One
//     exception: when the month's checks are used up (HTTP 429 with the code
//     monthly_quota_exceeded), requests reach the origin unchecked, with one
//     log line each, until the allowance resets on the 1st (00:00 UTC), so a
//     used-up month (or a flood that used it up) never takes the form offline.
// Deploy in watch mode, compare the log lines with the dashboard's Events for
// a few days, then set MASKBREAK_MODE to "enforce" and redeploy.
const enforcing = env => env?.MASKBREAK_MODE === 'enforce';

// Everything enforce mode decides, without forwarding. Returns
// { response } for a refusal, plus the buffered body `bytes` when it was read,
// the parsed `verdict` and the evaluation's `requestId` when there was one.
async function gate(request, env, enforce) {
  const url = new URL(request.url);
  const protectedHost = env?.PROTECTED_HOST || PROTECTED_HOST;
  const protectedPath = env?.PROTECTED_PATH || PROTECTED_PATH;
  if (url.host !== protectedHost || url.pathname !== protectedPath) {
    return { response: deny(404, 'Not found') };
  }
  if (url.protocol !== 'https:') return { response: deny(403, 'HTTPS required') };
  if (request.method !== 'POST') {
    const response = deny(405, 'POST required');
    response.headers.set('Allow', 'POST');
    return { response };
  }
  if (typeof env?.MASKBREAK_API_KEY !== 'string'
    || !/^sk_live_[A-Za-z0-9_-]{1,72}$/.test(env.MASKBREAK_API_KEY)) {
    return { response: deny(503, 'Verification unavailable') };
  }
  const type = (request.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase();
  if (!['application/json', 'application/x-www-form-urlencoded'].includes(type)
    || (request.headers.get('Content-Encoding') || 'identity').toLowerCase() !== 'identity') {
    return { response: deny(415, 'Use uncompressed JSON or URL-encoded form data') };
  }

  let bytes, inputs;
  try {
    bytes = await withTimeout(CHECK_TIMEOUT_MS, signal => readBytes(request, signal));
    inputs = browserTokens(bytes, type);
  } catch (error) {
    if (error instanceof Response) return { response: error, bytes };
    return { bytes, response: deny(error instanceof SyntaxError || error instanceof TypeError ? 400 : 503,
      error instanceof SyntaxError || error instanceof TypeError ? 'Invalid request body' : 'Verification unavailable') };
  }

  let verdict, requestId = null, monthUsedUp = false;
  const result = response => ({ bytes, verdict, requestId, monthUsedUp, response });
  try {
    verdict = await withTimeout(CHECK_TIMEOUT_MS, async signal => {
      const response = await fetch(EVALUATE_URL, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${env.MASKBREAK_API_KEY}`,
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify(inputs),
        redirect: 'error', // Never send the key to a redirect destination.
        cache: 'no-store',
        signal,
      });
      requestId = response.headers.get('X-Request-Id');
      if (response.status === 429 && await monthlyAllowanceUsed(response, signal)) {
        monthUsedUp = true;
        return null;
      }
      if (!response.ok || (response.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase() !== 'application/json') {
        if (response.body) await response.body.cancel();
        throw new Error('Evaluation failed');
      }
      return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(await readBytes(response, signal)));
    });
    // The month's checks are used up: through to the origin, logged (see above).
    if (monthUsedUp) return result(null);
    if (!liveVerdict(verdict)) return result(deny(503, 'Verification unavailable'));
    if (verdict.decision === 'block') return result(protectionResponse(request, env, 'block'));
    if (verdict.decision === 'review') {
      if (env.REVIEW_MODE !== 'turnstile') return result(protectionResponse(request, env, 'review'));
      if (!validToken(env.TURNSTILE_SITE_KEY, 100) || !validToken(env.TURNSTILE_SECRET, 256)) {
        return result(deny(503, 'Review verification is not configured'));
      }
      if (!complete(verdict)) return result(deny(503, 'Verification unavailable'));
      // Watch mode never shows a challenge, so it never spends a Turnstile token.
      if (!enforce) return result(protectionResponse(request, env, 'review', true));
      if (!await passedChallenge(request, env, protectedHost)) return result(protectionResponse(request, env, 'review', true));
    }
    if (!complete(verdict)) return result(deny(503, 'Verification unavailable'));
    return result(null);
  } catch {
    // No exception messages, tokens, response bodies or credentials in logs.
    return result(deny(503, 'Verification unavailable'));
  }
}

// Route subrequests reach the existing origin. Keep URL, body bytes, cookies,
// authorization and CSRF headers; never add the Maskbreak key. `bytes` is
// undefined only in watch mode when the gate stopped before reading the body,
// so the untouched original stream goes through.
async function forward(request, bytes) {
  const originHeaders = new Headers(request.headers);
  originHeaders.delete('X-Maskbreak-Challenge'); // Never leak CAPTCHA tokens into origin logs.
  const original = bytes === undefined
    ? new Request(request, { headers: originHeaders, redirect: 'manual' })
    : new Request(request, { headers: originHeaders, body: bytes, redirect: 'manual' });
  const response = await withTimeout(ORIGIN_TIMEOUT_MS, signal => fetch(original, {
    redirect: 'manual', cache: 'no-store', signal,
  }));
  return noStore(response);
}

// One line per watched request, and per request enforce mode let through
// because the month's checks are used up: never the key, browser tokens, form
// data, headers or error text. `enforce_would` is the status enforce mode returns.
function logWatch(check, forwarded, mode = 'watch') {
  const verdict = object(check.verdict) ? check.verdict : {};
  console.log('[maskbreak]', JSON.stringify({
    mode,
    decision: ['allow', 'review', 'block'].includes(verdict.decision) ? verdict.decision : null,
    reasons: Array.isArray(verdict.reasons)
      ? verdict.reasons.filter(reason => typeof reason === 'string').slice(0, 10).map(reason => reason.slice(0, 200))
      : null,
    risk_score: Number.isFinite(verdict.risk_score) ? verdict.risk_score : null,
    request_id: typeof check.requestId === 'string' ? check.requestId.slice(0, 100) : null,
    enforce_would: check.response ? 'return ' + check.response.status : 'continue',
    forwarded,
    ...(check.monthUsedUp ? { month_used_up: true } : {}),
  }));
}

export default {
  async fetch(request, env) {
    const enforce = enforcing(env);
    const check = await gate(request, env, enforce);
    if (enforce) {
      if (check.response) return check.response;
      if (check.monthUsedUp) logWatch(check, true, 'enforce');
      try {
        return await forward(request, check.bytes);
      } catch {
        return deny(503, 'Verification unavailable');
      }
    }
    // Watch: forward whatever the gate decided, unless the body is gone.
    const forwardable = check.bytes !== undefined || !request.bodyUsed;
    logWatch(check, forwardable);
    if (!forwardable) return check.response;
    if (check.response?.body) await check.response.body.cancel();
    try {
      return await forward(request, check.bytes);
    } catch {
      return deny(503, 'Verification unavailable');
    }
  },
};
