diff --git a/src/hooks.server.ts b/src/hooks.server.ts index a98fec3..e42ebab 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -1,11 +1,43 @@ import type { Handle } from '@sveltejs/kit'; +// Allow the marketing site (cryptographic-triangles.org) to read our +// dehydrated data endpoint so it can show a live block-height counter +// without having to expose the wallet RPC publicly. Caddy terminates +// TLS on blocks.cryptographic-triangles.org; the origin header below +// is the only site that needs read access right now. +const ALLOWED_ORIGINS = new Set([ + 'https://cryptographic-triangles.org', + 'http://localhost', + 'http://127.0.0.1' +]); + +function corsHeadersFor(request: Request): Record { + const origin = request.headers.get('origin') ?? ''; + if (!ALLOWED_ORIGINS.has(origin)) return {}; + return { + 'Access-Control-Allow-Origin': origin, + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type', + 'Access-Control-Max-Age': '600' + }; +} + export const handle: Handle = async ({ event, resolve }) => { + if (event.request.method === 'OPTIONS') { + const headers = corsHeadersFor(event.request); + return new Response(null, { status: 204, headers }); + } + const start = Date.now(); const response = await resolve(event); const duration = Date.now() - start; - + + const cors = corsHeadersFor(event.request); + for (const [k, v] of Object.entries(cors)) { + response.headers.set(k, v); + } + console.log(`[${response.status}] ${event.request.method} ${event.url.pathname} (${duration}ms)`); - + return response; };