Last active
October 27, 2023 20:55
-
-
Save CodaBool/163a8e71323a2b029f31e1bc5dd9b86e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Router } from 'itty-router' | |
const router = Router() | |
// from client | |
router.get('/', async (request, env) => { | |
const url = new URL(request.url) | |
const token = url.searchParams.get("token") | |
const module = url.searchParams.get("module") | |
if (!token || !module) { | |
return new Response('missing token or module query', { status: 400 }) | |
} | |
const tokenExists = await env.KV.get(token) | |
if (!tokenExists) { | |
return new Response('Expired token', { status: 403 }) | |
} | |
const zip = await env.R2.get(module) | |
if (zip === null) { | |
return new Response(`module ${module} does not exist`, { status: 404 }) | |
} | |
if (zip.status >= 400) { | |
return new Response('Error fetching the zip file', { status: 500 }) | |
} | |
// Return the zip file | |
return new Response(zip.body, { | |
headers: { | |
'Content-Type': 'application/zip', | |
'Content-Disposition': `attachment; filename="${module.slice(0, -7)}.zip"`, | |
}, | |
}) | |
}) | |
// from foundryvtt.com server | |
router.post('/', async (request, env)=> { | |
const body = await request.json() | |
const token = await crypto.randomUUID() | |
// timed token | |
await env.KV.put(token, body.user_id, { expirationTTL: 14400 }) | |
const data = JSON.stringify({ | |
package_name: body.package_name, | |
version: body.version, | |
download: `https://${env.DOMAIN}/?token=${token}&module=${body.package_name}-v${body.version}`, | |
}, null, 2) | |
return new Response(data, { | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
}) | |
}) | |
// 404 for everything else | |
router.all('*', () => new Response('Not Found.', { status: 404 })); | |
export default { | |
async fetch(request, env, ctx) { | |
return router.handle(request, env) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment