| 1 | /**
|
|---|
| 2 | * ap-transport.js — het transport onder de federatie (stap 3 van shaer-drc).
|
|---|
| 3 | *
|
|---|
| 4 | * Alles wat hier woont raakt het netwerk of de sleutels, en niets erin weet
|
|---|
| 5 | * iets van Notes, feeds of guardianship:
|
|---|
| 6 | * - de SSRF-poort (safeFetch en zijn wachters) voor ELKE uitgaande fetch
|
|---|
| 7 | * - de RSA-sleutels per actor
|
|---|
| 8 | * - HTTP Signatures: tekenen (deliver, signedGetHeaders) en controleren
|
|---|
| 9 | * (verifyRequest)
|
|---|
| 10 | * - de bezorging met wachtrij en backoff (deliverWithRetry en de worker)
|
|---|
| 11 | * - de ondertekende GET (signedGetJson) en zijn onbetekende broer (apGetJson)
|
|---|
| 12 | *
|
|---|
| 13 | * Verhuisd uit ActivityPubService.js, dat alles her-exporteert: bestaande
|
|---|
| 14 | * importeurs merken niets. De afhankelijkheden wijzen alleen omlaag (db,
|
|---|
| 15 | * ap-core, Node zelf) -- er mag hier nooit iets uit de dienstlaag bij.
|
|---|
| 16 | */
|
|---|
| 17 | import crypto from 'crypto';
|
|---|
| 18 | import fs from 'fs';
|
|---|
| 19 | import dns from 'dns';
|
|---|
| 20 | import net from 'net';
|
|---|
| 21 | import db from '../config/database.js';
|
|---|
| 22 | import { actorId } from './ap-core.js';
|
|---|
| 23 |
|
|---|
| 24 | // ── SSRF guard for outbound fetches ───────────────────────────────
|
|---|
| 25 | // Remote URLs (actor/keyId/webfinger/inbox/inReplyTo) are attacker-controlled, so
|
|---|
| 26 | // every outbound fetch must refuse hosts that resolve to private/loopback ranges
|
|---|
| 27 | // (cloud metadata, internal services) — on the initial host AND each redirect hop.
|
|---|
| 28 | function isBlockedIp(ip) {
|
|---|
| 29 | if (!ip) return true;
|
|---|
| 30 | const v = net.isIP(ip);
|
|---|
| 31 | if (v === 4) {
|
|---|
| 32 | const o = ip.split('.').map(Number);
|
|---|
| 33 | return o[0] === 127 || o[0] === 10 || o[0] === 0
|
|---|
| 34 | || (o[0] === 172 && o[1] >= 16 && o[1] <= 31)
|
|---|
| 35 | || (o[0] === 192 && o[1] === 168)
|
|---|
| 36 | || (o[0] === 169 && o[1] === 254)
|
|---|
| 37 | || (o[0] === 100 && o[1] >= 64 && o[1] <= 127); // CGNAT
|
|---|
| 38 | }
|
|---|
| 39 | if (v === 6) {
|
|---|
| 40 | const s = ip.toLowerCase().replace(/^\[|\]$/g, '');
|
|---|
| 41 | return s === '::1' || s === '::' || s.startsWith('fc') || s.startsWith('fd') || s.startsWith('fe80')
|
|---|
| 42 | || s.startsWith('::ffff:127.') || s.startsWith('::ffff:10.') || s.startsWith('::ffff:192.168.')
|
|---|
| 43 | || s.startsWith('::ffff:169.254.') || s.startsWith('::ffff:172.');
|
|---|
| 44 | }
|
|---|
| 45 | return true; // not an IP literal we recognise → refuse
|
|---|
| 46 | }
|
|---|
| 47 | /**
|
|---|
| 48 | * Uitzonderingen op de SSRF-poort, voor een testkudde op de eigen machine
|
|---|
| 49 | * (shaer-6wt: honderd wards met een guardian, Barts opdracht 8-8).
|
|---|
| 50 | *
|
|---|
| 51 | * WAAROM DIT MAG BESTAAN. De bescherming hierboven is er omdat een actor-URI van
|
|---|
| 52 | * een VREEMDE komt: een aanvaller die "http://169.254.169.254/" doorgeeft laat
|
|---|
| 53 | * ons zijn werk doen. Deze lijst gaat niet over vreemden -- hij staat in de
|
|---|
| 54 | * omgeving van deze server, wordt door de beheerder gezet, en is leeg tenzij
|
|---|
| 55 | * iemand hem expliciet vult.
|
|---|
| 56 | *
|
|---|
| 57 | * WAAROM HIJ ZO SMAL IS. Geen vlag die "loopback is oke" zegt, maar een lijst
|
|---|
| 58 | * van precieze host:poort-paren. `[::1]:3060` opent niet 127.0.0.1, niet poort
|
|---|
| 59 | * 3061, en niets in het interne netwerk. Een brede vlag zou de bescherming in
|
|---|
| 60 | * een dev-omgeving uitzetten, en dev-omgevingen worden productie.
|
|---|
| 61 | *
|
|---|
| 62 | * AP_ALLOW_HOSTS="[::1]:3060,[::1]:3061"
|
|---|
| 63 | */
|
|---|
| 64 | const AP_ALLOW_HOSTS = new Set(
|
|---|
| 65 | String(process.env.AP_ALLOW_HOSTS || '').split(',').map((x) => x.trim().toLowerCase()).filter(Boolean),
|
|---|
| 66 | );
|
|---|
| 67 | function isAllowedTestHost(u) {
|
|---|
| 68 | if (!AP_ALLOW_HOSTS.size) return false;
|
|---|
| 69 | return AP_ALLOW_HOSTS.has(u.host.toLowerCase());
|
|---|
| 70 | }
|
|---|
| 71 | async function assertPublicHost(hostname) {
|
|---|
| 72 | // URL.hostname geeft een IPv6-literal MET blokhaken ("[::1]"), en net.isIP
|
|---|
| 73 | // herkent die vorm niet. Zonder strippen viel elk IPv6-adres door naar de
|
|---|
| 74 | // DNS-tak, waar het strandde op ENOTFOUND: geweigerd, maar per ongeluk en met
|
|---|
| 75 | // de verkeerde reden. isBlockedIp strippde ze al -- die verwachtte dus input
|
|---|
| 76 | // die hier nooit aankwam.
|
|---|
| 77 | const naakt = String(hostname || '').replace(/^\[|\]$/g, '');
|
|---|
| 78 | if (net.isIP(naakt)) { if (isBlockedIp(naakt)) throw new Error('ssrf-blocked-ip'); return; }
|
|---|
| 79 | const addrs = await dns.promises.lookup(naakt, { all: true });
|
|---|
| 80 | if (!addrs.length || addrs.some((a) => isBlockedIp(a.address))) throw new Error('ssrf-blocked-host');
|
|---|
| 81 | }
|
|---|
| 82 | // One honest name on ALL outbound federation traffic (Robins vraag, 31-7):
|
|---|
| 83 | // safeFetch went out with the bare Node default before, and polite fediverse
|
|---|
| 84 | // citizens say who they are (some instances even refuse anonymous UAs). A
|
|---|
| 85 | // caller-provided User-Agent (the EmbedResolver) still wins.
|
|---|
| 86 | let _uaVer = '1.0';
|
|---|
| 87 | try { _uaVer = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url))).version || _uaVer; } catch { /* keep default */ }
|
|---|
| 88 | const KLONKT_UA = `Klonkt/${_uaVer} (+https://klonkt.com)`;
|
|---|
| 89 |
|
|---|
| 90 | export async function safeFetch(url, opts = {}, maxRedirects = 3) {
|
|---|
| 91 | let target = url;
|
|---|
| 92 | for (let hop = 0; ; hop++) {
|
|---|
| 93 | const u = new URL(target); // throws on malformed → caller's catch
|
|---|
| 94 | if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error('ssrf-bad-scheme');
|
|---|
| 95 | // Alleen op de precieze host:poort uit AP_ALLOW_HOSTS, en per hop opnieuw:
|
|---|
| 96 | // een omleiding naar een ANDER intern adres blijft geweigerd.
|
|---|
| 97 | if (!isAllowedTestHost(u)) await assertPublicHost(u.hostname);
|
|---|
| 98 | const r = await fetch(target, {
|
|---|
| 99 | ...opts,
|
|---|
| 100 | headers: { 'User-Agent': KLONKT_UA, ...(opts.headers || {}) },
|
|---|
| 101 | redirect: 'manual',
|
|---|
| 102 | signal: AbortSignal.timeout(8000),
|
|---|
| 103 | });
|
|---|
| 104 | const loc = (r.status >= 300 && r.status < 400) ? r.headers.get('location') : null;
|
|---|
| 105 | if (loc && hop < maxRedirects) { target = new URL(loc, target).toString(); continue; }
|
|---|
| 106 | return r;
|
|---|
| 107 | }
|
|---|
| 108 | }
|
|---|
| 109 |
|
|---|
| 110 | // ── RSA keys per actor (lazy, cached in DB) ───────────────────────
|
|---|
| 111 | // Prepared lazily (NOT at module load) — the ap_keys table is created in
|
|---|
| 112 | // initializeDatabase(), which runs after this module is imported.
|
|---|
| 113 | let _sel, _ins;
|
|---|
| 114 | function keyStmts() {
|
|---|
| 115 | if (!_sel) {
|
|---|
| 116 | _sel = db.prepare('SELECT public_pem, private_pem FROM ap_keys WHERE slug = ?');
|
|---|
| 117 | _ins = db.prepare('INSERT OR IGNORE INTO ap_keys (slug, public_pem, private_pem, created_at) VALUES (?,?,?,CURRENT_TIMESTAMP)');
|
|---|
| 118 | }
|
|---|
| 119 | return { sel: _sel, ins: _ins };
|
|---|
| 120 | }
|
|---|
| 121 |
|
|---|
| 122 | export function getOrCreateKeys(slug) {
|
|---|
| 123 | const { sel, ins } = keyStmts();
|
|---|
| 124 | const row = sel.get(slug);
|
|---|
| 125 | if (row) return row;
|
|---|
| 126 | const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
|
|---|
| 127 | modulusLength: 2048,
|
|---|
| 128 | publicKeyEncoding: { type: 'spki', format: 'pem' },
|
|---|
| 129 | privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
|
|---|
| 130 | });
|
|---|
| 131 | ins.run(slug, publicKey, privateKey);
|
|---|
| 132 | return sel.get(slug) || { public_pem: publicKey, private_pem: privateKey };
|
|---|
| 133 | }
|
|---|
| 134 |
|
|---|
| 135 | // ── HTTP Signatures + delivery ────────────────────────────────────
|
|---|
| 136 | // Sign + POST an activity to a remote inbox (draft-cavage HTTP Signatures, RSA-SHA256).
|
|---|
| 137 | export async function deliver(inboxUrl, bodyObj, keyId, privatePem) {
|
|---|
| 138 | const body = JSON.stringify(bodyObj);
|
|---|
| 139 | const u = new URL(inboxUrl);
|
|---|
| 140 | const date = new Date().toUTCString();
|
|---|
| 141 | const digest = 'SHA-256=' + crypto.createHash('sha256').update(body).digest('base64');
|
|---|
| 142 | const signingString = `(request-target): post ${u.pathname}\nhost: ${u.host}\ndate: ${date}\ndigest: ${digest}`;
|
|---|
| 143 | const signature = crypto.sign('sha256', Buffer.from(signingString), privatePem).toString('base64');
|
|---|
| 144 | const sig = `keyId="${keyId}",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="${signature}"`;
|
|---|
| 145 | const r = await safeFetch(inboxUrl, {
|
|---|
| 146 | method: 'POST',
|
|---|
| 147 | headers: { 'Content-Type': 'application/activity+json', Accept: 'application/activity+json', Date: date, Digest: digest, Signature: sig },
|
|---|
| 148 | body,
|
|---|
| 149 | });
|
|---|
| 150 | return r.status;
|
|---|
| 151 | }
|
|---|
| 152 |
|
|---|
| 153 | export async function fetchActor(url, opts = {}) {
|
|---|
| 154 | // Authorized fetch (Mastodons secure mode): zo'n instance serveert zijn
|
|---|
| 155 | // actor-document -- en dus zijn publieke sleutel -- alleen aan een ONDERTEKEND
|
|---|
| 156 | // verzoek en antwoordt anders met 401. Zonder sleutel kunnen we een correct
|
|---|
| 157 | // ondertekende Follow van die instance niet verifiëren en wijzen we hem af,
|
|---|
| 158 | // waarna Mastodon het dagenlang blijft proberen. Gemeten op boiert.eu: vier
|
|---|
| 159 | // accounts eindeloos geweigerd, en precies die vier geven 401 op een
|
|---|
| 160 | // onbetekende GET (shaer-afq).
|
|---|
| 161 | //
|
|---|
| 162 | // Geen kip-ei: om ONZE handtekening te controleren haalt de andere kant ons
|
|---|
| 163 | // actor-document op, en dat serveert Klonkt publiek.
|
|---|
| 164 | //
|
|---|
| 165 | // ONBETEKEND EERST, en dat is een veiligheidskeuze en geen optimalisatie.
|
|---|
| 166 | // verifyRequest haalt de keyId-URL op VOORDAT er iets geverifieerd is, en die
|
|---|
| 167 | // URL komt uit een header die iedereen mag sturen. Tekenden we dat verzoek
|
|---|
| 168 | // standaard, dan kan een volslagen onbekende ons een ONDERTEKEND verzoek laten
|
|---|
| 169 | // sturen naar een adres van zijn keuze -- met onze identiteit eronder. Dat is
|
|---|
| 170 | // precies hoe een instance op een blocklist belandt. Ondertekenen doen we dus
|
|---|
| 171 | // pas als het onbetekend niet lukt, en dan alleen voor deze ene URL.
|
|---|
| 172 | let doc = null;
|
|---|
| 173 | try {
|
|---|
| 174 | const r = await safeFetch(url, { headers: { Accept: 'application/activity+json' } });
|
|---|
| 175 | if (r.ok) {
|
|---|
| 176 | const len = Number(r.headers.get('content-length') || 0);
|
|---|
| 177 | if (len > 2_000_000) return null; // refuse oversized actor docs
|
|---|
| 178 | doc = await r.json();
|
|---|
| 179 | }
|
|---|
| 180 | } catch { /* val door naar de ondertekende poging */ }
|
|---|
| 181 | // Genoeg? Dan klaar. Sommige instances serveren onbetekend wel een document
|
|---|
| 182 | // maar zonder sleutel; voor een verificatie hebben we daar niets aan, dus die
|
|---|
| 183 | // telt als mislukt.
|
|---|
| 184 | if (doc && (!opts.asSlug || (doc.publicKey && doc.publicKey.publicKeyPem))) return doc;
|
|---|
| 185 | if (!opts.asSlug) return doc;
|
|---|
| 186 | const signed = await signedGetJson(opts.asSlug, url).catch(() => null);
|
|---|
| 187 | return (signed && signed.id) ? signed : doc;
|
|---|
| 188 | }
|
|---|
| 189 |
|
|---|
| 190 | // ── Delivery queue with retries ───────────────────────────────────
|
|---|
| 191 | // Outbound deliveries are tried immediately; on failure (down server, timeout,
|
|---|
| 192 | // non-2xx) they're queued and retried with backoff so a briefly-offline follower
|
|---|
| 193 | // doesn't silently miss the post. The signing key is NOT stored — the worker
|
|---|
| 194 | // re-derives it from the actor slug at send time.
|
|---|
| 195 | const DELIVERY_MAX_ATTEMPTS = 6;
|
|---|
| 196 | const DELIVERY_BACKOFF_MIN = [1, 5, 15, 60, 180, 360];
|
|---|
| 197 | let _insDeliv, _dueDeliv, _delDeliv, _bumpDeliv;
|
|---|
| 198 | function deliveryStmts() {
|
|---|
| 199 | if (!_insDeliv) {
|
|---|
| 200 | _insDeliv = db.prepare('INSERT INTO ap_delivery (slug, inbox, body, attempts, next_at) VALUES (?,?,?,0,CURRENT_TIMESTAMP)');
|
|---|
| 201 | _dueDeliv = db.prepare("SELECT * FROM ap_delivery WHERE datetime(next_at) <= datetime('now') ORDER BY next_at LIMIT 30");
|
|---|
| 202 | _delDeliv = db.prepare('DELETE FROM ap_delivery WHERE id = ?');
|
|---|
| 203 | _bumpDeliv = db.prepare('UPDATE ap_delivery SET attempts = ?, next_at = ? WHERE id = ?');
|
|---|
| 204 | }
|
|---|
| 205 | return { ins: _insDeliv, due: _dueDeliv, del: _delDeliv, bump: _bumpDeliv };
|
|---|
| 206 | }
|
|---|
| 207 | export function enqueueDelivery(slug, inbox, activity) {
|
|---|
| 208 | if (!slug || !inbox || !activity) return;
|
|---|
| 209 | try { deliveryStmts().ins.run(slug, inbox, JSON.stringify(activity)); } catch { /* ignore */ }
|
|---|
| 210 | }
|
|---|
| 211 | // Record delivery health per follower so the followers list can flag dead accounts.
|
|---|
| 212 | // Keyed by inbox: a shared-inbox POST reaches every follower behind it, so all of them
|
|---|
| 213 | // are marked. A non-follower inbox (inline @mention) simply matches 0 rows.
|
|---|
| 214 | let _fDelivOk, _fDelivErr;
|
|---|
| 215 | function markFollowerDelivery(slug, inbox, ok) {
|
|---|
| 216 | if (!slug || !inbox) return;
|
|---|
| 217 | try {
|
|---|
| 218 | if (!_fDelivOk) {
|
|---|
| 219 | _fDelivOk = db.prepare('UPDATE ap_followers SET last_delivery_at = CURRENT_TIMESTAMP WHERE slug = ? AND (inbox = ? OR shared_inbox = ?)');
|
|---|
| 220 | _fDelivErr = db.prepare('UPDATE ap_followers SET last_error_at = CURRENT_TIMESTAMP WHERE slug = ? AND (inbox = ? OR shared_inbox = ?)');
|
|---|
| 221 | }
|
|---|
| 222 | (ok ? _fDelivOk : _fDelivErr).run(slug, inbox, inbox);
|
|---|
| 223 | } catch { /* health tracking is non-fatal */ }
|
|---|
| 224 | }
|
|---|
| 225 | // Deliver now; queue for retry if it fails.
|
|---|
| 226 | export async function deliverWithRetry(slug, inbox, activity, keyId, privPem) {
|
|---|
| 227 | if (!inbox) return;
|
|---|
| 228 | try { const st = await deliver(inbox, activity, keyId, privPem); if (st >= 200 && st < 300) { markFollowerDelivery(slug, inbox, true); return; } } catch { /* queue below */ }
|
|---|
| 229 | enqueueDelivery(slug, inbox, activity);
|
|---|
| 230 | }
|
|---|
| 231 | let _processingDeliv = false;
|
|---|
| 232 | export async function processDeliveryQueue() {
|
|---|
| 233 | if (_processingDeliv) return; // re-entrancy guard: 30 rows × 8s can exceed the 60s tick → no double-delivery
|
|---|
| 234 | _processingDeliv = true;
|
|---|
| 235 | try {
|
|---|
| 236 | let rows;
|
|---|
| 237 | try { rows = deliveryStmts().due.all(); } catch { return; }
|
|---|
| 238 | if (!rows || !rows.length) return;
|
|---|
| 239 | const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
|---|
| 240 | for (const row of rows) {
|
|---|
| 241 | let ok = false;
|
|---|
| 242 | try {
|
|---|
| 243 | const keys = getOrCreateKeys(row.slug);
|
|---|
| 244 | const st = await deliver(row.inbox, JSON.parse(row.body), `${actorId(base, row.slug)}#main-key`, keys.private_pem);
|
|---|
| 245 | ok = st >= 200 && st < 300;
|
|---|
| 246 | } catch { ok = false; }
|
|---|
| 247 | if (ok) { markFollowerDelivery(row.slug, row.inbox, true); deliveryStmts().del.run(row.id); continue; }
|
|---|
| 248 | const attempts = row.attempts + 1;
|
|---|
| 249 | if (attempts >= DELIVERY_MAX_ATTEMPTS) { markFollowerDelivery(row.slug, row.inbox, false); deliveryStmts().del.run(row.id); console.warn('[AP] delivery gave up after', attempts, 'tries →', row.inbox); continue; }
|
|---|
| 250 | // Index the backoff on the CURRENT attempt count (row.attempts) so the first
|
|---|
| 251 | // retry uses the 1-min tier instead of skipping it.
|
|---|
| 252 | const mins = DELIVERY_BACKOFF_MIN[Math.min(row.attempts, DELIVERY_BACKOFF_MIN.length - 1)];
|
|---|
| 253 | deliveryStmts().bump.run(attempts, new Date(Date.now() + mins * 60000).toISOString(), row.id);
|
|---|
| 254 | }
|
|---|
| 255 | } finally { _processingDeliv = false; }
|
|---|
| 256 | }
|
|---|
| 257 | let _delivTimer = null;
|
|---|
| 258 | export function startDeliveryWorker() {
|
|---|
| 259 | if (_delivTimer) return;
|
|---|
| 260 | _delivTimer = setInterval(() => { processDeliveryQueue().catch(() => {}); }, 60 * 1000);
|
|---|
| 261 | if (_delivTimer.unref) _delivTimer.unref();
|
|---|
| 262 | }
|
|---|
| 263 |
|
|---|
| 264 | /** Een lokale site om GETs mee te ondertekenen wanneer er geen specifieke is
|
|---|
| 265 | * (de gedeelde inbox). Gecached: dit draait per binnenkomend verzoek. */
|
|---|
| 266 | let _signSlug;
|
|---|
| 267 | export function anySigningSlug() {
|
|---|
| 268 | if (_signSlug !== undefined) return _signSlug;
|
|---|
| 269 | try { const r = db.prepare('SELECT slug FROM sites ORDER BY rowid LIMIT 1').get(); _signSlug = (r && r.slug) || null; }
|
|---|
| 270 | catch { _signSlug = null; }
|
|---|
| 271 | return _signSlug;
|
|---|
| 272 | }
|
|---|
| 273 |
|
|---|
| 274 | // Best-effort verification of an incoming signed request. Returns the sender's
|
|---|
| 275 | // actor doc if the signature checks out, else null. (Not gating yet — MVP.)
|
|---|
| 276 | // Max clock skew for the signed Date header (replay window). Generous default to tolerate
|
|---|
| 277 | // federating servers with drifting clocks; an operator can widen it via env.
|
|---|
| 278 | const SIG_MAX_SKEW_MS = (Number(process.env.AP_SIG_MAX_SKEW_MIN) || 60) * 60 * 1000;
|
|---|
| 279 | export async function verifyRequest(req, asSlug = null) {
|
|---|
| 280 | const sigH = req.headers['signature'];
|
|---|
| 281 | if (!sigH) return null;
|
|---|
| 282 | const p = Object.fromEntries([...sigH.matchAll(/([a-zA-Z]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
|
|---|
| 283 | if (!p.keyId || !p.signature) return null;
|
|---|
| 284 | // Onderteken de sleutel-ophaal, anders faalt elke instance met authorized
|
|---|
| 285 | // fetch (shaer-afq). Zonder aangewezen site -- de gedeelde inbox -- tekenen we
|
|---|
| 286 | // als een willekeurige lokale actor: elke Klonkt-actor is een geldige
|
|---|
| 287 | // ondertekenaar, het gaat de andere kant er alleen om DAT er ondertekend is.
|
|---|
| 288 | const actor = await fetchActor(p.keyId.split('#')[0], { asSlug: asSlug || anySigningSlug() });
|
|---|
| 289 | const pem = actor && actor.publicKey && actor.publicKey.publicKeyPem;
|
|---|
| 290 | if (!pem) return null;
|
|---|
| 291 | // Bind the key to the actor it speaks for. Without this we hand back whatever
|
|---|
| 292 | // `id` the fetched document claims, so anyone could host a document carrying a
|
|---|
| 293 | // VICTIM's id next to their OWN public key, sign with their own private half,
|
|---|
| 294 | // and be believed: the victim's server is never contacted. The caller decides on
|
|---|
| 295 | // `verified.id`, so the identity has to come from where the key was FETCHED,
|
|---|
| 296 | // never from what the document says about itself.
|
|---|
| 297 | // Adds conditions only, and there is no exemption list on purpose: an
|
|---|
| 298 | // "unless it's a known peer" escape hatch is exactly the door this closes.
|
|---|
| 299 | // Note this does not narrow what we accept in practice, since the line above
|
|---|
| 300 | // already requires the embedded publicKey object (an array or a bare URI
|
|---|
| 301 | // reference never worked here).
|
|---|
| 302 | const key = actor.publicKey;
|
|---|
| 303 | try {
|
|---|
| 304 | if (new URL(p.keyId).host !== new URL(actor.id).host) return null; // same origin as the key
|
|---|
| 305 | if (key.id && key.id !== p.keyId) return null; // this key, not a neighbour's
|
|---|
| 306 | if (key.owner && key.owner !== actor.id) return null; // and it belongs to this actor
|
|---|
| 307 | } catch { return null; } // unparseable id or keyId
|
|---|
| 308 | const hs = (p.headers || '(request-target) host date').split(/\s+/);
|
|---|
| 309 | // Behind a reverse proxy the raw Host header is the backend bind (e.g. localhost:3000, when
|
|---|
| 310 | // the proxy doesn't preserve it — Apache .htaccess [P] proxying), but the sender signed the
|
|---|
| 311 | // HTTP-Signature over the PUBLIC host. Try each candidate host (the configured PUBLIC_BASE_URL
|
|---|
| 312 | // host, the proxy's X-Forwarded-Host, and the raw Host) and accept if the signature verifies
|
|---|
| 313 | // against any. An attacker can't forge a match (no private key), so this only rescues the
|
|---|
| 314 | // legitimate proxied case. Also normalise a leading double-slash in the request-target.
|
|---|
| 315 | let _pubHost = null;
|
|---|
| 316 | if (process.env.PUBLIC_BASE_URL) { try { _pubHost = new URL(process.env.PUBLIC_BASE_URL).host; } catch { /* ignore */ } }
|
|---|
| 317 | const _hosts = [...new Set([_pubHost, req.headers['x-forwarded-host'], req.headers['host']].filter(Boolean))];
|
|---|
| 318 | const _target = `${req.method.toLowerCase()} ${String(req.originalUrl || '').replace(/^\/{2,}/, '/')}`;
|
|---|
| 319 | const _sig = Buffer.from(p.signature, 'base64');
|
|---|
| 320 | let ok = false;
|
|---|
| 321 | for (const _h of _hosts) {
|
|---|
| 322 | const line = hs.map((x) => x === '(request-target)'
|
|---|
| 323 | ? `(request-target): ${_target}`
|
|---|
| 324 | : x === 'host' ? `host: ${_h}`
|
|---|
| 325 | : `${x}: ${req.headers[x] || ''}`).join('\n');
|
|---|
| 326 | try { if (crypto.verify('sha256', Buffer.from(line), pem, _sig)) { ok = true; break; } } catch { /* try next host */ }
|
|---|
| 327 | }
|
|---|
| 328 | // Replay defence: the Date header must be signed and recent. A captured signed request
|
|---|
| 329 | // replayed later (or with a swapped body) is rejected.
|
|---|
| 330 | if (ok) {
|
|---|
| 331 | if (!hs.includes('date')) ok = false;
|
|---|
| 332 | else {
|
|---|
| 333 | const t = Date.parse(req.headers['date'] || '');
|
|---|
| 334 | if (isNaN(t) || Math.abs(Date.now() - t) > SIG_MAX_SKEW_MS) ok = false;
|
|---|
| 335 | }
|
|---|
| 336 | }
|
|---|
| 337 | // Digest is MANDATORY when the request carries a body: without a signed digest the body
|
|---|
| 338 | // isn't covered by the signature and could be swapped on a replay.
|
|---|
| 339 | if (ok && req.rawBody && req.rawBody.length) {
|
|---|
| 340 | if (!hs.includes('digest')) ok = false;
|
|---|
| 341 | else {
|
|---|
| 342 | const exp = 'SHA-256=' + crypto.createHash('sha256').update(req.rawBody).digest('base64');
|
|---|
| 343 | if (req.headers['digest'] !== exp) ok = false;
|
|---|
| 344 | }
|
|---|
| 345 | }
|
|---|
| 346 | return ok ? actor : null;
|
|---|
| 347 | }
|
|---|
| 348 |
|
|---|
| 349 | // A generic SSRF-safe AP GET (collections / pages).
|
|---|
| 350 | /**
|
|---|
| 351 | * A signed GET as one of our local actors (friends-history, 30-7): the remote
|
|---|
| 352 | * server can then recognise the caller and serve what THAT caller may see,
|
|---|
| 353 | * exactly like the guardian's authorized fetch. The signature covers
|
|---|
| 354 | * (request-target) host date, the set verifyRequest checks.
|
|---|
| 355 | */
|
|---|
| 356 | /**
|
|---|
| 357 | * De handtekening-headers voor een GET als `slug`. Losgetrokken uit
|
|---|
| 358 | * signedGetJson omdat een verhuizing ook BYTES moet kunnen ophalen (FEP-1580:
|
|---|
| 359 | * gehoste audio zit achter dezelfde poort als de rest, en een ongetekende fetch
|
|---|
| 360 | * krijgt daar terecht een 403).
|
|---|
| 361 | */
|
|---|
| 362 | export function signedGetHeaders(slug, url, accept = 'application/activity+json') {
|
|---|
| 363 | const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
|---|
| 364 | if (!base || !slug) return null;
|
|---|
| 365 | const me = actorId(base, slug);
|
|---|
| 366 | const keys = getOrCreateKeys(slug);
|
|---|
| 367 | const u = new URL(url);
|
|---|
| 368 | const date = new Date().toUTCString();
|
|---|
| 369 | const target = `${u.pathname}${u.search || ''}`;
|
|---|
| 370 | const signingString = `(request-target): get ${target}\nhost: ${u.host}\ndate: ${date}`;
|
|---|
| 371 | const signature = crypto.sign('sha256', Buffer.from(signingString), keys.private_pem).toString('base64');
|
|---|
| 372 | return {
|
|---|
| 373 | Accept: accept,
|
|---|
| 374 | Date: date,
|
|---|
| 375 | Signature: `keyId="${me}#main-key",algorithm="rsa-sha256",headers="(request-target) host date",signature="${signature}"`,
|
|---|
| 376 | };
|
|---|
| 377 | }
|
|---|
| 378 |
|
|---|
| 379 | export async function signedGetJson(slug, url, onStatus) {
|
|---|
| 380 | try {
|
|---|
| 381 | const headers = signedGetHeaders(slug, url);
|
|---|
| 382 | if (!headers) return apGetJson(url);
|
|---|
| 383 | const r = await safeFetch(url, { headers });
|
|---|
| 384 | // De status doorgeven aan wie erom vroeg: null alleen zegt "het lukte
|
|---|
| 385 | // niet", en dat is te weinig om een WEIGERING van een STORING te
|
|---|
| 386 | // onderscheiden. Wie geen callback meegeeft merkt hier niets van.
|
|---|
| 387 | if (typeof onStatus === 'function') onStatus(r.status);
|
|---|
| 388 | if (!r.ok) return null;
|
|---|
| 389 | const len = Number(r.headers.get('content-length') || 0);
|
|---|
| 390 | if (len > 3_000_000) return null;
|
|---|
| 391 | return await r.json();
|
|---|
| 392 | } catch { return null; }
|
|---|
| 393 | }
|
|---|
| 394 |
|
|---|
| 395 | export async function apGetJson(url) {
|
|---|
| 396 | try {
|
|---|
| 397 | const r = await safeFetch(url, { headers: { Accept: 'application/activity+json' } });
|
|---|
| 398 | if (!r.ok) return null;
|
|---|
| 399 | const len = Number(r.headers.get('content-length') || 0);
|
|---|
| 400 | if (len > 3_000_000) return null;
|
|---|
| 401 | return await r.json();
|
|---|
| 402 | } catch { return null; }
|
|---|
| 403 | }
|
|---|