/** 서명된 아티팩트의 loopback HTTP 조회. docs/specs/artifacts-web-hub.md v1.2.0 */ const http = require('node:http'); function createArtifactHttpServer(readArtifact) { let server, starting, stopping, closed = false; const sockets = new Set(); const headers = { 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" }; async function handle(req, res) { const reply = (status, body, extra = {}) => { const bytes = Buffer.from(body); res.writeHead(status, { ...headers, 'Content-Type': 'text/plain; charset=utf-8', 'Content-Length': bytes.length, ...extra }); res.end(req.method === 'HEAD' ? undefined : bytes); }; try { if (!['GET', 'HEAD'].includes(req.method)) return reply(405, 'Method not allowed', { Allow: 'GET, HEAD' }); const url = new URL(req.url, 'http://127.0.0.1'); const match = /^\/artifacts\/(art_[a-z0-9]+_[a-f0-9]{8})$/.exec(url.pathname); if (!match || url.searchParams.getAll('token').length !== 1 || url.searchParams.getAll('exp').length !== 1) return reply(404, 'Artifact unavailable'); const item = await readArtifact(match[1], url.searchParams.get('token'), url.searchParams.get('exp')); if (!item?.success) return reply(404, 'Artifact unavailable'); const type = ['html', 'htm'].includes(item.type) ? 'text/html' : item.type === 'json' ? 'application/json' : 'text/plain'; reply(200, item.content, { 'Content-Type': type + '; charset=utf-8' }); } catch { if (!res.headersSent) reply(500, 'Artifact could not be read'); else res.destroy(); } } return { start(port) { if (closed) return Promise.reject(new Error('Artifact server is stopped')); if (starting) return starting; if (server?.listening) return Promise.resolve(server.address().port); const candidate = http.createServer({ maxHeaderSize: 16384 }, handle); server = candidate; candidate.headersTimeout = 10000; candidate.requestTimeout = 10000; candidate.on('connection', socket => { sockets.add(socket); socket.once('close', () => sockets.delete(socket)); }); starting = new Promise((resolve, reject) => { candidate.on('error', error => { if (!candidate.listening && server === candidate) server = null; reject(error); }); candidate.listen({ port, host: '127.0.0.1' }, () => { if (closed) reject(new Error('Artifact server stopped during startup')); else resolve(candidate.address().port); }); }).finally(() => { starting = null; }); return starting; }, stop() { if (stopping) return stopping; closed = true; // 대기 중인 연결도 바로 닫고 listen 완료 경합은 아래에서 회수한다. for (const socket of sockets) socket.destroy(); stopping = (async () => { try { await starting; } catch {} for (const socket of sockets) socket.destroy(); const current = server; server = null; if (current?.listening) await new Promise(resolve => current.close(resolve)); })(); return stopping; } }; } module.exports = { createArtifactHttpServer };