frontend: web UI track handoff (contract revision 1)

Static frontend with vendored marked/DOMPurify, bounded Markdown
pipeline, same-origin mock server with scenario selection, unit,
contract and CDP end-to-end tests under frontend/**.
This commit is contained in:
Artur Mukhamadiev 2026-09-14 21:57:54 +03:00
parent e65fbf4b67
commit a9908a533f
23 changed files with 5427 additions and 0 deletions

2
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules/
.DS_Store

92
frontend/README.md Normal file
View File

@ -0,0 +1,92 @@
# Confluence Research - Web UI
Minimalist, secure Web UI for Confluence Research, designed to operate against the backend API contracts specified in `docs/SPECIFICATION.md` and `docs/implementation/CONTRACTS.md`.
## Directory Layout
```text
frontend/
├── index.html # Main HTML entrypoint (clean white minimalist theme)
├── css/
│ └── style.css # Responsive styling, accessible components, gear animation
├── js/
│ ├── app.js # State transitions, keyboard handling, memory credentials, staleness guards
│ ├── api.js # Relative /api/v1/... fetch boundary with UTF-8 byte validation
│ ├── render.js # marked.js + DOMPurify, fail-safe render, bounded sectioning
│ └── history.js # Sources, lazy bounded history serialization, artifacts listing
├── vendor/ # Pinned vendor libraries & licenses (locally served)
│ ├── marked.min.js
│ ├── marked.LICENSE
│ ├── purify.min.js
│ └── dompurify.LICENSE
├── dev/
│ ├── mock-server.js # Zero-dependency same-origin mock server & scenario runner
│ ├── scenario-toolbar.js # External dev toolbar script (CSP compliant, no inline scripts)
│ └── scenario-toolbar.css # External dev toolbar styling (CSP compliant, no inline styles)
├── tests/
│ ├── contract.test.js # Wire format, status code, header, & scenario tests (14 tests)
│ ├── api.test.js # UTF-8 byte boundary and credential validation tests (6 tests)
│ ├── render.test.js # Markdown section partitioning and fallback tests (10 tests)
│ └── e2e_runner.js # End-to-end browser test runner connecting to Chrome (9444) via CDP (16 tests)
├── package.json
├── package-lock.json
├── .gitignore
├── README.md
└── HANDOFF.md
```
## Security & Architecture Highlights
1. **In-Memory Credentials**:
- Confluence Base URL and Personal Access Token (PAT) reside strictly in browser JavaScript memory.
- Never written to `localStorage`, `sessionStorage`, cookies, query parameters, console logs, or exported files.
- A `cw_session` HttpOnly cookie is set by the origin for artifact download ownership.
2. **Content Security Policy (CSP)**:
- `default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'none'; media-src 'none'; font-src 'self'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`
- Completely prevents automatic third-party network requests, tracking pixels, and unauthorized script injection.
- Verified via browser network tracing (zero automatic external requests).
3. **Markdown Sanitization & Link Safety**:
- Restricted element allowlist using locally vendored DOMPurify.
- Fail-safe rendering: if parser or sanitizer are absent or fail, displays a safe notice without ever injecting raw untrusted HTML.
- All links rewritten to require explicit user clicks with `target="_blank"` and `rel="noopener noreferrer"`.
- Disallowed protocols (`javascript:`, `data:`, `file:`) have `href` stripped.
4. **Large Result Handling & Memory Bounding**:
- Large answers partitioned into bounded sections (~48 KiB soft target, ~64 KiB hard cap) rendered on demand.
- Giant code fences (e.g. 12 MB) are safely split and re-opened so every section is a valid Markdown code block.
- Tables preserve row boundaries and repeat column headers across sections.
- Pathological blocks fall back to a bounded plain-text preview with full export available.
- "Export to MD" always exports the complete, untouched raw Markdown client-side via Blob.
- Tool call results in history are rendered lazily with bounded serialization buffers (`serializeBounded`).
## Development & Testing
### Running the Dev Mock Server
The mock server runs entirely with Node.js built-ins (zero dependencies) on loopback:
```bash
cd frontend
npm run dev
# Or custom port:
node dev/mock-server.js --port 5173
```
Open `http://127.0.0.1:5173/` in your browser. A floating dev toolbar in the bottom-right corner allows toggling between all 13 deterministic mock scenarios (e.g. normal shared example, 403 verify, 409 busy, 504 timeout, malicious content, large output, delayed cancellation).
### Running Unit & Contract Tests
Tests verify API limits, wire contracts, headers, cookies, and markdown partitioning (30 tests):
```bash
cd frontend
npm test
```
### Running E2E Browser Tests
Runs comprehensive browser tests against Chrome on port 9444 via CDP (16 tests):
```bash
cd frontend
npm run test:e2e
```

BIN
frontend/assets/book.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

1
frontend/assets/key.svg Normal file
View File

@ -0,0 +1 @@
<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24px" height="24px"> <path d="M 6.5625 5.0136719 C 2.4595703 5.2668613 -0.68726562 9.0536406 0.13085938 13.369141 C 0.65285938 16.124141 2.8748594 18.347141 5.6308594 18.869141 C 9.378008 19.579519 12.720128 17.298793 13.703125 14 L 18 14 L 18 15 C 18 16.105 18.895 17 20 17 C 21.105 17 22 16.105 22 15 L 22 14 C 23.105 14 24 13.105 24 12 C 24 10.895 23.105 10 22 10 L 13.699219 10 C 12.979424 7.5432523 10.909496 5.6120152 8.3691406 5.1308594 C 7.7527656 5.0139844 7.1486328 4.977502 6.5625 5.0136719 z M 7 9 C 8.657 9 10 10.343 10 12 C 10 13.657 8.657 15 7 15 C 5.343 15 4 13.657 4 12 C 4 10.343 5.343 9 7 9 z"/></svg>

After

Width:  |  Height:  |  Size: 712 B

1085
frontend/css/style.css Normal file

File diff suppressed because it is too large Load Diff

823
frontend/dev/mock-server.js Normal file
View File

@ -0,0 +1,823 @@
/**
* Same-origin Mock HTTP Server for the Confluence Research Web UI.
* Implements exact HTTP contracts, security headers, cookie sessions, and deterministic scenarios.
* Strictly binds loopback (default 5173). Zero external dependencies.
*/
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const FRONTEND_ROOT = path.resolve(__dirname, '..');
const DEFAULT_PORT = 5173;
const HOST = '127.0.0.1';
// Active state
let currentGlobalScenario = 'normal';
let isQueryBusy = false;
// Predefined available scenarios
export const SCENARIOS = [
'normal',
'empty_search',
'no_artifacts',
'repeated_cached_view',
'failed_tool',
'warning_truncated_history',
'403_verify',
'409_busy',
'504_timeout',
'delayed_cancellation',
'unknown_expired_download',
'malicious_content',
'large_output'
];
/**
* Standard Security Headers
*/
const SECURITY_HEADERS = {
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'none'; media-src 'none'; font-src 'self'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
'Referrer-Policy': 'no-referrer',
'X-Content-Type-Options': 'nosniff'
};
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.md': 'text/markdown; charset=utf-8',
'.map': 'application/json'
};
/**
* Parses cookies from request.
*/
function parseCookies(cookieHeader) {
const list = {};
if (!cookieHeader) return list;
cookieHeader.split(';').forEach((cookie) => {
const parts = cookie.split('=');
if (parts.length >= 2) {
list[parts[0].trim()] = decodeURIComponent(parts.slice(1).join('=').trim());
}
});
return list;
}
/**
* Determines the active scenario for a request.
*/
function getScenarioForRequest(req, urlObj) {
// 1. Query parameter
const qScenario = urlObj.searchParams.get('scenario');
if (qScenario && SCENARIOS.includes(qScenario)) return qScenario;
// 2. Custom header
const hScenario = req.headers['x-mock-scenario'];
if (hScenario && SCENARIOS.includes(hScenario)) return hScenario;
// 3. Cookie
const cookies = parseCookies(req.headers.cookie);
if (cookies.mock_scenario && SCENARIOS.includes(cookies.mock_scenario)) {
return cookies.mock_scenario;
}
// 4. Global fallback
return currentGlobalScenario;
}
/**
* Generates fixture data for the requested scenario.
*/
function buildScenarioResponse(scenario, prompt) {
const now = new Date();
const nowIso = now.toISOString();
const expiresAtIso = new Date(now.getTime() + 15 * 60 * 1000).toISOString();
switch (scenario) {
case 'empty_search':
return {
session_id: 'mock-session-empty',
markdown: '# Research Results\n\nNo Confluence documentation matched your query.',
pages_accessed: [],
tool_history: [
{
tool_call_id: 'b_search_01',
tool: 'confluence_search',
parameters: { query: prompt || 'empty query', limit: 10 },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
pages: [],
pagination: { offset: 0, limit: 10, has_more: false }
},
error: null,
result_truncated: false
}
],
artifacts: [],
warnings: [],
duration_seconds: 1.1
};
case 'no_artifacts':
return {
session_id: 'mock-session-no-art',
markdown: '# Research Summary\n\nInformation gathered from [Deployment Guide](https://approved.example.com/pages/viewpage.action?pageId=847291).\n\nNo artifacts produced.',
pages_accessed: [
{
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
accessed_at: nowIso
}
],
tool_history: [
{
tool_call_id: 'b_view_01',
tool: 'confluence_view',
parameters: { page_id: '847291' },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
markdown: 'Deploy service X.',
truncated: false
},
error: null,
result_truncated: false
}
],
artifacts: [],
warnings: [],
duration_seconds: 2.3
};
case 'repeated_cached_view':
return {
session_id: 'mock-session-cached',
markdown: '# Deployment Summary\n\nReferenced [Deployment Guide](https://approved.example.com/pages/viewpage.action?pageId=847291) across multiple steps.',
pages_accessed: [
{
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
accessed_at: nowIso
}
],
tool_history: [
{
tool_call_id: 'b_call_01',
tool: 'confluence_view',
parameters: { page_id: '847291' },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
markdown: 'Initial view.',
truncated: false
},
error: null,
result_truncated: false
},
{
tool_call_id: 'b_call_02',
tool: 'confluence_view',
parameters: { page_id: '847291' },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: true,
result: {
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
markdown: 'Initial view (from cache).',
truncated: false
},
error: null,
result_truncated: false
}
],
artifacts: [],
warnings: [],
duration_seconds: 1.8
};
case 'failed_tool':
return {
session_id: 'mock-session-failed-tool',
markdown: '# Partial Summary\n\nSearch succeeded, but page 999999 could not be accessed due to an upstream error.',
pages_accessed: [],
tool_history: [
{
tool_call_id: 'b_search_01',
tool: 'confluence_search',
parameters: { query: 'archived docs', limit: 5 },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
pages: [{ page_id: '999999', title: 'Archived Page', space: 'ARCH', url: 'https://approved.example.com/pages/viewpage.action?pageId=999999', snippet: 'Missing page' }],
pagination: { offset: 0, limit: 5, has_more: false }
},
error: null,
result_truncated: false
},
{
tool_call_id: 'b_view_02',
tool: 'confluence_view',
parameters: { page_id: '999999' },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'error',
cache_hit: false,
result: null,
error: {
code: 'page_not_found',
message: 'Confluence page 999999 was not found or has been deleted.'
},
result_truncated: false
}
],
artifacts: [],
warnings: [
{ code: 'page_not_found', message: 'Page 999999 access failed', tool_call_id: 'b_view_02' }
],
duration_seconds: 2.7
};
case 'warning_truncated_history':
return {
session_id: 'mock-session-warn-trunc',
markdown: '# Bounded Results\n\nExtensive data retrieved with truncated history logs.',
pages_accessed: [
{
page_id: '12345',
title: 'Large Architecture Document',
space: 'ARCH',
url: 'https://approved.example.com/pages/viewpage.action?pageId=12345',
accessed_at: nowIso
}
],
tool_history: [
{
tool_call_id: 'b_call_trunc_01',
tool: 'confluence_view',
parameters: { page_id: '12345', details: 'A'.repeat(500) },
parameters_truncated: true,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
page_id: '12345',
summary: 'Summary preserved while large raw content was truncated.'
},
error: null,
result_truncated: true
}
],
artifacts: [],
warnings: [
{
code: 'history_truncated',
message: 'History result budget exceeded; 1 entry truncated.',
tool_call_id: 'b_call_trunc_01'
},
{
code: 'unknown_custom_warning',
message: 'Custom backend warning code test.'
}
],
duration_seconds: 4.1
};
case 'malicious_content':
return {
session_id: 'mock-session-malicious',
markdown: [
'# Malicious Input Test',
'',
'Attempting XSS and unsafe content:',
'<script>alert("xss-script")</script>',
'<img src="https://attacker.example.com/beacon.png" onerror="alert(\'xss-img\')">',
'<style>body { display: none !important; }</style>',
'<iframe src="https://attacker.example.com"></iframe>',
'<form action="https://attacker.example.com"><input type="submit" value="Phish"></form>',
'',
'Harmful links:',
'- [JavaScript link](javascript:alert("xss-link"))',
'- [Data URI link](data:text/html,<script>alert(1)</script>)',
'- [Safe citation link](https://approved.example.com/safe/page)',
'',
'```html',
'<script>console.log("safe inside code fence");</script>',
'```'
].join('\n'),
pages_accessed: [
{
page_id: '777',
title: '<script>alert("xss-title")</script> Safe Title',
space: 'SEC',
url: 'https://approved.example.com/page/777',
accessed_at: nowIso
}
],
tool_history: [
{
tool_call_id: 'b_xss_01',
tool: 'confluence_view',
parameters: { page_id: '<script>alert("xss-param")</script>' },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
raw_payload: '<img src=x onerror=alert(1)>',
nested: { malicious: '<script>evil()</script>' }
},
error: null,
result_truncated: false
}
],
artifacts: [],
warnings: [],
duration_seconds: 1.0
};
case 'large_output': {
// Dynamically generate multi-megabyte markdown with sections, tables, and code blocks
const sectionCount = 40;
const mdParts = ['# Large Document Benchmark\n\nGenerated large output to test bounded section rendering and responsive UI.\n'];
for (let i = 1; i <= sectionCount; i++) {
mdParts.push(`\n## Section ${i}: Architectural Components\n`);
mdParts.push(`This is paragraph content for section ${i} detailing deployment topologies, container security, and protocol isolation.\n`);
mdParts.push('```bash\n# Simulated shell commands\necho "Running container isolation check for section ' + i + '"\nfind /work -type f -ls\n```\n');
mdParts.push('| Component | Status | Metric |\n|---|---|---|\n| Bridge | Active | 100% |\n| Storage | Bounded | 50 MiB |\n| Latency | Nominal | 12ms |\n');
// Repeat text to bulk up section size (~50 KiB per section)
mdParts.push('Confluence documentation analysis paragraph '.repeat(200) + '\n');
}
return {
session_id: 'mock-session-large',
markdown: mdParts.join('\n'),
pages_accessed: [
{
page_id: '99991',
title: 'Enterprise Architecture Overview',
space: 'ARCH',
url: 'https://approved.example.com/pages/viewpage.action?pageId=99991',
accessed_at: nowIso
}
],
tool_history: [
{
tool_call_id: 'b_large_01',
tool: 'confluence_view',
parameters: { page_id: '99991' },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
page_id: '99991',
title: 'Enterprise Architecture Overview',
space: 'ARCH',
status: 'ok'
},
error: null,
result_truncated: false
}
],
artifacts: [
{
id: 'art-large-export',
name: 'full_architecture.md',
size_bytes: 32,
expires_at: expiresAtIso
}
],
warnings: [],
duration_seconds: 5.4
};
}
case 'normal':
default:
// Shared example scenario from CONTRACTS.md Section 7
return {
session_id: 'a0f2b3c4-1234-5678-9abc-def012345678',
markdown: '# Deployment Guide for Service X\n\nTo deploy **Service X**, follow the steps outlined in the [Deployment Guide](https://approved.example.com/pages/viewpage.action?pageId=847291).\n\n### Key Steps:\n1. Verify container runtime prerequisites.\n2. Review the checklist exported to `checklist.md`.\n3. Execute staged rollout.\n',
pages_accessed: [
{
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
accessed_at: nowIso
}
],
tool_history: [
{
tool_call_id: 'b_call_01',
tool: 'confluence_search',
parameters: { query: 'deploy service X', limit: 10 },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
pages: [
{
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
snippet: 'Deployment steps for service X'
}
],
pagination: { offset: 0, limit: 10, has_more: false }
},
error: null,
result_truncated: false
},
{
tool_call_id: 'b_call_02',
tool: 'confluence_view',
parameters: { page_id: '847291' },
parameters_truncated: false,
started_at: nowIso,
completed_at: nowIso,
status: 'success',
cache_hit: false,
result: {
page_id: '847291',
title: 'Deployment Guide',
space: 'OPS',
url: 'https://approved.example.com/pages/viewpage.action?pageId=847291',
markdown: 'Deploy service X using the release checklist.',
truncated: false
},
error: null,
result_truncated: false
}
],
artifacts: [
{
id: 'art-checklist-01',
name: 'checklist.md',
size_bytes: 32,
expires_at: expiresAtIso
}
],
warnings: [],
duration_seconds: 3.2
};
}
}
/**
* Validates that credentials in mock mode are synthetic/dummy credentials.
*/
function validateMockCredentials(url, pat) {
if (!url || !pat) return false;
// Prevent common production token patterns
if (pat.startsWith('ghp_') || pat.startsWith('glpat-') || pat.startsWith('xoxb-')) {
return false;
}
return true;
}
/**
* Creates the HTTP server.
*/
export function createMockServer() {
const server = http.createServer(async (req, res) => {
const urlObj = new URL(req.url, `http://${req.headers.host || `${HOST}:${DEFAULT_PORT}`}`);
const pathname = urlObj.pathname;
const method = req.method.toUpperCase();
// Attach security headers to all responses
Object.entries(SECURITY_HEADERS).forEach(([key, val]) => {
res.setHeader(key, val);
});
// Session cookie: cw_session
const cookies = parseCookies(req.headers.cookie);
if (!cookies.cw_session) {
const newSession = crypto.randomBytes(16).toString('hex');
res.setHeader('Set-Cookie', `cw_session=${newSession}; Path=/; HttpOnly; SameSite=Strict`);
}
// Origin check for mutation requests
if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
const origin = req.headers.origin;
if (origin) {
try {
const origUrl = new URL(origin);
if (!['127.0.0.1', 'localhost'].includes(origUrl.hostname)) {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: { code: 'origin_denied', message: 'Cross-origin request denied.' } }));
return;
}
} catch {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: { code: 'origin_denied', message: 'Malformed origin.' } }));
return;
}
}
}
// Dev Scenario API (development tooling outside user flow)
if (pathname === '/dev/scenario') {
if (method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ scenario: currentGlobalScenario, available: SCENARIOS }));
return;
}
if (method === 'POST') {
let body = '';
req.on('data', (chunk) => { body += chunk; });
req.on('end', () => {
try {
const data = JSON.parse(body);
if (data.scenario && SCENARIOS.includes(data.scenario)) {
currentGlobalScenario = data.scenario;
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Set-Cookie': `mock_scenario=${data.scenario}; Path=/; SameSite=Strict`
});
res.end(JSON.stringify({ ok: true, scenario: currentGlobalScenario }));
} else {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Unknown scenario' } }));
}
} catch {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Invalid JSON' } }));
}
});
return;
}
}
// API Endpoint 1: POST /api/v1/auth/verify
if (pathname === '/api/v1/auth/verify' && method === 'POST') {
let body = '';
req.on('data', (chunk) => { body += chunk; });
req.on('end', () => {
try {
const data = JSON.parse(body);
if (!data.url || !data.pat) {
res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Missing URL or PAT' } }));
return;
}
if (!validateMockCredentials(data.url, data.pat)) {
res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'confluence_auth_failed', message: 'Invalid mock credentials' } }));
return;
}
const scenario = getScenarioForRequest(req, urlObj);
if (scenario === '403_verify') {
res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'confluence_auth_failed', message: 'Confluence authentication failed: invalid PAT.' } }));
return;
}
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ valid: true }));
} catch {
res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Invalid JSON body' } }));
}
});
return;
}
// API Endpoint 2: POST /api/v1/query
if (pathname === '/api/v1/query' && method === 'POST') {
let body = '';
req.on('data', (chunk) => { body += chunk; });
req.on('end', async () => {
try {
const data = JSON.parse(body);
if (!data.prompt || !data.credentials || !data.credentials.url || !data.credentials.pat) {
res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Missing required query parameters' } }));
return;
}
if (!validateMockCredentials(data.credentials.url, data.credentials.pat)) {
res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'confluence_auth_failed', message: 'Invalid mock credentials' } }));
return;
}
const scenario = getScenarioForRequest(req, urlObj);
// 409 Busy check
if (scenario === '409_busy' || isQueryBusy) {
res.writeHead(409, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'busy', message: 'A query is currently executing or prior cleanup is in progress' } }));
return;
}
// 504 Timeout check
if (scenario === '504_timeout') {
res.writeHead(504, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'query_timeout', message: 'The query deadline of 180 seconds was exceeded' } }));
return;
}
// Delayed cancellation test scenario
if (scenario === 'delayed_cancellation') {
isQueryBusy = true;
let aborted = false;
const cancelTimeout = setTimeout(() => {
isQueryBusy = false;
if (!aborted && !res.writableEnded) {
const responseData = buildScenarioResponse('normal', data.prompt);
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(responseData));
}
}, 30000); // 30s delay
req.on('close', () => {
if (!res.writableEnded) {
aborted = true;
clearTimeout(cancelTimeout);
// Simulate backend cleanup budget
setTimeout(() => {
isQueryBusy = false;
}, 400);
}
});
return;
}
// Normal response
const responseData = buildScenarioResponse(scenario, data.prompt);
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(responseData));
} catch {
res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Malformed JSON query body' } }));
}
});
return;
}
// API Endpoint 3: GET /api/v1/artifacts/{id}
if (pathname.startsWith('/api/v1/artifacts/') && method === 'GET') {
const scenario = getScenarioForRequest(req, urlObj);
const artifactId = pathname.slice('/api/v1/artifacts/'.length);
if (scenario === 'unknown_expired_download' || artifactId === 'expired' || artifactId === 'non-existent') {
res.writeHead(404, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
res.end(JSON.stringify({ error: { code: 'artifact_not_found', message: 'Artifact has expired or does not exist.' } }));
return;
}
// Exact 32 bytes from CONTRACTS.md Section 7
const artifactContent = '# Checklist\n\n- Deploy service X\n';
const buffer = Buffer.from(artifactContent, 'utf-8');
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': buffer.length,
'Content-Disposition': 'attachment; filename="checklist.md"',
'Cache-Control': 'no-store'
});
res.end(buffer);
return;
}
// Static File Serving
if (method === 'GET' || method === 'HEAD') {
let relativePath = pathname === '/' ? 'index.html' : pathname.slice(1);
const safePath = path.normalize(relativePath).replace(/^(\.\.[/\\])+/, '');
const filePath = path.join(FRONTEND_ROOT, safePath);
// Security check: ensure path is within FRONTEND_ROOT
if (!filePath.startsWith(FRONTEND_ROOT)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
// For index.html in dev mode, inject a dev scenario selector bar
if (ext === '.html') {
fs.readFile(filePath, 'utf8', (readErr, htmlContent) => {
if (readErr) {
res.writeHead(500);
res.end('Server Error');
return;
}
const activeScenario = getScenarioForRequest(req, urlObj);
// Dev scenario selector toolbar (external CSS and JS to satisfy CSP script-src 'self' style-src 'self')
const devBar = `
<!-- Mock Server Dev Toolbar (Dev Only) -->
<link rel="stylesheet" href="/dev/scenario-toolbar.css">
<aside id="dev-scenario-bar">
<span id="dev-scenario-label">Mock Scenario:</span>
<select id="dev-scenario-select">
${SCENARIOS.map((s) => `<option value="${s}" ${s === activeScenario ? 'selected' : ''}>${s}</option>`).join('')}
</select>
</aside>
<script type="module" src="/dev/scenario-toolbar.js"></script>
`;
const modifiedHtml = htmlContent.replace('</body>', `${devBar}</body>`);
res.writeHead(200, {
'Content-Type': contentType,
'Content-Length': Buffer.byteLength(modifiedHtml)
});
res.end(modifiedHtml);
});
return;
}
// Other static files
res.writeHead(200, {
'Content-Type': contentType,
'Content-Length': stats.size
});
if (method === 'HEAD') {
res.end();
return;
}
const stream = fs.createReadStream(filePath);
stream.pipe(res);
});
return;
}
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
});
return server;
}
// If run directly from CLI
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const portArgIdx = process.argv.indexOf('--port');
const port = portArgIdx !== -1 ? parseInt(process.argv[portArgIdx + 1], 10) : (parseInt(process.env.PORT, 10) || DEFAULT_PORT);
const server = createMockServer();
server.listen(port, HOST, () => {
console.log(`Mock server running at http://${HOST}:${port}/`);
console.log(`Current default scenario: ${currentGlobalScenario}`);
});
}

