import type { Request } from "caido:utils";
import jwt from "jsonwebtoken";

export class TokenLeakCheck {
  public static extractIdToken(req: Request): string | null {
    // 1. Authorization 헤더 확인\\
    const header = req.getHeaders() as Record<string, string | string[] | undefined>;
    const authHeader = header["authorization"] || header["Authorization"];
    if (typeof authHeader === "string" && authHeader.startsWith("Bearer ")) {
      return authHeader.slice(7).trim();
    }

    // 2. 쿼리 파라미터
    const query = req.getQuery();
    if (query && typeof query === "object" && "id_token" in query) {
      return (query as Record<string, any>).id_token;
    }

    // 3. POST 바디 안에 id_token이 있을 경우
    const rawBody = req.getRaw();
    const body = rawBody ? rawBody.toString() : "";
    const match = body.match(/id_token=([^&\s]+)/);
    if (match && typeof match[1] === "string") {
      return decodeURIComponent(match[1]);
    }

    return null;
  }

  public static decodeIdToken(req: Request): Record<string, any> | null {
    const token = this.extractIdToken(req);
    if (!token) return null;

    const decoded = jwt.decode(token, { complete: true });
    if (!decoded || typeof decoded !== "object") return null;

    return {
      header: decoded.header,
      payload: decoded.payload,
    };
  }
}
