Inkspring / website / functions / _middleware.js
| 1 | import { serveSponsoredInstagramImage, sponsored, sponsoredInstagramImage } from '../server/sponsored.mjs'; |
| 2 | import connect from '../api/connect.js'; |
| 3 | import media from '../api/media.js'; |
| 4 | import config from '../vercel.json'; |
| 5 | |
| 6 | const canonical = 'https://inkspring.ai'; |
| 7 | const globalHeaders = config.headers.find(rule => rule.source === '/(.*)'); |
| 8 | const desktopHeaders = config.headers.find(rule => rule.source === '/desktop-connect/:path*'); |
| 9 | |
| 10 | function redirect(location, status, original) { |
| 11 | if (original?.search) { |
| 12 | const destination = new URL(location, original); |
| 13 | for (const [key, value] of original.searchParams) destination.searchParams.append(key, value); |
| 14 | location = location.startsWith('/') ? destination.pathname + destination.search + destination.hash : destination.href; |
| 15 | } |
| 16 | return new Response(null, { status, headers: { Location: location, 'Cache-Control': 'public, max-age=0, must-revalidate' } }); |
| 17 | } |
| 18 | |
| 19 | function headersFor(url, actual) { |
| 20 | const headers = new Headers(actual); |
| 21 | const rules = [globalHeaders]; |
| 22 | if (url.pathname === '/desktop-connect' || url.pathname.startsWith('/desktop-connect/')) { |
| 23 | rules.push(desktopHeaders); |
| 24 | } |
| 25 | for (const rule of rules) { |
| 26 | for (const { key, value } of rule.headers) { |
| 27 | if (key === 'Set-Cookie') headers.append(key, value); |
| 28 | else if (key === 'Cache-Control' || rule !== globalHeaders || !headers.has(key)) headers.set(key, value); |
| 29 | } |
| 30 | } |
| 31 | return headers; |
| 32 | } |
| 33 | |
| 34 | async function boundedText(request) { |
| 35 | if (!request.body) return ''; |
| 36 | const reader = request.body.getReader(); |
| 37 | const decoder = new TextDecoder(); |
| 38 | let count = 0; |
| 39 | let text = ''; |
| 40 | for (;;) { |
| 41 | const { done, value } = await reader.read(); |
| 42 | if (done) return text + decoder.decode(); |
| 43 | count += value.length; |
| 44 | if (count > 24000) { |
| 45 | await reader.cancel(); |
| 46 | throw new Error('Invalid connection request.'); |
| 47 | } |
| 48 | text += decoder.decode(value, { stream: true }); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | async function handleApi(handler, request, url, env) { |
| 53 | let status = 200; |
| 54 | const headers = new Headers(); |
| 55 | const send = body => new Response(body, { status, headers }); |
| 56 | const response = { |
| 57 | setHeader: (key, value) => headers.set(key, value), |
| 58 | status(code) { status = code; return this; }, |
| 59 | json(value) { |
| 60 | headers.set('Content-Type', 'application/json; charset=utf-8'); |
| 61 | return send(JSON.stringify(value)); |
| 62 | }, |
| 63 | redirect(code, location) { |
| 64 | status = code; |
| 65 | headers.set('Location', location); |
| 66 | return send(null); |
| 67 | }, |
| 68 | send(value) { |
| 69 | headers.set('Content-Type', 'text/html; charset=utf-8'); |
| 70 | return send(value); |
| 71 | }, |
| 72 | end: () => send(null), |
| 73 | }; |
| 74 | const query = Object.fromEntries([...new Set(url.searchParams.keys())].map(key => { |
| 75 | const values = url.searchParams.getAll(key); |
| 76 | return [key, values.length === 1 ? values[0] : values]; |
| 77 | })); |
| 78 | const input = { |
| 79 | method: request.method, |
| 80 | url: url.href, |
| 81 | query, |
| 82 | headers: Object.fromEntries(request.headers), |
| 83 | [Symbol.asyncIterator]: () => request.body[Symbol.asyncIterator](), |
| 84 | }; |
| 85 | if (handler === connect && request.method === 'POST' && query.action === 'refresh') { |
| 86 | try { |
| 87 | input.body = await boundedText(request); |
| 88 | } catch { |
| 89 | status = 400; |
| 90 | headers.set('Cache-Control', 'no-store'); |
| 91 | return response.json({ error: 'Invalid connection request.' }); |
| 92 | } |
| 93 | } |
| 94 | return handler(input, response, { env, sendStream: send }); |
| 95 | } |
| 96 | |
| 97 | // /careers was removed (2026-12-02). Answer it here with the normal 404 page so a stale |
| 98 | // copy in the Pages asset layer can never be served again. |
| 99 | async function notFoundPage(context) { |
| 100 | let page = await context.env.ASSETS.fetch(new URL('/404.html', context.request.url)); |
| 101 | const moved = page.status >= 300 && page.status < 400 && page.headers.get('Location'); |
| 102 | if (moved) page = await context.env.ASSETS.fetch(new URL(moved, context.request.url)); |
| 103 | return new Response(page.body, { status: 404, headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' } }); |
| 104 | } |
| 105 | |
| 106 | async function route(context, url) { |
| 107 | const { request, env } = context; |
| 108 | if (/^\/careers\/?$/i.test(url.pathname)) return notFoundPage(context); |
| 109 | if (url.hostname === 'www.inkspring.ai') return redirect(canonical + url.pathname + url.search, 308); |
| 110 | if (url.pathname === '/' && url.searchParams.has('state') && (url.searchParams.has('code') || url.searchParams.has('error'))) { |
| 111 | const destination = new URL(canonical + '/api/connect'); |
| 112 | destination.searchParams.set('action', 'callback'); |
| 113 | destination.searchParams.set('provider', 'x'); |
| 114 | for (const key of ['state', 'code', 'error']) if (url.searchParams.has(key)) destination.searchParams.set(key, url.searchParams.get(key)); |
| 115 | return new Response(null, { status: 302, headers: { Location: destination.href, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' } }); |
| 116 | } |
| 117 | const old = config.redirects.find(rule => !rule.has && rule.source === url.pathname); |
| 118 | if (old) return redirect(old.destination, old.permanent ? 308 : 307, url); |
| 119 | if (/^\/(?:about|about-us)\/?$/.test(url.pathname)) return redirect('/', 308, url); |
| 120 | if (/^\/(?:account\/?|auth(?:\/.*)?)$/.test(url.pathname)) return redirect('/#desktop', 307, url); |
| 121 | |
| 122 | if (url.pathname === '/api/desktop/sponsored') return sponsored(request, env); |
| 123 | if (url.pathname === '/api/desktop/sponsored/instagram-image') return sponsoredInstagramImage(request, env); |
| 124 | if (url.pathname.startsWith('/instagram-sponsor-media/')) return serveSponsoredInstagramImage(request, env); |
| 125 | const connectPath = url.pathname.match(/^\/api\/desktop\/connect\/([^/]+)$/); |
| 126 | const callbackPath = url.pathname.match(/^\/api\/auth\/callback\/([^/]+)$/); |
| 127 | const legacyMediaPath = /^\/tiktok-media(?:\/|$)/.test(url.pathname); |
| 128 | if (connectPath || callbackPath || url.pathname === '/api/connect') { |
| 129 | if (connectPath) url.searchParams.set('action', decodeURIComponent(connectPath[1])); |
| 130 | if (callbackPath) { |
| 131 | url.searchParams.set('action', 'callback'); |
| 132 | url.searchParams.set('provider', decodeURIComponent(callbackPath[1])); |
| 133 | } |
| 134 | return handleApi(connect, request, url, env); |
| 135 | } |
| 136 | if (legacyMediaPath || ['/api/media', '/api/desktop/media', '/api/desktop/media/delete'].includes(url.pathname)) { |
| 137 | return handleApi(media, request, url, env); |
| 138 | } |
| 139 | return context.next(); |
| 140 | } |
| 141 | |
| 142 | export async function onRequest(context) { |
| 143 | const url = new URL(context.request.url); |
| 144 | let response; |
| 145 | try { |
| 146 | response = await route(context, url); |
| 147 | } catch (error) { |
| 148 | if (!(error instanceof URIError)) throw error; |
| 149 | response = new Response('Invalid URL encoding', { status: 400 }); |
| 150 | } |
| 151 | if (response.status === 307 || response.status === 308 || url.pathname.startsWith('/api/desktop/sponsored') || url.pathname.startsWith('/instagram-sponsor-media/')) return response; |
| 152 | return new Response(response.body, { status: response.status, statusText: response.statusText, headers: headersFor(url, response.headers) }); |
| 153 | } |