mirror of
https://github.com/multipleof4/4ev.link.git
synced 2026-01-13 23:57:55 +00:00
Fix: Accept naked domains; normalize URLs
This commit is contained in:
@@ -1,33 +1,17 @@
|
|||||||
const C='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',L=4,H={'Access-Control-Allow-Origin':'*'}
|
const C='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',L=4,H={'Access-Control-Allow-Origin':'*'},r=_=>[...Array(L)].map(_=>C[Math.random()*C.length|0]).join(''),n=u=>{try{return new URL(u).href}catch(_){try{return new URL('https://'+u).href}catch(_){}}}
|
||||||
const r=()=>[...Array(L)].map(()=>C[Math.random()*C.length|0]).join('')
|
|
||||||
|
|
||||||
export async function onRequest({request, env, next}){
|
export async function onRequest({request,env,next}){
|
||||||
if(request.method==='OPTIONS')return new Response(null,{headers:{...H,'Access-Control-Allow-Methods':'POST','Access-Control-Allow-Headers':'Content-Type'}})
|
if(request.method==='OPTIONS')return new Response(null,{headers:{...H,'Access-Control-Allow-Methods':'POST','Access-Control-Allow-Headers':'Content-Type'}})
|
||||||
|
|
||||||
const u=new URL(request.url)
|
const u=new URL(request.url)
|
||||||
|
|
||||||
// Handle POST request to create a link (API call)
|
|
||||||
if(u.pathname==='/api/create'&&request.method==='POST'){
|
if(u.pathname==='/api/create'&&request.method==='POST'){
|
||||||
try{
|
try{
|
||||||
const{url:t}=await request.json();
|
let{url:t}=await request.json();t=n(t);if(!t)throw 0
|
||||||
new URL(t);
|
let s;do s=r();while(await env.EV.get(s))
|
||||||
let s;
|
await env.EV.put(s,t)
|
||||||
do s=r();while(await env.EV.get(s));
|
return new Response(JSON.stringify({slug:s,target:t,shortUrl:`${u.origin}/${s}`}),{headers:{'Content-Type':'application/json',...H}})
|
||||||
await env.EV.put(s,t);
|
}catch(_){return new Response('Invalid URL',{status:400,headers:H})}
|
||||||
const d={slug:s,target:t,shortUrl:`${u.origin}/${s}`};
|
|
||||||
return new Response(JSON.stringify(d),{headers:{'Content-Type':'application/json',...H}})
|
|
||||||
}catch(e){
|
|
||||||
return new Response('Invalid URL',{status:400,headers:H})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle GET request for a slug (Redirect)
|
|
||||||
const p=u.pathname.slice(1)
|
const p=u.pathname.slice(1)
|
||||||
if(p){
|
if(p){const t=await env.EV.get(p);if(t)return Response.redirect(t,302)}
|
||||||
const t=await env.EV.get(p)
|
|
||||||
if(t)return Response.redirect(t,302)
|
|
||||||
}
|
|
||||||
|
|
||||||
// For all other requests (like GET /), pass them to the static asset handler.
|
|
||||||
return next()
|
return next()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user