File size: 4,081 Bytes
e7d800d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Small shared helpers: SSRF-safe fetch, rate limiting, JSON-file store, signed webhooks.
import dns from 'node:dns/promises';
import net from 'node:net';
import crypto from 'node:crypto';
import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from 'node:fs';
import path from 'node:path';

function privateIp(ip) {
  if (net.isIPv4(ip)) {
    const [a, b] = ip.split('.').map(Number);
    return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31)
      || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
  }
  const l = ip.toLowerCase();
  return l === '::1' || l === '::' || l.startsWith('fc') || l.startsWith('fd') || l.startsWith('fe80')
    || (l.startsWith('::ffff:') && privateIp(l.slice(7)));
}

/** Fetch a public http(s) URL, refusing private/internal targets and following ≤3 checked redirects. */
export async function safeFetch(raw, maxBytes = 40 * 1024 * 1024) {
  let url = new URL(raw);
  for (let hop = 0; hop < 4; hop++) {
    if (!['http:', 'https:'].includes(url.protocol)) throw new Error('only http(s) URLs are allowed');
    const addrs = await dns.lookup(url.hostname, { all: true });
    if (!addrs.length || addrs.some(a => privateIp(a.address))) throw new Error('URL resolves to a private address');
    const r = await fetch(url, {
      redirect: 'manual', signal: AbortSignal.timeout(20000),
      headers: { 'user-agent': 'EagleEyeVerify/1.0 (+media authenticity check)' },
    });
    if (r.status >= 300 && r.status < 400 && r.headers.get('location')) { url = new URL(r.headers.get('location'), url); continue; }
    if (!r.ok) throw new Error(`fetch failed: HTTP ${r.status}`);
    const len = Number(r.headers.get('content-length') || 0);
    if (len > maxBytes) throw new Error('file too large');
    const chunks = []; let total = 0;
    for await (const c of r.body) { total += c.length; if (total > maxBytes) throw new Error('file too large'); chunks.push(c); }
    return { buf: Buffer.concat(chunks), mime: (r.headers.get('content-type') || '').split(';')[0].trim(), finalUrl: String(url) };
  }
  throw new Error('too many redirects');
}

/** Fixed-window in-memory limiter keyed by IP. */
export function rateLimit(max, windowMs) {
  const hits = new Map();
  return (req, res, next) => {
    const k = req.ip; const now = Date.now();
    const e = hits.get(k);
    if (!e || now > e.reset) { hits.set(k, { n: 1, reset: now + windowMs }); return next(); }
    if (++e.n > max) return res.status(429).json({ error: 'Too many requests — please wait a minute.' });
    next();
  };
}

/** Durable-enough JSON store: atomic write-rename into DATA_DIR (/data on a Space with storage). */
export function jsonStore(name, fallback) {
  const dir = process.env.DATA_DIR || (existsSync('/data') ? '/data' : path.resolve('data'));
  mkdirSync(dir, { recursive: true });
  const file = path.join(dir, name);
  let data = fallback;
  try { data = JSON.parse(readFileSync(file, 'utf8')); } catch { /* first boot */ }
  return {
    get: () => data,
    save(next) { data = next; const tmp = file + '.tmp'; writeFileSync(tmp, JSON.stringify(data)); renameSync(tmp, file); },
    file,
  };
}

/** Send an HMAC-SHA256 signed webhook (header X-Verify-Signature: sha256=<hex>). Never throws. */
export async function signedWebhook(url, secret, payload) {
  if (!url) return { sent: false, reason: 'no webhook configured' };
  const body = JSON.stringify(payload);
  const sig = crypto.createHmac('sha256', secret || '').update(body).digest('hex');
  try {
    const r = await fetch(url, {
      method: 'POST', body, signal: AbortSignal.timeout(10000),
      headers: { 'content-type': 'application/json', 'x-verify-signature': `sha256=${sig}` },
    });
    return { sent: true, status: r.status };
  } catch (e) { return { sent: false, reason: e.message }; }
}

export const keyEq = (a, b) => {
  const x = Buffer.from(String(a || '')), y = Buffer.from(String(b || ''));
  return x.length === y.length && x.length > 0 && crypto.timingSafeEqual(x, y);
};