const IPV4_PART = /^(?:0|[1-9][0-9]{0,2})$/; const HEX_PART = /^[0-9a-f]{1,4}$/i; const PREFIX = /^(?:0|[1-9][0-9]{0,2})$/; function validIPv4(address) { const parts = String(address).split('.'); return parts.length === 4 && parts.every(part => ( IPV4_PART.test(part) && Number(part) <= 255 )); } function validIPv6(address) { let value = String(address); if (!value || value.includes('%')) return false; if (value.includes('.')) { const separator = value.lastIndexOf(':'); if (separator < 0 || !validIPv4(value.slice(separator + 1))) return false; value = `${value.slice(0, separator + 1)}0:0`; } const compression = value.indexOf('::'); if (compression !== value.lastIndexOf('::')) return false; const compressed = compression >= 0; const sections = compressed ? value.split('::') : [value]; if (sections.length > 2) return false; const left = sections[0] === '' ? [] : sections[0].split(':'); const right = !compressed || sections[1] === '' ? [] : sections[1].split(':'); if (![...left, ...right].every(part => HEX_PART.test(part))) return false; const total = left.length + right.length; return compressed ? total < 8 : total === 8; } export function validFirewallCidr(value) { const raw = String(value).trim(); if (!raw || raw.length > 43 || /\s/.test(raw)) return false; const parts = raw.split('/'); if (parts.length > 2) return false; const address = parts[0]; const family = validIPv4(address) ? 4 : (validIPv6(address) ? 6 : 0); if (family === 0 || parts.length === 1) return family !== 0; const prefix = parts[1]; return PREFIX.test(prefix) && Number(prefix) <= (family === 4 ? 32 : 128); } const PRESETS = Object.freeze({ ssh: Object.freeze({ port_from: 22, port_to: 22, description: 'SSH' }), http: Object.freeze({ port_from: 80, port_to: 80, description: 'HTTP' }), https: Object.freeze({ port_from: 443, port_to: 443, description: 'HTTPS' }), }); export function firewallPresetRules(name, currentCount, limit = 50) { const preset = PRESETS[String(name || '').toLowerCase()]; const count = Number(currentCount); const maximum = Number(limit); if (!preset || !Number.isInteger(count) || count < 0 || !Number.isInteger(maximum) || maximum < 2 || count > maximum - 2) { return []; } return ['0.0.0.0/0', '::/0'].map(sourceCidr => ({ protocol: 'TCP', source_cidr: sourceCidr, ...preset, })); }