Files
homeclaw/wol-gate/server.js
T

352 lines
15 KiB
JavaScript

#!/usr/bin/env node
'use strict';
// Reverse-proxy gate: if the backend is asleep, send a WOL magic packet and
// show a "waking up" page instead of proxying, until the backend answers.
// Must run on an always-on host with L2 access to the target's broadcast
// domain (host networking) so the magic packet actually reaches the target.
const http = require('http');
const dgram = require('dgram');
const krCidrs = require('./kr-cidrs.json');
const denyFile = require('./deny-cidrs.json');
const TARGET_HOST = process.env.TARGET_HOST || '192.168.0.5';
const TARGET_PORT = parseInt(process.env.TARGET_PORT || '18789', 10);
const TARGET_MAC = process.env.TARGET_MAC || '64:00:6a:53:fd:8f';
const BROADCAST_ADDR = process.env.BROADCAST_ADDR || '192.168.0.255';
const WOL_PORT = parseInt(process.env.WOL_PORT || '9', 10);
const LISTEN_PORT = parseInt(process.env.LISTEN_PORT || '8099', 10);
const HEALTH_TIMEOUT_MS = parseInt(process.env.HEALTH_TIMEOUT_MS || '1200', 10);
const WAKE_COOLDOWN_MS = parseInt(process.env.WAKE_COOLDOWN_MS || '30000', 10);
const REFRESH_SECONDS = parseInt(process.env.REFRESH_SECONDS || '5', 10);
// 사람만 깨우기(2026-10-23): 국내 IP 스캐너(59.14.17.48 "PHP-Inventory-Audit/1.0", /phpinfo.php)가 새벽 2:20에
// 클로서버를 깨웠다. UA 블랙리스트·국가 필터로는 계속 뚫리므로, 로그인 흔적(홈클로 세션 쿠키·Bearer 토큰·
// 전에 깨우기 버튼을 누른 쿠키)이 있는 요청만 자동으로 깨우고, 나머지는 '깨우기' 버튼(POST)을 눌러야 깨운다.
// 봇은 GET만 두드리고 버튼을 누르지 않는다. 홈클로(18789) 대상은 기본 켬, 지서버 Ollama(게이트웨이가 쿠키 없이
// 부름)는 기본 끔. REQUIRE_HUMAN=0/1로 강제할 수 있다.
const REQUIRE_HUMAN = process.env.REQUIRE_HUMAN !== undefined
? process.env.REQUIRE_HUMAN === '1'
: TARGET_PORT === 18789;
const HUMAN_COOKIE = 'wolgate_human';
const WAKE_PATH = '/__wolgate/wake';
let lastWakeAt = 0;
// docker logs -t의 접두 시각은 UTC(Z)라 읽을 때 +9시간을 해야 한다 — 줄 안에 KST 시각을 직접 찍는다.
function kst() {
return new Date(Date.now() + 9 * 3600 * 1000).toISOString().replace('T', ' ').slice(0, 19) + ' KST';
}
// --- Domestic (KR) IP gating for wake triggers -----------------------------
// CIDR list is generated from APNIC's delegated-apnic-latest (KR allocations).
// LAN/loopback ranges are always allowed too, since a home NAT hairpin can
// make the requester's own visit show up as a private address (see
// project_wol_gate / reference_truenas_fail2ban memory for the same issue
// tripping up fail2ban's npm-scan jail).
function ipToInt(ip) {
const parts = ip.split('.').map(Number);
if (parts.length !== 4 || parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return null;
return parts[0] * 2 ** 24 + parts[1] * 2 ** 16 + parts[2] * 2 ** 8 + parts[3];
}
function cidrToRangeV4(cidr) {
const [base, bits] = cidr.split('/');
const baseInt = ipToInt(base);
const maskBits = parseInt(bits, 10);
const size = 2 ** (32 - maskBits);
return [baseInt, baseInt + size - 1];
}
function ipv6ToBigInt(ip) {
ip = ip.split('%')[0];
let head = ip;
let tail = '';
if (ip.includes('::')) {
const idx = ip.indexOf('::');
head = ip.slice(0, idx);
tail = ip.slice(idx + 2);
}
const expandV4Tail = (parts) => {
if (parts.length && parts[parts.length - 1].includes('.')) {
const v4 = parts.pop().split('.').map(Number);
parts.push((((v4[0] << 8) | v4[1]) >>> 0).toString(16));
parts.push((((v4[2] << 8) | v4[3]) >>> 0).toString(16));
}
return parts;
};
const h = expandV4Tail(head ? head.split(':') : []);
const t = expandV4Tail(tail ? tail.split(':') : []);
const missing = 8 - h.length - t.length;
const full = [...h, ...Array(Math.max(missing, 0)).fill('0'), ...t];
let result = 0n;
for (const group of full) result = (result << 16n) | BigInt(parseInt(group || '0', 16));
return result;
}
function cidrToRangeV6(cidr) {
const [base, bits] = cidr.split('/');
const prefixLen = BigInt(parseInt(bits, 10));
const baseInt = ipv6ToBigInt(base);
const hostBits = 128n - prefixLen;
const mask = (1n << hostBits) - 1n;
const start = baseInt & ~mask;
return [start, start | mask];
}
function inSortedRanges(value, ranges) {
let lo = 0;
let hi = ranges.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
const [start, end] = ranges[mid];
if (value < start) hi = mid - 1;
else if (value > end) lo = mid + 1;
else return true;
}
return false;
}
// 100.64.0.0/10 = Tailscale(CGNAT 대역) — tailnet 안의 기기는 사설망처럼 취급
const PRIVATE_V4_RANGES = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/8', '100.64.0.0/10']
.map(cidrToRangeV4)
.sort((a, b) => a[0] - b[0]);
// 요주의 대역(IDC 스캐너 등)은 국내 IP여도 깨우지 않는다. deny-cidrs.json + 환경변수 DENY_CIDRS.
const DENY_V4_RANGES = [
...(denyFile.ipv4 || []),
...String(process.env.DENY_CIDRS || '').split(',').map((s) => s.trim()).filter(Boolean),
].filter((c) => /^\d+\.\d+\.\d+\.\d+\/\d+$/.test(c)).map(cidrToRangeV4).sort((a, b) => a[0] - b[0]);
const KR_V4_RANGES = krCidrs.ipv4.map(cidrToRangeV4).sort((a, b) => a[0] - b[0]);
const KR_V6_RANGES = krCidrs.ipv6.map(cidrToRangeV6).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
function extractClientIp(req) {
const xff = req.headers['x-forwarded-for'];
let ip = (xff ? xff.split(',')[0].trim() : req.socket.remoteAddress) || '';
if (ip.startsWith('::ffff:')) ip = ip.slice(7);
return ip;
}
function isDomesticIp(ip) {
if (!ip) return false;
if (ip.includes(':')) {
try {
const big = ipv6ToBigInt(ip);
if (big === 1n) return true; // ::1 loopback
return inSortedRanges(big, KR_V6_RANGES);
} catch {
return false;
}
}
const n = ipToInt(ip);
if (n === null) return false;
return inSortedRanges(n, PRIVATE_V4_RANGES) || inSortedRanges(n, KR_V4_RANGES);
}
// -----------------------------------------------------------------------------
function sendMagicPacket(mac, broadcastAddr, port) {
const macBytes = mac.split(/[:-]/).map(h => parseInt(h, 16));
if (macBytes.length !== 6 || macBytes.some(Number.isNaN)) {
throw new Error('Invalid MAC address: ' + mac);
}
const packet = Buffer.alloc(6 + 16 * 6);
packet.fill(0xff, 0, 6);
for (let i = 0; i < 16; i++) Buffer.from(macBytes).copy(packet, 6 + i * 6);
const socket = dgram.createSocket('udp4');
socket.bind(() => {
socket.setBroadcast(true);
socket.send(packet, 0, packet.length, port, broadcastAddr, (err) => {
socket.close();
if (err) console.error('WOL send error:', err.message);
else console.log(`[wol-gate] ${kst()} magic packet sent to ${mac} via ${broadcastAddr}:${port}`);
});
});
}
// HTTP-level check, not just TCP connect: a target mid-boot can have its listener socket
// open (TCP connect succeeds) well before the actual service behind it is answering requests
// (e.g. Ollama's port opens before the model/runtime is ready) — a bare TCP check reports
// "alive" during that gap, so proxyRequest() gets sent through and times out with its own
// "Bad gateway: read ETIMEDOUT" instead of the caller seeing the (retryable) waking-up page.
// Observed live 2026-08-08 on a wol-gate-fronted Ollama target. Any real HTTP response
// (regardless of status code — even a 404 proves the app layer is serving, not just the
// socket) counts as alive; only a connection error/timeout counts as still-waking.
function checkTargetAlive() {
return new Promise((resolve) => {
let done = false;
const finish = (alive) => {
if (done) return;
done = true;
resolve(alive);
};
const req = http.request({
host: TARGET_HOST, port: TARGET_PORT, method: 'GET', path: '/', timeout: HEALTH_TIMEOUT_MS,
}, (res) => {
res.destroy();
finish(true);
});
req.on('timeout', () => req.destroy());
req.on('error', () => finish(false));
req.end();
});
}
function hasHumanCredential(req) {
const cookie = String(req.headers['cookie'] || '');
if (/(?:^|;\s*)(?:smallclaw_session|wolgate_human)=[^;\s]+/.test(cookie)) return true;
return /^Bearer\s+\S+/i.test(String(req.headers['authorization'] || ''));
}
// 메인 채팅만 깨우기(2026-10-27): 원인 불명 새벽 기상 대응. 로그인 흔적이 있어도 API·다른 앱 페이지·WebSocket·
// 홈어시스턴트 쪽 호출은 깨우지 않고, 브라우저가 메인 채팅 주소(/ 또는 /index.html)를 '페이지로 여는' 요청만 깨운다.
// 다른 요청은 서버가 자는 동안 안내 화면(버튼)만 받는다. 버튼(POST)은 항상 깨운다.
const WAKE_PAGE_PATHS = new Set(['/', '/index.html']);
function isMainChatNavigation(req) {
if (req.method !== 'GET') return false;
if (!WAKE_PAGE_PATHS.has(String(req.url || '').split('?')[0])) return false;
const dest = String(req.headers['sec-fetch-dest'] || '');
if (dest) return dest === 'document';
return /text\/html/i.test(String(req.headers['accept'] || ''));
}
function renderAskPage() {
return `<!doctype html>
<html lang="ko"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex">
<title>서버가 자는 중</title>
<style>
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#111;color:#eee;
display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0;gap:16px}
button{font-size:16px;padding:12px 28px;border-radius:8px;border:0;background:#7c5c2e;color:#fff;cursor:pointer}
p{color:#999;font-size:14px}
</style></head>
<body>
<div>서버가 절전 중입니다</div>
<form method="post" action="${WAKE_PATH}"><button type="submit">서버 깨우기</button></form>
<p>한 번 누르면 이 브라우저는 다음부터 접속만으로 깨어납니다</p>
</body></html>`;
}
function renderWakingPage(toRoot) {
return `<!doctype html>
<html lang="ko"><head><meta charset="utf-8">
<meta http-equiv="refresh" content="${REFRESH_SECONDS}${toRoot ? ';url=/' : ''}">
<title>서버 깨우는 중...</title>
<style>
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#111;color:#eee;
display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0;gap:16px}
.spinner{width:40px;height:40px;border:4px solid #333;border-top-color:#7c5c2e;border-radius:50%;
animation:spin 0.9s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
p{color:#999;font-size:14px}
</style></head>
<body>
<div class="spinner"></div>
<div>서버를 깨우는 중입니다...</div>
<p>${REFRESH_SECONDS}초마다 자동으로 다시 확인합니다</p>
</body></html>`;
}
function describeRequester(req) {
const ip = extractClientIp(req) || '-';
const ua = req.headers['user-agent'] || '-';
const host = req.headers['host'] || '-';
return `${ip} "${req.method} ${host}${maskSecrets(req.url)}" UA="${ua}"`;
}
// 로그에 인증 토큰이 그대로 남지 않게 쿼리의 token·key·secret·password 류 값을 가린다
function maskSecrets(url) {
return String(url || '').replace(/([?&](?:token|access_token|auth|auth_token|api_key|apikey|key|secret|password|pw|sid|session)=)[^&#\s]*/gi, '$1***');
}
function maybeWake(req) {
const ip = extractClientIp(req);
const ipn = ipToInt(ip || '');
if (ipn !== null && inSortedRanges(ipn, DENY_V4_RANGES)) {
console.log(`[wol-gate] ${kst()} wake denied (watchlist) - triggered by ${describeRequester(req)}`);
return;
}
if (!isDomesticIp(ip)) {
console.log(`[wol-gate] ${kst()} wake blocked (non-KR) - triggered by ${describeRequester(req)}`);
return;
}
const now = Date.now();
if (now - lastWakeAt <= WAKE_COOLDOWN_MS) {
console.log(`[wol-gate] ${kst()} wake suppressed (cooldown) - triggered by ${describeRequester(req)}`);
return;
}
lastWakeAt = now;
console.log(`[wol-gate] ${kst()} waking - triggered by ${describeRequester(req)}`);
try {
sendMagicPacket(TARGET_MAC, BROADCAST_ADDR, WOL_PORT);
} catch (e) {
console.error(`[wol-gate] ${kst()}`, e.message);
}
}
function proxyRequest(req, res) {
const proxyReq = http.request({
host: TARGET_HOST, port: TARGET_PORT,
method: req.method, path: req.url, headers: req.headers,
}, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
proxyReq.on('error', (err) => {
res.writeHead(502);
res.end('Bad gateway: ' + err.message);
});
req.pipe(proxyReq);
}
const server = http.createServer(async (req, res) => {
const isWakeButton = req.method === 'POST' && (req.url || '').split('?')[0] === WAKE_PATH;
if (await checkTargetAlive()) {
if (isWakeButton) { // 깨어난 뒤 버튼 POST가 늦게 도착 — 백엔드로 넘기지 않고 첫 화면으로
res.writeHead(303, { Location: '/' });
res.end();
return;
}
proxyRequest(req, res);
return;
}
if (REQUIRE_HUMAN && !isWakeButton && !(isMainChatNavigation(req) && hasHumanCredential(req))) {
console.log(`[wol-gate] ${kst()} wake held (not main-chat page or no login, button shown) - triggered by ${describeRequester(req)}`);
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(renderAskPage());
return;
}
maybeWake(req);
const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' };
if (isWakeButton) {
// 버튼을 누른 브라우저는 1년간 사람으로 기억 — 다음부터 접속만으로 깨운다
headers['Set-Cookie'] = `${HUMAN_COOKIE}=1; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax; Secure`;
}
res.writeHead(200, headers);
res.end(renderWakingPage(isWakeButton));
});
// Forward WebSocket upgrades too, once awake (homeclaw uses WS heavily).
server.on('upgrade', async (req, socket, head) => {
if (!(await checkTargetAlive())) {
if (!REQUIRE_HUMAN) maybeWake(req); // 사람 확인 모드에선 WebSocket 재연결이 깨우지 않는다
socket.destroy();
return;
}
const proxyReq = http.request({
host: TARGET_HOST, port: TARGET_PORT,
method: req.method, path: req.url, headers: req.headers,
});
proxyReq.on('upgrade', (proxyRes, proxySocket) => {
const headerLines = Object.entries(proxyRes.headers).map(([k, v]) => `${k}: ${v}`).join('\r\n');
socket.write(`HTTP/1.1 101 Switching Protocols\r\n${headerLines}\r\n\r\n`);
proxySocket.pipe(socket);
socket.pipe(proxySocket);
});
proxyReq.on('error', () => socket.destroy());
proxyReq.end();
});
server.listen(LISTEN_PORT, () => {
console.log(`[wol-gate] ${kst()} listening on :${LISTEN_PORT} -> ${TARGET_HOST}:${TARGET_PORT}, WOL target ${TARGET_MAC} via ${BROADCAST_ADDR}:${WOL_PORT}, require-human=${REQUIRE_HUMAN}`);
});