Inkspring / website / server / sponsored.mjs
| 1 | const json = (status, result) => Response.json(result, { status, headers: { |
| 2 | 'Cache-Control': 'no-store, private', |
| 3 | 'X-Content-Type-Options': 'nosniff', |
| 4 | } }); |
| 5 | const error = (status, code) => json(status, { error: code }); |
| 6 | const clean = (value, size) => typeof value === 'string' && value.trim().length > 0 && value.length <= size && |
| 7 | !/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value); |
| 8 | const validModel = value => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(value); |
| 9 | const credits = { write: 1, image: 4 }; |
| 10 | const scheme = /^Bearer (is1_[A-Za-z0-9_-]{43})$/; |
| 11 | export const digest = async token => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token))), b => b.toString(16).padStart(2,'0')).join(''); |
| 12 | const memberQuery = 'SELECT subject FROM sponsored_members WHERE token_digest = ?1 AND enabled = 1 AND expires_at > ?2'; |
| 13 | export const reserveSQL = ` |
| 14 | INSERT INTO sponsored_usage (id, subject, minute, day, month, operation, credits) |
| 15 | SELECT ?1, subject, ?3, ?4, ?5, ?6, ?7 FROM sponsored_members AS m |
| 16 | WHERE m.token_digest = ?2 AND m.enabled = 1 AND m.expires_at > ?8 |
| 17 | AND (SELECT count(*) FROM sponsored_usage WHERE minute = ?3) < 8 |
| 18 | AND (SELECT coalesce(sum(credits), 0) FROM sponsored_usage WHERE subject = m.subject AND day = ?4) + ?7 <= 12 |
| 19 | AND (SELECT coalesce(sum(credits), 0) FROM sponsored_usage WHERE day = ?4) + ?7 <= 120 |
| 20 | AND (SELECT coalesce(sum(credits), 0) FROM sponsored_usage WHERE month = ?5) + ?7 <= 1200 |
| 21 | `; |
| 22 | |
| 23 | async function boundedJSON(message, limit) { |
| 24 | if (Number(message.headers.get('Content-Length')) > limit || !message.body) throw new Error('bounded'); |
| 25 | const reader = message.body.getReader(); |
| 26 | const decoder = new TextDecoder('utf-8', { fatal: true }); |
| 27 | let size = 0; |
| 28 | let output = ''; |
| 29 | try { |
| 30 | for (;;) { |
| 31 | const { done, value } = await reader.read(); |
| 32 | if (done) return JSON.parse(output + decoder.decode()); |
| 33 | size += value.byteLength; |
| 34 | if (size > limit) throw new Error('bounded'); |
| 35 | output += decoder.decode(value, { stream: true }); |
| 36 | } |
| 37 | } catch (e) { |
| 38 | await reader.cancel().catch(() => {}); |
| 39 | throw e; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | function vendors(env) { |
| 44 | return { |
| 45 | write: [ |
| 46 | env.SPONSORED_ANTHROPIC_API_KEY && validModel(env.SPONSORED_ANTHROPIC_TEXT_MODEL) && 'anthropic', |
| 47 | env.SPONSORED_OPENAI_API_KEY && validModel(env.SPONSORED_OPENAI_TEXT_MODEL) && 'openai', |
| 48 | env.SPONSORED_GEMINI_API_KEY && validModel(env.SPONSORED_GEMINI_TEXT_MODEL) && 'gemini', |
| 49 | ].filter(Boolean), |
| 50 | image: [ |
| 51 | env.SPONSORED_OPENAI_API_KEY && validModel(env.SPONSORED_OPENAI_IMAGE_MODEL) && 'openai', |
| 52 | env.SPONSORED_GEMINI_API_KEY && validModel(env.SPONSORED_GEMINI_IMAGE_MODEL) && 'gemini', |
| 53 | ].filter(Boolean), |
| 54 | }; |
| 55 | } |
| 56 | function modelCall(env, body) { |
| 57 | const { operation, provider } = body; |
| 58 | if (operation === 'write') { |
| 59 | const { instructions, input } = body; |
| 60 | if (!clean(instructions, 8000) || typeof input !== 'object' || input === null || Array.isArray(input)) return; |
| 61 | const prompt = JSON.stringify(input); |
| 62 | if (!clean(prompt, 16000)) return; |
| 63 | if (provider === 'anthropic') return { |
| 64 | url: 'https://api.anthropic.com/v1/messages', headers: { 'x-api-key': env.SPONSORED_ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01' }, |
| 65 | payload: { model: env.SPONSORED_ANTHROPIC_TEXT_MODEL, max_tokens: 4000, system: instructions, messages: [{ role: 'user', content: prompt }] }, |
| 66 | select: result => result.stop_reason === 'end_turn' && result.content?.filter(p => p.type === 'text').map(p => p.text).join(''), |
| 67 | }; |
| 68 | if (provider === 'openai') return { |
| 69 | url: 'https://api.openai.com/v1/responses', headers: { Authorization: 'Bearer ' + env.SPONSORED_OPENAI_API_KEY }, |
| 70 | payload: { model: env.SPONSORED_OPENAI_TEXT_MODEL, max_output_tokens: 4000, store: false, instructions, input: prompt, text: { format: { type: 'json_object' } } }, |
| 71 | select: result => result.status === 'completed' && result.output?.flatMap(p => p.content ?? []).filter(p => p.type === 'output_text').map(p => p.text).join(''), |
| 72 | }; |
| 73 | const model = env.SPONSORED_GEMINI_TEXT_MODEL; |
| 74 | if (model.startsWith('gemini-4-')) return { |
| 75 | url: 'https://generativelanguage.googleapis.com/v1beta/interactions', headers: { 'x-goog-api-key': env.SPONSORED_GEMINI_API_KEY, 'Api-Revision': '2026-05-20' }, |
| 76 | payload: { model, system_instruction: instructions, input: prompt, store: false, |
| 77 | response_format: { type: 'text', mime_type: 'application/json' }, generation_config: { max_output_tokens: 4000 } }, |
| 78 | select: result => result.status === 'completed' && result.steps?.findLast(p => p.type === 'model_output')?.content?.filter(p => p.type === 'text').map(p => p.text).join(''), |
| 79 | }; |
| 80 | return { |
| 81 | url: 'https://generativelanguage.googleapis.com/v1beta/models/' + model + ':generateContent', |
| 82 | headers: { 'x-goog-api-key': env.SPONSORED_GEMINI_API_KEY }, |
| 83 | payload: { systemInstruction: { parts: [{ text: instructions }] }, contents: [{ role: 'user', parts: [{ text: prompt }] }], |
| 84 | generationConfig: { maxOutputTokens: 4000, responseMimeType: 'application/json' } }, |
| 85 | select: result => result.candidates?.[0]?.finishReason === 'STOP' && result.candidates[0].content?.parts?.filter(p => !p.thought).map(p => p.text).join(''), |
| 86 | }; |
| 87 | } |
| 88 | if (operation === 'image') { |
| 89 | if (!clean(body.prompt, 4000)) return; |
| 90 | if (provider === 'openai') return { |
| 91 | url: 'https://api.openai.com/v1/images/generations', headers: { Authorization: 'Bearer ' + env.SPONSORED_OPENAI_API_KEY }, |
| 92 | payload: { model: env.SPONSORED_OPENAI_IMAGE_MODEL, prompt: body.prompt, n: 1, size: '1024x1024', quality: 'low' }, |
| 93 | select: result => result.data?.[0]?.b64_json, |
| 94 | }; |
| 95 | return { |
| 96 | url: 'https://generativelanguage.googleapis.com/v1beta/models/' + env.SPONSORED_GEMINI_IMAGE_MODEL + ':generateContent', |
| 97 | headers: { 'x-goog-api-key': env.SPONSORED_GEMINI_API_KEY }, |
| 98 | payload: { contents: [{ role: 'user', parts: [{ text: body.prompt }] }], |
| 99 | generationConfig: { responseModalities: ['IMAGE'], imageConfig: { aspectRatio: '1:1', imageSize: '1K' } } }, |
| 100 | select: result => result.candidates?.[0]?.content?.parts?.find(p => p.inlineData?.data)?.inlineData.data, |
| 101 | }; |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | export async function sponsored(request, env, { fetcher = fetch, now = Date.now() } = {}) { |
| 106 | if (env.INKSPRING_SPONSORED_ENABLED !== 'true' || !env.SPONSORED_DB) return error(503, 'sponsored_unavailable'); |
| 107 | if (!['GET', 'POST'].includes(request.method)) return error(405, 'method_not_allowed'); |
| 108 | const token = scheme.exec(request.headers.get('Authorization') ?? '')?.[1]; |
| 109 | if (!token) return error(401, 'sign_in_required'); |
| 110 | const hash = await digest(token); |
| 111 | try { |
| 112 | if (!await env.SPONSORED_DB.prepare(memberQuery).bind(hash, now).first()) return error(401, 'sign_in_required'); |
| 113 | const available = vendors(env); |
| 114 | if (request.method === 'GET') return json(200, { available, perUserDailyCredits: 12, |
| 115 | instagramImage: env.SPONSORED_INSTAGRAM_IMAGE_ENABLED === 'true' && Boolean(env.SPONSORED_INSTAGRAM_R2) }); |
| 116 | if (!request.headers.get('Content-Type')?.toLowerCase().startsWith('application/json')) return error(415, 'json_required'); |
| 117 | let body; |
| 118 | try { body = await boundedJSON(request, 32_000); } catch { return error(400, 'invalid_request'); } |
| 119 | if (!body || Array.isArray(body) || !Object.hasOwn(credits, body.operation) || |
| 120 | typeof body.provider !== 'string') return error(400, 'invalid_request'); |
| 121 | const accepted = available[body.operation]; |
| 122 | if (!accepted.includes(body.provider)) return error(503, 'provider_unavailable'); |
| 123 | const call = modelCall(env, body); |
| 124 | if (!call) return error(400, 'invalid_request'); |
| 125 | const day = new Date(now).toISOString().slice(0,10); |
| 126 | const metered = await env.SPONSORED_DB.prepare(reserveSQL).bind(crypto.randomUUID(), hash, Math.floor(now/60_000), |
| 127 | day, day.slice(0,7), body.operation, credits[body.operation], now).run(); |
| 128 | if (metered.meta?.changes !== 1) return error(429, 'sponsored_limit'); |
| 129 | const upstream = await fetcher(call.url, { method: call.payload ? 'POST' : 'GET', redirect: 'error', |
| 130 | headers: { Accept: 'application/json', ...(call.payload ? { 'Content-Type': 'application/json' } : {}), ...call.headers }, |
| 131 | ...(call.payload ? { body: JSON.stringify(call.payload) } : {}), signal: AbortSignal.timeout(body.operation === 'image' ? 75_000 : 50_000) }); |
| 132 | if (!upstream.ok) return error(502, 'provider_unavailable'); |
| 133 | const selected = call.select(await boundedJSON(upstream, body.operation === 'image' ? 16_000_000 : 1_500_000)); |
| 134 | if (!selected) return error(502, 'provider_reply'); |
| 135 | if (body.operation === 'write') { |
| 136 | const text = selected.trim().replace(/^```(?:json)?\s*|\s*```$/g,''); |
| 137 | const result = JSON.parse(text); |
| 138 | if (!result || typeof result !== 'object' || Array.isArray(result) || text.length > 50_000) return error(502,'provider_reply'); |
| 139 | return json(200, { result }); |
| 140 | } |
| 141 | if (body.operation === 'image' && !/^[A-Za-z0-9+/]+={0,2}$/.test(selected)) return error(502,'provider_reply'); |
| 142 | return json(200, { result: selected }); |
| 143 | } catch { |
| 144 | return error(503, 'sponsored_unavailable'); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Instagram accepts a fetchable URL for a feed image. This is an unguessable, short-lived |
| 149 | // bearer link, not an identity check on Meta's crawler. Do not log or publish the URL. |
| 150 | const imagePrefix = '/instagram-sponsor-media/'; |
| 151 | const imageTTL = 60 * 60_000; |
| 152 | const imageLimit = 4 * 1024 * 1024; |
| 153 | const imagePath = /^\/instagram-sponsor-media\/([0-9a-f]{32})\.jpg$/; |
| 154 | |
| 155 | async function boundedJPEG(message) { |
| 156 | if (message.headers.get('Content-Type')?.toLowerCase() !== 'image/jpeg' || |
| 157 | Number(message.headers.get('Content-Length')) > imageLimit || !message.body) return; |
| 158 | const reader = message.body.getReader(); |
| 159 | const chunks = []; |
| 160 | let size = 0; |
| 161 | try { |
| 162 | for (;;) { |
| 163 | const { done,value } = await reader.read(); |
| 164 | if (done) break; |
| 165 | size += value.byteLength; |
| 166 | if (size > imageLimit) return; |
| 167 | chunks.push(value); |
| 168 | } |
| 169 | } finally { |
| 170 | await reader.cancel().catch(() => {}); |
| 171 | } |
| 172 | if (size < 12) return; |
| 173 | const b = new Uint8Array(size); |
| 174 | let offset = 0; |
| 175 | for (const chunk of chunks) { b.set(chunk,offset); offset += chunk.byteLength; } |
| 176 | // Require JPEG SOI/EOI with at least one parsed frame and scan. Disallow injected |
| 177 | // trailers; publish only the native app's freshly encoded JPEGs, never SVG or HTML. |
| 178 | if (b[0] !== 0xff || b[1] !== 0xd8 || b[size-2] !== 0xff || b[size-1] !== 0xd9) return; |
| 179 | let foundFrame = false; |
| 180 | for (let p = 2; p + 4 < size;) { |
| 181 | if (b[p++] !== 0xff) return; |
| 182 | const marker = b[p++]; |
| 183 | const width = (b[p]<<8) + b[p+1]; |
| 184 | if (width < 2 || p + width > size - 2) return; |
| 185 | if (marker === 0xc0 || marker === 0xc2) { |
| 186 | if (width < 8 || !(b[p+3] || b[p+4]) || !(b[p+5] || b[p+6])) return; |
| 187 | foundFrame = true; |
| 188 | } |
| 189 | if (marker === 0xda) return foundFrame && p + width < size - 2 ? b : undefined; |
| 190 | p += width; |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | export async function sponsoredInstagramImage(request, env, { now = Date.now() } = {}) { |
| 195 | if (env.INKSPRING_SPONSORED_ENABLED !== 'true' || env.SPONSORED_INSTAGRAM_IMAGE_ENABLED !== 'true' || |
| 196 | !env.SPONSORED_DB || !env.SPONSORED_INSTAGRAM_R2) return error(503, 'sponsored_unavailable'); |
| 197 | if (request.method !== 'POST') return error(405, 'method_not_allowed'); |
| 198 | const token = scheme.exec(request.headers.get('Authorization') ?? '')?.[1]; |
| 199 | if (!token) return error(401,'sign_in_required'); |
| 200 | const hash = await digest(token); |
| 201 | try { |
| 202 | if (!await env.SPONSORED_DB.prepare(memberQuery).bind(hash, now).first()) return error(401, 'sign_in_required'); |
| 203 | const image = await boundedJPEG(request); |
| 204 | if (!image) return error(400,'invalid_image'); |
| 205 | const day = new Date(now).toISOString().slice(0,10); |
| 206 | const granted = await env.SPONSORED_DB.prepare(reserveSQL).bind(crypto.randomUUID(), hash, Math.floor(now/60_000), |
| 207 | day, day.slice(0,7), 'instagram_image', 4, now).run(); |
| 208 | if (granted.meta?.changes !== 1) return error(429,'sponsored_limit'); |
| 209 | const id = crypto.randomUUID().replace(/-/g,''); |
| 210 | const expires = now + imageTTL; |
| 211 | await env.SPONSORED_INSTAGRAM_R2.put(id, image, { |
| 212 | httpMetadata: { contentType: 'image/jpeg', cacheControl: 'no-store, private' }, |
| 213 | customMetadata: { expires: String(expires) }, |
| 214 | }); |
| 215 | return json(201, { url: 'https://inkspring.ai' + imagePrefix + id + '.jpg', expiresAt: expires }); |
| 216 | } catch { return error(503,'sponsored_unavailable'); } |
| 217 | } |
| 218 | |
| 219 | export async function serveSponsoredInstagramImage(request, env, { now = Date.now() } = {}) { |
| 220 | if (env.INKSPRING_SPONSORED_ENABLED !== 'true' || env.SPONSORED_INSTAGRAM_IMAGE_ENABLED !== 'true' || |
| 221 | !env.SPONSORED_INSTAGRAM_R2 || !['GET','HEAD'].includes(request.method)) return error(404,'not_found'); |
| 222 | const id = imagePath.exec(new URL(request.url).pathname)?.[1]; |
| 223 | if (!id) return error(404,'not_found'); |
| 224 | try { |
| 225 | const object = await env.SPONSORED_INSTAGRAM_R2[request.method === 'HEAD' ? 'head' : 'get'](id); |
| 226 | const expiry = Number(object?.customMetadata?.expires); |
| 227 | if (!object || !Number.isSafeInteger(expiry) || expiry <= now) { |
| 228 | await object?.body?.cancel().catch(() => {}); |
| 229 | return error(404,'not_found'); |
| 230 | } |
| 231 | return new Response(request.method === 'HEAD' ? null : object.body, { headers: { |
| 232 | 'Content-Type': 'image/jpeg', 'Content-Length': String(object.size), |
| 233 | 'Cache-Control': 'no-store, private', 'Referrer-Policy': 'no-referrer', |
| 234 | 'X-Content-Type-Options': 'nosniff', 'X-Robots-Tag': 'noindex, nofollow, noarchive', |
| 235 | } }); |
| 236 | } catch { return error(404,'not_found'); } |
| 237 | } |