Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions STATE.md
Original file line number Diff line number Diff line change
@@ -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와 배포 환경 검증을 진행한다.
18 changes: 18 additions & 0 deletions STATUS.md
Original file line number Diff line number Diff line change
@@ -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와 배포 환경 확인을 진행한다.
24 changes: 24 additions & 0 deletions docs/pr-draft-security-ux-architecture-20261121.md
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 27 additions & 0 deletions docs/security-audit-20261121.md
Original file line number Diff line number Diff line change
@@ -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.
38 changes: 28 additions & 10 deletions src/lib/core/llm-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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",
Expand All @@ -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",
Expand Down
30 changes: 26 additions & 4 deletions src/server/workbench-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<string, unknown>> {
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 {};
Expand Down Expand Up @@ -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",
});
}
}
});
}
Loading
Loading