View File

@ -0,0 +1,32 @@
#dev-scenario-bar {
position: fixed;
bottom: 12px;
right: 12px;
z-index: 9999;
background: #111827;
color: #F9FAFB;
padding: 8px 12px;
border-radius: 8px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
display: flex;
align-items: center;
gap: 8px;
}
#dev-scenario-label {
font-weight: 600;
color: #9CA3AF;
}
#dev-scenario-select {
background: #1F2937;
color: #FFFFFF;
border: 1px solid #374151;
border-radius: 4px;
padding: 4px 8px;
font-size: 12px;
outline: none;
cursor: pointer;
}

View File

@ -0,0 +1,21 @@
/**
* Mock Server Dev Toolbar client logic.
* External module to comply with strict CSP (script-src 'self').
*/
(function() {
const sel = document.getElementById('dev-scenario-select');
if (sel) {
sel.addEventListener('change', async function() {
try {
await fetch('/dev/scenario', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ scenario: sel.value })
});
} catch (err) {
console.error('Failed to change scenario:', err);
}
window.location.reload();
});
}
})();

168
frontend/index.html Normal file
View File

@ -0,0 +1,168 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Confluence Research</title>
<link rel="stylesheet" href="css/style.css">
<script src="vendor/marked.min.js"></script>
<script src="vendor/purify.min.js"></script>
<script type="module" src="js/app.js"></script>
</head>
<body>
<!-- Top Navigation Header -->
<header class="app-header">
<div class="app-brand">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path>
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path>
</svg>
<span>Confluence Research</span>
</div>
<button id="key-btn" class="key-btn" type="button" aria-label="Configure Confluence Credentials" title="Configure Confluence Credentials">
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M 6.5625 5.0136719 C 2.4595703 5.2668613 -0.68726562 9.0536406 0.13085938 13.369141 C 0.65285938 16.124141 2.8748594 18.347141 5.6308594 18.869141 C 9.378008 19.579519 12.720128 17.298793 13.703125 14 L 18 14 L 18 15 C 18 16.105 18.895 17 20 17 C 21.105 17 22 16.105 22 15 L 22 14 C 23.105 14 24 13.105 24 12 C 24 10.895 23.105 10 22 10 L 13.699219 10 C 12.979424 7.5432523 10.909496 5.6120152 8.3691406 5.1308594 C 7.7527656 5.0139844 7.1486328 4.977502 6.5625 5.0136719 z M 7 9 C 8.657 9 10 10.343 10 12 C 10 13.657 8.657 15 7 15 C 5.343 15 4 13.657 4 12 C 4 10.343 5.343 9 7 9 z"></path>
</svg>
<span id="cred-indicator" class="cred-indicator" aria-hidden="true"></span>
<span id="cred-status-sr" class="sr-only">Credentials not set</span>
</button>
</header>
<!-- Main View Container -->
<main class="app-main">
<!-- State 1: Prompt View -->
<section id="view-prompt" class="view-prompt" aria-label="Research prompt view">
<div class="prompt-wrapper">
<h1 class="prompt-title">What would you like to research?</h1>
<div id="prompt-error" class="alert-box error-box hidden" role="alert"></div>
<div class="prompt-box">
<textarea
id="prompt-input"
class="prompt-input"
placeholder="Search or ask about Confluence documentation..."
rows="3"
aria-label="Research prompt"
></textarea>
<div class="prompt-footer">
<span class="prompt-helper">Press Enter ↵ to send · Shift + Enter for new line</span>
<button id="submit-btn" class="submit-btn" type="button" aria-label="Send query">
<span>Send</span>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="22" y1="2" x2="11" y2="13"></line>
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
</svg>
</button>
</div>
</div>
</div>
</section>
<!-- State 3: Loading View -->
<section id="view-loading" class="view-loading hidden" aria-label="Loading execution view">
<div class="spinner-wrapper">
<svg class="gear-spinner" viewBox="0 0 48 48" width="48" height="48" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="24" cy="24" r="8"></circle>
<path d="M24 4v4m0 32v4M4 24h4m32 0h4m-6.3-13.7l-2.8 2.8m-22.6 22.6l-2.8 2.8m0-28.2l2.8 2.8m22.6 22.6l2.8 2.8M24 10a14 14 0 1 0 0 28 14 14 0 0 0 0-28z"></path>
</svg>
</div>
<p class="loading-status" aria-live="polite">Agent researching Confluence...</p>
<button id="cancel-btn" class="cancel-btn" type="button">Cancel</button>
</section>
<!-- State 4: Result View -->
<section id="view-result" class="view-result hidden" aria-label="Research result view">
<div class="action-bar">
<button id="back-btn" class="action-btn back-btn" type="button">← Back to prompt</button>
<button id="export-btn" class="action-btn export-btn" type="button">Export to MD</button>
</div>
<div id="result-warnings" class="warnings-container hidden" role="region" aria-label="Result warnings"></div>
<div id="section-nav" class="section-nav hidden"></div>
<div id="output-content" class="output-content"></div>
<!-- Artifacts Section -->
<div id="artifacts-section" class="artifacts-section hidden" role="region" aria-label="Generated artifacts">
<h2 class="artifacts-heading">Generated Artifacts</h2>
<div id="artifacts-error" class="alert-box error-box hidden" role="alert"></div>
<ul id="artifacts-list" class="artifacts-list"></ul>
</div>
<!-- Sources & Request History Section -->
<div id="history-section" class="history-section" role="region" aria-label="Sources and request history">
<button id="history-toggle-btn" class="history-toggle-btn" type="button" aria-expanded="false" aria-controls="history-content">
<span id="history-toggle-title">Sources &amp; Request History (0 pages accessed)</span>
<span class="toggle-icon"></span>
</button>
<div id="history-content" class="history-content hidden">
<h3 class="history-subheading">Pages Read</h3>
<div id="pages-accessed-list" class="pages-list"></div>
<h3 class="history-subheading">Tool Operations</h3>
<div id="tool-history-list" class="tool-list"></div>
</div>
</div>
</section>
</main>
<!-- State 2: Credentials Configuration Modal -->
<div id="modal-backdrop" class="modal-backdrop hidden" tabindex="-1">
<div id="modal-dialog" class="modal-dialog" role="dialog" aria-modal="true" aria-labelledby="modal-title">
<div class="modal-header">
<h2 id="modal-title" class="modal-title">Confluence Credentials</h2>
<button id="modal-close-btn" class="modal-close-btn" type="button" aria-label="Close credentials dialog">&times;</button>
</div>
<form id="credentials-form" novalidate>
<div class="form-group">
<label for="cred-url" class="form-label">Confluence Base URL</label>
<input
type="url"
id="cred-url"
class="modal-input"
placeholder="https://confluence.example.com"
autocomplete="off"
spellcheck="false"
required
>
<span class="field-hint">Must be a valid HTTP or HTTPS URL (max 8 KiB)</span>
</div>
<div class="form-group">
<label for="cred-pat" class="form-label">Personal Access Token (PAT)</label>
<div class="password-input-wrapper">
<input
type="password"
id="cred-pat"
class="modal-input"
placeholder="Personal Access Token"
autocomplete="off"
spellcheck="false"
required
>
<button type="button" id="toggle-pat-btn" class="toggle-password-btn" aria-label="Show token">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
<circle cx="12" cy="12" r="3"></circle>
</svg>
</button>
</div>
<span class="field-hint">Token is kept strictly in browser memory (max 8 KiB)</span>
</div>
<div id="modal-feedback" class="modal-feedback hidden" role="status" aria-live="polite"></div>
<div class="modal-actions">
<div class="modal-actions-left">
<button type="button" id="btn-clear-cred" class="btn-secondary danger">Clear credentials</button>
</div>
<div class="modal-actions-right">
<button type="button" id="btn-test-cred" class="btn-secondary">Test Connection</button>
<button type="button" id="btn-cancel-cred" class="btn-secondary">Cancel</button>
<button type="submit" id="btn-save-cred" class="btn-primary">Save &amp; Close</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>

