Spaces:
Paused
Paused
File size: 7,174 Bytes
2276d59 62527b4 2276d59 fcc9edb 2276d59 fcc9edb d0f7796 fcc9edb d0f7796 2276d59 d0f7796 fcc9edb d0f7796 fcc9edb d0f7796 fcc9edb 62527b4 fcc9edb 2276d59 fcc9edb 2276d59 fcc9edb d0f7796 2276d59 62527b4 2276d59 | 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | import path from 'node:path';
import { logger } from '../infra/logger.util.js';
import os from 'node:os';
import { lookup } from 'node:dns/promises';
import { lookup as dnsLookup, type LookupAddress } from 'node:dns';
import { isIP } from 'node:net';
import { randomUUID } from 'node:crypto';
import { URL } from 'node:url';
import { fetch as undiciFetch, Agent } from 'undici';
import { createRedisClient } from '../infra/redis.util.js';
const redis = createRedisClient('security');
const PRIVATE_IP_RANGES = [
/^127\./, // localhost
/^10\./, // class a
/^192\.168\./, // class c
/^172\.(?:1[6-9]|2\d|3[0-1])\./, // class b
/^169\.254\./, // link-local
/^0\./, // 0.0.0.0/8
/^100\.(?:6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\./, // nat prefix
/^255\.255\.255\.255$/, // broadcast
/^(?:22[4-9]|23\d)\./, // multicast IPv4
/^::1$/, // ipv6 local
/^[fF][cCdD]/, // ipv6 unique
/^[fF][eE][8-9a-bA-B]/, // ipv6 link-local
/^::$/, // ipv6 unspecified
/^[fF][fF]/, // ipv6 multicast
/^::ffff:(?:127\.|10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[0-1])\.|169\.254\.|0\.|100\.(?:6[4-9]|[7-9]\d|1[0-1]\d|12[0-7])\.|255\.255\.255\.255|22[4-9]\.|23\d\.)/, // ipv4 private
];
export function isSafeIp(ip: string): boolean {
if (!isIP(ip)) return false;
return !PRIVATE_IP_RANGES.some((regex) => regex.test(ip));
}
export async function resolveAndValidateHost(
hostname: string
): Promise<string> {
if (isIP(hostname)) {
if (!isSafeIp(hostname)) {
throw new Error(
`SSRF Blocked: Attempted to access private IP (${hostname})`
);
}
return hostname;
}
try {
const { address } = await lookup(hostname, { family: 0 });
if (!isSafeIp(address)) {
throw new Error(
`SSRF Blocked: Hostname ${hostname} resolved to private IP (${address})`
);
}
return address;
} catch (error: unknown) {
if (error instanceof Error && error.message.includes('SSRF')) throw error;
throw new Error(`DNS Lookup failed for hostname: ${hostname}`, {
cause: error,
});
}
}
const ssrfSafeAgent = new Agent({
connect: {
lookup: (hostname, options, callback) => {
return dnsLookup(hostname, options, (error, address, family) => {
if (error) {
callback(error, address as unknown as string, family);
return;
}
const isArray = Array.isArray(address);
const addrsToCheck = isArray
? (address as LookupAddress[])
: [{ address: address as unknown as string }];
for (const addr of addrsToCheck) {
if (!isSafeIp(addr.address)) {
callback(
new Error(
`[SSRF BLOCK] Resolution to internal IP blocked: ${addr.address}`
),
address as unknown as string,
family
);
return;
}
}
callback(null, address as unknown as string, family);
});
},
},
});
export async function secureFetch(
targetUrl: string | URL,
options: RequestInit = {}
): Promise<globalThis.Response> {
const parsedUrl =
typeof targetUrl === 'string' ? new URL(targetUrl) : targetUrl;
const normalizedHeaders = new Headers(options.headers as HeadersInit);
if (process.env.NODE_ENV === 'test' || process.env.VITEST) {
const response = await fetch(parsedUrl.toString(), {
...options,
headers: normalizedHeaders,
redirect: 'follow',
});
return response as globalThis.Response;
}
const response = await undiciFetch(parsedUrl.toString(), {
...(options as unknown as Record<string, unknown>),
headers: normalizedHeaders,
dispatcher: ssrfSafeAgent,
redirect: 'follow',
});
return response as unknown as globalThis.Response;
}
export async function acquireLock(ip: string, limit = 2): Promise<boolean> {
const key = `lock:concurrency:${ip}`;
const current = await redis.incr(key);
if (current === 1) {
await redis.expire(key, 1800);
}
if (current > limit) {
await redis.decr(key);
return false;
}
return true;
}
export async function releaseLock(ip: string): Promise<void> {
const key = `lock:concurrency:${ip}`;
await redis.decr(key);
const val = await redis.get(key);
if (val && parseInt(val, 10) <= 0) {
await redis.del(key);
}
}
import { Request, Response, NextFunction } from 'express';
import { sendEvent } from './sse.util.js';
const MEDIA_ACTIVE_KEY = 'media:active';
// stale slots self-heal after this
const MEDIA_SLOT_TTL_MS = Number(process.env.MEDIA_SLOT_TTL_MS) || 1800000;
interface MediaGuardOptions {
limit?: number;
key?: string;
}
// cap heavy media jobs across instances
export const globalMediaGuard = (options: number | MediaGuardOptions = {}) => {
const opts = typeof options === 'number' ? { limit: options } : options;
// fallback to 4 if cpus undefined
const limit =
opts.limit ??
(Number(process.env.MAX_CONCURRENT_MEDIA) || os.cpus().length || 4);
const key = opts.key ?? MEDIA_ACTIVE_KEY;
return async (_req: Request, res: Response, next: NextFunction) => {
const jobId = randomUUID();
const now = Date.now();
try {
await redis.zremrangebyscore(key, 0, now - MEDIA_SLOT_TTL_MS);
await redis.zadd(key, now, jobId);
const active = await redis.zcard(key);
if (active > limit) {
await redis.zrem(key, jobId);
res.status(503).json({ error: 'Server busy, please retry shortly.' });
return;
}
} catch (error: unknown) {
// redis down; fail open
logger.warn('[MediaGuard] redis unavailable:', (error as Error).message);
next();
return;
}
let released = false;
const release = () => {
if (released) return;
released = true;
redis.zrem(key, jobId).catch(() => {});
};
res.on('finish', release);
res.on('close', release);
next();
};
};
export const concurrencyGuard = (limit = 2) => {
return async (req: Request, res: Response, next: NextFunction) => {
const clientIp = req.ip || 'unknown';
const clientId = (req.query?.id || req.body?.id) as string | undefined;
const hasLock = await acquireLock(clientIp, limit);
if (!hasLock) {
if (clientId) {
sendEvent(clientId, {
status: 'error',
message: 'Too many active operations. Please wait for one to finish.',
});
}
res.status(429).json({ error: 'Concurrency limit reached.' });
return;
}
let released = false;
const cleanup = () => {
if (!released) {
released = true;
releaseLock(clientIp).catch((error) =>
logger.error(
'[Security] Lock release error:',
(error as Error).message
)
);
}
};
res.on('finish', cleanup);
res.on('close', cleanup);
next();
};
};
// reject path traversal outside base
export function resolveWithin(
base: string,
...segments: string[]
): string | null {
const root = path.resolve(base);
const target = path.resolve(root, ...segments);
if (target !== root && !target.startsWith(root + path.sep)) return null;
return target;
}
|