export default { async fetch(request, env) { const url = new URL(request.url); // 1. Authenticate incoming webhook requests const authHeader = request.headers.get("Authorization"); if (authHeader !== `Bearer ${env.WEBHOOK_SECRET}`) { return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 }); } // 2. Register iOS Device Token: POST /register if (request.method === "POST" && url.pathname === "/register") { const { device_id = "primary", token } = await request.json(); if (!token) return new Response("Missing token", { status: 400 }); await env.BEACON_KV.put(`token:${device_id}`, token); return Response.json({ status: "registered", device_id }); } // 3. Trigger APNs Location Push: POST /ping if (request.method === "POST" && url.pathname === "/ping") { const { device_id = "primary", sandbox = false } = await request.json().catch(() => ({})); const deviceToken = await env.BEACON_KV.get(`token:${device_id}`); if (!deviceToken) return Response.json({ error: "Device token not found" }, { status: 404 }); const jwt = await generateApnsJwt(env.APNS_TEAM_ID, env.APNS_KEY_ID, env.APNS_P8_KEY); const apnsHost = sandbox ? "https://api.sandbox.push.apple.com" : "https://api.push.apple.com"; const apnsRes = await fetch(`${apnsHost}/3/device/${deviceToken}`, { method: "POST", headers: { "authorization": `bearer ${jwt}`, "apns-topic": `${env.BUNDLE_ID}.location-query`, "apns-push-type": "location", "apns-priority": "10", "content-type": "application/json" }, body: "{}" }); const apnsId = apnsRes.headers.get("apns-id"); const errorBody = apnsRes.ok ? null : await apnsRes.text(); return Response.json({ delivered: apnsRes.ok, status: apnsRes.status, apns_id: apnsId, error: errorBody }, { status: apnsRes.status }); } // 4. Receive Location Callback from iOS Extension: POST /report if (request.method === "POST" && url.pathname === "/report") { const payload = await request.json(); const record = { ...payload, received_at: new Date().toISOString() }; await env.BEACON_KV.put(`last_location:${payload.device_id || "primary"}`, JSON.stringify(record)); return Response.json({ status: "logged", record }); } // 5. Read Latest Coordinates: GET /status if (request.method === "GET" && url.pathname === "/status") { const deviceId = url.searchParams.get("device_id") || "primary"; const latest = await env.BEACON_KV.get(`last_location:${deviceId}`); return new Response(latest || JSON.stringify({ status: "no_data" }), { headers: { "content-type": "application/json" } }); } return new Response("Not Found", { status: 404 }); } }; // Native Web Crypto ES256 Signer for Apple .p8 Keys async function generateApnsJwt(teamId, keyId, p8Pem) { const header = { alg: "ES256", kid: keyId }; const claims = { iss: teamId, iat: Math.floor(Date.now() / 1000) }; const encode = (obj) => btoa(JSON.stringify(obj)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); const unsigned = `${encode(header)}.${encode(claims)}`; const pemContents = p8Pem .replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replace(/\s+/g, ""); const binaryDer = Uint8Array.from(atob(pemContents), (c) => c.charCodeAt(0)); const key = await crypto.subtle.importKey( "pkcs8", binaryDer.buffer, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"] ); const signature = await crypto.subtle.sign( { name: "ECDSA", hash: "SHA-256" }, key, new TextEncoder().encode(unsigned) ); const sigBase64 = btoa(String.fromCharCode(...new Uint8Array(signature))) .replace(/=/g, "") .replace(/\+/g, "-") .replace(/\//g, "_"); return `${unsigned}.${sigBase64}`; }