237
frontend/js/api.js Normal file
View File

@ -0,0 +1,237 @@
/**
* API client boundary for same-origin backend communication.
* Strictly uses relative URLs (/api/v1/...) with no mock toggles or hardcoded origins.
*/
const MAX_PROMPT_BYTES = 16 * 1024 * 1024; // 16 MiB
const MAX_FIELD_BYTES = 8 * 1024; // 8 KiB for Confluence URL / PAT
/**
* Returns the UTF-8 byte length of a string.
* @param {string} str
* @returns {number}
*/
export function getUtf8ByteLength(str) {
if (typeof str !== 'string') return 0;
return new TextEncoder().encode(str).length;
}
/**
* Validates Confluence URL and PAT strings according to contract limits.
* @param {{ url: string, pat: string }} credentials
* @throws {Error} If credentials fail validation
*/
export function validateCredentials({ url, pat }) {
if (!url || typeof url !== 'string' || !url.trim()) {
const err = new Error('Confluence URL is required.');
err.code = 'invalid_input';
throw err;
}
if (!pat || typeof pat !== 'string' || !pat.trim()) {
const err = new Error('Personal Access Token (PAT) is required.');
err.code = 'invalid_input';
throw err;
}
const urlBytes = getUtf8ByteLength(url);
if (urlBytes > MAX_FIELD_BYTES) {
const err = new Error('Confluence URL exceeds the 8 KiB limit.');
err.code = 'invalid_input';
throw err;
}
const patBytes = getUtf8ByteLength(pat);
if (patBytes > MAX_FIELD_BYTES) {
const err = new Error('Personal Access Token exceeds the 8 KiB limit.');
err.code = 'invalid_input';
throw err;
}
try {
const parsed = new URL(url);
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error();
}
} catch {
const err = new Error('Confluence URL must be a valid HTTP or HTTPS URL.');
err.code = 'invalid_input';
throw err;
}
}
/**
* Parses and normalizes API error responses.
* @param {Response} response
* @returns {Promise<Error>}
*/
async function parseApiError(response) {
let code = 'execution_failed';
let message = `Request failed with status ${response.status}`;
let rawText = '';
try {
rawText = await response.text();
if (rawText) {
const data = JSON.parse(rawText);
if (data && data.error) {
if (typeof data.error.code === 'string') {
code = data.error.code;
}
if (typeof data.error.message === 'string') {
message = data.error.message;
}
const err = new Error(message);
err.code = code;
err.status = response.status;
return err;
}
}
} catch {
// Non-JSON body fallback
}
// Non-JSON or empty error body fallback based on HTTP status
if (response.status === 400) {
code = 'invalid_input';
} else if (response.status === 403) {
// Differentiate origin / destination denials from PAT failures per CONTRACTS §2
const lower = (rawText || response.statusText || '').toLowerCase();
if (lower.includes('origin')) {
code = 'origin_denied';
message = 'Request forbidden: origin denied.';
} else if (lower.includes('destination') || lower.includes('host')) {
code = 'destination_denied';
message = 'Request forbidden: destination URL not permitted.';
} else if (lower.includes('auth') || lower.includes('pat') || lower.includes('token') || lower.includes('credential')) {
code = 'confluence_auth_failed';
message = 'Confluence authentication failed.';
} else {
// Ingress / reverse proxy 403 rejection
code = 'origin_denied';
message = 'Request forbidden by server policy.';
}
} else if (response.status === 404) {
code = 'artifact_not_found';
} else if (response.status === 409) {
code = 'busy';
} else if (response.status === 413) {
code = 'request_too_large';
} else if (response.status === 502) {
code = 'upstream_failed';
} else if (response.status === 504) {
code = 'query_timeout';
}
const err = new Error(message);
err.code = code;
err.status = response.status;
return err;
}
/**
* Verifies credentials against the backend.
* @param {{ url: string, pat: string }} credentials
* @param {{ signal?: AbortSignal }} [options]
* @returns {Promise<{ valid: boolean }>}
*/
export async function verifyCredentials(credentials, { signal } = {}) {
validateCredentials(credentials);
const response = await fetch('/api/v1/auth/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: credentials.url.trim(),
pat: credentials.pat.trim()
}),
signal
});
if (!response.ok) {
throw await parseApiError(response);
}
return await response.json();
}
/**
* Submits a research prompt with credentials.
* @param {{ prompt: string, credentials: { url: string, pat: string } }} params
* @param {{ signal?: AbortSignal }} [options]
* @returns {Promise<object>} Query result object
*/
export async function submitQuery({ prompt, credentials }, { signal } = {}) {
if (!prompt || typeof prompt !== 'string' || !prompt.trim()) {
const err = new Error('Prompt cannot be empty.');
err.code = 'invalid_input';
throw err;
}
const promptBytes = getUtf8ByteLength(prompt);
if (promptBytes > MAX_PROMPT_BYTES) {
const err = new Error(`Prompt exceeds the 16 MiB UTF-8 limit (${promptBytes} bytes).`);
err.code = 'invalid_input';
throw err;
}
validateCredentials(credentials);
const response = await fetch('/api/v1/query', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: prompt, // Preserve original untrimmed text inside payload while verifying trimmed was non-empty
credentials: {
url: credentials.url.trim(),
pat: credentials.pat.trim()
}
}),
signal
});
if (!response.ok) {
throw await parseApiError(response);
}
return await response.json();
}
/**
* Downloads an artifact by its backend-issued ID.
* @param {string} artifactId
* @param {{ signal?: AbortSignal }} [options]
* @returns {Promise<{ blob: Blob, filename: string }>}
*/
export async function downloadArtifact(artifactId, { signal } = {}) {
if (!artifactId || typeof artifactId !== 'string') {
const err = new Error('Invalid artifact ID.');
err.code = 'invalid_input';
throw err;
}
const response = await fetch(`/api/v1/artifacts/${encodeURIComponent(artifactId)}`, {
method: 'GET',
signal
});
if (!response.ok) {
throw await parseApiError(response);
}
// Extract filename from Content-Disposition if present
let filename = 'download';
const disposition = response.headers.get('Content-Disposition');
if (disposition) {
const match = disposition.match(/filename=["']?([^"';]+)["']?/i);
if (match && match[1]) {
filename = match[1].trim();
}
}
const blob = await response.blob();
return { blob, filename };
}

538
frontend/js/app.js Normal file
View File

