// packages/backend/src/index.ts
import { promises as fs } from "fs";
import * as path from "path";
import os from "os";
var requestMap = /* @__PURE__ */ new Map();
function init(sdk) {
  sdk.events.onInterceptRequest(async (sdk2, req) => {
    try {
      const urlString = req.getUrl();
      const url = new URL(urlString);
      sdk2.console.log(`[OAuthPlugin] Intercepted request: ${urlString}`);
      if (!url.pathname.includes("/authorize") && !url.pathname.includes("/auth")) return;
      const params = new URLSearchParams(url.search);
      const redirectUri = params.get("redirect_uri");
      if (!redirectUri) return;
      const reqId = req.getId();
      requestMap.set(reqId, redirectUri);
      const clientId = params.get("client_id") ?? "(missing)";
      const responseType = params.get("response_type") ?? "(missing)";
      const isScan = params.has("scan");
      if (isScan) return;
      const output = {
        original_url: urlString,
        client_id: clientId,
        redirect_uri: redirectUri,
        response_type: responseType
      };
      try {
        const filePath = path.join(os.tmpdir(), "oauth-fuzz-input.json");
        await fs.writeFile(filePath, JSON.stringify(output, null, 2));
      } catch (err) {
        await sdk2.findings.create({
          title: "[fs] Write Failed",
          description: `Could not write to file: ${err}`,
          request: req,
          reporter: "oauth-open-redirect-detector"
        });
      }
      await sdk2.findings.create({
        title: "[ ] OAuth2 Authorization Request Collected",
        description: `client_id: ${clientId}
redirect_uri: ${redirectUri}
response_type: ${responseType}`,
        request: req,
        reporter: "oauth-open-redirect-detector"
      });
    } catch (err) {
      sdk2.console.error(`Error in onInterceptRequest: ${err}`);
    }
  });
  sdk.events.onInterceptResponse(async (sdk2, req, resp) => {
    try {
      const reqId = req.getId();
      const url = new URL(req.getUrl());
      const status = resp.getCode();
      const location = resp.getHeader("location")?.[0];
      const params = new URLSearchParams(url.search);
      const isScan = params.has("scan");
      if (!isScan) {
        requestMap.delete(reqId);
        return;
      }
      if (status >= 300 && status < 400 && location) {
        const redirectUri = requestMap.get(reqId) ?? "(unknown)";
        await sdk2.findings.create({
          title: "[+] Redirect URI Misconfiguration Detected",
          description: `Status: ${status}
Location: ${location}
Original Redirect URI: ${redirectUri}
Request URL: ${url.href}`,
          request: req,
          reporter: "oauth-open-redirect-detector"
        });
      }
      requestMap.delete(reqId);
    } catch (err) {
      sdk2.console.error(`Error in onInterceptResponse: ${err}`);
    }
  });
}
export {
  init
};
