import { createHmac, webcrypto } from 'node:crypto'; import { equal } from './connect-crypto.mjs'; // TikTok only pulls photos from a domain the app has verified. Managed TikTok posts are hosted here briefly: // the desktop uploads one JPEG with the person's TikTok token, TikTok downloads it, and the desktop deletes it. // Anything left behind stops being served after two hours and is removed on a later upload. const ORIGIN = 'https://inkspring.ai'; const PREFIX = 'tiktok-media/'; const LIFETIME = 2 * 3600000; export const MAX_BYTES = 4000000; const FILE = /^(\d{13})-([A-Za-z0-9_-]{43})\.jpg$/; function deleteKey(file, secret) { if (typeof secret !== 'string' || secret.length < 64) throw new Error('Media service unavailable.'); return createHmac('sha256', secret).update(`tiktok-media-delete:${file}`).digest('base64url'); } function fileName(value) { const match = FILE.exec(String(value || '')); if (!match) throw new Error('Not found.'); return { file: match[0], createdAt: Number(match[1]) }; } export function createMedia({ env = process.env, fetchImpl = fetch, now = Date.now } = {}) { const bucket = env.TIKTOK_MEDIA; async function tiktokAccount(token) { if (typeof token !== 'string' || !/^[\x21-\x7e]{10,4000}$/.test(token)) throw new Error('Unauthorized.'); let response; try { response = await fetchImpl('https://open.tiktokapis.com/v2/user/info/?fields=open_id', { headers: { Authorization: `Bearer ${token}` }, redirect: 'error', signal: AbortSignal.timeout(10000) }); } catch { throw new Error('Unauthorized.'); } const body = await response.json().catch(() => ({})); if (!response.ok || body.error?.code !== 'ok' || typeof body.data?.user?.open_id !== 'string') throw new Error('Unauthorized.'); } async function sweep() { try { const { objects } = await bucket.list({ prefix: PREFIX, limit: 100 }); const stale = objects.filter(({ key }) => { try { return now() - fileName(key.slice(PREFIX.length)).createdAt > LIFETIME; } catch { return true; } }).map(({ key }) => key); if (stale.length) await bucket.delete(stale); } catch { /* Cleanup is best effort and never blocks an upload. */ } } return { available: () => Boolean(bucket && env.CONNECT_SECRET?.length >= 64), async upload({ authorization, bytes }) { if (!Buffer.isBuffer(bytes) || bytes.length < 100 || bytes.length > MAX_BYTES || bytes[0] !== 0xff || bytes[1] !== 0xd8 || bytes[2] !== 0xff) throw new Error('Send one JPEG image up to 4 MB.'); await tiktokAccount(String(authorization || '').replace(/^Bearer /, '')); await sweep(); const file = `${now()}-${Buffer.from(webcrypto.getRandomValues(new Uint8Array(32))).toString('base64url')}.jpg`; await bucket.put(PREFIX + file, bytes, { httpMetadata: { contentType: 'image/jpeg' } }); return { url: `${ORIGIN}/${PREFIX}${file}`, deleteKey: deleteKey(file, env.CONNECT_SECRET) }; }, async serve(value) { const { file, createdAt } = fileName(value); if (now() - createdAt > LIFETIME || createdAt > now() + 60000) throw new Error('Not found.'); const key = PREFIX + file; const object = await bucket.get(key); if (!object?.body) throw new Error('Not found.'); return { stream: object.body, blob: { size: object.size } }; }, async remove({ url, deleteKey: key }) { const parsed = new URL(String(url || '')); if (parsed.origin !== ORIGIN || !parsed.pathname.startsWith(`/${PREFIX}`)) throw new Error('Not found.'); const { file } = fileName(parsed.pathname.slice(PREFIX.length + 1)); if (!equal(String(key || ''), deleteKey(file, env.CONNECT_SECRET))) throw new Error('Not found.'); const objectKey = PREFIX + file; await bucket.delete(objectKey); } }; }