import { serveSponsoredInstagramImage, sponsored, sponsoredInstagramImage } from '../server/sponsored.mjs'; import connect from '../api/connect.js'; import media from '../api/media.js'; import config from '../vercel.json'; const canonical = 'https://inkspring.ai'; const globalHeaders = config.headers.find(rule => rule.source === '/(.*)'); const desktopHeaders = config.headers.find(rule => rule.source === '/desktop-connect/:path*'); function redirect(location, status, original) { if (original?.search) { const destination = new URL(location, original); for (const [key, value] of original.searchParams) destination.searchParams.append(key, value); location = location.startsWith('/') ? destination.pathname + destination.search + destination.hash : destination.href; } return new Response(null, { status, headers: { Location: location, 'Cache-Control': 'public, max-age=0, must-revalidate' } }); } function headersFor(url, actual) { const headers = new Headers(actual); const rules = [globalHeaders]; if (url.pathname === '/desktop-connect' || url.pathname.startsWith('/desktop-connect/')) { rules.push(desktopHeaders); } for (const rule of rules) { for (const { key, value } of rule.headers) { if (key === 'Set-Cookie') headers.append(key, value); else if (key === 'Cache-Control' || rule !== globalHeaders || !headers.has(key)) headers.set(key, value); } } return headers; } async function boundedText(request) { if (!request.body) return ''; const reader = request.body.getReader(); const decoder = new TextDecoder(); let count = 0; let text = ''; for (;;) { const { done, value } = await reader.read(); if (done) return text + decoder.decode(); count += value.length; if (count > 24000) { await reader.cancel(); throw new Error('Invalid connection request.'); } text += decoder.decode(value, { stream: true }); } } async function handleApi(handler, request, url, env) { let status = 200; const headers = new Headers(); const send = body => new Response(body, { status, headers }); const response = { setHeader: (key, value) => headers.set(key, value), status(code) { status = code; return this; }, json(value) { headers.set('Content-Type', 'application/json; charset=utf-8'); return send(JSON.stringify(value)); }, redirect(code, location) { status = code; headers.set('Location', location); return send(null); }, send(value) { headers.set('Content-Type', 'text/html; charset=utf-8'); return send(value); }, end: () => send(null), }; const query = Object.fromEntries([...new Set(url.searchParams.keys())].map(key => { const values = url.searchParams.getAll(key); return [key, values.length === 1 ? values[0] : values]; })); const input = { method: request.method, url: url.href, query, headers: Object.fromEntries(request.headers), [Symbol.asyncIterator]: () => request.body[Symbol.asyncIterator](), }; if (handler === connect && request.method === 'POST' && query.action === 'refresh') { try { input.body = await boundedText(request); } catch { status = 400; headers.set('Cache-Control', 'no-store'); return response.json({ error: 'Invalid connection request.' }); } } return handler(input, response, { env, sendStream: send }); } // /careers was removed (2026-12-02). Answer it here with the normal 404 page so a stale // copy in the Pages asset layer can never be served again. async function notFoundPage(context) { let page = await context.env.ASSETS.fetch(new URL('/404.html', context.request.url)); const moved = page.status >= 300 && page.status < 400 && page.headers.get('Location'); if (moved) page = await context.env.ASSETS.fetch(new URL(moved, context.request.url)); return new Response(page.body, { status: 404, headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' } }); } async function route(context, url) { const { request, env } = context; if (/^\/careers\/?$/i.test(url.pathname)) return notFoundPage(context); if (url.hostname === 'www.inkspring.ai') return redirect(canonical + url.pathname + url.search, 308); if (url.pathname === '/' && url.searchParams.has('state') && (url.searchParams.has('code') || url.searchParams.has('error'))) { const destination = new URL(canonical + '/api/connect'); destination.searchParams.set('action', 'callback'); destination.searchParams.set('provider', 'x'); for (const key of ['state', 'code', 'error']) if (url.searchParams.has(key)) destination.searchParams.set(key, url.searchParams.get(key)); return new Response(null, { status: 302, headers: { Location: destination.href, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' } }); } const old = config.redirects.find(rule => !rule.has && rule.source === url.pathname); if (old) return redirect(old.destination, old.permanent ? 308 : 307, url); if (/^\/(?:about|about-us)\/?$/.test(url.pathname)) return redirect('/', 308, url); if (/^\/(?:account\/?|auth(?:\/.*)?)$/.test(url.pathname)) return redirect('/#desktop', 307, url); if (url.pathname === '/api/desktop/sponsored') return sponsored(request, env); if (url.pathname === '/api/desktop/sponsored/instagram-image') return sponsoredInstagramImage(request, env); if (url.pathname.startsWith('/instagram-sponsor-media/')) return serveSponsoredInstagramImage(request, env); const connectPath = url.pathname.match(/^\/api\/desktop\/connect\/([^/]+)$/); const callbackPath = url.pathname.match(/^\/api\/auth\/callback\/([^/]+)$/); const legacyMediaPath = /^\/tiktok-media(?:\/|$)/.test(url.pathname); if (connectPath || callbackPath || url.pathname === '/api/connect') { if (connectPath) url.searchParams.set('action', decodeURIComponent(connectPath[1])); if (callbackPath) { url.searchParams.set('action', 'callback'); url.searchParams.set('provider', decodeURIComponent(callbackPath[1])); } return handleApi(connect, request, url, env); } if (legacyMediaPath || ['/api/media', '/api/desktop/media', '/api/desktop/media/delete'].includes(url.pathname)) { return handleApi(media, request, url, env); } return context.next(); } export async function onRequest(context) { const url = new URL(context.request.url); let response; try { response = await route(context, url); } catch (error) { if (!(error instanceof URIError)) throw error; response = new Response('Invalid URL encoding', { status: 400 }); } if (response.status === 307 || response.status === 308 || url.pathname.startsWith('/api/desktop/sponsored') || url.pathname.startsWith('/instagram-sponsor-media/')) return response; return new Response(response.body, { status: response.status, statusText: response.statusText, headers: headersFor(url, response.headers) }); }