Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
58 lines
2.5 KiB
JavaScript
58 lines
2.5 KiB
JavaScript
import dns from 'dns';
|
|
import net from 'net';
|
|
import { GitError } from './errors.js';
|
|
|
|
// URL- und Host-Prüfung (ADR 0003 §4, SSRF-Schutz).
|
|
|
|
export const parseRepoUrl = (value, { allowHttp = false } = {})=>{
|
|
let u;
|
|
try { u = new URL(String(value)); } catch { throw new GitError('G08', 'Die Repository-URL ist ungültig.'); }
|
|
const okProtocol = u.protocol === 'https:' || (allowHttp && u.protocol === 'http:');
|
|
if(!okProtocol) throw new GitError('G08', 'Nur https://-URLs sind erlaubt.');
|
|
if(u.username || u.password) throw new GitError('G08', 'Die URL darf keine Zugangsdaten enthalten.');
|
|
if(u.search || u.hash) throw new GitError('G08', 'Die URL darf keine Query oder kein Fragment enthalten.');
|
|
if(!u.hostname || u.pathname === '/' || u.pathname === '') throw new GitError('G08', 'Die URL muss einen Repository-Pfad enthalten.');
|
|
if(String(value).length > 500) throw new GitError('G08', 'Die URL ist zu lang.');
|
|
return u;
|
|
};
|
|
|
|
const hostMatches = (host, pattern)=>pattern.startsWith('*.') ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1 : host === pattern;
|
|
|
|
const v4Private = (ip)=>{
|
|
const [a, b] = ip.split('.').map(Number);
|
|
return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254)
|
|
|| (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || a >= 224;
|
|
};
|
|
|
|
export const isPrivateAddress = (address)=>{
|
|
let ip = address.toLowerCase();
|
|
if(ip.startsWith('::ffff:') && net.isIPv4(ip.slice(7))) ip = ip.slice(7);
|
|
if(net.isIPv4(ip)) return v4Private(ip);
|
|
if(net.isIPv6(ip)) {
|
|
return ip === '::' || ip === '::1' || /^f[cd]/.test(ip) || /^fe[89ab]/.test(ip) || ip.startsWith('ff');
|
|
}
|
|
return true;
|
|
};
|
|
|
|
/**
|
|
* Wirft G08, wenn die URL nicht erlaubt ist. `lookup` ist für Tests austauschbar.
|
|
*/
|
|
export const assertUrlAllowed = async (value, cfg, { lookup = dns.promises.lookup } = {})=>{
|
|
const u = parseRepoUrl(value, cfg);
|
|
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
if(cfg.allowedHosts?.length) {
|
|
if(!cfg.allowedHosts.some((p)=>hostMatches(host, p)))
|
|
throw new GitError('G08', 'Dieser Git-Host ist auf dieser Instanz nicht erlaubt.');
|
|
return u;
|
|
}
|
|
if(cfg.allowPrivate) return u;
|
|
let addrs;
|
|
if(net.isIP(host)) addrs = [{ address: host }];
|
|
else {
|
|
try { addrs = await lookup(host, { all: true }); } catch { throw new GitError('G04', 'Der Git-Host konnte nicht aufgelöst werden.'); }
|
|
}
|
|
if(!addrs.length || addrs.some((a)=>isPrivateAddress(a.address)))
|
|
throw new GitError('G08', 'Interne oder private Adressen sind als Git-Ziel nicht erlaubt.');
|
|
return u;
|
|
};
|