@ -0,0 +1,538 @@
/**
* Main application wiring and state management.
* Credentials remain strictly in browser memory and are never persisted or logged.
*/
import { verifyCredentials, submitQuery, downloadArtifact, validateCredentials } from './api.js';
import { MarkdownRenderer, exportToMarkdown, renderWarnings } from './render.js';
import { renderPagesAccessed, renderToolHistory, renderArtifacts } from './history.js';
// Application memory state
let committedCredentials = null; // { url: string, pat: string } | null
let draftCredentials = { url: '', pat: '' };
let activeAbortController = null;
let currentRequestGeneration = 0;
let activeVerifyAbortController = null;
let currentVerifyGeneration = 0;
let currentResult = null;
let lastSubmittedPrompt = '';
// DOM Elements
let viewPrompt, viewLoading, viewResult;
let promptInput, submitBtn, promptError;
let keyBtn, credIndicator, credStatusSr;
let modalBackdrop, modalDialog, modalCloseBtn, credentialsForm;
let credUrlInput, credPatInput, togglePatBtn, modalFeedback;
let btnTestCred, btnSaveCred, btnCancelCred, btnClearCred;
let cancelBtn, backBtn, exportBtn;
let outputContent, sectionNav, resultWarnings;
let artifactsSection, artifactsList, artifactsError;
let historySection, historyToggleBtn, historyToggleTitle, historyContent;
let pagesAccessedList, toolHistoryList;
let markdownRenderer = null;
/**
* Initializes DOM element references and event listeners.
*/
document.addEventListener('DOMContentLoaded', () => {
// Views
viewPrompt = document.getElementById('view-prompt');
viewLoading = document.getElementById('view-loading');
viewResult = document.getElementById('view-result');
// Prompt View
promptInput = document.getElementById('prompt-input');
submitBtn = document.getElementById('submit-btn');
promptError = document.getElementById('prompt-error');
// Header / Credentials
keyBtn = document.getElementById('key-btn');
credIndicator = document.getElementById('cred-indicator');
credStatusSr = document.getElementById('cred-status-sr');
// Modal
modalBackdrop = document.getElementById('modal-backdrop');
modalDialog = document.getElementById('modal-dialog');
modalCloseBtn = document.getElementById('modal-close-btn');
credentialsForm = document.getElementById('credentials-form');
credUrlInput = document.getElementById('cred-url');
credPatInput = document.getElementById('cred-pat');
togglePatBtn = document.getElementById('toggle-pat-btn');
modalFeedback = document.getElementById('modal-feedback');
btnTestCred = document.getElementById('btn-test-cred');
btnSaveCred = document.getElementById('btn-save-cred');
btnCancelCred = document.getElementById('btn-cancel-cred');
btnClearCred = document.getElementById('btn-clear-cred');
// Loading & Result Controls
cancelBtn = document.getElementById('cancel-btn');
backBtn = document.getElementById('back-btn');
exportBtn = document.getElementById('export-btn');
// Result Area
outputContent = document.getElementById('output-content');
sectionNav = document.getElementById('section-nav');
resultWarnings = document.getElementById('result-warnings');
// Artifacts Area
artifactsSection = document.getElementById('artifacts-section');
artifactsList = document.getElementById('artifacts-list');
artifactsError = document.getElementById('artifacts-error');
// History Area
historySection = document.getElementById('history-section');
historyToggleBtn = document.getElementById('history-toggle-btn');
historyToggleTitle = document.getElementById('history-toggle-title');
historyContent = document.getElementById('history-content');
pagesAccessedList = document.getElementById('pages-accessed-list');
toolHistoryList = document.getElementById('tool-history-list');
// Markdown renderer
markdownRenderer = new MarkdownRenderer(outputContent, sectionNav);
// Wire events
setupPromptEvents();
setupModalEvents();
setupResultEvents();
updateCredentialIndicator();
});
/**
* Updates textarea height dynamically up to 280px.
*/
function autoResizeTextarea() {
if (!promptInput) return;
promptInput.style.height = 'auto';
const newHeight = Math.min(promptInput.scrollHeight, 280);
promptInput.style.height = `${newHeight}px`;
}
/**
* Sets up prompt input and submission listeners.
*/
function setupPromptEvents() {
promptInput.addEventListener('input', autoResizeTextarea);
// Enter to submit (outside IME), Shift+Enter for newline
promptInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
if (e.isComposing || e.keyCode === 229) {
return; // IME composition in progress
}
if (!e.shiftKey) {
e.preventDefault();
handleSubmitQuery();
}
}
});
submitBtn.addEventListener('click', (e) => {
e.preventDefault();
handleSubmitQuery();
});
}
/**
* Handles query submission.
*/
async function handleSubmitQuery() {
const prompt = promptInput.value;
if (!prompt || !prompt.trim()) {
showPromptError('Please enter a research prompt.');
return;
}
// Ensure credentials are configured
if (!committedCredentials || !committedCredentials.url || !committedCredentials.pat) {
showPromptError('Confluence credentials required. Click the key icon to configure URL and PAT.');
openCredentialsModal();
return;
}
hidePromptError();
lastSubmittedPrompt = prompt;
// Transition to loading view
switchView('loading');
const generation = ++currentRequestGeneration;
activeAbortController = new AbortController();
try {
const result = await submitQuery(
{ prompt, credentials: committedCredentials },
{ signal: activeAbortController.signal }
);
// Stale check
if (generation !== currentRequestGeneration) {
return;
}
currentResult = result;
renderResultView(result);
switchView('result');
} catch (err) {
// Stale check
if (generation !== currentRequestGeneration) {
return;
}
if (err.name === 'AbortError') {
// User cancelled, smoothly return to prompt view
switchView('prompt');
return;
}
// Switch back to prompt view and display error
switchView('prompt');
if (err.code === 'confluence_auth_failed') {
showPromptError('Confluence authentication failed. Please verify your URL and PAT in the credentials modal.');
} else if (err.code === 'origin_denied') {
showPromptError('Request forbidden: Origin denied by server policy.');
} else if (err.code === 'destination_denied') {
showPromptError('Request forbidden: Confluence destination URL is not permitted by server policy.');
} else if (err.code === 'busy') {
showPromptError('The server is currently busy processing another query or cleaning up. Please try again shortly.');
} else if (err.code === 'query_timeout') {
showPromptError('The query timed out. The operation exceeded the allowed execution time.');
} else if (err.code === 'request_too_large') {
showPromptError('The request exceeds the maximum allowed payload size.');
} else {
showPromptError(`Query failed [${err.code || 'error'}]: ${err.message || 'An unexpected error occurred.'}`);
}
} finally {
if (generation === currentRequestGeneration) {
activeAbortController = null;
}
}
}
/**
* Sets up credentials modal and actions.
*/
function setupModalEvents() {
keyBtn.addEventListener('click', openCredentialsModal);
modalCloseBtn.addEventListener('click', closeCredentialsModal);
btnCancelCred.addEventListener('click', closeCredentialsModal);
// Close modal on Escape
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !modalBackdrop.classList.contains('hidden')) {
closeCredentialsModal();
}
});
// Close on backdrop click outside dialog
modalBackdrop.addEventListener('click', (e) => {
if (e.target === modalBackdrop) {
closeCredentialsModal();
}
});
// Focus trap inside modal dialog
modalDialog.addEventListener('keydown', (e) => {
if (e.key !== 'Tab') return;
const focusable = modalDialog.querySelectorAll(
'button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])'
);
if (focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
});
// Password visibility toggle
togglePatBtn.addEventListener('click', () => {
const isPassword = credPatInput.type === 'password';
credPatInput.type = isPassword ? 'text' : 'password';
togglePatBtn.setAttribute('aria-label', isPassword ? 'Hide token' : 'Show token');
});
// Typing in inputs invalidates any in-flight test connection
credUrlInput.addEventListener('input', () => {
abortActiveVerify();
btnTestCred.disabled = false;
});
credPatInput.addEventListener('input', () => {
abortActiveVerify();
btnTestCred.disabled = false;
});
// Test connection button (draft credentials only, does NOT commit; guarded against staleness)
btnTestCred.addEventListener('click', async () => {
draftCredentials.url = credUrlInput.value.trim();
draftCredentials.pat = credPatInput.value.trim();
try {
validateCredentials(draftCredentials);
} catch (err) {
showModalFeedback(err.message, 'error');
return;
}
const verifyGen = ++currentVerifyGeneration;
if (activeVerifyAbortController) {
activeVerifyAbortController.abort();
}
activeVerifyAbortController = new AbortController();
btnTestCred.disabled = true;
showModalFeedback('Testing connection...', 'info');
try {
await verifyCredentials(draftCredentials, { signal: activeVerifyAbortController.signal });
if (verifyGen !== currentVerifyGeneration) return;
showModalFeedback('Connection successful! Credentials are valid.', 'success');
} catch (err) {
if (verifyGen !== currentVerifyGeneration) return;
if (err.name === 'AbortError') return;
showModalFeedback(`Connection failed [${err.code || 'error'}]: ${err.message}`, 'error');
} finally {
if (verifyGen === currentVerifyGeneration) {
btnTestCred.disabled = false;
activeVerifyAbortController = null;
}
}
});
// Save & Close form submit
credentialsForm.addEventListener('submit', (e) => {
e.preventDefault();
abortActiveVerify();
draftCredentials.url = credUrlInput.value.trim();
draftCredentials.pat = credPatInput.value.trim();
try {
validateCredentials(draftCredentials);
} catch (err) {
showModalFeedback(err.message, 'error');
return;
}
// Commit credentials to memory
committedCredentials = {
url: draftCredentials.url,
pat: draftCredentials.pat
};
updateCredentialIndicator();
closeCredentialsModal();
hidePromptError();
});
// Clear credentials
btnClearCred.addEventListener('click', () => {
abortActiveVerify();
// If a query is active, abort it
if (activeAbortController) {
currentRequestGeneration++;
activeAbortController.abort();
activeAbortController = null;
switchView('prompt');
}
committedCredentials = null;
draftCredentials = { url: '', pat: '' };
credUrlInput.value = '';
credPatInput.value = '';
updateCredentialIndicator();
showModalFeedback('Credentials cleared from browser memory.', 'info');
});
}
/**
* Aborts any pending verify connection request and increments generation counter.
*/
function abortActiveVerify() {
currentVerifyGeneration++;
if (activeVerifyAbortController) {
activeVerifyAbortController.abort();
activeVerifyAbortController = null;
}
}
/**
* Opens credentials modal and restores draft from committed state.
*/
function openCredentialsModal() {
modalFeedback.className = 'modal-feedback hidden';
modalFeedback.textContent = '';
if (committedCredentials) {
credUrlInput.value = committedCredentials.url;
credPatInput.value = committedCredentials.pat;
} else {
credUrlInput.value = draftCredentials.url || '';
credPatInput.value = draftCredentials.pat || '';
}
modalBackdrop.classList.remove('hidden');
credUrlInput.focus();
}
/**
* Closes credentials modal and restores focus to key button.
*/
function closeCredentialsModal() {
abortActiveVerify();
modalBackdrop.classList.add('hidden');
keyBtn.focus();
}
/**
* Displays modal feedback messages.
* @param {string} msg
* @param {'error'|'success'|'info'} type
*/
function showModalFeedback(msg, type) {
modalFeedback.className = `modal-feedback ${type === 'error' ? 'error-box' : type === 'success' ? 'success-box' : 'warning-box'}`;
modalFeedback.textContent = msg;
}
/**
* Updates the key icon indicator state.
*/
function updateCredentialIndicator() {
if (committedCredentials && committedCredentials.url && committedCredentials.pat) {
credIndicator.classList.add('active');
credStatusSr.textContent = 'Credentials active in memory';
keyBtn.title = 'Credentials active (Click to edit)';
} else {
credIndicator.classList.remove('active');
credStatusSr.textContent = 'Credentials not set';
keyBtn.title = 'Configure Confluence Credentials';
}
}
/**
* Sets up result view buttons and interactions.
*/
function setupResultEvents() {
// Cancel button during loading
cancelBtn.addEventListener('click', () => {
if (activeAbortController) {
currentRequestGeneration++;
activeAbortController.abort();
activeAbortController = null;
}
switchView('prompt');
});
// Back to prompt button
backBtn.addEventListener('click', () => {
switchView('prompt');
promptInput.focus();
});
// Export to MD button
exportBtn.addEventListener('click', () => {
if (currentResult && typeof currentResult.markdown === 'string') {
exportToMarkdown(currentResult.markdown, lastSubmittedPrompt);
}
});
// History toggle button
historyToggleBtn.addEventListener('click', () => {
const expanded = historyToggleBtn.getAttribute('aria-expanded') === 'true';
historyToggleBtn.setAttribute('aria-expanded', String(!expanded));
if (expanded) {
historyContent.classList.add('hidden');
} else {
historyContent.classList.remove('hidden');
}
});
}
/**
* Renders the query result view.
* @param {object} result
*/
function renderResultView(result) {
// 1. Warnings
renderWarnings(resultWarnings, result.warnings || []);
// 2. Markdown output (with bounded section renderer)
markdownRenderer.load(result.markdown || '');
// 3. Artifacts
artifactsError.classList.add('hidden');
artifactsError.textContent = '';
if (Array.isArray(result.artifacts) && result.artifacts.length > 0) {
artifactsSection.classList.remove('hidden');
renderArtifacts(artifactsList, result.artifacts, async (id, name) => {
try {
artifactsError.classList.add('hidden');
const { blob, filename } = await downloadArtifact(id);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err) {
artifactsError.classList.remove('hidden');
artifactsError.textContent = `Download failed [${err.code || 'error'}]: ${err.message || 'Artifact not found or expired.'}`;
}
});
} else {
artifactsSection.classList.add('hidden');
artifactsList.replaceChildren();
}
// 4. Sources and Tool History
const pages = result.pages_accessed || [];
historyToggleTitle.textContent = `Sources & Request History (${pages.length} page${pages.length === 1 ? '' : 's'} accessed)`;
renderPagesAccessed(pagesAccessedList, pages);
renderToolHistory(toolHistoryList, result.tool_history || []);
// Collapse history by default
historyToggleBtn.setAttribute('aria-expanded', 'false');
historyContent.classList.add('hidden');
}
/**
* Switches the active view.
* @param {'prompt'|'loading'|'result'} viewName
*/
function switchView(viewName) {
viewPrompt.classList.add('hidden');
viewLoading.classList.add('hidden');
viewResult.classList.add('hidden');
if (viewName === 'prompt') {
viewPrompt.classList.remove('hidden');
} else if (viewName === 'loading') {
viewLoading.classList.remove('hidden');
} else if (viewName === 'result') {
viewResult.classList.remove('hidden');
}
}
/**
* Shows prompt error message.
* @param {string} msg
*/
function showPromptError(msg) {
promptError.textContent = msg;
promptError.classList.remove('hidden');
}
/**
* Hides prompt error message.
*/
function hidePromptError() {
promptError.textContent = '';
promptError.classList.add('hidden');
}

419
frontend/js/history.js Normal file
View File

