#!/usr/bin/env bun
// cdp-key — capture a secret value from a network response in the attached
// Chrome, optionally after triggering the page action that produces it.
//
// Built for one-time API-key reveals: the value goes to stdout so it can be
// piped into `secretctl add NAME` and never printed into a transcript.
//
//   cdp-key --url=groq \
//           --match='/keys|api_keys' \
//           --pattern='gsk_[A-Za-z0-9]{20,}' \
//           --trigger='[...document.querySelectorAll("button")].find(b=>/create|submit/i.test(b.innerText)).click()'
//
// Options:
//   --port=9222        CDP port
//   --url=substring    page target filter
//   --match=regex      response URL filter
//   --pattern=regex    secret pattern searched in the response body
//   --trigger=js       expression run right after listeners attach
//   --wait=8000        ms to wait for a match
//   --in-page          also try the page text after a match attempt
//
// Exit: 0 found, 1 not found or CDP error, 2 usage.

const opts = { port: 9222, url: "", match: "", pattern: "", trigger: "", wait: 8000, inPage: false };
for (const a of process.argv.slice(2)) {
  if (a === "-h" || a === "--help") {
    console.log("usage: cdp-key --url=<sub> --match=<regex> --pattern=<regex> [--trigger=<js>] [--wait=ms] [--in-page]");
    process.exit(0);
  }
  if (a === "--in-page") { opts.inPage = true; continue; }
  const m = a.match(/^--(port|url|match|pattern|trigger|wait)=(.*)$/s);
  if (!m) continue;
  if (m[1] === "port" || m[1] === "wait") opts[m[1]] = Number(m[2]);
  else if (m[1] === "match") opts.match = m[2];
  else if (m[1] === "pattern") opts.pattern = m[2];
  else if (m[1] === "trigger") opts.trigger = m[2];
  else opts.url = m[2];
}
if (!opts.pattern) { console.error("cdp-key: --pattern is required"); process.exit(2); }

const list = await (await fetch(`http://127.0.0.1:${opts.port}/json`)).json();
const pages = list.filter((t) => t.type === "page");
const page = (opts.url && pages.find((t) => t.url.includes(opts.url))) || pages[0];
if (!page) { console.error("cdp-key: no page target"); process.exit(1); }

const secretRe = new RegExp(opts.pattern);
const urlRe = opts.match ? new RegExp(opts.match) : null;
const ws = new WebSocket(page.webSocketDebuggerUrl);
let id = 0;
const pending = new Map();
const send = (method, params = {}) =>
  new Promise((resolve, reject) => {
    const msgId = ++id;
    pending.set(msgId, { resolve, reject });
    ws.send(JSON.stringify({ id: msgId, method, params }));
  });

ws.onmessage = async (e) => {
  let msg;
  try { msg = JSON.parse(String(e.data)); } catch { return; }
  if (msg.id && pending.has(msg.id)) {
    const p = pending.get(msg.id);
    pending.delete(msg.id);
    msg.error ? p.reject(new Error(msg.error.message)) : p.resolve(msg.result);
    return;
  }
  if (msg.method === "Network.responseReceived") {
    const url = msg.params?.response?.url || "";
    if (urlRe && !urlRe.test(url)) return;
    try {
      const body = await send("Network.getResponseBody", { requestId: msg.params.requestId });
      const text = body.base64Encoded ? atob(body.body) : body.body;
      const hit = text.match(secretRe);
      if (hit) finish(hit[0]);
    } catch {}
  }
};

let finished = false;
function finish(value) {
  if (finished) return;
  finished = true;
  process.stdout.write(value);
  try { ws.close(); } catch {}
  process.exit(0);
}

const evaluate = (expression) =>
  send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true, userGesture: true });

ws.onopen = async () => {
  try {
    await send("Network.enable");
    await send("Page.enable");
    if (opts.trigger) {
      const r = await evaluate(opts.trigger);
      if (r?.exceptionDetails) console.error("cdp-key: trigger threw: " + (r.exceptionDetails.exception?.description || ""));
    }
    setTimeout(async () => {
      if (finished) return;
      if (opts.inPage) {
        try {
          const r = await evaluate(
            `(()=>{const m=document.body.innerText.match(${JSON.stringify(opts.pattern)});return m?m[0]:""})()`
          );
          const v = r?.result?.value;
          if (v) return finish(v);
        } catch {}
      }
      finished = true;
      console.error("cdp-key: no match within " + opts.wait + "ms");
      try { ws.close(); } catch {}
      process.exit(1);
    }, opts.wait);
  } catch (e) {
    console.error("cdp-key: " + e.message);
    process.exit(1);
  }
};
ws.onerror = () => { if (!finished) { console.error("cdp-key: websocket error"); process.exit(1); } };
