it/web/app/api/free/edge-headers/route.ts
2025-10-25 20:37:00 +02:00

15 lines
2.2 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
export const runtime = "nodejs";
function gradeFrom(headers: Headers, https:boolean){ const get=(k:string)=>headers.get(k)||headers.get(k.toLowerCase())||""; const hsts=get("strict-transport-security"); const csp=get("content-security-policy"); const xfo=get("x-frame-options"); const rp=get("referrer-policy"); const psp=get("permissions-policy"); const xcto=get("x-content-type-options"); let score=0; const s:string[]=[]; if(https&&/max-age=\d+/.test(hsts)) score+=2; else s.push("Add HSTS."); if(/^nosniff$/i.test(xcto)) score+=1; else s.push("Add X-Content-Type-Options: nosniff."); if(/^deny$|^sameorigin$/i.test(xfo)) score+=1; else s.push("Set X-Frame-Options."); if(rp) score+=1; else s.push("Add Referrer-Policy."); if(psp) score+=1; else s.push("Add Permissions-Policy."); if(csp) score+=3; else s.push("Add a Content-Security-Policy."); if(!https) s.unshift("Use HTTPS."); const g = score>=8?"A":score>=6?"B":score>=4?"C":score>=2?"D":"F"; return {grade:g as any, suggestions:s}; }
export async function POST(req: NextRequest){
try{
const {url}=await req.json(); let target:URL; try{ target=new URL(String(url||"")); }catch{ return NextResponse.json({ok:false,error:"Invalid URL."},{status:400}); }
const controller=new AbortController(); const to=setTimeout(()=>controller.abort(),5000); let resp:Response;
try{ resp=await fetch(target.toString(),{method:"HEAD",redirect:"follow",signal:controller.signal}); }catch{ resp=await fetch(target.toString(),{method:"GET",redirect:"follow",signal:controller.signal}); } finally{ clearTimeout(to); }
const https = target.protocol==="https:" || resp.url.startsWith("https://");
const keep:Record<string,string>={}; for(const k of ["strict-transport-security","content-security-policy","x-frame-options","referrer-policy","permissions-policy","x-content-type-options","server"]){ const v=resp.headers.get(k); if(v) keep[k]=v; }
const {grade,suggestions}=gradeFrom(resp.headers,https);
return NextResponse.json({ok:true,url:resp.url,https,headers:keep,grade,suggestions});
}catch{ return NextResponse.json({ok:false,error:"Unexpected error."},{status:500}); }
}