@ -0,0 +1,419 @@
/**
* Sources, Request History, and Artifacts rendering module.
* Provides bounded lazy expansion of huge tool results, sanitized textContent rendering,
* and distinct display of repeated/cache-hit calls.
*/
const MAX_HISTORY_RESULT_DISPLAY_BYTES = 32 * 1024; // 32 KiB display limit per entry
/**
* Formats byte counts into human-readable strings.
* @param {number} bytes
* @returns {string}
*/
export function formatBytes(bytes) {
if (typeof bytes !== 'number' || isNaN(bytes) || bytes < 0) return '0 B';
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
/**
* Bounded JSON serializer that traverses data structures lazily and terminates
* immediately when maxBytes is exceeded, avoiding full serialization memory cost.
* @param {any} value
* @param {number} [maxBytes]
* @returns {string}
*/
export function serializeBounded(value, maxBytes = MAX_HISTORY_RESULT_DISPLAY_BYTES) {
if (value === undefined) return 'undefined';
if (value === null) return 'null';
if (typeof value !== 'object') {
const s = String(value);
if (s.length > maxBytes) {
return s.slice(0, maxBytes) + `\n\n... [Truncated: ${formatBytes(s.length)} total]`;
}
return JSON.stringify(value);
}
let totalChars = 0;
let truncated = false;
const parts = [];
function append(str) {
if (!str) return;
if (totalChars + str.length > maxBytes) {
const allowed = Math.max(0, maxBytes - totalChars);
if (allowed > 0) {
parts.push(str.slice(0, allowed));
totalChars += allowed;
}
truncated = true;
} else {
parts.push(str);
totalChars += str.length;
}
}
function walk(val, indent) {
if (totalChars >= maxBytes) {
truncated = true;
return;
}
if (val === null) {
append('null');
return;
}
const type = typeof val;
if (type !== 'object') {
if (type === 'string') {
const remaining = maxBytes - totalChars;
if (val.length > remaining) {
truncated = true;
const sliced = val.slice(0, Math.max(0, remaining - 15));
append(JSON.stringify(sliced).slice(0, -1) + '... [truncated]"');
} else {
append(JSON.stringify(val));
}
} else {
append(JSON.stringify(val));
}
return;
}
const spaces = ' '.repeat(indent);
const nextSpaces = ' '.repeat(indent + 1);
if (Array.isArray(val)) {
if (val.length === 0) {
append('[]');
return;
}
append('[\n');
for (let i = 0; i < val.length; i++) {
if (totalChars >= maxBytes) {
truncated = true;
append(`${nextSpaces}... [${val.length - i} more items truncated]\n`);
break;
}
append(nextSpaces);
walk(val[i], indent + 1);
if (i < val.length - 1) append(',');
append('\n');
}
append(`${spaces}]`);
return;
}
// Object
const keys = Object.keys(val);
if (keys.length === 0) {
append('{}');
return;
}
append('{\n');
for (let i = 0; i < keys.length; i++) {
if (totalChars >= maxBytes) {
truncated = true;
append(`${nextSpaces}... [${keys.length - i} more properties truncated]\n`);
break;
}
const key = keys[i];
append(`${nextSpaces}${JSON.stringify(key)}: `);
walk(val[key], indent + 1);
if (i < keys.length - 1) append(',');
append('\n');
}
append(`${spaces}}`);
}
walk(value, 0);
let result = parts.join('');
if (truncated) {
result += `\n\n... [Result display bounded to ${formatBytes(maxBytes)}; click Export to MD for full output]`;
}
return result;
}
/**
* Formats ISO timestamp into readable UTC string.
* @param {string} isoString
* @returns {string}
*/
export function formatTimestamp(isoString) {
if (!isoString) return 'Unknown';
try {
const d = new Date(isoString);
if (isNaN(d.getTime())) return isoString;
return d.toISOString().replace('T', ' ').replace('Z', ' UTC');
} catch {
return isoString;
}
}
/**
* Renders the list of accessed Confluence pages.
* @param {HTMLElement} container
* @param {Array<{ page_id: string, title: string, space: string, url: string, accessed_at: string }>} pages
*/
export function renderPagesAccessed(container, pages) {
container.replaceChildren();
if (!Array.isArray(pages) || pages.length === 0) {
const emptyMsg = document.createElement('p');
emptyMsg.className = 'page-card-meta';
emptyMsg.textContent = 'No Confluence pages were read during this query.';
container.appendChild(emptyMsg);
return;
}
pages.forEach((page) => {
const card = document.createElement('div');
card.className = 'page-card';
const left = document.createElement('div');
left.className = 'page-card-left';
const spaceBadge = document.createElement('span');
spaceBadge.className = 'badge-space';
spaceBadge.textContent = page.space || 'PAGE';
const link = document.createElement('a');
link.className = 'page-title-link';
link.textContent = page.title || `Page ${page.page_id}`;
if (page.url) {
try {
const u = new URL(page.url, window.location.href);
if (['http:', 'https:'].includes(u.protocol)) {
link.href = u.href;
link.target = '_blank';
link.rel = 'noopener noreferrer';
}
} catch {
// Leave link without href if invalid
}
}
left.appendChild(spaceBadge);
left.appendChild(link);
const meta = document.createElement('div');
meta.className = 'page-card-meta';
meta.textContent = `ID: ${page.page_id} · Accessed: ${formatTimestamp(page.accessed_at)}`;
card.appendChild(left);
card.appendChild(meta);
container.appendChild(card);
});
}
/**
* Renders the authoritative tool history with bounded lazy result expansion.
* @param {HTMLElement} container
* @param {Array<object>} toolHistory
*/
export function renderToolHistory(container, toolHistory) {
container.replaceChildren();
if (!Array.isArray(toolHistory) || toolHistory.length === 0) {
const emptyMsg = document.createElement('p');
emptyMsg.className = 'page-card-meta';
emptyMsg.textContent = 'No remote tool operations recorded.';
container.appendChild(emptyMsg);
return;
}
toolHistory.forEach((entry) => {
const card = document.createElement('div');
card.className = 'tool-card';
// Header
const header = document.createElement('div');
header.className = 'tool-card-header';
const headerLeft = document.createElement('div');
headerLeft.className = 'tool-card-header-left';
const idSpan = document.createElement('span');
idSpan.className = 'tool-id';
idSpan.textContent = `#${entry.tool_call_id || 'call'}`;
const nameSpan = document.createElement('span');
nameSpan.className = 'tool-name';
nameSpan.textContent = entry.tool || 'unknown_tool';
headerLeft.appendChild(idSpan);
headerLeft.appendChild(nameSpan);
const badges = document.createElement('div');
badges.className = 'tool-badges';
// Status badge
const statusBadge = document.createElement('span');
const isSuccess = entry.status === 'success';
statusBadge.className = `badge ${isSuccess ? 'badge-success' : 'badge-error'}`;
statusBadge.textContent = isSuccess ? 'Success' : 'Error';
badges.appendChild(statusBadge);
// Cache hit badge
if (entry.cache_hit) {
const cacheBadge = document.createElement('span');
cacheBadge.className = 'badge badge-cache';
cacheBadge.textContent = 'Cache Hit';
badges.appendChild(cacheBadge);
}
// Truncation badges
if (entry.parameters_truncated) {
const paramTrunc = document.createElement('span');
paramTrunc.className = 'badge badge-truncated';
paramTrunc.textContent = 'Params Truncated';
badges.appendChild(paramTrunc);
}
if (entry.result_truncated) {
const resTrunc = document.createElement('span');
resTrunc.className = 'badge badge-truncated';
resTrunc.textContent = 'Result Truncated';
badges.appendChild(resTrunc);
}
header.appendChild(headerLeft);
header.appendChild(badges);
card.appendChild(header);
// Body
const body = document.createElement('div');
body.className = 'tool-card-body';
const metaRow = document.createElement('div');
metaRow.className = 'tool-meta-row';
const timeText = `Started: ${formatTimestamp(entry.started_at)} · Completed: ${formatTimestamp(entry.completed_at)}`;
metaRow.textContent = timeText;
body.appendChild(metaRow);
// Expandable toggle button
const toggleBtn = document.createElement('button');
toggleBtn.type = 'button';
toggleBtn.className = 'tool-expand-btn';
toggleBtn.textContent = 'Show details';
toggleBtn.setAttribute('aria-expanded', 'false');
let detailsRendered = false;
let detailsContainer = null;
toggleBtn.addEventListener('click', () => {
const isExpanded = toggleBtn.getAttribute('aria-expanded') === 'true';
if (isExpanded) {
toggleBtn.setAttribute('aria-expanded', 'false');
toggleBtn.textContent = 'Show details';
if (detailsContainer) {
detailsContainer.classList.add('hidden');
}
} else {
toggleBtn.setAttribute('aria-expanded', 'true');
toggleBtn.textContent = 'Hide details';
if (!detailsRendered) {
detailsContainer = document.createElement('div');
detailsContainer.className = 'tool-details';
// Parameters section
const paramLabel = document.createElement('div');
paramLabel.className = 'history-subheading';
paramLabel.textContent = 'Parameters';
detailsContainer.appendChild(paramLabel);
const paramBox = document.createElement('pre');
paramBox.className = 'tool-result-box';
paramBox.textContent = serializeBounded(entry.parameters || {}, MAX_HISTORY_RESULT_DISPLAY_BYTES);
detailsContainer.appendChild(paramBox);
// Result or Error section
const resultLabel = document.createElement('div');
resultLabel.className = 'history-subheading';
resultLabel.textContent = entry.error ? 'Error' : 'Result';
detailsContainer.appendChild(resultLabel);
const resultBox = document.createElement('pre');
resultBox.className = 'tool-result-box';
if (entry.error) {
resultBox.textContent = serializeBounded(entry.error, MAX_HISTORY_RESULT_DISPLAY_BYTES);
} else {
// Lazy bounded serialization without paying full in-memory stringification cost
resultBox.textContent = serializeBounded(entry.result, MAX_HISTORY_RESULT_DISPLAY_BYTES);
}
detailsContainer.appendChild(resultBox);
body.appendChild(detailsContainer);
detailsRendered = true;
} else if (detailsContainer) {
detailsContainer.classList.remove('hidden');
}
}
});
body.appendChild(toggleBtn);
card.appendChild(body);
container.appendChild(card);
});
}
/**
* Renders the list of exported artifacts.
* @param {HTMLElement} container
* @param {Array<{ id: string, name: string, size_bytes: number, expires_at: string }>} artifacts
* @param {(id: string, name: string) => Promise<void>} onDownload
*/
export function renderArtifacts(container, artifacts, onDownload) {
container.replaceChildren();
if (!Array.isArray(artifacts) || artifacts.length === 0) {
return;
}
artifacts.forEach((art) => {
const item = document.createElement('li');
item.className = 'artifact-item';
const info = document.createElement('div');
info.className = 'artifact-info';
const nameSpan = document.createElement('span');
nameSpan.className = 'artifact-name';
nameSpan.textContent = art.name || 'unnamed_artifact';
const metaSpan = document.createElement('span');
metaSpan.className = 'artifact-meta';
metaSpan.textContent = `${formatBytes(art.size_bytes)} · Expires: ${formatTimestamp(art.expires_at)}`;
info.appendChild(nameSpan);
info.appendChild(metaSpan);
const dlBtn = document.createElement('button');
dlBtn.type = 'button';
dlBtn.className = 'download-btn';
dlBtn.textContent = 'Download';
dlBtn.setAttribute('aria-label', `Download ${art.name}`);
dlBtn.addEventListener('click', async () => {
dlBtn.disabled = true;
const originalText = dlBtn.textContent;
dlBtn.textContent = 'Downloading...';
try {
await onDownload(art.id, art.name);
} finally {
dlBtn.disabled = false;
dlBtn.textContent = originalText;
}
});
item.appendChild(info);
item.appendChild(dlBtn);
container.appendChild(item);
});
}

464
frontend/js/render.js Normal file
View File

@ -0,0 +1,464 @@
/**
* Markdown rendering and bounded sectioning pipeline.
* Uses pinned marked.js and DOMPurify with strict tag allowlist and link normalization.
*/
// Target maximum size for a single rendered Markdown section
export const SECTION_TARGET_BYTES = 48 * 1024; // ~48 KiB soft target
export const SECTION_HARD_LIMIT_BYTES = 64 * 1024; // ~64 KiB hard cap per section
export const PATHOLOGICAL_BLOCK_LIMIT = 128 * 1024; // 128 KiB fallback threshold
const textEncoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;
/**
* Calculates UTF-8 byte length for a string.
* @param {string} str
* @returns {number}
*/
export function getUtf8Bytes(str) {
if (!str) return 0;
if (textEncoder) {
return textEncoder.encode(str).length;
}
let bytes = 0;
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code <= 0x7f) bytes += 1;
else if (code <= 0x7ff) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
i++;
} else bytes += 3;
}
return bytes;
}
/**
* Configure marked options once.
*/
if (typeof window !== 'undefined' && window.marked) {
window.marked.setOptions({
gfm: true,
breaks: true
});
}
/**
* Normalizes and sanitizes a single bounded markdown section into HTML.
* Fails safe: never injects raw untrusted markdown if parser or sanitizer is absent.
* @param {string} rawMd
* @returns {DocumentFragment}
*/
export function renderMarkdownSectionToFragment(rawMd) {
if (typeof rawMd !== 'string') {
return document.createDocumentFragment();
}
// Fail-safe render: if marked or DOMPurify are absent, fail safe with an empty fragment + notice.
// Never inject raw untrusted markdown as innerHTML.
if (typeof window === 'undefined' || typeof document === 'undefined' || !window.marked || !window.DOMPurify) {
if (typeof document === 'undefined') {
return {
textContent: 'Markdown renderer or sanitizer is unavailable. Content cannot be displayed safely.',
isFailSafe: true
};
}
const fragment = document.createDocumentFragment();
const notice = document.createElement('div');
notice.className = 'render-error-notice';
notice.textContent = 'Markdown renderer or sanitizer is unavailable. Content cannot be displayed safely.';
fragment.appendChild(notice);
return fragment;
}
// Parse Markdown using locally vendored marked
let rawHtml = '';
try {
rawHtml = window.marked.parse(rawMd);
} catch {
const fragment = document.createDocumentFragment();
const notice = document.createElement('div');
notice.className = 'render-error-notice';
notice.textContent = 'Failed to parse Markdown section.';
fragment.appendChild(notice);
return fragment;
}
// Sanitize with strict allowlist
const cleanHtml = window.DOMPurify.sanitize(rawHtml, {
ALLOWED_TAGS: [
'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'strong', 'em', 'del', 's', 'blockquote', 'pre', 'code',
'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'a'
],
ALLOWED_ATTR: ['href', 'title', 'colspan', 'rowspan', 'start'],
ALLOW_DATA_ATTR: false,
ALLOW_ARIA_ATTR: false
});
// Build template and normalize links
const template = document.createElement('template');
template.innerHTML = cleanHtml;
template.content.querySelectorAll('a').forEach((link) => {
try {
const href = link.getAttribute('href');
if (!href) throw new Error('Empty href');
const url = new URL(href, window.location.href);
if (!['https:', 'http:'].includes(url.protocol)) {
throw new Error('Disallowed protocol');
}
link.href = url.href;
link.target = '_blank';
link.rel = 'noopener noreferrer';
} catch {
// Strip unsafe/invalid hrefs (e.g. javascript:, data:, relative file URLs)
link.removeAttribute('href');
}
});
return template.content;
}
/**
* Partitions large markdown documents into bounded sections to prevent DOM exhaustion.
* Preserves code fences and table boundaries where feasible.
* Forces section splits even inside large code fences by safely closing and re-opening the fence.
* Keeps table rows together and repeats table headers if forced to split.
* Dense lists without blank lines split cleanly at item or line boundaries.
* Falls back to bounded plain-text preview for single pathological blocks.
* @param {string} rawMd
* @returns {Array<{ text: string, isPathologicalFallback?: boolean }>}
*/
export function partitionMarkdown(rawMd) {
if (!rawMd) return [];
const totalBytes = getUtf8Bytes(rawMd);
if (totalBytes <= SECTION_TARGET_BYTES) {
if (totalBytes > PATHOLOGICAL_BLOCK_LIMIT) {
return [{
text: rawMd.slice(0, 32 * 1024) + '\n\n... [Block truncated for performance; click Export to MD for full document]',
isPathologicalFallback: true
}];
}
return [{ text: rawMd }];
}
const sections = [];
const lines = rawMd.split('\n');
let currentChunk = [];
let currentSize = 0;
let inCodeFence = false;
let fenceIndent = '';
let fenceChar = '`';
let fenceLen = 3;
let fenceInfo = '';
let inTable = false;
let tableHeader = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineBytes = getUtf8Bytes(line) + 1; // +1 for newline
// Check for single pathological line/block exceeding safety limit
if (lineBytes > PATHOLOGICAL_BLOCK_LIMIT) {
if (currentChunk.length > 0) {
if (inCodeFence) {
currentChunk.push(`${fenceIndent}${fenceChar.repeat(fenceLen)}`);
}
const chunkText = currentChunk.join('\n');
if (chunkText.trim().length > 0) {
sections.push({ text: chunkText });
}
currentChunk = [];
currentSize = 0;
}
// Pathological chunk fallback: bounded slice
sections.push({
text: line.slice(0, 32 * 1024) + '\n\n... [Block truncated for performance; click Export to MD for full document]',
isPathologicalFallback: true
});
if (inCodeFence) {
const reopen = `${fenceIndent}${fenceChar.repeat(fenceLen)}${fenceInfo || ''}`;
currentChunk.push(reopen);
currentSize = getUtf8Bytes(reopen) + 1;
}
continue;
}
// Code fence detection
const fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})(.*)$/);
if (!inCodeFence && fenceMatch) {
inCodeFence = true;
fenceIndent = fenceMatch[1];
fenceChar = fenceMatch[2][0];
fenceLen = fenceMatch[2].length;
fenceInfo = fenceMatch[3].trim();
} else if (inCodeFence) {
const closeRegex = new RegExp(`^\\s*${fenceChar === '`' ? '`' : '~'}{${fenceLen},}\\s*$`);
if (closeRegex.test(line)) {
inCodeFence = false;
}
}
// Table detection (GFM tables)
const isTableRow = /^\s*\|.*\|\s*$/.test(line);
const isTableSep = /^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/.test(line);
if (!inCodeFence) {
if (isTableRow && !inTable && i + 1 < lines.length && /^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/.test(lines[i + 1])) {
inTable = true;
tableHeader = `${line}\n${lines[i + 1]}`;
} else if (inTable && (line.trim() === '' || !isTableRow)) {
inTable = false;
tableHeader = null;
}
}
// Split decision when inside code fence:
// Force split if current chunk exceeds hard limit
if (inCodeFence) {
if (currentSize + lineBytes > SECTION_HARD_LIMIT_BYTES && currentChunk.length > 0) {
// Safely close fence in current chunk
const closeFence = `${fenceIndent}${fenceChar.repeat(fenceLen)}`;
currentChunk.push(closeFence);
sections.push({ text: currentChunk.join('\n') });
// Re-open fence in new chunk
const reopenFence = `${fenceIndent}${fenceChar.repeat(fenceLen)}${fenceInfo || ''}`;
currentChunk = [reopenFence];
currentSize = getUtf8Bytes(reopenFence) + 1;
}
currentChunk.push(line);
currentSize += lineBytes;
continue;
}
// Split decision when inside table:
if (inTable) {
if (currentSize + lineBytes > SECTION_HARD_LIMIT_BYTES && currentChunk.length > 0 && !isTableSep) {
sections.push({ text: currentChunk.join('\n') });
currentChunk = [];
currentSize = 0;
if (tableHeader) {
currentChunk.push(tableHeader);
currentSize = getUtf8Bytes(tableHeader) + 1;
}
}
currentChunk.push(line);
currentSize += lineBytes;
continue;
}
// Outside code fences and tables:
const isHeading = /^\s*#{1,3}\s/.test(line);
const isEmptyLine = line.trim() === '';
const isListItem = /^\s*([*+-]|\d+\.)\s/.test(line);
const shouldSplit = (
(isHeading && currentSize >= 16 * 1024) ||
((isHeading || isEmptyLine) && currentSize >= SECTION_TARGET_BYTES) ||
(isListItem && currentSize >= SECTION_TARGET_BYTES) ||
(currentSize + lineBytes > SECTION_HARD_LIMIT_BYTES)
);
if (shouldSplit && currentChunk.length > 0) {
const chunkText = currentChunk.join('\n');
if (chunkText.trim().length > 0) {
sections.push({ text: chunkText });
}
currentChunk = [];
currentSize = 0;
}
currentChunk.push(line);
currentSize += lineBytes;
}
if (currentChunk.length > 0) {
if (inCodeFence) {
currentChunk.push(`${fenceIndent}${fenceChar.repeat(fenceLen)}`);
}
const chunkText = currentChunk.join('\n');
if (chunkText.trim().length > 0) {
sections.push({ text: chunkText });
}
}
return sections.length > 0 ? sections : [{ text: rawMd }];
}
/**
* State container for bounded section rendering in the UI.
*/
export class MarkdownRenderer {
/**
* @param {HTMLElement} containerElement
* @param {HTMLElement} navElement
*/
constructor(containerElement, navElement) {
this.container = containerElement;
this.nav = navElement;
this.sections = [];
this.currentIndex = 0;
}
/**
* Loads and partitions new markdown text.
* @param {string} rawMd
*/
load(rawMd) {
this.sections = partitionMarkdown(rawMd);
this.currentIndex = 0;
this.renderCurrentSection();
}
/**
* Renders the current active section, limiting retained rendered DOM nodes.
*/
renderCurrentSection() {
this.container.replaceChildren();
if (this.sections.length === 0) {
this.nav.classList.add('hidden');
return;
}
const current = this.sections[this.currentIndex];
// If pathological fallback was triggered, render plain-text preview (never raw to marked)
if (current.isPathologicalFallback) {
const banner = document.createElement('div');
banner.className = 'pathological-banner';
banner.textContent = 'Pathological large block detected. Display bounded for performance; use "Export to MD" to download the full document.';
this.container.appendChild(banner);
const pre = document.createElement('pre');
pre.className = 'pathological-preview';
pre.textContent = current.text;
this.container.appendChild(pre);
} else {
// Normal section: parse and sanitize
const fragment = renderMarkdownSectionToFragment(current.text);
this.container.appendChild(fragment);
}
// Update section navigation controls (show for multiple sections OR single pathological section)
if (this.sections.length > 1 || current.isPathologicalFallback) {
this.nav.classList.remove('hidden');
this.updateNavUI();
} else {
this.nav.classList.add('hidden');
}
}
/**
* Updates navigation buttons and indicators.
*/
updateNavUI() {
this.nav.replaceChildren();
const banner = document.createElement('div');
banner.className = 'section-nav-banner';
const info = document.createElement('span');
if (this.sections.length === 1 && this.sections[0].isPathologicalFallback) {
info.textContent = 'Showing bounded plain-text preview (pathological input; click Export to MD for full document)';
} else {
info.textContent = `Showing section ${this.currentIndex + 1} of ${this.sections.length} (bounded for responsiveness)`;
}
const controls = document.createElement('div');
controls.className = 'section-nav-controls';
if (this.sections.length > 1) {
const prevBtn = document.createElement('button');
prevBtn.type = 'button';
prevBtn.className = 'section-btn';
prevBtn.textContent = '← Previous';
prevBtn.disabled = this.currentIndex === 0;
prevBtn.addEventListener('click', () => {
if (this.currentIndex > 0) {
this.currentIndex--;
this.renderCurrentSection();
this.container.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
const nextBtn = document.createElement('button');
nextBtn.type = 'button';
nextBtn.className = 'section-btn';
nextBtn.textContent = 'Next →';
nextBtn.disabled = this.currentIndex >= this.sections.length - 1;
nextBtn.addEventListener('click', () => {
if (this.currentIndex < this.sections.length - 1) {
this.currentIndex++;
this.renderCurrentSection();
this.container.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
controls.appendChild(prevBtn);
controls.appendChild(nextBtn);
}
banner.appendChild(info);
if (this.sections.length > 1) {
banner.appendChild(controls);
}
this.nav.appendChild(banner);
}
}
/**
* Downloads raw Markdown content client-side via Blob.
* Uses exact specification naming: confluence_summary_<slug>_<timestamp>.md
* Revokes object URL after dispatch.
* @param {string} rawMarkdown
* @param {string} queryText
*/
export function exportToMarkdown(rawMarkdown, queryText) {
const slug = (queryText || '').slice(0, 30).replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
const filename = `confluence_summary_${slug || 'export'}_${Date.now()}.md`;
const blob = new Blob([rawMarkdown], { type: 'text/markdown;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
/**
* Renders warning items safely into the warnings container.
* @param {HTMLElement} container
* @param {Array<{ code: string, message: string, tool_call_id?: string, name?: string }>} warnings
*/
export function renderWarnings(container, warnings) {
container.replaceChildren();
if (!Array.isArray(warnings) || warnings.length === 0) {
container.classList.add('hidden');
return;
}
container.classList.remove('hidden');
warnings.forEach((w) => {
const item = document.createElement('div');
item.className = 'warning-item';
const codeSpan = document.createElement('span');
codeSpan.className = 'warning-code';
codeSpan.textContent = `[${w.code || 'warning'}]`;
const msgSpan = document.createElement('span');
msgSpan.className = 'warning-msg';
msgSpan.textContent = w.message || 'An unknown warning occurred.';
item.appendChild(codeSpan);
item.appendChild(msgSpan);
container.appendChild(item);
});
}

45
frontend/package-lock.json generated Normal file
View File

@ -0,0 +1,45 @@
{
"name": "frontend",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frontend",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"dompurify": "^3.4.15",
"marked": "^18.0.13"
}
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/dompurify": {
"version": "3.4.15",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz",
"integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/marked": {
"version": "18.0.13",
"resolved": "https://registry.npmjs.org/marked/-/marked-18.0.13.tgz",
"integrity": "sha512-xTxVzZsBFwunP6HDmtBkabUQEYArnP7/rMDGmPj9SlrKlQ4i8MdYVow+nJL0eOqwpUqhzBoTBRADGN6uYwPyOw==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 20"
}
}
}
}

17
frontend/package.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "frontend",
"version": "1.0.0",
"description": "Confluence Research Web UI and Mock Server",
"main": "js/app.js",
"type": "module",
"scripts": {
"dev": "node dev/mock-server.js",
"start": "node dev/mock-server.js",
"test": "node --test tests/*.test.js",
"test:e2e": "node tests/e2e_runner.js"
},
"dependencies": {
"dompurify": "3.4.15",
"marked": "18.0.13"
}
}

110
frontend/tests/api.test.js Normal file
View File

@ -0,0 +1,110 @@
/**
* Unit tests for api.js validation logic and boundaries.
*/
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { getUtf8ByteLength, validateCredentials, submitQuery } from '../js/api.js';
describe('API validation and boundaries', () => {
test('getUtf8ByteLength correctly calculates ASCII and multibyte UTF-8 lengths', () => {
assert.equal(getUtf8ByteLength('hello'), 5);
// Multibyte characters:
// '€' is 3 bytes (0xE2 0x82 0xAC)
// '🚀' is 4 bytes (0xF0 0x9F 0x99 0x80)
assert.equal(getUtf8ByteLength('€'), 3);
assert.equal(getUtf8ByteLength('🚀'), 4);
assert.equal(getUtf8ByteLength('こんにちは'), 15); // 5 x 3 bytes
});
test('validateCredentials validates valid HTTP and HTTPS URLs', () => {
assert.doesNotThrow(() => {
validateCredentials({
url: 'https://confluence.example.com',
pat: 'valid-pat-string'
});
});
assert.doesNotThrow(() => {
validateCredentials({
url: 'http://localhost:8080/confluence',
pat: 'pat-token'
});
});
});
test('validateCredentials rejects empty or missing fields', () => {
assert.throws(
() => validateCredentials({ url: '', pat: 'pat' }),
(err) => err.code === 'invalid_input'
);
assert.throws(
() => validateCredentials({ url: 'https://example.com', pat: ' ' }),
(err) => err.code === 'invalid_input'
);
});
test('validateCredentials rejects invalid protocols like javascript: or file:', () => {
assert.throws(
() => validateCredentials({ url: 'javascript:alert(1)', pat: 'pat' }),
(err) => err.code === 'invalid_input'
);
assert.throws(
() => validateCredentials({ url: 'file:///etc/passwd', pat: 'pat' }),
(err) => err.code === 'invalid_input'
);
});
test('validateCredentials exact 8 KiB boundary check', () => {
// Exactly 8192 bytes (8 KiB) passes
const exact8KiBPat = 'a'.repeat(8192);
assert.doesNotThrow(() => {
validateCredentials({ url: 'https://example.com', pat: exact8KiBPat });
});
// 8193 bytes fails
const over8KiBPat = 'a'.repeat(8193);
assert.throws(
() => validateCredentials({ url: 'https://example.com', pat: over8KiBPat }),
(err) => err.code === 'invalid_input' && err.message.includes('8 KiB')
);
// Multibyte 8 KiB boundary: 2048 emojis = 8192 bytes (passes)
const exact8KiBEmoji = '🚀'.repeat(2048);
assert.equal(getUtf8ByteLength(exact8KiBEmoji), 8192);
assert.doesNotThrow(() => {
validateCredentials({ url: 'https://example.com', pat: exact8KiBEmoji });
});
// 2049 emojis = 8196 bytes (fails)
const over8KiBEmoji = exact8KiBEmoji + '🚀';
assert.throws(
() => validateCredentials({ url: 'https://example.com', pat: over8KiBEmoji }),
(err) => err.code === 'invalid_input' && err.message.includes('8 KiB')
);
});
test('runtime 16 MiB multibyte UTF-8 boundary validation on prompt', async () => {
const validCredentials = { url: 'https://approved.example.com', pat: 'dummy-pat-123' };
// Construct a real 16 MiB string containing 4-byte multibyte emojis at runtime
// 4 bytes * 4,194,304 = 16,777,216 bytes (exactly 16 MiB)
const chunk = '🚀'.repeat(1024); // 4096 bytes
const exactly16MiBPrompt = chunk.repeat(4096); // 16 MiB
assert.equal(getUtf8ByteLength(exactly16MiBPrompt), 16 * 1024 * 1024);
// Prompt exceeding 16 MiB by 1 byte
const over16MiBPrompt = exactly16MiBPrompt + 'a';
assert.equal(getUtf8ByteLength(over16MiBPrompt), 16 * 1024 * 1024 + 1);
// Rejection above 16 MiB
await assert.rejects(
async () => {
await submitQuery({ prompt: over16MiBPrompt, credentials: validCredentials });
},
(err) => err.code === 'invalid_input' && err.message.includes('16 MiB')
);
});
});

View File

@ -0,0 +1,303 @@
/**
* Contract and Mock Server tests.
* Validates wire formats, security headers, session cookies, and scenarios against CONTRACTS.md.
*/
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { createMockServer, SCENARIOS } from '../dev/mock-server.js';
const TEST_PORT = 5199;
const BASE_URL = `http://127.0.0.1:${TEST_PORT}`;
describe('Mock Server and Wire Contract Tests', () => {
let server;
before(async () => {
server = createMockServer();
await new Promise((resolve) => {
server.listen(TEST_PORT, '127.0.0.1', resolve);
});
});
after(async () => {
await new Promise((resolve) => {
server.close(resolve);
});
});
test('GET / sets cw_session cookie and serves security headers', async () => {
const res = await fetch(`${BASE_URL}/`);
assert.equal(res.status, 200);
// Security headers
assert.equal(res.headers.get('x-content-type-options'), 'nosniff');
assert.equal(res.headers.get('referrer-policy'), 'no-referrer');
const csp = res.headers.get('content-security-policy');
assert.ok(csp.includes("default-src 'none'"));
assert.ok(csp.includes("script-src 'self'"));
assert.ok(csp.includes("style-src 'self'"));
assert.ok(csp.includes("connect-src 'self'"));
assert.ok(csp.includes("img-src 'none'"));
// Session cookie
const cookie = res.headers.get('set-cookie');
assert.ok(cookie, 'Set-Cookie header must be present');
assert.ok(cookie.includes('cw_session='), 'Cookie name must be cw_session');
assert.ok(cookie.includes('HttpOnly'), 'Cookie must be HttpOnly');
assert.ok(cookie.includes('SameSite=Strict'), 'Cookie must be SameSite=Strict');
});
test('POST /api/v1/auth/verify succeeds with dummy credentials', async () => {
const res = await fetch(`${BASE_URL}/api/v1/auth/verify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
url: 'https://confluence.example.com',
pat: 'dummy-pat-token-123'
})
});
assert.equal(res.status, 200);
assert.equal(res.headers.get('cache-control'), 'no-store');
const body = await res.json();
assert.deepEqual(body, { valid: true });
});
test('POST /api/v1/auth/verify fails with 403 in 403_verify scenario', async () => {
const res = await fetch(`${BASE_URL}/api/v1/auth/verify?scenario=403_verify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
url: 'https://confluence.example.com',
pat: 'dummy-pat-token-123'
})
});
assert.equal(res.status, 403);
const body = await res.json();
assert.ok(body.error);
assert.equal(body.error.code, 'confluence_auth_failed');
});
test('POST /api/v1/query handles normal scenario matching section 7 shared contract', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query?scenario=normal`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
prompt: 'deploy service X',
credentials: {
url: 'https://approved.example.com',
pat: 'dummy-pat-123'
}
})
});
assert.equal(res.status, 200);
assert.equal(res.headers.get('cache-control'), 'no-store');
const data = await res.json();
assert.ok(data.session_id);
assert.ok(data.markdown.includes('Deployment Guide'));
assert.equal(data.pages_accessed.length, 1);
assert.equal(data.pages_accessed[0].page_id, '847291');
assert.equal(data.pages_accessed[0].space, 'OPS');
assert.ok(data.pages_accessed[0].accessed_at);
assert.equal(data.tool_history.length, 2);
assert.equal(data.tool_history[0].tool, 'confluence_search');
assert.equal(data.tool_history[1].tool, 'confluence_view');
assert.equal(data.tool_history[1].cache_hit, false);
assert.equal(data.artifacts.length, 1);
assert.equal(data.artifacts[0].name, 'checklist.md');
assert.equal(data.artifacts[0].size_bytes, 32);
assert.ok(data.artifacts[0].expires_at);
});
test('GET /api/v1/artifacts/:id downloads exact 32 bytes for checklist.md', async () => {
const res = await fetch(`${BASE_URL}/api/v1/artifacts/art-checklist-01`);
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'application/octet-stream');
assert.equal(res.headers.get('x-content-type-options'), 'nosniff');
assert.ok(res.headers.get('content-disposition').includes('attachment; filename="checklist.md"'));
const text = await res.text();
assert.equal(text, '# Checklist\n\n- Deploy service X\n');
assert.equal(Buffer.byteLength(text, 'utf-8'), 32);
});
test('GET /api/v1/artifacts/:id returns 404 in unknown_expired_download scenario', async () => {
const res = await fetch(`${BASE_URL}/api/v1/artifacts/art-checklist-01?scenario=unknown_expired_download`);
assert.equal(res.status, 404);
const body = await res.json();
assert.equal(body.error.code, 'artifact_not_found');
});
test('POST /api/v1/query handles 409 busy scenario', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query?scenario=409_busy`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
prompt: 'test prompt',
credentials: { url: 'https://example.com', pat: 'dummy' }
})
});
assert.equal(res.status, 409);
const body = await res.json();
assert.equal(body.error.code, 'busy');
});
test('POST /api/v1/query handles 504 timeout scenario', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query?scenario=504_timeout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
prompt: 'test prompt',
credentials: { url: 'https://example.com', pat: 'dummy' }
})
});
assert.equal(res.status, 504);
const body = await res.json();
assert.equal(body.error.code, 'query_timeout');
});
test('POST /api/v1/query handles empty_search scenario', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query?scenario=empty_search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
prompt: 'non-existent query',
credentials: { url: 'https://example.com', pat: 'dummy' }
})
});
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.pages_accessed.length, 0);
assert.equal(body.artifacts.length, 0);
assert.equal(body.tool_history.length, 1);
assert.equal(body.tool_history[0].result.pages.length, 0);
});
test('POST /api/v1/query handles repeated_cached_view scenario', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query?scenario=repeated_cached_view`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
prompt: 'cache test',
credentials: { url: 'https://example.com', pat: 'dummy' }
})
});
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.pages_accessed.length, 1);
assert.equal(body.tool_history.length, 2);
assert.equal(body.tool_history[0].cache_hit, false);
assert.equal(body.tool_history[1].cache_hit, true);
});
test('POST /api/v1/query handles failed_tool scenario with status="error"', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query?scenario=failed_tool`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
prompt: 'failed tool test',
credentials: { url: 'https://example.com', pat: 'dummy' }
})
});
assert.equal(res.status, 200);
const body = await res.json();
const errorTool = body.tool_history.find((t) => t.status === 'error');
assert.ok(errorTool);
assert.equal(errorTool.result, null);
assert.equal(errorTool.error.code, 'page_not_found');
});
test('POST /api/v1/query handles warning_truncated_history scenario', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query?scenario=warning_truncated_history`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': BASE_URL
},
body: JSON.stringify({
prompt: 'truncation test',
credentials: { url: 'https://example.com', pat: 'dummy' }
})
});
assert.equal(res.status, 200);
const body = await res.json();
assert.ok(body.warnings.length > 0);
assert.equal(body.tool_history[0].parameters_truncated, true);
assert.equal(body.tool_history[0].result_truncated, true);
});
test('Origin check rejects untrusted external origins', async () => {
const res = await fetch(`${BASE_URL}/api/v1/query`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Origin': 'https://evil-attacker.example.com'
},
body: JSON.stringify({
prompt: 'attack',
credentials: { url: 'https://example.com', pat: 'dummy' }
})
});
assert.equal(res.status, 403);
const body = await res.json();
assert.equal(body.error.code, 'origin_denied');
});
test('Mock dev toolbar external assets served with correct headers and zero inline script/style', async () => {
// CSS asset
const cssRes = await fetch(`${BASE_URL}/dev/scenario-toolbar.css`);
assert.equal(cssRes.status, 200);
assert.ok(cssRes.headers.get('content-type').includes('text/css'));
assert.equal(cssRes.headers.get('x-content-type-options'), 'nosniff');
// JS asset
const jsRes = await fetch(`${BASE_URL}/dev/scenario-toolbar.js`);
assert.equal(jsRes.status, 200);
assert.ok(jsRes.headers.get('content-type').includes('javascript'));
assert.equal(jsRes.headers.get('x-content-type-options'), 'nosniff');
// Root HTML page must not contain inline scripts or inline style attributes
const htmlRes = await fetch(`${BASE_URL}/`);
const html = await htmlRes.text();
assert.ok(!/<script(?![^>]*src=)[^>]*>/i.test(html), 'Root HTML in dev mode must not contain inline <script>');
assert.ok(!/style\s*=\s*["'][^"']*["']/i.test(html), 'Root HTML in dev mode must not contain inline style attributes');
});
});

View File

@ -0,0 +1,592 @@
/**
* Comprehensive End-to-End Browser Test Runner.
* Connects directly to Chrome running on port 9444 via CDP,
* tests the Web UI against all requirements in docs/implementation/WEBUI.md and CONTRACTS.md.
*/
import http from 'node:http';
import assert from 'node:assert/strict';
import { createMockServer } from '../dev/mock-server.js';
const MOCK_PORT = 5173;
const CHROME_PORT = 9444;
const APP_URL = `http://127.0.0.1:${MOCK_PORT}/`;
class CDPClient {
constructor(wsUrl) {
this.wsUrl = wsUrl;
this.ws = null;
this.msgId = 1;
this.pending = new Map();
this.consoleLogs = [];
this.networkRequests = [];
}
async connect() {
this.ws = new WebSocket(this.wsUrl);
await new Promise((resolve, reject) => {
this.ws.onopen = resolve;
this.ws.onerror = reject;
});
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.id && this.pending.has(data.id)) {
const { resolve, reject } = this.pending.get(data.id);
this.pending.delete(data.id);
if (data.error) reject(new Error(data.error.message || JSON.stringify(data.error)));
else resolve(data.result);
} else if (data.method === 'Runtime.consoleAPICalled') {
this.consoleLogs.push(data.params);
} else if (data.method === 'Network.requestWillBeSent') {
this.networkRequests.push(data.params);
}
};
// Enable Runtime and Network domains
await this.send('Runtime.enable');
await this.send('Network.enable');
}
send(method, params = {}) {
return new Promise((resolve, reject) => {
const id = this.msgId++;
this.pending.set(id, { resolve, reject });
this.ws.send(JSON.stringify({ id, method, params }));
});
}
async eval(expression) {
const res = await this.send('Runtime.evaluate', {
expression,
returnByValue: true,
awaitPromise: true
});
if (res.exceptionDetails) {
throw new Error(`Eval error: ${res.exceptionDetails.text || ''} ${res.exceptionDetails.exception?.description || ''}`);
}
return res.result ? res.result.value : undefined;
}
async navigate(url) {
await this.send('Page.navigate', { url });
// Wait for load event
await new Promise((resolve) => setTimeout(resolve, 800));
}
close() {
if (this.ws) {
this.ws.close();
}
}
}
async function runTests() {
console.log('=== Starting Web UI End-to-End Tests with Chrome (port 9444) ===\n');
// 1. Start mock server
const server = createMockServer();
await new Promise((resolve) => server.listen(MOCK_PORT, '127.0.0.1', resolve));
console.log(`✓ Mock server started at http://127.0.0.1:${MOCK_PORT}/`);
// 2. Discover Chrome tab on port 9444
const tabsRes = await fetch(`http://127.0.0.1:${CHROME_PORT}/json`);
const tabs = await tabsRes.json();
const pageTab = tabs.find((t) => t.type === 'page') || tabs[0];
if (!pageTab || !pageTab.webSocketDebuggerUrl) {
throw new Error('No active Chrome page tab found on port 9444');
}
const cdp = new CDPClient(pageTab.webSocketDebuggerUrl);
await cdp.connect();
console.log(`✓ Connected to Chrome tab: "${pageTab.title}" via CDP\n`);
let passed = 0;
let failed = 0;
async function step(name, fn) {
process.stdout.write(`• Test: ${name}... `);
try {
await fn();
console.log('PASS');
passed++;
} catch (err) {
console.log(`FAIL: ${err.message}`);
failed++;
}
}
try {
// Reset scenario on mock server
await fetch(`http://127.0.0.1:${MOCK_PORT}/dev/scenario`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ scenario: 'normal' })
});
// Navigate to Web UI
await cdp.navigate(APP_URL);
await cdp.eval('document.cookie = "mock_scenario=normal; path=/";');
await cdp.navigate(APP_URL);
// Test 1: Page Load & Initial View
await step('Page Load & Initial View', async () => {
const title = await cdp.eval('document.title');
assert.equal(title, 'Confluence Research');
const isPromptVisible = await cdp.eval('!document.getElementById("view-prompt").classList.contains("hidden")');
assert.equal(isPromptVisible, true, 'Prompt view must be visible initially');
const hasIndicator = await cdp.eval('document.getElementById("cred-indicator").classList.contains("active")');
assert.equal(hasIndicator, false, 'Credentials indicator must be unset (gray)');
const helperText = await cdp.eval('document.querySelector(".prompt-helper").textContent');
assert.ok(helperText.includes('Press Enter ↵ to send'));
});
// Test 2: Credentials Modal Opening and Focus Trapping
await step('Credentials Modal & Focus Trapping', async () => {
// Click key button
await cdp.eval('document.getElementById("key-btn").click()');
const isModalOpen = await cdp.eval('!document.getElementById("modal-backdrop").classList.contains("hidden")');
assert.equal(isModalOpen, true, 'Modal should be open');
const focusedId = await cdp.eval('document.activeElement.id');
assert.equal(focusedId, 'cred-url', 'URL input should be focused on open');
// Test Cancel closes modal and restores focus
await cdp.eval('document.getElementById("btn-cancel-cred").click()');
const isModalClosed = await cdp.eval('document.getElementById("modal-backdrop").classList.contains("hidden")');
assert.equal(isModalClosed, true, 'Modal should close on cancel');
const restoredFocus = await cdp.eval('document.activeElement.id');
assert.equal(restoredFocus, 'key-btn', 'Focus should return to key-btn');
});
// Test 3: Password Visibility Toggle & Test Connection
await step('Password Toggle & Test Connection', async () => {
await cdp.eval('document.getElementById("key-btn").click()');
// Set input values
await cdp.eval(`
document.getElementById("cred-url").value = "https://approved.example.com";
document.getElementById("cred-pat").value = "dummy-pat-123";
`);
// Toggle password
const typeBefore = await cdp.eval('document.getElementById("cred-pat").type');
assert.equal(typeBefore, 'password');
await cdp.eval('document.getElementById("toggle-pat-btn").click()');
const typeAfter = await cdp.eval('document.getElementById("cred-pat").type');
assert.equal(typeAfter, 'text');
await cdp.eval('document.getElementById("toggle-pat-btn").click()');
// Click Test Connection
await cdp.eval('document.getElementById("btn-test-cred").click()');
await new Promise((r) => setTimeout(r, 400));
const feedback = await cdp.eval('document.getElementById("modal-feedback").textContent');
assert.ok(feedback.includes('Connection successful'), `Feedback should indicate success: ${feedback}`);
});
// Test 4: Save Credentials & Canary Leak Inspection
await step('Save Credentials & Memory Canary Inspection', async () => {
// Click Save & Close
await cdp.eval('document.getElementById("btn-save-cred").click()');
await new Promise((r) => setTimeout(r, 200));
const isModalClosed = await cdp.eval('document.getElementById("modal-backdrop").classList.contains("hidden")');
assert.equal(isModalClosed, true, 'Modal should close after save');
const isActive = await cdp.eval('document.getElementById("cred-indicator").classList.contains("active")');
assert.equal(isActive, true, 'Credential indicator should turn green/active');
// Canary inspection: ensure credentials never entered localStorage, sessionStorage, or URL
const canary = 'dummy-pat-123';
const localDump = await cdp.eval('JSON.stringify(localStorage)');
const sessionDump = await cdp.eval('JSON.stringify(sessionStorage)');
const href = await cdp.eval('window.location.href');
assert.ok(!localDump.includes(canary), 'localStorage must not contain credential canary');
assert.ok(!sessionDump.includes(canary), 'sessionStorage must not contain credential canary');
assert.ok(!href.includes(canary), 'URL must not contain tokens');
});
// Test 5: Research Query Submission & Loading View
await step('Query Submission & Loading Gear Spinner', async () => {
// Set prompt
await cdp.eval('document.getElementById("prompt-input").value = "How do I deploy service X?"');
await cdp.eval('document.getElementById("submit-btn").click()');
// Check loading view
const isLoadingVisible = await cdp.eval('!document.getElementById("view-loading").classList.contains("hidden")');
assert.equal(isLoadingVisible, true, 'Loading view must be visible while query executes');
const statusText = await cdp.eval('document.querySelector(".loading-status").textContent');
assert.equal(statusText, 'Agent researching Confluence...');
const gearPresent = await cdp.eval('!!document.querySelector(".gear-spinner")');
assert.equal(gearPresent, true, 'Gear spinner glyph must be present');
// Wait for query completion and result view
await new Promise((r) => setTimeout(r, 600));
const isResultVisible = await cdp.eval('!document.getElementById("view-result").classList.contains("hidden")');
assert.equal(isResultVisible, true, 'Result view must be displayed upon query completion');
});
// Test 6: Result View Rendering, Citation Links, and Security
await step('Result View, Citation Links & Sanitization', async () => {
const heading = await cdp.eval('document.querySelector("#output-content h1").textContent');
assert.ok(heading.includes('Deployment Guide for Service X'));
// Verify citation link attributes
const linkTarget = await cdp.eval('document.querySelector("#output-content a").target');
const linkRel = await cdp.eval('document.querySelector("#output-content a").rel');
const linkHref = await cdp.eval('document.querySelector("#output-content a").href');
assert.equal(linkTarget, '_blank', 'Citation link must open in new tab');
assert.equal(linkRel, 'noopener noreferrer', 'Citation link must have rel=noopener noreferrer');
assert.ok(linkHref.includes('847291'));
// Intercept click: verify click targets canonical URL without automatic prefetch
const citationTarget = await cdp.eval(`
(() => {
const link = document.querySelector("#output-content a");
return {
target: link.getAttribute('target'),
rel: link.getAttribute('rel'),
href: link.href
};
})()
`);
assert.equal(citationTarget.target, '_blank');
assert.equal(citationTarget.rel, 'noopener noreferrer');
assert.ok(citationTarget.href.startsWith('https://approved.example.com'));
});
// Test 7: Export to MD Client-Side Blob and Exact Bytes
await step('Export to MD Client-Side Blob and Exact Bytes', async () => {
const exportResult = await cdp.eval(`
new Promise((resolve) => {
let capturedBlob = null;
let revoked = false;
const origCreate = URL.createObjectURL;
const origRevoke = URL.revokeObjectURL;
URL.createObjectURL = (blob) => {
capturedBlob = blob;
return origCreate(blob);
};
URL.revokeObjectURL = (url) => {
revoked = true;
return origRevoke(url);
};
document.getElementById("export-btn").click();
URL.createObjectURL = origCreate;
URL.revokeObjectURL = origRevoke;
if (!capturedBlob) {
resolve({ error: 'No blob captured' });
return;
}
const reader = new FileReader();
reader.onload = () => {
resolve({
text: reader.result,
size: capturedBlob.size,
type: capturedBlob.type,
revoked
});
};
reader.readAsText(capturedBlob);
})
`);
assert.ok(!exportResult.error, exportResult.error);
assert.ok(exportResult.text.includes('Deployment Guide for Service X'), 'Exported text must match result markdown');
assert.ok(exportResult.type.includes('text/markdown'), 'Blob type must be text/markdown');
assert.equal(exportResult.revoked, true, 'Object URL must be revoked after dispatch');
});
// Test 8: Artifact Listing & Exact Download
await step('Artifact Listing & Attachment Download', async () => {
const artName = await cdp.eval('document.querySelector(".artifact-name").textContent');
assert.equal(artName, 'checklist.md');
const artMeta = await cdp.eval('document.querySelector(".artifact-meta").textContent');
assert.ok(artMeta.includes('32 B'), 'Artifact metadata should show 32 B');
// Verify download trigger executes without error
await cdp.eval('document.querySelector(".download-btn").click()');
await new Promise((r) => setTimeout(r, 400));
const errorBoxHidden = await cdp.eval('document.getElementById("artifacts-error").classList.contains("hidden")');
assert.equal(errorBoxHidden, true, 'Artifacts error box must remain hidden on successful download');
});
// Test 9: Sources and Request History Expansion
await step('Sources & Request History Drawer', async () => {
const headerTitle = await cdp.eval('document.getElementById("history-toggle-title").textContent');
assert.ok(headerTitle.includes('1 page accessed'));
// Expand history
await cdp.eval('document.getElementById("history-toggle-btn").click()');
const isExpanded = await cdp.eval('document.getElementById("history-toggle-btn").getAttribute("aria-expanded")');
assert.equal(isExpanded, 'true');
// Page accessed check
const pageTitle = await cdp.eval('document.querySelector(".page-title-link").textContent');
assert.equal(pageTitle, 'Deployment Guide');
const spaceKey = await cdp.eval('document.querySelector(".badge-space").textContent');
assert.equal(spaceKey, 'OPS');
// Tool call checks (2 calls)
const toolCardsCount = await cdp.eval('document.querySelectorAll(".tool-card").length');
assert.equal(toolCardsCount, 2, 'Should display 2 distinct tool call cards');
// Expand details on first tool call
await cdp.eval('document.querySelectorAll(".tool-expand-btn")[0].click()');
const detailsShown = await cdp.eval('!!document.querySelector(".tool-details")');
assert.equal(detailsShown, true, 'Tool details should be rendered lazily');
});
// Test 10: Back to Prompt Restores Text
await step('Back to Prompt Restores Textarea', async () => {
await cdp.eval('document.getElementById("back-btn").click()');
const isPromptVisible = await cdp.eval('!document.getElementById("view-prompt").classList.contains("hidden")');
assert.equal(isPromptVisible, true);
const promptVal = await cdp.eval('document.getElementById("prompt-input").value');
assert.equal(promptVal, 'How do I deploy service X?', 'Prompt text must be preserved');
});
// Test 11: Query Cancellation in Loading View & Busy Recovery
await step('Query Cancellation in Loading View & Busy Recovery', async () => {
// Switch scenario to delayed_cancellation
await cdp.eval(`
fetch("/dev/scenario", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scenario: "delayed_cancellation" })
})
`);
// Submit query
await cdp.eval('document.getElementById("submit-btn").click()');
await new Promise((r) => setTimeout(r, 200));
const isLoading = await cdp.eval('!document.getElementById("view-loading").classList.contains("hidden")');
assert.equal(isLoading, true, 'Should enter loading view');
// Click Cancel
await cdp.eval('document.getElementById("cancel-btn").click()');
const isPrompt = await cdp.eval('!document.getElementById("view-prompt").classList.contains("hidden")');
assert.equal(isPrompt, true, 'Should return to prompt view on cancel');
const promptVal = await cdp.eval('document.getElementById("prompt-input").value');
assert.equal(promptVal, 'How do I deploy service X?', 'Prompt preserved on cancellation');
// Wait a tick for the client abort to propagate to server
await new Promise((r) => setTimeout(r, 80));
// Retry while cleanup is still pending (server holds busy for 400ms)
await cdp.eval('document.getElementById("submit-btn").click()');
await new Promise((r) => setTimeout(r, 200));
const busyText = await cdp.eval('document.getElementById("prompt-error").textContent');
assert.ok(busyText.includes('busy'), `Should report busy while cleanup pending: ${busyText}`);
// Wait for cleanup budget to expire (400ms)
await new Promise((r) => setTimeout(r, 400));
// Reset scenario to normal and retry query
await cdp.eval(`
fetch("/dev/scenario", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scenario: "normal" })
})
`);
await cdp.eval('document.getElementById("submit-btn").click()');
await new Promise((r) => setTimeout(r, 500));
const isRecovered = await cdp.eval('!document.getElementById("view-result").classList.contains("hidden")');
assert.equal(isRecovered, true, 'Subsequent query must recover and succeed after cleanup completes');
// Return to prompt for next tests
await cdp.eval('document.getElementById("back-btn").click()');
});
// Test 12: Error Recovery (409 Busy & 504 Timeout)
await step('Error Recovery (409 Busy & 504 Timeout)', async () => {
// 409 Busy
await cdp.eval(`
fetch("/dev/scenario", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scenario: "409_busy" })
})
`);
await cdp.eval('document.getElementById("submit-btn").click()');
await new Promise((r) => setTimeout(r, 300));
const errorText = await cdp.eval('document.getElementById("prompt-error").textContent');
assert.ok(errorText.includes('busy'), `Should show busy error: ${errorText}`);
// 504 Timeout
await cdp.eval(`
fetch("/dev/scenario", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scenario: "504_timeout" })
})
`);
await cdp.eval('document.getElementById("submit-btn").click()');
await new Promise((r) => setTimeout(r, 300));
const timeoutText = await cdp.eval('document.getElementById("prompt-error").textContent');
assert.ok(timeoutText.includes('timed out'), `Should show timeout error: ${timeoutText}`);
});
// Test 13: Malicious Input, CSP Defense & History Field Sanitization
await step('Malicious Markdown, CSP Defense & History Field Sanitization', async () => {
await cdp.eval(`
fetch("/dev/scenario", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scenario: "malicious_content" })
})
`);
await cdp.eval('document.getElementById("submit-btn").click()');
await new Promise((r) => setTimeout(r, 500));
// Assert no <script> executed in document
const scriptTagsInOutput = await cdp.eval('document.querySelectorAll("#output-content script").length');
assert.equal(scriptTagsInOutput, 0, 'No executable script tags should be present in output');
// Assert no <img> or <iframe> or <form> tags survived sanitization
const imgCount = await cdp.eval('document.querySelectorAll("#output-content img").length');
const iframeCount = await cdp.eval('document.querySelectorAll("#output-content iframe").length');
const formCount = await cdp.eval('document.querySelectorAll("#output-content form").length');
assert.equal(imgCount, 0, 'No img tags allowed');
assert.equal(iframeCount, 0, 'No iframe tags allowed');
assert.equal(formCount, 0, 'No form tags allowed');
// Assert malicious javascript: link had href removed
const jsLinkHasHref = await cdp.eval(`
Array.from(document.querySelectorAll("#output-content a")).some(a => a.href && a.href.startsWith("javascript:"))
`);
assert.equal(jsLinkHasHref, false, 'No javascript: href links permitted');
// History field sanitization check
await cdp.eval('document.getElementById("history-toggle-btn").click()');
await cdp.eval('document.querySelectorAll(".tool-expand-btn")[0].click()');
await new Promise((r) => setTimeout(r, 100));
const historyScripts = await cdp.eval('document.querySelectorAll("#history-content script").length');
const historyImgs = await cdp.eval('document.querySelectorAll("#history-content img").length');
assert.equal(historyScripts, 0, 'No script tags in history content');
assert.equal(historyImgs, 0, 'No img tags in history content');
const toolParamText = await cdp.eval('document.querySelectorAll(".tool-result-box")[0].textContent');
assert.ok(toolParamText.includes('xss-param'), 'Parameters rendered safely as plain text');
});
// Test 14: Large Output & Bounded Section Navigation
await step('Large Output & Bounded Section Navigation', async () => {
await cdp.eval(`
fetch("/dev/scenario", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ scenario: "large_output" })
})
`);
await cdp.eval('document.getElementById("back-btn").click()');
await cdp.eval('document.getElementById("submit-btn").click()');
await new Promise((r) => setTimeout(r, 800));
// Check section navigation banner
const isNavVisible = await cdp.eval('!document.getElementById("section-nav").classList.contains("hidden")');
assert.equal(isNavVisible, true, 'Section nav should be visible for large document');
const navText = await cdp.eval('document.querySelector(".section-nav-banner").textContent');
assert.ok(navText.includes('Showing section 1'), `Should show section 1: ${navText}`);
// Click Next
await cdp.eval('document.querySelectorAll(".section-btn")[1].click()');
const nextNavText = await cdp.eval('document.querySelector(".section-nav-banner").textContent');
assert.ok(nextNavText.includes('Showing section 2'), `Should show section 2: ${nextNavText}`);
// Click Previous
await cdp.eval('document.querySelectorAll(".section-btn")[0].click()');
const prevNavText = await cdp.eval('document.querySelector(".section-nav-banner").textContent');
assert.ok(prevNavText.includes('Showing section 1'), `Should return to section 1: ${prevNavText}`);
});
// Test 15: Clear Credentials
await step('Clear Credentials Memory & Guard', async () => {
await cdp.eval('document.getElementById("key-btn").click()');
await cdp.eval('document.getElementById("btn-clear-cred").click()');
const isActive = await cdp.eval('document.getElementById("cred-indicator").classList.contains("active")');
assert.equal(isActive, false, 'Indicator should be deactivated after clear');
await cdp.eval('document.getElementById("modal-close-btn").click()');
await cdp.eval('document.getElementById("back-btn").click()');
// Attempt submit without credentials
await cdp.eval('document.getElementById("submit-btn").click()');
const promptErr = await cdp.eval('document.getElementById("prompt-error").textContent');
assert.ok(promptErr.includes('credentials required'), 'Submitting without credentials must show error');
const modalReopened = await cdp.eval('!document.getElementById("modal-backdrop").classList.contains("hidden")');
assert.equal(modalReopened, true, 'Modal should open when attempting query without credentials');
});
// Test 16: Zero Automatic External Requests Network Assertion
await step('Zero Automatic External Requests Network Assertion', async () => {
// Filter any requests initiated to destinations other than loopback mock server or internal data/blob URLs
const externalRequests = cdp.networkRequests.filter((r) => {
const url = r.request.url;
if (url.startsWith(`http://127.0.0.1:${MOCK_PORT}/`) || url.startsWith('data:') || url.startsWith('blob:')) {
return false;
}
return true;
});
assert.equal(
externalRequests.length,
0,
`Zero automatic external requests permitted! Found: ${externalRequests.map((r) => r.request.url).join(', ')}`
);
});
} finally {
cdp.close();
server.close();
}
console.log(`\n=== E2E Test Results: ${passed} passed, ${failed} failed ===`);
if (failed > 0) {
process.exit(1);
}
}
runTests().catch((err) => {
console.error('Fatal E2E error:', err);
process.exit(1);
});

