JavaScript Python PHP
async function executar(values) {
function generateInfraNginx(v) {
const mode = infraChoice(v.mode, ['Arquivos estáticos', 'SPA', 'Proxy reverso']), port = infraInteger(v.listen, 'Porta HTTP', 1, 65535), websocket = infraChoice(v.websocket, ['Sim', 'Não']) === 'Sim';
if (v.domain.length > 253 || !v.domain.split('.').every(label => label.length <= 63 && /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(label)))
throw new Error('Domínio inválido. Use DNS ASCII/IPv4, sem protocolo, caminho ou diretivas.');
let location = '', preface = '# Inclua no contexto http, por exemplo em conf.d. Não configura TLS.\n';
if (mode === 'Proxy reverso') {
let upstream;
try {
upstream = new URL(v.upstream);
}
catch {
throw new Error('Origem do proxy inválida.');
}
if (!/^https?:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?\/?$/.test(v.upstream) || !['http:', 'https:'].includes(upstream.protocol) || upstream.username || upstream.password || upstream.pathname !== '/' || upstream.search || upstream.hash || !upstream.hostname.split('.').every(label => /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(label)))
throw new Error('Proxy exige origem HTTP/HTTPS simples, sem caminho, credenciais, query ou fragmento.');
if (websocket)
preface += 'map $http_upgrade $connection_upgrade {\n default upgrade;\n "" close;\n}\n';
let ssl = '';
if (upstream.protocol === 'https:') {
if (!/^\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+$/.test(v.sslCA) || v.sslCA.split('/').includes('..'))
throw new Error('Proxy HTTPS exige o caminho absoluto do bundle CA real para verificar o certificado do upstream.');
ssl = ` proxy_ssl_server_name on;\n proxy_ssl_verify on;\n proxy_ssl_trusted_certificate ${v.sslCA};\n proxy_ssl_verify_depth 3;\n`;
}
location = ` proxy_pass ${upstream.origin};\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $remote_addr;\n proxy_set_header X-Forwarded-Proto $scheme;\n` + ssl + (websocket ? ' proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection $connection_upgrade;\n' : '');
}
else {
if (!/^\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\/?$/.test(v.root) || v.root.split('/').includes('..'))
throw new Error('Diretório inválido: use caminho absoluto simples, sem .., espaços ou diretivas.');
if (websocket)
throw new Error('WebSocket só se aplica ao modo Proxy reverso.');
location = ' try_files $uri $uri/ ' + (mode === 'SPA' ? '/index.html' : '=404') + ';\n';
}
const text = preface + `server {\n listen ${port};\n server_name ${v.domain.toLowerCase()};\n` + (mode !== 'Proxy reverso' ? ` root ${v.root};\n index index.html;\n` : '') + ' location / {\n' + location + ' }\n}\n';
return { text, files: [{ name: 'site.conf', content: text }], notes: [mode === 'SPA' ? 'try_files usa index.html como fallback para rotas da SPA. Arquivos inexistentes também podem receber esse fallback; ajuste regras de assets conforme o projeto.' : mode === 'Arquivos estáticos' ? 'try_files entrega arquivos/diretórios existentes e retorna 404 nos demais casos.' : 'proxy_pass sem caminho mantém a URI; cabeçalhos informam host, protocolo e IP recebidos por este proxy.', 'Não inclui TLS, autenticação ou configuração completa de confiança em proxies. Teste com nginx -t no ambiente de destino antes de aplicar.'] };
}
function infraText(value, limit = 100000) {
if (typeof value !== 'string' || value.length > limit)
throw new Error(`Use texto com até ${limit} caracteres.`);
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) || /[\uD800-\uDFFF]/u.test(value))
throw new Error('Há caracteres de controle ou Unicode inválidos na entrada.');
return value;
}
function infraInteger(value, label, min, max) {
if (!/^\d{1,10}$/.test(value || '') || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max)
throw new Error(`${label}: use um inteiro de ${min} a ${max}.`);
return Number(value);
}
function infraChoice(value, options) {
if (!options.includes(value))
throw new Error('Opção não suportada: ' + value);
return value;
}
for (const value of Object.values(values)) infraText(value);
const output = await generateInfraNginx(values);
if (output.text.length > 1000000) throw new Error("Resultado excede 1 milhão de caracteres.");
return output;
}
import re
from urllib.parse import urlsplit
def executar(values):
def text(value, limit=100000):
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > limit or re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff\ud800-\udfff]', value):
raise ValueError('Texto excede o limite ou contém caracteres inválidos.')
return value
def choice(value, options):
if value not in options:
raise ValueError('Opção não suportada.')
return value
def integer(value, minimum, maximum):
if not isinstance(value, str) or not re.fullmatch(r'[0-9]{1,10}', value) or not minimum <= int(value) <= maximum:
raise ValueError('Inteiro fora dos limites.')
return int(value)
for value in values.values(): text(value)
mode, port = choice(values['mode'], ['Arquivos estáticos', 'SPA', 'Proxy reverso']), integer(values['listen'], 1, 65535)
websocket, domain = choice(values['websocket'], ['Sim', 'Não']) == 'Sim', values['domain']
if len(domain) > 253 or not all(len(label) <= 63 and re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?', label) for label in domain.split('.')): raise ValueError('Domínio inválido.')
preface = '# Inclua no contexto http, por exemplo em conf.d. Não configura TLS.\n'
if mode == 'Proxy reverso':
address = urlsplit(values['upstream'])
if not re.fullmatch(r'https?://[A-Za-z0-9.-]+(?::[0-9]{1,5})?/?', values['upstream']) or not address.hostname or not all(re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?', label) for label in address.hostname.split('.')): raise ValueError('Origem do proxy inválida.')
upstream = address.scheme + '://' + address.hostname.lower() + (':' + str(address.port) if address.port and address.port != (443 if address.scheme == 'https' else 80) else '')
if websocket: preface += 'map $http_upgrade $connection_upgrade {\n default upgrade;\n "" close;\n}\n'
location = f' proxy_pass {upstream};\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $remote_addr;\n proxy_set_header X-Forwarded-Proto $scheme;\n'
if address.scheme == 'https':
if not re.fullmatch(r'/(?:[A-Za-z0-9_.-]+/)*[A-Za-z0-9_.-]+', values['sslCA']) or '..' in values['sslCA'].split('/'): raise ValueError('Proxy HTTPS exige bundle CA real.')
location += ' proxy_ssl_server_name on;\n proxy_ssl_verify on;\n proxy_ssl_trusted_certificate ' + values['sslCA'] + ';\n proxy_ssl_verify_depth 3;\n'
if websocket: location += ' proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection $connection_upgrade;\n'
else:
root = values['root']
if not re.fullmatch(r'/(?:[A-Za-z0-9_.-]+/)*[A-Za-z0-9_.-]+/?', root) or '..' in root.split('/'): raise ValueError('Diretório inválido.')
if websocket: raise ValueError('WebSocket exige proxy.')
location = ' try_files $uri $uri/ ' + ('/index.html' if mode == 'SPA' else '=404') + ';\n'
result = preface + f'server {{\n listen {port};\n server_name {domain.lower()};\n' + (f' root {values["root"]};\n index index.html;\n' if mode != 'Proxy reverso' else '') + ' location / {\n' + location + ' }\n}\n'
note = 'try_files usa index.html como fallback para rotas da SPA. Arquivos inexistentes também podem receber esse fallback; ajuste regras de assets conforme o projeto.' if mode == 'SPA' else 'try_files entrega arquivos/diretórios existentes e retorna 404 nos demais casos.' if mode == 'Arquivos estáticos' else 'proxy_pass sem caminho mantém a URI; cabeçalhos informam host, protocolo e IP recebidos por este proxy.'
return {'text': result, 'files': [{'name': 'site.conf', 'content': result}], 'notes': [note, 'Não inclui TLS, autenticação ou configuração completa de confiança em proxies. Teste com nginx -t no ambiente de destino antes de aplicar.']}
<?php
function executar(array $values): array {
$text = static function ($value, $limit = 100000) { if (!is_string($value) || !preg_match('//u', $value) || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > $limit || preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x{fffe}\x{ffff}]/u', $value)) throw new InvalidArgumentException('Texto excede o limite ou contém caracteres inválidos.'); return $value; };
$choice = static function ($value, $options) { if (!in_array($value, $options, true)) throw new InvalidArgumentException('Opção não suportada.'); return $value; };
$integer = static function ($value, $min, $max) { if (!is_string($value) || !preg_match('/^[0-9]{1,10}$/D', $value) || (int)$value < $min || (int)$value > $max) throw new InvalidArgumentException('Inteiro fora dos limites.'); return (int)$value; };
foreach ($values as $value) $text($value);
$mode = $choice($values['mode'], ['Arquivos estáticos', 'SPA', 'Proxy reverso']); $port = $integer($values['listen'], 1, 65535); $websocket = $choice($values['websocket'], ['Sim', 'Não']) === 'Sim'; $domain = $values['domain'];
if (strlen($domain) > 253) throw new InvalidArgumentException('Domínio inválido.'); foreach (explode('.', $domain) as $label) if (strlen($label) > 63 || !preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/D', $label)) throw new InvalidArgumentException('Domínio inválido.');
$preface = "# Inclua no contexto http, por exemplo em conf.d. Não configura TLS.\n";
if ($mode === 'Proxy reverso') { $p = parse_url($values['upstream']); if (!$p || !preg_match('~^https?://[A-Za-z0-9.-]+(?::[0-9]{1,5})?/?$~D', $values['upstream'])) throw new InvalidArgumentException('Origem do proxy inválida.'); foreach (explode('.', $p['host']) as $label) if (!preg_match('/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/D', $label)) throw new InvalidArgumentException('Origem do proxy inválida.'); $upstream = $p['scheme'] . '://' . strtolower($p['host']) . (isset($p['port']) && $p['port'] !== ($p['scheme'] === 'https' ? 443 : 80) ? ':' . $p['port'] : '');
if ($websocket) $preface .= 'map $http_upgrade $connection_upgrade {' . "\n default upgrade;\n \"\" close;\n}\n";
$location = ' proxy_pass ' . $upstream . ";\n proxy_http_version 1.1;\n" . ' proxy_set_header Host $host;' . "\n" . ' proxy_set_header X-Real-IP $remote_addr;' . "\n" . ' proxy_set_header X-Forwarded-For $remote_addr;' . "\n" . ' proxy_set_header X-Forwarded-Proto $scheme;' . "\n";
if ($p['scheme'] === 'https') { if (!preg_match('~^/(?:[A-Za-z0-9_.-]+/)*[A-Za-z0-9_.-]+$~D', $values['sslCA']) || in_array('..', explode('/', $values['sslCA']), true)) throw new InvalidArgumentException('Proxy HTTPS exige bundle CA real.'); $location .= " proxy_ssl_server_name on;\n proxy_ssl_verify on;\n proxy_ssl_trusted_certificate " . $values['sslCA'] . ";\n proxy_ssl_verify_depth 3;\n"; } if ($websocket) $location .= ' proxy_set_header Upgrade $http_upgrade;' . "\n" . ' proxy_set_header Connection $connection_upgrade;' . "\n";
} else { if (!preg_match('~^/(?:[A-Za-z0-9_.-]+/)*[A-Za-z0-9_.-]+/?$~D', $values['root']) || in_array('..', explode('/', $values['root']), true)) throw new InvalidArgumentException('Diretório inválido.'); if ($websocket) throw new InvalidArgumentException('WebSocket exige proxy.'); $location = ' try_files $uri $uri/ ' . ($mode === 'SPA' ? '/index.html' : '=404') . ";\n"; }
$output = $preface . "server {\n listen $port;\n server_name " . strtolower($domain) . ";\n" . ($mode !== 'Proxy reverso' ? ' root ' . $values['root'] . ";\n index index.html;\n" : '') . " location / {\n" . $location . " }\n}\n";
$note = $mode === 'SPA' ? 'try_files usa index.html como fallback para rotas da SPA. Arquivos inexistentes também podem receber esse fallback; ajuste regras de assets conforme o projeto.' : ($mode === 'Arquivos estáticos' ? 'try_files entrega arquivos/diretórios existentes e retorna 404 nos demais casos.' : 'proxy_pass sem caminho mantém a URI; cabeçalhos informam host, protocolo e IP recebidos por este proxy.');
return ['text' => $output, 'files' => [['name' => 'site.conf', 'content' => $output]], 'notes' => [$note, 'Não inclui TLS, autenticação ou configuração completa de confiança em proxies. Teste com nginx -t no ambiente de destino antes de aplicar.']];
}