Branchwell

Inkspring / website / server / media.mjs

1import { createHmac, webcrypto } from 'node:crypto';
2import { equal } from './connect-crypto.mjs';
3// TikTok only pulls photos from a domain the app has verified. Managed TikTok posts are hosted here briefly:
4// the desktop uploads one JPEG with the person's TikTok token, TikTok downloads it, and the desktop deletes it.
5// Anything left behind stops being served after two hours and is removed on a later upload.
6const ORIGIN = 'https://inkspring.ai';
7const PREFIX = 'tiktok-media/';
8const LIFETIME = 2 * 3600000;
9export const MAX_BYTES = 4000000;
10const FILE = /^(\d{13})-([A-Za-z0-9_-]{43})\.jpg$/;
11function 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'); }
12function fileName(value) { const match = FILE.exec(String(value || '')); if (!match) throw new Error('Not found.'); return { file: match[0], createdAt: Number(match[1]) }; }
13export function createMedia({ env = process.env, fetchImpl = fetch, now = Date.now } = {}) {
14 const bucket = env.TIKTOK_MEDIA;
15 async function tiktokAccount(token) {
16 if (typeof token !== 'string' || !/^[\x21-\x7e]{10,4000}$/.test(token)) throw new Error('Unauthorized.');
17 let response;
18 try { response = await fetchImpl('https://open.tiktokapis.com/v2/user/info/?fields=open_id', { headers: { Authorization: `Bearer ${token}` }, redirect: 'error', signal: AbortSignal.timeout(10000) }); }
19 catch { throw new Error('Unauthorized.'); }
20 const body = await response.json().catch(() => ({}));
21 if (!response.ok || body.error?.code !== 'ok' || typeof body.data?.user?.open_id !== 'string') throw new Error('Unauthorized.');
22 }
23 async function sweep() {
24 try {
25 const { objects } = await bucket.list({ prefix: PREFIX, limit: 100 });
26 const stale = objects.filter(({ key }) => {
27 try { return now() - fileName(key.slice(PREFIX.length)).createdAt > LIFETIME; }
28 catch { return true; }
29 }).map(({ key }) => key);
30 if (stale.length) await bucket.delete(stale);
31 } catch { /* Cleanup is best effort and never blocks an upload. */ }
32 }
33 return {
34 available: () => Boolean(bucket && env.CONNECT_SECRET?.length >= 64),
35 async upload({ authorization, bytes }) {
36 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.');
37 await tiktokAccount(String(authorization || '').replace(/^Bearer /, ''));
38 await sweep();
39 const file = `${now()}-${Buffer.from(webcrypto.getRandomValues(new Uint8Array(32))).toString('base64url')}.jpg`;
40 await bucket.put(PREFIX + file, bytes, { httpMetadata: { contentType: 'image/jpeg' } });
41 return { url: `${ORIGIN}/${PREFIX}${file}`, deleteKey: deleteKey(file, env.CONNECT_SECRET) };
42 },
43 async serve(value) {
44 const { file, createdAt } = fileName(value);
45 if (now() - createdAt > LIFETIME || createdAt > now() + 60000) throw new Error('Not found.');
46 const key = PREFIX + file;
47 const object = await bucket.get(key);
48 if (!object?.body) throw new Error('Not found.');
49 return { stream: object.body, blob: { size: object.size } };
50 },
51 async remove({ url, deleteKey: key }) {
52 const parsed = new URL(String(url || ''));
53 if (parsed.origin !== ORIGIN || !parsed.pathname.startsWith(`/${PREFIX}`)) throw new Error('Not found.');
54 const { file } = fileName(parsed.pathname.slice(PREFIX.length + 1));
55 if (!equal(String(key || ''), deleteKey(file, env.CONNECT_SECRET))) throw new Error('Not found.');
56 const objectKey = PREFIX + file;
57 await bucket.delete(objectKey);
58 }
59 };
60}