View File

@ -0,0 +1,149 @@
/**
* Unit tests for render.js partitioning, export, and bounded history helpers.
*/
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import {
partitionMarkdown,
renderMarkdownSectionToFragment,
SECTION_TARGET_BYTES,
SECTION_HARD_LIMIT_BYTES,
PATHOLOGICAL_BLOCK_LIMIT,
getUtf8Bytes
} from '../js/render.js';
import { serializeBounded } from '../js/history.js';
describe('Render module helpers and partition logic', () => {
test('partitionMarkdown returns single section for normal sized text', () => {
const text = '# Small Document\n\nThis is a short markdown text.';
const sections = partitionMarkdown(text);
assert.equal(sections.length, 1);
assert.equal(sections[0].text, text);
});
test('partitionMarkdown splits large documents at heading/blank line boundaries', () => {
// Generate text exceeding SECTION_TARGET_BYTES (~48 KiB)
const part1 = '# Section One\n' + 'Content line.\n'.repeat(3500);
const part2 = '# Section Two\n' + 'More content line.\n'.repeat(3500);
const combined = `${part1}\n\n${part2}`;
const sections = partitionMarkdown(combined);
assert.ok(sections.length >= 2, 'Large text should be partitioned into at least 2 sections');
assert.ok(sections[0].text.includes('Section One'));
assert.ok(sections[1].text.includes('Section Two'));
});
test('partitionMarkdown forces split inside giant 12 MB code fence and re-opens fence', () => {
// 12 MB code fence (runtime probe from H1)
const line = 'const val = 1234567890;\n';
const linesCount = Math.ceil((12 * 1024 * 1024) / line.length);
const codeBlock = '```typescript\n' + line.repeat(linesCount) + '```\n';
const sections = partitionMarkdown(codeBlock);
assert.ok(sections.length > 100, `12 MB fence must be split into multiple sections, got ${sections.length}`);
// Every section must stay strictly bounded
for (let i = 0; i < sections.length; i++) {
const secBytes = getUtf8Bytes(sections[i].text);
assert.ok(secBytes <= SECTION_HARD_LIMIT_BYTES + 1024, `Section ${i} size ${secBytes} must be <= hard limit`);
// Each section must be a valid closed code block
const text = sections[i].text.trim();
assert.ok(text.startsWith('```typescript'), `Section ${i} must open with code fence`);
assert.ok(text.endsWith('```'), `Section ${i} must close with code fence`);
}
});
test('partitionMarkdown splits dense 2.2 MB list with no blank lines into bounded sections', () => {
// 2.2 MB dense list (runtime probe from H1)
const listItem = '- Item with detailed specification text and metadata\n';
const itemsCount = Math.ceil((2.2 * 1024 * 1024) / listItem.length);
const denseList = listItem.repeat(itemsCount);
const sections = partitionMarkdown(denseList);
assert.ok(sections.length >= 30, `2.2 MB dense list must be partitioned, got ${sections.length} sections`);
for (let i = 0; i < sections.length; i++) {
const secBytes = getUtf8Bytes(sections[i].text);
assert.ok(secBytes <= SECTION_HARD_LIMIT_BYTES + 512, `Section ${i} size ${secBytes} must not exceed hard limit`);
}
});
test('partitionMarkdown partitions ~122 MB simulated answer into bounded sections', () => {
// 122 MB simulated answer (from H1 runtime probe)
// Construct in chunks to avoid single-line issues
const chunk = '# Header\n' + 'Paragraph content line for analysis.\n'.repeat(1000); // ~37 KB
const chunkBytes = getUtf8Bytes(chunk);
const repetitions = Math.ceil((122 * 1024 * 1024) / chunkBytes);
const hugeDoc = chunk.repeat(repetitions);
const sections = partitionMarkdown(hugeDoc);
assert.ok(sections.length >= 1000, `122 MB document must partition into >1000 sections, got ${sections.length}`);
for (let i = 0; i < Math.min(20, sections.length); i++) {
assert.ok(getUtf8Bytes(sections[i].text) <= SECTION_HARD_LIMIT_BYTES + 512);
}
});
test('partitionMarkdown splits large tables at row boundaries and repeats table headers', () => {
const header = '| Column 1 | Column 2 | Column 3 |\n|---|---|---|\n';
const row = '| data alpha | data beta | data gamma |\n';
const table = header + row.repeat(3000); // ~120 KB
const sections = partitionMarkdown(table);
assert.ok(sections.length >= 2, 'Large table should partition into multiple sections');
// Section 2 should continue with repeated table header
assert.ok(sections[1].text.includes('| Column 1 | Column 2 | Column 3 |'), 'Subsequent section must repeat table header');
assert.ok(sections[1].text.includes('|---|---|---|'), 'Subsequent section must repeat table separator');
});
test('partitionMarkdown handles multibyte UTF-8 byte boundary correctly', () => {
// 4-byte UTF-8 emoji
const emojiLine = '🚀'.repeat(500) + '\n'; // 2000 bytes per line
const multibyteDoc = emojiLine.repeat(40); // 80,000 bytes
const sections = partitionMarkdown(multibyteDoc);
assert.ok(sections.length >= 2, 'Should partition multibyte document based on byte size');
for (const sec of sections) {
assert.ok(getUtf8Bytes(sec.text) <= SECTION_HARD_LIMIT_BYTES + 2048);
}
});
test('partitionMarkdown falls back to bounded plain-text for single pathological line', () => {
// Single line exceeding 128 KiB
const hugeLine = 'A'.repeat(150 * 1024);
const sections = partitionMarkdown(hugeLine);
assert.ok(sections.length >= 1);
assert.ok(sections[0].isPathologicalFallback);
assert.ok(sections[0].text.includes('Block truncated for performance'));
assert.ok(sections[0].text.length < 35 * 1024);
});
test('renderMarkdownSectionToFragment fails safe when marked or DOMPurify absent', () => {
// In Node test environment, window.marked and window.DOMPurify are undefined
const rawUntrusted = '<script>alert("xss")</script><img src="x" onerror="alert(1)">';
const fragment = renderMarkdownSectionToFragment(rawUntrusted);
// Must return a safe DocumentFragment containing the render error notice, NEVER raw innerHTML
assert.ok(fragment);
if (typeof document !== 'undefined') {
const notice = fragment.querySelector('.render-error-notice');
assert.ok(notice, 'Must contain error notice when parser/sanitizer is absent');
assert.ok(!fragment.querySelector('script'), 'Must never inject script tags');
assert.ok(!fragment.querySelector('img'), 'Must never inject img tags');
}
});
test('serializeBounded bounds huge 10 MB objects to <= 32 KiB without memory exhaustion', () => {
const hugeObject = {
title: 'Large Tool Result',
markdown: 'x'.repeat(10 * 1024 * 1024), // 10 MB string
items: Array.from({ length: 50000 }, (_, i) => ({ id: i, name: `item_${i}` }))
};
const serialized = serializeBounded(hugeObject, 32 * 1024);
assert.ok(serialized.length <= 34 * 1024, `Serialized result length ${serialized.length} must be bounded around 32 KB`);
assert.ok(serialized.includes('Result display bounded to 32.0 KB'), 'Must include truncation indicator');
});
});

202
frontend/vendor/dompurify.LICENSE vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

44
frontend/vendor/marked.LICENSE vendored Normal file
View File

@ -0,0 +1,44 @@
# License information
## Contribution License Agreement
If you contribute code to this project, you are implicitly allowing your code
to be distributed under the MIT license. You are also implicitly verifying that
all code is your original work. `</legalese>`
## Marked
Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## Markdown
Copyright © 2004, John Gruber
http://daringfireball.net/
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

80
frontend/vendor/marked.min.js vendored Normal file

File diff suppressed because one or more lines are too long

3
frontend/vendor/purify.min.js vendored Normal file

File diff suppressed because one or more lines are too long