diff --git a/STATE.md b/STATE.md new file mode 100644 index 0000000..0ca65f4 --- /dev/null +++ b/STATE.md @@ -0,0 +1,11 @@ +# STATE + +- 목표: 2026-11-22 01:00 KST까지 pullim의 보안·사용성·아키텍처 검수와 독립 검증을 완료하고 수정 PR을 준비한다. +- 금지 조건: main 직접 수정, 강제 덮어쓰기, 다른 작업 트리 삭제, 비밀값 기록, 검증되지 않은 취약점 단정. +- 확인된 사실: provider destination, HTML renderer sink, JSON body limit 문제를 수정했다. +- 근거: 1eed3570589770dcad9a53aca27baa8ce7bffed8, 6ec4a13f1243ad4cf863355e5475681cd642b340, 독립 re-review 보고서. +- 검증: npm test 57/57, lint zero warnings, build, Content-Length·chunked overflow 413, health recovery와 source sink 검토 통과. +- PR: Draft #22, head audit/security-ux-architecture-20261121, head 6ec4a13f1243ad4cf863355e5475681cd642b340. +- 미검증: browser execution, CSP, DNS rebinding, reverse proxy, deployment authentication, live provider. +- 복구: 1eed3570589770dcad9a53aca27baa8ce7bffed8와 6ec4a13f1243ad4cf863355e5475681cd642b340를 함께 revert한다. +- 다음 행동: PR #22 review와 배포 환경 검증을 진행한다. diff --git a/STATUS.md b/STATUS.md new file mode 100644 index 0000000..2b78e6f --- /dev/null +++ b/STATUS.md @@ -0,0 +1,18 @@ +# lee3Q/pullim + +## 단계 / 로드맵 + +- [x] 1단계: 최신 main, 작업장 정본, 실행 호스트와 작업 브랜치 확인 +- [x] 2단계: 보안·사용성·아키텍처 병렬 검수와 재현 +- [x] 3단계: provider·renderer·HTTP body boundary 수정과 독립 검수 +- [x] 4단계: 테스트·문서·복구 기록·Draft PR #22 완료 + +## 블로커 + +- 블로커: 없음. PR #22가 검토 대기 중이다. + +## AI 실행 맥락 + +- 마지막 커밋: 6ec4a13f1243ad4cf863355e5475681cd642b340 +- 지금 손댄 파일: 없음. audit branch는 clean +- 다음 할 일: PR #22 review와 배포 환경 확인을 진행한다. diff --git a/docs/pr-draft-security-ux-architecture-20261121.md b/docs/pr-draft-security-ux-architecture-20261121.md new file mode 100644 index 0000000..0244ca8 --- /dev/null +++ b/docs/pr-draft-security-ux-architecture-20261121.md @@ -0,0 +1,24 @@ +# Draft PR — security and UX architecture fixes + +## Summary + +- Restrict server-side BYOK provider destinations. +- Cap HTTP JSON bodies at 1 MiB with a 413 response. +- Escape untrusted renderer text and move affected dynamic actions to data attributes. +- Add focused adversarial regression tests for declared-length and chunked body limits. + +## Contract + +Built-in processing remains local. OpenAI BYOK uses the official HTTPS v1 endpoint. Ollama remains available on explicit loopback HTTP endpoints. Invalid external configuration falls back to the built-in engine. JSON POST bodies above 1 MiB are rejected. + +## Reproduction and patch rationale + +The audit reproduced API-key and concern exfiltration through arbitrary `baseUrl`, HTML/inline-handler injection through user and LLM text, and memory amplification from unbounded JSON buffering. The follow-up review also identified three missed renderer fields and a chunked-body connection reset. The patch places the smallest enforceable boundaries at the provider fetch and shared body reader, then escapes affected UI fields without changing local storage or BYOK defaults. + +## Verification + +Run `npm test`, `npm run lint`, `npm run build`, and the focused HTTP adversarial tests. The follow-up covers raw chunked overflow and verifies `/api/health` remains available. Record the exact commands and commit SHA in the final audit evidence. + +## Unknowns and rollback + +Deployment proxy limits, CSP, DNS rebinding, and browser execution remain deployment-level unknowns. Roll back by reverting the implementation commit on the audit branch. diff --git a/docs/security-audit-20261121.md b/docs/security-audit-20261121.md new file mode 100644 index 0000000..6505166 --- /dev/null +++ b/docs/security-audit-20261121.md @@ -0,0 +1,27 @@ +# Pullim security audit implementation — 2026-11-21 + +## Reproduction and confirmation + +F-01, F-02, and F-03 were independently confirmed by the supplied security, UX/architecture, and findings-verification reports. F-01 reproduced an attacker-controlled provider listener receiving the BYOK bearer token and concern. F-02 traced concern, provider, ladder, and local journal text into `innerHTML` and inline handlers. F-03 accepted an 8 MiB JSON request and showed substantial RSS amplification. + +## Contract and boundary + +Pullim remains local-first. The built-in engine sends no concern to an external provider. BYOK OpenAI uses only `https://api.openai.com/v1`. Ollama overrides are restricted to explicit loopback HTTP URLs with a port. Rejected provider configuration falls back to the deterministic engine without contacting the rejected address. Every JSON POST body is capped at 1 MiB and returns 413 when the declared or received body exceeds the cap. + +The web renderer escapes all identified untrusted text before inserting HTML. Dynamic renderer actions use data attributes handled by a listener. Fixed static controls retain their existing behavior. + +## Patch rationale + +The URL policy prevents arbitrary server-side fetches and key forwarding while preserving the intended OpenAI endpoint and local Ollama workflow. The body cap bounds buffering before JSON parsing. Escaping covers user, model, engine, and stored journal text in the affected renderers. The patch avoids broad schema or persistence changes. + +## Tests + +`npm test`, `npm run lint`, and `npm run build` are run with the login-shell Node/npm PATH. Focused adversarial tests cover an unapproved OpenAI URL, both declared-length and chunked 413 body-size boundaries, health availability after rejection, and the renderer source contract. The supplied baseline also records 54 passing Node tests before this patch. + +## Unknowns + +Reverse-proxy limits, deployment authentication, browser CSP, DNS rebinding behavior after URL validation, and real browser execution were not verified in this repository. The Ollama rule intentionally rejects remote/private-network endpoints because the current server has no operator-authenticated allowlist boundary. + +## Rollback + +Revert the implementation commit on `audit/security-ux-architecture-20261121`. This restores the previous provider, body-reader, and renderer behavior. Do not remove the pre-existing `STATE.md` or `STATUS.md` files. diff --git a/src/lib/core/llm-gateway.ts b/src/lib/core/llm-gateway.ts index 008aec8..b524196 100644 --- a/src/lib/core/llm-gateway.ts +++ b/src/lib/core/llm-gateway.ts @@ -19,6 +19,26 @@ export interface ProviderConfig { model?: string; } +function isLoopbackHostname(hostname: string): boolean { + return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; +} + +export function validateProviderBaseUrl(provider: OpenSourceProviderType, candidate: string): string { + let url: URL; + try { url = new URL(candidate); } catch { throw new Error("Provider base URL is invalid"); } + if (url.username || url.password) throw new Error("Provider base URL is not allowed"); + if (provider === "ollama") { + if (url.protocol !== "http:" || !isLoopbackHostname(url.hostname) || url.port === "") { + throw new Error("Ollama base URL must be an explicit loopback HTTP address"); + } + } else if (provider === "openai") { + if (url.protocol !== "https:" || url.origin !== "https://api.openai.com" || url.pathname !== "/v1") { + throw new Error("OpenAI base URL must be https://api.openai.com/v1"); + } + } + return url.toString().replace(/\/$/, ""); +} + export interface EnhancedUnravelResponse { result: UnravelResult; providerUsed: OpenSourceProviderType; @@ -44,11 +64,10 @@ async function callExternalProvider( const systemPrompt = buildSocraticSystemPrompt(lens); if (config.provider === "ollama") { - const baseUrl = ( - config.baseUrl || - process.env.OLLAMA_BASE_URL || - "http://127.0.0.1:11434" - ).replace(/\/$/, ""); + const baseUrl = validateProviderBaseUrl( + "ollama", + config.baseUrl || process.env.OLLAMA_BASE_URL || "http://127.0.0.1:11434", + ); const model = config.model || process.env.OLLAMA_MODEL || "llama3.2"; const res = await fetch(`${baseUrl}/api/chat`, { method: "POST", @@ -73,11 +92,10 @@ async function callExternalProvider( if (config.provider === "openai") { const apiKey = config.apiKey || process.env.OPENAI_API_KEY; if (!apiKey) throw new Error("OpenAI API key not configured"); - const baseUrl = ( - config.baseUrl || - process.env.OPENAI_BASE_URL || - "https://api.openai.com/v1" - ).replace(/\/$/, ""); + const baseUrl = validateProviderBaseUrl( + "openai", + config.baseUrl || process.env.OPENAI_BASE_URL || "https://api.openai.com/v1", + ); const model = config.model || "gpt-4o-mini"; const res = await fetch(`${baseUrl}/chat/completions`, { method: "POST", diff --git a/src/server/workbench-server.ts b/src/server/workbench-server.ts index a516328..1752c8e 100644 --- a/src/server/workbench-server.ts +++ b/src/server/workbench-server.ts @@ -19,10 +19,29 @@ import { exportUnravelToMarkdown } from "../lib/core/journal-portability.ts"; import { detectCrisis } from "../lib/safety/crisis-detector.ts"; import { getSessionSaveAccess } from "../lib/supabase/session-save-auth.ts"; +const MAX_JSON_BODY_BYTES = 1024 * 1024; + +class RequestBodyTooLargeError extends Error { + status = 413; + constructor() { super("Request body is too large"); } +} + async function readJsonBody(req: IncomingMessage): Promise> { + const contentLength = Number(req.headers["content-length"] || 0); + if (Number.isFinite(contentLength) && contentLength > MAX_JSON_BODY_BYTES) { + req.resume(); + throw new RequestBodyTooLargeError(); + } const chunks: Buffer[] = []; + let received = 0; for await (const chunk of req) { - chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk); + const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk; + received += buffer.byteLength; + if (received > MAX_JSON_BODY_BYTES) { + req.resume(); + throw new RequestBodyTooLargeError(); + } + chunks.push(buffer); } const raw = Buffer.concat(chunks).toString("utf8").trim(); if (!raw) return {}; @@ -227,9 +246,12 @@ export function createPullimServer(): http.Server { sendJson(res, 404, { error: "Not found" }); } catch (err) { - sendJson(res, 400, { - error: err instanceof Error ? err.message : "Bad request", - }); + const status = err instanceof RequestBodyTooLargeError ? err.status : 400; + if (!res.headersSent) { + sendJson(res, status, { + error: err instanceof Error ? err.message : "Bad request", + }); + } } }); } diff --git a/src/server/workbench-ui.ts b/src/server/workbench-ui.ts index d0b475b..1e82e7a 100644 --- a/src/server/workbench-ui.ts +++ b/src/server/workbench-ui.ts @@ -381,6 +381,12 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" document.getElementById("settings-drawer").classList.add("hidden"); } + function escapeHtml(value) { + return String(value ?? "").replace(/[&<>"']/g, character => ({ + "&": "&", "<": "<", ">": ">", '"': """, "'": "'" + }[character])); + } + function loadEngineConfig() { try { const raw = localStorage.getItem(ENGINE_CFG_KEY); @@ -416,11 +422,11 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" return; } const hotlines = (crisisResponse.hotlines || []) - .map(h => "
  • " + h.name + " (" + h.number + ") — " + h.description + "
  • ") + .map(h => "
  • " + escapeHtml(h.name) + " (" + escapeHtml(h.number) + ") — " + escapeHtml(h.description) + "
  • ") .join(""); banner.innerHTML = "

    ⚠️ 안전과 보호가 가장 먼저입니다

    " + - "

    " + crisisResponse.userMessage + "

    " + + "

    " + escapeHtml(crisisResponse.userMessage) + "

    " + ""; banner.classList.remove("hidden"); } @@ -452,45 +458,45 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" return; } - const factsHtml = r.facts.map(f => "
  • [사실] " + f + "
  • ").join(""); + const factsHtml = r.facts.map(f => "
  • [사실] " + escapeHtml(f) + "
  • ").join(""); const assumptionsHtml = r.assumptions.map(a => - "
  • [가정] " + a.statement + - "
    ↳ 점검 질문: " + a.checkQuestion + "
  • " + "
  • [가정] " + escapeHtml(a.statement) + + "
    ↳ 점검 질문: " + escapeHtml(a.checkQuestion) + "
  • " ).join(""); const trapsHtml = r.cognitiveTraps.map(t => - "
    • " + t.name + ": " + t.evidence + - "
    ↳ 전환 질문: " + t.reframeQuestion + "
    " + "
    • " + escapeHtml(t.name) + ": " + escapeHtml(t.evidence) + + "
    ↳ 전환 질문: " + escapeHtml(t.reframeQuestion) + "
    " ).join(""); const lensesHtml = r.lenses.map(l => "
    " + - "
    " + l.badge + "
    " + - "

    " + l.title + "

    " + - "

    " + l.summary + "

    " + - "

    소크라테스 질문: " + l.socraticQuestion + "

    " + + "
    " + escapeHtml(l.badge) + "
    " + + "

    " + escapeHtml(l.title) + "

    " + + "

    " + escapeHtml(l.summary) + "

    " + + "

    소크라테스 질문: " + escapeHtml(l.socraticQuestion) + "

    " + "
    " ).join(""); const optionsHtml = r.options.map(o => "
    " + - "
    " + o.title + "" + + "
    " + escapeHtml(o.title) + "" + (o.recommended ? "✦ 추천 기본값" : "") + " (" + o.costMinutes + "분 · 가역성 " + o.reversibility + ")
    " + - "
    " + o.description + "
    " + - "" + + "
    " + escapeHtml(o.description) + "
    " + + "" + "
    " ).join(""); out.innerHTML = - (data.aiSynthesisNote ? "
    🤖 연결된 LLM 코멘트 (" + data.modelUsed + "):

    " + data.aiSynthesisNote + "

    " : "") + + (data.aiSynthesisNote ? "
    🤖 연결된 LLM 코멘트 (" + escapeHtml(data.modelUsed) + "):

    " + escapeHtml(data.aiSynthesisNote) + "

    " : "") + "
    " + "
    " + "핵심 질문 재정의" + "
    " + - "" + + "" + "" + "
    " + "
    " + - "

    " + r.reframedQuestion + "

    " + - "

    핵심 갈등: " + r.coreTension + "

    " + + "

    " + escapeHtml(r.reframedQuestion) + "

    " + + "

    핵심 갈등: " + escapeHtml(r.coreTension) + "

    " + "
    " + "
    " + "

    1. 사실(Fact) vs 가정(Assumption) 분리

      " + factsHtml + assumptionsHtml + "
    " + @@ -610,9 +616,9 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" ).join(" "); const optsHtml = card.options.map(o => - "" ).join(""); @@ -625,11 +631,11 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" "" + "
    " + "
    " + - (s.latestFacetShift?.detected ? "
    " + s.latestFacetShift.message + "
    " : "") + - "

    " + card.levelName + " — " + card.question + "

    " + - "

    " + card.helperNote + "

    " + + (s.latestFacetShift?.detected ? "
    " + escapeHtml(s.latestFacetShift.message) + "
    " : "") + + "

    " + escapeHtml(card.levelName) + " — " + escapeHtml(card.question) + "

    " + + "

    " + escapeHtml(card.helperNote) + "

    " + "
    " + optsHtml + "
    " + - "" + + "" + ""; } @@ -643,11 +649,11 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" ? "

    아직 저장된 확정 행동이 없습니다.

    " : actions.map(a => "
    " + - "
    " + a.action + " " + a.status + "
    " + - "
    기한: " + (a.deadline || "없음") + "
    " + + "
    " + escapeHtml(a.action) + " " + escapeHtml(a.status) + "
    " + + "
    기한: " + escapeHtml(a.deadline || "없음") + "
    " + "
    " + - "" + - "" + + "" + + "" + "
    " + "
    " ).join(""); @@ -656,12 +662,12 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" ? "

    아직 저장된 If-Then 약속이 없습니다.

    " : promises.map(p => "
    " + - "
    만약: " + p.trigger + "
    " + - "
    → " + p.action + " " + p.status + "
    " + - (p.reflection ? "
    회고: " + p.reflection + "
    " : "") + + "
    만약: " + escapeHtml(p.trigger) + "
    " + + "
    → " + escapeHtml(p.action) + " " + escapeHtml(p.status) + "
    " + + (p.reflection ? "
    회고: " + escapeHtml(p.reflection) + "
    " : "") + "
    " + - "" + - "" + + "" + + "" + "
    " + "
    " ).join(""); @@ -670,8 +676,8 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" ? "

    아직 등재된 핵심 통찰이 없습니다.

    " : insights.map(i => "" ).join(""); @@ -684,7 +690,7 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" document.getElementById("journal-profile").innerHTML = dims.map(([key, left, right]) => { const val = profile?.[key]?.value ?? 0; const pct = Math.round(((val + 1) / 2) * 100); - return "
    " + left + "" + right + "
    " + + return "
    " + escapeHtml(left) + "" + escapeHtml(right) + "
    " + "
    "; }).join(""); } @@ -731,7 +737,7 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" ...actions.map(a => "- [" + (a.status === "completed" ? "x" : " ") + "] " + a.action), "", "## If-Then 약속", - ...promises.map(p => "- [" + (p.status === "completed" ? "x" : " ") + "] 만약 " + p.trigger + " → " + p.action), + ...promises.map(p => "- [" + (p.status === "completed" ? "x" : " ") + "] 만약 " + escapeHtml(p.trigger) + " → " + escapeHtml(p.action)), "", "## 명예의 전당 (핵심 통찰)", ...insights.map(i => "- ✦ " + i.insightText) @@ -759,6 +765,17 @@ export function renderWorkbenchHtml(initialTab: "unravel" | "ladder" | "journal" } } + document.addEventListener("click", event => { + const button = event.target.closest("[data-action]"); + if (!button) return; + const action = button.dataset.action; + if (action === "commit-action") commitActionFromUnravel(button.dataset.title || ""); + if (action === "start-ladder") startLadderFromConcern(button.dataset.direction || "up"); + if (action === "select-option") stepLadder({ type: "select_option", optionId: button.dataset.optionId, userText: document.getElementById("ladder-free")?.value || "" }); + if (action === "action-status") updateActionStatus(button.dataset.id || "", button.dataset.status || ""); + if (action === "promise-status") updatePromiseStatus(button.dataset.id || "", button.dataset.status || ""); + }); + switchTab("${initialTab}"); diff --git a/tests/workbench-http-and-cli.test.mjs b/tests/workbench-http-and-cli.test.mjs index 23757a0..570ca92 100644 --- a/tests/workbench-http-and-cli.test.mjs +++ b/tests/workbench-http-and-cli.test.mjs @@ -4,6 +4,8 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { test } from "node:test"; +import { readFile } from "node:fs/promises"; +import net from "node:net"; import { createPullimServer } from "../src/server/workbench-server.ts"; const exec = promisify(execFile); @@ -111,3 +113,68 @@ test("CLI commands (demo, unravel, ladder, crisis-check) execute cleanly", async const crisisJson = JSON.parse(crisisOut); assert.equal(crisisJson.tier, "A"); }); + +test("security boundaries reject unapproved provider endpoints and oversized JSON", async (t) => { + const server = createPullimServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(() => new Promise((resolve) => server.close(resolve))); + const baseUrl = `http://127.0.0.1:${server.address().port}`; + + const rejected = await fetch(`${baseUrl}/api/unravel`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + concern: "일반적인 고민", + config: { provider: "openai", apiKey: "synthetic-secret", baseUrl: "http://127.0.0.1:9" }, + }), + }); + assert.equal(rejected.status, 200); + const rejectedData = await rejected.json(); + assert.equal(rejectedData.providerUsed, "builtin"); + assert.match(rejectedData.fallbackReason, /연결 실패/); + + const oversized = await fetch(`${baseUrl}/api/crisis-check`, { + method: "POST", + headers: { "Content-Type": "application/json", "Content-Length": String(1024 * 1024 + 1) }, + body: "{" + "\"text\":\"" + "x".repeat(1024 * 1024 - 10) + "\"}", + }); + assert.equal(oversized.status, 413); + assert.equal((await oversized.json()).error, "Request body is too large"); +}); + +test("workbench HTML escapes untrusted renderer fields and has no dynamic inline handlers", async (t) => { + const server = createPullimServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(() => new Promise((resolve) => server.close(resolve))); + const html = await (await fetch(`http://127.0.0.1:${server.address().port}/`)).text(); + assert.match(html, /function escapeHtml/); + const uiSource = await readFile(new URL("../src/server/workbench-ui.ts", import.meta.url), "utf8"); + assert.doesNotMatch(uiSource, /onclick=\\\"commitActionFromUnravel/); + assert.doesNotMatch(uiSource, /onclick=\\\"stepLadder\(\{type:'select_option'/); +}); + + +test("chunked oversized JSON returns 413 and health remains available", async (t) => { + const server = createPullimServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(() => new Promise((resolve) => server.close(resolve))); + const port = server.address().port; + const response = await new Promise((resolve, reject) => { + const socket = net.createConnection({ host: "127.0.0.1", port }); + let data = ""; + socket.setEncoding("utf8"); + socket.on("data", (chunk) => { data += chunk; }); + socket.on("error", reject); + socket.on("end", () => resolve(data)); + socket.on("connect", () => { + socket.write("POST /api/crisis-check HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n"); + const chunk = "a".repeat(256 * 1024); + for (let i = 0; i < 5; i += 1) socket.write(`${chunk.length.toString(16)}\r\n${chunk}\r\n`); + socket.end("0\r\n\r\n"); + }); + }); + assert.match(response, /HTTP\/1\.1 413/); + assert.match(response, /Request body is too large/); + const health = await fetch(`http://127.0.0.1:${port}/api/health`); + assert.equal(health.status, 200); +});