diff --git a/packages/webui/src/public/files.css b/packages/webui/src/public/files.css new file mode 100644 index 000000000..88d4e98f6 --- /dev/null +++ b/packages/webui/src/public/files.css @@ -0,0 +1,4 @@ +.mosaic-files { min-width: 0; } +.mosaic-files-request { border: 1px solid var(--border); border-radius: 6px; padding: 1rem; margin-block: 1rem; overflow-wrap: anywhere; } +.mosaic-files-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; } +.mosaic-files-actions a { display: inline-flex; align-items: center; min-height: 44px; } diff --git a/packages/webui/src/public/files.js b/packages/webui/src/public/files.js new file mode 100644 index 000000000..5021dcb9d --- /dev/null +++ b/packages/webui/src/public/files.js @@ -0,0 +1,78 @@ +/* The caller supplies request IDs, never paths or authority. Every mount reads the owner API. */ +(() => { + 'use strict'; + const id = value => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(value); + const generations = new WeakMap(); + let signedOut = false; + document.addEventListener('mosaic-signed-out', () => { signedOut = true; document.querySelectorAll('.mosaic-files').forEach(el => el.replaceChildren()); }); + function element(tag, content, className) { + const node = document.createElement(tag); + if (content !== undefined) node.textContent = content; + if (className) node.className = className; + return node; + } + async function read(url) { + try { + const response = await fetch(url, { cache: 'no-store', redirect: 'manual' }); + if (response.status === 401 || response.type === 'opaqueredirect') { + if (!signedOut) document.dispatchEvent(new CustomEvent('mosaic-signed-out', { detail: { signIn: true } })); + return null; + } + return response.ok ? await response.json() : null; + } catch { return null; } + } + function link(label, href, download) { + const a = element('a', label); + a.href = href; + if (download) a.setAttribute('download', ''); + else { a.target = '_blank'; a.rel = 'noopener noreferrer'; } + return a; + } + async function mount({ container, requestIds }) { + if (!(container instanceof Element)) return; + const generation = (generations.get(container) || 0) + 1; + generations.set(container, generation); + container.classList.add('mosaic-files'); + container.replaceChildren(element('h3', 'Files'), element('p', 'Reading files…')); + const ids = Array.isArray(requestIds) ? [...new Set(requestIds.filter(id))] : []; + const results = await Promise.all(ids.map(async request => { + const base = `/api/requests/${encodeURIComponent(request)}`; + const [state, workspace] = await Promise.all([read(base), read(`${base}/workspace`)]); + return { request, base, state, workspace }; + })); + if (signedOut || generations.get(container) !== generation || document.body.classList.contains('signed-out')) return; + container.replaceChildren(element('h3', 'Files')); + if (!ids.length) { container.append(element('p', 'No request files are available.')); return; } + for (const { request, base, state, workspace } of results) { + const section = element('section', undefined, 'mosaic-files-request'); + section.append(element('h4', `Request ${request}`), element('h5', 'Reviewed delivery')); + const d = state?.delivery_evidence; + if (state?.version === 1 && state.request === request && Number.isSafeInteger(state.revision) && state.revision > 0 && typeof state.phase === 'string' && id(state.delivery) && d?.id === state.delivery && d.request === request && typeof d.artifact?.path === 'string') { + const filename = d.artifact.path.split('/').at(-1); + if (/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(filename)) { + const row = element('p', undefined, 'mosaic-files-actions'); + row.append(element('span', filename), link('Open as text', `${base}/artifact/${encodeURIComponent(d.id)}/text`, false), link('Download', `${base}/artifact/${encodeURIComponent(d.id)}`, true)); + section.append(row, element('p', 'Open shows plain text in a new tab. Downloaded HTML can be opened locally after saving.')); + } else section.append(element('p', 'Reviewed file is unavailable.')); + } else section.append(element('p', state ? 'No reviewed file is available.' : 'Reviewed files are unavailable.')); + section.append(element('p', 'No request-bound pull request link is available.')); + section.append(element('h5', 'Product workspace, draft')); + if (!workspace || workspace.available !== true || !Array.isArray(workspace.entries)) { + section.append(element('p', 'Draft workspace is unavailable.')); + } else { + section.append(element('p', 'Names only. Draft files may change and are not reviewed deliveries.')); + if (!workspace.entries.length) section.append(element('p', 'No draft files found.')); + else { + const list = element('ul'); + for (const entry of workspace.entries.slice(0, 100)) { + if (typeof entry?.name === 'string') list.append(element('li', entry.name)); + } + section.append(list); + } + if (workspace.truncated) section.append(element('p', 'The draft list was truncated.')); + } + container.append(section); + } + } + window.MosaicFiles = Object.freeze({ mount }); +})(); diff --git a/packages/webui/src/request-http.mjs b/packages/webui/src/request-http.mjs index bb98a21f0..369e41c51 100644 --- a/packages/webui/src/request-http.mjs +++ b/packages/webui/src/request-http.mjs @@ -20,7 +20,7 @@ import { BusReadError } from './bus.mjs'; import { createHash } from 'node:crypto'; import { CONSOLE_VERBS } from '../../bus/src/broker.mjs'; -export const REQUEST_ROUTE = /^\/api\/requests\/([^/]+)(?:\/(projects|draft|answer|attach|mode|cancel|revoke)|\/(artifact)\/([^/]+))?$/; +export const REQUEST_ROUTE = /^\/api\/requests\/([^/]+)(?:\/(projects|draft|answer|attach|mode|cancel|revoke)|\/(artifact)\/([^/]+)(\/(?:text))?)?$/; const WRITE_VERBS = Object.freeze({ answer: 'request.answer.console', attach: 'request.attach.console', mode: 'request.mode.console', cancel: 'request.cancel.console', revoke: 'prd.revoke.console', }); @@ -147,7 +147,7 @@ const picker = v => Array.isArray(v) && v.every(p => p && typeof p === 'object' // transports; either is null when the Console has no such transport. `verbs` is the console verb // list: the draft read exists only while it names `request.draft.console`. export async function requestHTTP(req, res, { path, requestRead, requestWrite, session, live, origin, log, verbs = CONSOLE_VERBS }) { - const [, raw, suffix, artifactSuffix, rawDelivery] = REQUEST_ROUTE.exec(path); + const [, raw, suffix, artifactSuffix, rawDelivery, textSuffix] = REQUEST_ROUTE.exec(path); const action = suffix ?? artifactSuffix ?? 'get'; const write = Object.hasOwn(WRITE_VERBS, action); let id = null; @@ -189,7 +189,9 @@ export async function requestHTTP(req, res, { path, requestRead, requestWrite, s const bytes = Buffer.from(artifact.base64, 'base64'); if (bytes.length > 1024 * 1024 || bytes.toString('base64') !== artifact.base64 || createHash('sha256').update(bytes).digest('hex') !== artifact.sha256) return refuse('unavailable'); line(''); - res.writeHead(200, { 'content-type': artifact.mime, 'content-disposition': `attachment; filename="${artifact.filename}"`, 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' }); + res.writeHead(200, textSuffix + ? { 'content-type': 'text/plain; charset=utf-8', 'content-security-policy': "sandbox; default-src 'none'", 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' } + : { 'content-type': artifact.mime, 'content-disposition': `attachment; filename="${artifact.filename}"`, 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' }); return res.end(bytes); } const verb = READ_VERBS[action]; diff --git a/packages/webui/src/serve.mjs b/packages/webui/src/serve.mjs index 3fb2cb5f4..628e10a79 100644 --- a/packages/webui/src/serve.mjs +++ b/packages/webui/src/serve.mjs @@ -34,6 +34,8 @@ const files = new Map([ ['/settings/model-proxy', ['proxy.html', 'text/html; charset=utf-8']], ['/proxy.js', ['proxy.js', 'text/javascript; charset=utf-8']], ...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js', 'processing.js', 'agents.js', 'federation.js', 'requests.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]), + ['/files.js', ['files.js', 'text/javascript; charset=utf-8']], + ['/files.css', ['files.css', 'text/css; charset=utf-8']], ...['shared/app.css', 'tokens.css', 'console.css', 'live.css', 'bus.css', 'shell.css', 'chat.css', 'processing.css'].map(f => ['/' + f, [f, 'text/css; charset=utf-8']]), ['/editor.js', ['editor.js', 'text/javascript; charset=utf-8']], // Row 225 (C2-10b): the one reply renderer, shared with the Discord relay, imported by chat.js. diff --git a/packages/webui/tests/artifact-http.test.mjs b/packages/webui/tests/artifact-http.test.mjs index 64effb28b..94bb0e35e 100644 --- a/packages/webui/tests/artifact-http.test.mjs +++ b/packages/webui/tests/artifact-http.test.mjs @@ -37,3 +37,31 @@ test('artifact access refuses foreign ownership, tampered bytes and expired sess assert.equal((await attempt(async verb => verb === 'request.get.console' ? state : { mime: 'text/html', filename: 'timer.html', base64: 'eA==', sha256: '0'.repeat(64) })).status, 503); assert.equal((await attempt(async () => state, () => null)).status, 401); }); + +test('text view is inert and uses the same current delivery and digest checks', async () => { + const path = '/api/requests/r1/artifact/d1/text'; + assert.match(path, REQUEST_ROUTE); + const bytes = Buffer.from(''); + const session = { name: 'owner', provider: 'test', iss: 'test', sub: 'owner' }; + const req = { method: 'GET', headersDistinct: { 'sec-fetch-site': ['same-origin'] } }; + const state = { version: 1, request: 'r1', revision: 1, phase: 'complete', delivery: 'd1' }; + const artifact = { mime: 'text/html', filename: 'timer.html', base64: bytes.toString('base64'), sha256: createHash('sha256').update(bytes).digest('hex') }; + const attempt = async (read, live = () => session) => { + const res = { writeHead(status, headers) { this.status = status; this.headers = headers; }, end(data) { this.data = data; } }; + await requestHTTP(req, res, { path, session, live, origin: 'https://console.test', log() {}, requestRead: read }); + return res; + }; + const good = await attempt(async verb => verb === 'request.get.console' ? state : artifact); + assert.equal(good.status, 200); + assert.deepEqual(good.data, bytes); + assert.equal(good.headers['content-type'], 'text/plain; charset=utf-8'); + assert.equal(good.headers['x-content-type-options'], 'nosniff'); + assert.equal(good.headers['content-security-policy'], "sandbox; default-src 'none'"); + assert.equal(good.headers['cache-control'], 'private, no-store'); + assert.equal((await attempt(async verb => verb === 'request.get.console' ? { ...state, delivery: 'd2' } : artifact)).status, 404); + assert.equal((await attempt(async verb => verb === 'request.get.console' ? state : { ...artifact, sha256: '0'.repeat(64) })).status, 503); + let reads = 0; + assert.equal((await attempt(async verb => { reads++; return verb === 'request.get.console' ? state : artifact; }, () => reads < 2 ? session : null)).status, 401); + assert.doesNotMatch('/api/requests/r1/artifact/d1/text/extra', REQUEST_ROUTE); + assert.doesNotMatch('/api/requests/r1/artifact/d1/html', REQUEST_ROUTE); +}); diff --git a/packages/webui/tests/helpers/w15-files.mjs b/packages/webui/tests/helpers/w15-files.mjs new file mode 100644 index 000000000..bcbff182a --- /dev/null +++ b/packages/webui/tests/helpers/w15-files.mjs @@ -0,0 +1,27 @@ +import { fixture } from '../fixture.mjs'; +import { browser } from '../browser.mjs'; + +// This isolated slice has no shell mount yet. Attach the actual feature to the local Console fixture. +export async function filesFixture(t) { + const f = await fixture(); t.after(() => f.close()); + const b = await browser({ machine: false }); t.after(() => b.close()); + const errors = []; + b.on('Runtime.exceptionThrown', event => errors.push(event.exceptionDetails.text)); + await b.call('Fetch.enable', { patterns: [{ urlPattern: '*' }] }); + b.on('Fetch.requestPaused', e => { + const same = e.request.url.startsWith(f.base + '/') || e.request.url === 'about:blank'; + b.call(same ? 'Fetch.continueRequest' : 'Fetch.failRequest', same ? { requestId: e.requestId } : { requestId: e.requestId, errorReason: 'BlockedByClient' }).catch(error => errors.push(error.message)); + }); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { + const real = window.fetch.bind(window); + window.fixtureState = null; window.fixtureWorkspace = null; + window.fetch = async (url, init) => { + const path = String(url); + if (path === '/api/requests/request-1') return new Response(JSON.stringify(window.fixtureState), {status: 200, headers: {'content-type':'application/json'}}); + if (path === '/api/requests/request-1/workspace') return window.fixtureWorkspace === null ? new Response('{}', {status: 503}) : new Response(JSON.stringify(window.fixtureWorkspace), {status: 200, headers: {'content-type':'application/json'}}); + if (path.startsWith('/api/')) return new Response('{}', {status: 503}); + return real(url, init); + }; + })();` }); + return { f, b, errors }; +} diff --git a/packages/webui/tests/w15-files-browser.test.mjs b/packages/webui/tests/w15-files-browser.test.mjs new file mode 100644 index 000000000..cbf6aedc9 --- /dev/null +++ b/packages/webui/tests/w15-files-browser.test.mjs @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { writeFile } from 'node:fs/promises'; +import { filesFixture } from './helpers/w15-files.mjs'; + +test('Files mount reads request identity and presents safe reviewed links and unavailable draft', async t => { + const { f, b, errors } = await filesFixture(t); + const shots = process.env.MOSAIC_UX_SHOTS; + const state = { version: 1, revision: 1, phase: 'complete', request: 'request-1', delivery: 'delivery-1', delivery_evidence: { id: 'delivery-1', request: 'request-1', artifact: { path: 'output/timer.html' } } }; + for (const width of [1440, 390]) { + await b.viewport(width, 1000); + await b.navigate(f.base + '/#/'); + await b.evaluate(`(async () => { + const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = '/files.css'; document.head.append(css); + await new Promise((resolve, reject) => { const s = document.createElement('script'); s.src = '/files.js'; s.onload = resolve; s.onerror = reject; document.head.append(s); }); + window.fixtureState = ${JSON.stringify(state)}; + const main = document.querySelector('#main'); main.replaceChildren(); const mount = document.createElement('div'); mount.id = 'slice-fixture'; main.append(mount); + await window.MosaicFiles.mount({container: mount, requestIds: ['request-1']}); + })()`); + assert.match(await b.evaluate("document.querySelector('#slice-fixture').textContent"), /Reviewed delivery.*timer.html.*Open as text.*Download.*Product workspace, draft.*unavailable/s); + assert.equal(await b.evaluate("document.querySelector('#slice-fixture a').getAttribute('href')"), '/api/requests/request-1/artifact/delivery-1/text'); + assert.equal(await b.evaluate("document.querySelector('#slice-fixture a').rel"), 'noopener noreferrer'); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= innerWidth'), true); + if (shots) { + await b.screenshot(join(shots, `files-isolated-unavailable-${width}.png`)); + const { cssContentSize } = await b.call('Page.getLayoutMetrics'); + const { data } = await b.call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: { x: 0, y: 0, width: cssContentSize.width, height: cssContentSize.height, scale: 1 } }); + await writeFile(join(shots, `files-isolated-unavailable-${width}-full.png`), Buffer.from(data, 'base64')); + } + } + await b.evaluate(`(async () => { window.fixtureState.request = 'foreign'; await MosaicFiles.mount({container: document.querySelector('#slice-fixture'), requestIds:['request-1']}); })()`); + assert.equal(await b.evaluate("document.querySelectorAll('#slice-fixture a').length"), 0); + assert.deepEqual(errors, []); +});