event.puter//user puter and automatic cors exemption handling in puter workers (#1342)

* event.puter

* automatic opt out cors handling

* remove "starting puterjs initialization" log

* Set compatibility date

* remove body log
This commit is contained in:
Neal Shah
2025-07-17 18:37:34 -04:00
committed by GitHub
parent cc2670444c
commit 481210b6a6
3 changed files with 67 additions and 12 deletions
@@ -4,6 +4,7 @@ function inits2w() {
// s2w router itself: Not part of any package, just a simple router.
const s2w = {
routing: true,
handleCors: true,
map: new Map(),
custom(eventName, route, eventListener) {
const matchExp = match(route);
@@ -28,14 +29,52 @@ function inits2w() {
delete(...args) {
this.custom("DELETE", ...args)
},
async handleOptions(request) {
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
};
if (
request.headers.get("Origin") !== null &&
request.headers.get("Access-Control-Request-Method") !== null &&
request.headers.get("Access-Control-Request-Headers") !== null
) {
// Handle CORS preflight requests.
return new Response(null, {
headers: {
...corsHeaders,
"Access-Control-Allow-Headers": request.headers.get(
"Access-Control-Request-Headers",
),
},
});
} else {
// Handle standard OPTIONS request.
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
});
}
},
/**
*
* @param {FetchEvent } event
* @returns
*/
async route(event) {
if (!globalThis.puter) {
console.log("Puter not loaded, initializing...");
const success = init_puter_portable(globalThis.puter_auth, globalThis.puter_endpoint || "https://api.puter.com");
console.log("Puter.js initialized successfully");
}
if (event.request.headers.has("puter-authorization")) {
event.puter = init_puter_portable(event.request.headers.get("puter-authorization"), globalThis.puter_endpoint || "https://api.puter.com", "userPuter");
}
const mappings = this.map.get(event.request.method);
if (this.handleCors && event.request.method === "OPTIONS" && !mappings) {
return this.handleOptions(event.request);
}
const url = new URL(event.request.url);
try {
for (const mapping of mappings) {
@@ -43,18 +82,22 @@ function inits2w() {
const results = mapping[0](url.pathname)
if (results) {
event.params = results.params;
return mapping[1](event);
const response = await mapping[1](event);
if (this.handleCors && !response.headers.has("access-control-allow-origin")) {
response.headers.set("Access-Control-Allow-Origin", "*");
}
return response;
}
}
} catch (e) {
return new Response(e, {status: 500, statusText: "Server Error"})
return new Response(e, { status: 500, statusText: "Server Error" })
}
return new Response("Path not found", {status: 404, statusText: "Not found"});
return new Response("Path not found", { status: 404, statusText: "Not found" });
}
}
globalThis.s2w = s2w;
self.addEventListener("fetch", (event)=> {
self.addEventListener("fetch", (event) => {
if (!s2w.routing)
return false;
event.respondWith(s2w.route(event));
@@ -15,9 +15,7 @@ if (globalThis.Cloudflare) {
}
}
globalThis.init_puter_portable = (auth, apiOrigin) => {
console.log("Starting puter.js initialization");
globalThis.init_puter_portable = (auth, apiOrigin, type) => {
// Who put C in my JS??
/*
* This is a hack to include the puter.js file.
@@ -25,7 +23,21 @@ globalThis.init_puter_portable = (auth, apiOrigin) => {
* The puter.js file is handled by the C preprocessor here because webpack cant behave with already minified files.
* The C preprocessor basically just includes the file and then we can use the puter.js file in the worker.
*/
#include "../../../../../puter-js/dist/puter.js"
if (type === "userPuter") {
const goodContext = {}
Object.getOwnPropertyNames(globalThis).forEach(name => { try { goodContext[name] = globalThis[name]; } catch {} })
goodContext.globalThis = goodContext;
goodContext.addEventListener = ()=>{};
// @ts-ignore
with (goodContext) {
#include "../../../../../puter-js/dist/puter.js"
}
goodContext.puter.setAPIOrigin(apiOrigin);
goodContext.puter.setAuthToken(auth);
return goodContext.puter;
} else {
#include "../../../../../puter-js/dist/puter.js"
}
puter.setAPIOrigin(apiOrigin);
puter.setAuthToken(auth);
}
@@ -19,12 +19,12 @@ async function getWorker(userData, authorization, workerId) {
await cfFetch(`${WORKERS_BASE_URL}/scripts/${calculateWorkerName(userData.username, workerId)}`, "GET");
}
async function createWorker(userData, authorization, workerId, body, PREAMBLE_LENGTH) {
console.log(body)
const formData = new FormData();
const workerMetaData = {
body_part: "swCode",
compatibility_date: "2025-07-15",
bindings: [
{
type: "secret_text",