From 00e81d787c193c16b2ba821e0ca257abc95b12b8 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 18:00:48 +0800 Subject: [PATCH 1/4] =?UTF-8?q?refactor(headless):=20=E5=85=B1=E7=94=A8?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E8=B5=84=E6=96=99=E6=A0=A1=E9=AA=8C=E8=BE=B9?= =?UTF-8?q?=E7=95=8C=20/=20share=20document=20validation=20limits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/headless/project-docs-format.ts | 9 +++++++++ apps/desktop/src/headless/project-snapshot.ts | 10 ++++------ 2 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 apps/desktop/src/headless/project-docs-format.ts diff --git a/apps/desktop/src/headless/project-docs-format.ts b/apps/desktop/src/headless/project-docs-format.ts new file mode 100644 index 00000000..ab965ef7 --- /dev/null +++ b/apps/desktop/src/headless/project-docs-format.ts @@ -0,0 +1,9 @@ +// Byte limits shared by the offline validator, startup publication and browser reader. +export const MAX_PROJECT_DOCUMENTS = 32 +export const MAX_PROJECT_TEXT_BYTES = 256 * 1024 +export const MAX_PROJECT_LIST_JSON = 32 * 1024 +export const MAX_PROJECT_DETAIL_JSON = 200 * 1024 +const badLabel = /[/:\\\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069\uD800-\uDFFF]/u +const utf8 = new TextEncoder() +export const isProjectDocsLabel = (v: unknown): v is string => typeof v === 'string' && v.length > 0 && + v.length <= 80 && v === v.trim() && v !== '.' && v !== '..' && !badLabel.test(v) && utf8.encode(v).length <= 80 diff --git a/apps/desktop/src/headless/project-snapshot.ts b/apps/desktop/src/headless/project-snapshot.ts index cff442e5..edc455c2 100644 --- a/apps/desktop/src/headless/project-snapshot.ts +++ b/apps/desktop/src/headless/project-snapshot.ts @@ -1,10 +1,9 @@ import { createHash } from 'node:crypto' import { isSharedArrayBuffer, isUint8Array } from 'node:util/types' import { textAttachmentProblem } from './text-file' +import { isProjectDocsLabel, MAX_PROJECT_DOCUMENTS, MAX_PROJECT_TEXT_BYTES } from './project-docs-format' export const MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024 -const MAX_DOCUMENTS = 32, MAX_TOTAL_TEXT_BYTES = 256 * 1024 -const badProjectChar = /[/:\\\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069\uD800-\uDFFF]/u export const isSnapshotDigest = (v: unknown): v is string => typeof v === 'string' && v.length === 64 && !/[^a-f0-9]/u.test(v) type ErrorCode = 'invalid_digest' | 'digest_mismatch' | 'invalid_snapshot' | 'snapshot_limit' export class SnapshotError extends Error { @@ -56,13 +55,12 @@ function parseV1(source: string): ProjectSnapshot { if (key === 'version') { expect('1'); return } if (key === 'project') { project = string() - if (!project || project !== project.trim() || project === '.' || project === '..' || - badProjectChar.test(project) || Buffer.byteLength(project) > 80) invalid() + if (!isProjectDocsLabel(project)) invalid() return } expect('[') do { - if (documents.length >= MAX_DOCUMENTS) limit() + if (documents.length >= MAX_PROJECT_DOCUMENTS) limit() let name = '', text = '' object(['name', 'text'], field => { if (field === 'name') name = string(); else text = string() }) const issue = textAttachmentProblem({ name, text }) @@ -73,7 +71,7 @@ function parseV1(source: string): ProjectSnapshot { names.add(canonical) const bytes = Buffer.byteLength(text) totalTextBytes += bytes - if (totalTextBytes > MAX_TOTAL_TEXT_BYTES) limit() + if (totalTextBytes > MAX_PROJECT_TEXT_BYTES) limit() documents.push(Object.freeze({ name, text, bytes })) } while (take(',')) expect(']') From faee04a2c7bf44a7fafc2e3baf7dffeb7614b1ca Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 18:00:48 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(headless):=20=E5=8F=AA=E4=BB=8E?= =?UTF-8?q?=E5=B7=B2=E6=A0=B8=E5=87=86=E7=9A=84=E5=8F=AA=E8=AF=BB=E6=8C=82?= =?UTF-8?q?=E8=BD=BD=E5=8F=91=E5=B8=83=E8=B5=84=E6=96=99=20/=20serve=20doc?= =?UTF-8?q?uments=20from=20a=20verified=20read-only=20file=20mount?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/headless/access.ts | 4 +- .../desktop/src/headless/project-documents.ts | 27 ++ apps/desktop/src/headless/project-mount.ts | 155 ++++++++++++ apps/desktop/src/headless/server.ts | 40 ++- apps/desktop/test/project-docs-mount.test.mjs | 237 ++++++++++++++++++ apps/desktop/test/project-documents.test.mjs | 30 +++ 6 files changed, 486 insertions(+), 7 deletions(-) create mode 100644 apps/desktop/src/headless/project-documents.ts create mode 100644 apps/desktop/src/headless/project-mount.ts create mode 100644 apps/desktop/test/project-docs-mount.test.mjs create mode 100644 apps/desktop/test/project-documents.test.mjs diff --git a/apps/desktop/src/headless/access.ts b/apps/desktop/src/headless/access.ts index 5684c63b..8f860b95 100644 --- a/apps/desktop/src/headless/access.ts +++ b/apps/desktop/src/headless/access.ts @@ -64,9 +64,9 @@ export function lockHome(): number { } catch (err) { closeSync(fd); throw err } } -type Session = { expires: number; aborts: Set<() => void> } +export type OwnerSession = { expires: number; aborts: Set<() => void> } export function sessions(owner: Buffer, secure: boolean) { - const users = new Map(), name = secure ? '__Host-deva_web' : 'deva_web' + const users = new Map(), name = secure ? '__Host-deva_web' : 'deva_web' const cookie = (id: string, seconds: number) => `${name}=${id}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${seconds}${secure ? '; Secure' : ''}` const forget = (id: string) => { const s = users.get(id); users.delete(id); for (const stop of s?.aborts ?? []) stop() } const idOf = (req: IncomingMessage) => { diff --git a/apps/desktop/src/headless/project-documents.ts b/apps/desktop/src/headless/project-documents.ts new file mode 100644 index 00000000..5a287cdd --- /dev/null +++ b/apps/desktop/src/headless/project-documents.ts @@ -0,0 +1,27 @@ +import { randomBytes } from 'node:crypto' +import { MAX_PROJECT_DETAIL_JSON, MAX_PROJECT_LIST_JSON } from './project-docs-format' +import { SnapshotError, type ProjectSnapshot } from './project-snapshot' + +export const PROJECT_DOCS = '/api/project-docs' +const opaqueId = () => randomBytes(16).toString('hex') +export type ProjectResponse = Readonly<{ json: string; bytes: number }> + +function encode(value: unknown, maxBytes: number): ProjectResponse { + const json = JSON.stringify(value), bytes = Buffer.byteLength(json) + if (bytes > maxBytes) throw new SnapshotError('snapshot_limit') + return Object.freeze({ json, bytes }) +} + +/** An immutable, process-local publication. A URL is an exact lookup key, never a filesystem path. */ +export function projectDocumentResponses(snapshot: ProjectSnapshot | undefined) { + if (!snapshot) return undefined + const generation = opaqueId(), responses = new Map() + const documents = snapshot.documents.map(({ name, text, bytes }) => { + let id: string, path: string + do { id = opaqueId(); path = `${PROJECT_DOCS}/${generation}/${id}` } while (responses.has(path)) + responses.set(path, encode({ generation, id, name, bytes, text }, MAX_PROJECT_DETAIL_JSON)) + return { id, name, bytes } + }) + responses.set(PROJECT_DOCS, encode({ project: snapshot.project, generation, documents }, MAX_PROJECT_LIST_JSON)) + return (path: string) => responses.get(path) +} diff --git a/apps/desktop/src/headless/project-mount.ts b/apps/desktop/src/headless/project-mount.ts new file mode 100644 index 00000000..a8c8fc32 --- /dev/null +++ b/apps/desktop/src/headless/project-mount.ts @@ -0,0 +1,155 @@ +import { + closeSync, constants, fstatSync, lstatSync, openSync, readlinkSync, readSync, statfsSync, statSync, + type BigIntStats, +} from 'node:fs' +import { isSnapshotDigest, MAX_SNAPSHOT_BYTES, SnapshotError, validateProjectSnapshot, type ProjectSnapshot } from './project-snapshot' + +const TARGET = '/run/deva-project-docs/snapshot.json' +const PROC = '/proc/self' +const PROC_MAGIC = 0x9fa0 +const PIN = 0o10000000 | constants.O_NOFOLLOW // Linux O_PATH is absent from Node's constants. +const READ = constants.O_RDONLY | constants.O_NONBLOCK +const FDINFO_LIMIT = 4096, MOUNTINFO_LIMIT = 4 * 1024 * 1024 + +type MountErrorCode = 'invalid_mount' | 'mount_changed' +export class SnapshotMountError extends Error { + constructor(readonly code: MountErrorCode) { super(code) } +} + +type Pin = { fd: number; stat: BigIntStats } +const sameInode = (a: BigIntStats, b: BigIntStats): boolean => a.dev === b.dev && a.ino === b.ino +const sameFile = (a: BigIntStats, b: BigIntStats): boolean => sameInode(a, b) && + a.mode === b.mode && a.size === b.size && a.nlink === b.nlink && a.uid === b.uid && a.gid === b.gid && + a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs + +function boundedRead(fd: number, max: number, overflow: () => never): Buffer { + const buffer = Buffer.allocUnsafe(max + 1) + let used = 0 + while (used <= max) { + const count = readSync(fd, buffer, used, buffer.length - used, null) + if (!count) return buffer.subarray(0, used) + used += count + } + return overflow() +} + +export function loadMountedProjectSnapshot(expected: string | undefined): ProjectSnapshot | undefined { + if (expected === undefined) return undefined + if (!isSnapshotDigest(expected)) throw new SnapshotError('invalid_digest') + if (process.platform !== 'linux') throw new SnapshotMountError('invalid_mount') + + let code: MountErrorCode = 'invalid_mount' + const fail = (): never => { throw new SnapshotMountError(code) } + const descriptors: number[] = [] + function open(path: string, flags: number): number { + const fd = openSync(path, flags) + descriptors.push(fd) + return fd + } + function release(keep = 0): void { + while (descriptors.length > keep) { + try { closeSync(descriptors.pop()!) } catch { /* Continue closing the other descriptors. */ } + } + } + function pin(path: string, directory = false): Pin { + const fd = open(path, PIN | (directory ? constants.O_DIRECTORY : 0)) + return { fd, stat: fstatSync(fd, { bigint: true }) } + } + + try { + const proc = pin('/proc', true) + const fds = pin(`${PROC}/fd`, true), fdinfo = pin(`${PROC}/fdinfo`, true) + const mounts = pin(`${PROC}/mountinfo`) + const pid = `/proc/${process.pid}` + function checkProc(): void { + if (statfsSync('/proc').type !== PROC_MAGIC || proc.stat.ino !== 1n || + !sameInode(lstatSync('/proc', { bigint: true }), proc.stat) || readlinkSync(PROC) !== String(process.pid)) fail() + for (const [entry, held] of [['fd', fds], ['fdinfo', fdinfo], ['mountinfo', mounts]] as const) { + if (held.stat.dev !== proc.stat.dev || !sameInode(lstatSync(`${pid}/${entry}`, { bigint: true }), held.stat)) fail() + } + } + function ref(held: Pin): string { + const path = `${PROC}/fd/${held.fd}` + const link = lstatSync(path, { bigint: true }) + if (link.dev !== proc.stat.dev || !link.isSymbolicLink() || !sameInode(statSync(path, { bigint: true }), held.stat)) fail() + return path + } + function procText(held: Pin, max: number): string { + if (held.stat.dev !== proc.stat.dev || !held.stat.isFile()) fail() + const fd = open(ref(held), READ) + if (!sameInode(fstatSync(fd, { bigint: true }), held.stat)) fail() + const text = boundedRead(fd, max, fail).toString('latin1') + if (!text.endsWith('\n') || text.includes('\0')) fail() + return text + } + function mountId(fd: number): string { + const keep = descriptors.length + try { + const info = pin(`${ref(fdinfo)}/${fd}`) + const ids = procText(info, FDINFO_LIMIT).split('\n').filter(line => line.startsWith('mnt_id:')) + const match = /^mnt_id:[\t ]+([1-9][0-9]{0,9})$/.exec(ids[0] ?? '') + if (ids.length !== 1 || !match) return fail() + return match[1] + } finally { release(keep) } + } + function checkMount(leaf: string, parent: string): void { + const keep = descriptors.length + try { + checkProc() + const procId = mountId(proc.fd) + if ([fds, fdinfo, mounts].some(entry => mountId(entry.fd) !== procId) || leaf === parent) fail() + let procFound = false, leafFound = false + for (const line of procText(mounts, MOUNTINFO_LIMIT).split('\n')) { + const [id, , , root, point, flags, ...tail] = line.split(' ') + // A genuine proc root can contain unrelated mounts, but not over our metadata paths. + if (point === pid || point?.startsWith(`${pid}/`) || point === PROC || point?.startsWith(`${PROC}/`)) fail() + if (id === procId) { + const separator = tail.indexOf('-') + if (procFound || root !== '/' || point !== '/proc' || separator < 0 || tail[separator + 1] !== 'proc') fail() + procFound = true + } + if (id === leaf) { + const options = flags?.split(',') ?? [] + if (leafFound || point !== TARGET || !options.includes('ro') || options.includes('rw')) fail() + leafFound = true + } + } + if (!procFound || !leafFound) fail() + } finally { release(keep) } + } + function namedChain(): Pin[] { + const root = pin('/', true) + const run = pin(`${ref(root)}/run`, true) + const parent = pin(`${ref(run)}/deva-project-docs`, true) + return [root, run, parent, pin(`${ref(parent)}/snapshot.json`)] + } + + checkProc() + const chain = namedChain(), leaf = chain[3] + const ids = chain.map(({ fd }) => mountId(fd)) + checkMount(ids[3], ids[2]) + if (!leaf.stat.isFile() || leaf.stat.nlink !== 1n || leaf.stat.size <= 0n) fail() + const overflow = (): never => { throw new SnapshotError('snapshot_limit') } + if (leaf.stat.size > MAX_SNAPSHOT_BYTES) overflow() + + code = 'mount_changed' + const data = open(ref(leaf), READ) + const unchanged = (): boolean => sameFile(fstatSync(data, { bigint: true }), leaf.stat) && mountId(data) === ids[3] + if (!unchanged()) fail() + const bytes = boundedRead(data, MAX_SNAPSHOT_BYTES, overflow) + try { + return validateProjectSnapshot(bytes, expected) + } finally { + bytes.fill(0) + checkProc() + const current = namedChain() + if (current.some((entry, i) => !sameInode(entry.stat, chain[i].stat) || mountId(entry.fd) !== ids[i]) || + !sameFile(current[3].stat, leaf.stat) || BigInt(bytes.length) !== leaf.stat.size) fail() + checkMount(ids[3], ids[2]) + if (!unchanged() || !sameFile(fstatSync(leaf.fd, { bigint: true }), leaf.stat)) fail() + } + } catch (error) { + if (error instanceof SnapshotError || error instanceof SnapshotMountError) throw error + return fail() + } finally { release() } +} diff --git a/apps/desktop/src/headless/server.ts b/apps/desktop/src/headless/server.ts index 97fee69e..7c370bbf 100644 --- a/apps/desktop/src/headless/server.ts +++ b/apps/desktop/src/headless/server.ts @@ -2,8 +2,11 @@ import { readFileSync, readdirSync } from 'node:fs' import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import { lockHome, options, sessions } from './access' +import { lockHome, options, sessions, type OwnerSession } from './access' import { ChatError, createTextChat } from './chat' +import { loadMountedProjectSnapshot, SnapshotMountError } from './project-mount' +import { SnapshotError } from './project-snapshot' +import { PROJECT_DOCS, projectDocumentResponses, type ProjectResponse } from './project-documents' class HttpError extends Error { constructor(readonly status: number, readonly code: string) { super(code) } @@ -12,6 +15,23 @@ const fail = (status: number, code: string): never => { throw new HttpError(stat const json = (res: ServerResponse, status: number, data: unknown) => { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(JSON.stringify(data)) } +function sendDocument(res: ServerResponse, session: OwnerSession, payload: ProjectResponse): void { + const ttl = session.expires - Date.now() + if (ttl <= 0) fail(401, 'auth') + const stop = () => { res.destroy() } + const timer = setTimeout(stop, Math.min(ttl, 10_000)).unref() + const cleanup = () => { + clearTimeout(timer); session.aborts.delete(stop) + res.off('close', cleanup); res.off('finish', cleanup) + } + session.aborts.add(stop); res.once('close', cleanup); res.once('finish', cleanup) + try { + res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': payload.bytes, + 'Referrer-Policy': 'no-referrer', 'X-Deva-Session-Ttl-Ms': Math.min(ttl, 8 * 3600_000) }) + res.end(payload.json) + } catch (error) { cleanup(); throw error } +} + async function body(req: IncomingMessage, keys: string[], limit = 52 * 1024, optional: string[] = []): Promise> { if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(req.headers['content-type'] ?? '') || (req.headers['content-encoding'] ?? 'identity') !== 'identity') fail(415, 'json_required') if (Number(req.headers['content-length'] ?? 0) > limit) fail(413, 'limit') @@ -44,6 +64,8 @@ function assets() { function start() { const { host, port, site, owner, provider } = options() + // Validate the explicit grant before creating state or listening; default startup does no snapshot I/O. + const documents = projectDocumentResponses(loadMountedProjectSnapshot(process.env.DEVA_PROJECT_DOCS_SHA256)) const pages = assets(); lockHome() // FD remains open for the lifetime of this dedicated CLI process. const auth = sessions(owner, site.protocol === 'https:'), chat = createTextChat(provider) let closing = false @@ -62,14 +84,20 @@ function start() { res.writeHead(200, { 'Content-Type': page.type, 'Content-Length': page.bytes.length }); res.end(method === 'HEAD' ? undefined : page.bytes); return } if (!path.startsWith('/api/') || path.includes('?')) fail(404, 'missing') - if (method !== 'GET' && method !== 'POST') fail(405, 'method') - if (method === 'POST' && req.headers.origin !== site.origin) fail(403, 'origin') + const docRoute = path === PROJECT_DOCS || path.startsWith(`${PROJECT_DOCS}/`) + if (!docRoute && method !== 'GET' && method !== 'POST') fail(405, 'method') + if ((method === 'POST' || (docRoute && method !== 'GET' && method !== 'HEAD')) && req.headers.origin !== site.origin) fail(403, 'origin') if (method === 'POST' && path === '/api/login') { const { token } = await body(req, ['token'], 1024) const cookie = auth.login(token) ?? fail(401, 'auth') res.setHeader('Set-Cookie', cookie); return json(res, 200, { ok: true }) } const session = auth.current(req) ?? fail(401, 'auth') + if (docRoute) { + const payload = documents?.(path) ?? fail(404, 'missing') + if (method !== 'GET') { res.setHeader('Allow', 'GET'); return fail(405, 'method') } + return sendDocument(res, session, payload) + } // A slow request body may outlive this login, a closed connection or shutdown. const input = async (keys: string[], limit?: number, optional?: string[]) => { const data = await body(req, keys, limit, optional) @@ -82,7 +110,8 @@ function start() { } if (path === '/api/sessions' || path === '/api/sessions/archived') { const archived = path.endsWith('/archived') - if (method === 'GET') return json(res, 200, { model: provider.model, sessions: chat.list(archived) }) + if (method === 'GET') return json(res, 200, { model: provider.model, sessions: chat.list(archived), + ...(!archived && documents ? { projectDocs: true } : {}) }) if (archived) fail(405, 'method') await input([]); return json(res, 201, chat.create()) } @@ -143,6 +172,7 @@ function start() { try { start() } catch (err) { const message = err instanceof Error ? err.message : '' // Only our setting/directory diagnostics are safe for deployment logs; never print URLs, prompts or secrets. - console.error(/^(Invalid DEVA_|Invalid model configuration|Web data directory is busy|An empty or previously initialized)/u.test(message) ? message : 'Deva Web startup failed: check the settings, data directory and web build') + if (err instanceof SnapshotError || err instanceof SnapshotMountError) console.error(`Deva Web project documents: ${err.code}`) + else console.error(/^(Invalid DEVA_|Invalid model configuration|Web data directory is busy|An empty or previously initialized)/u.test(message) ? message : 'Deva Web startup failed: check the settings, data directory and web build') process.exitCode = 1 } diff --git a/apps/desktop/test/project-docs-mount.test.mjs b/apps/desktop/test/project-docs-mount.test.mjs new file mode 100644 index 00000000..3dabc4fe --- /dev/null +++ b/apps/desktop/test/project-docs-mount.test.mjs @@ -0,0 +1,237 @@ +import assert from 'node:assert/strict' +import { execFileSync, spawn, spawnSync } from 'node:child_process' +import { createHash, randomBytes, randomUUID } from 'node:crypto' +import { once } from 'node:events' +import * as fs from 'node:fs' +import { createServer, request } from 'node:http' +import { join, resolve } from 'node:path' +import test from 'node:test' +import { setTimeout as delay } from 'node:timers/promises' +import { fileURLToPath } from 'node:url' +import { gateway, modelStream, route } from './headless-model-wire.mjs' + +const env = { PATH: '/usr/bin:/bin', LANG: 'C' }, deadline = () => AbortSignal.timeout(5000) +const ns = kind => fs.readlinkSync(`/proc/self/ns/${kind}`) +const runId = () => { const s = fs.lstatSync('/run'); assert.ok(s.isDirectory()); return `${s.dev}:${s.ino}` } +const flags = ['--user', '--map-root-user', '--mount', '--propagation', 'private', '--'] +const wait = child => once(child, 'close').then(([code, signal]) => ({ code, signal })) +const cmd = (file, ...args) => execFileSync(file, args, { env, timeout: 3000, stdio: ['ignore', 'pipe', 'pipe'] }) +const main = import.meta.filename +const digest = bytes => createHash('sha256').update(bytes).digest('hex') +const mountRows = () => fs.readFileSync('/proc/self/mountinfo', 'utf8').trim().split('\n').map(row => row.split(' - ')[0].split(' ')) +const docPath = '/api/project-docs', sessions = '/api/sessions' +const dir = '/run/deva-project-docs', target = `${dir}/snapshot.json` +const leaf = path => mountRows().filter(row => row[4] === path) + +if (process.argv[2] === '--private') { + const [, , , parentUser, parentMount, parentRun, parentUid, bundle] = process.argv + assert.match(parentUser, /^user:\[\d+\]$/); assert.match(parentMount, /^mnt:\[\d+\]$/) + assert.equal(fs.readFileSync('/proc/self/uid_map', 'utf8').trim().split(/\s+/).join(' '), `0 ${parentUid} 1`) + assert.notEqual(ns('user'), parentUser); assert.notEqual(ns('mnt'), parentMount) + assert.equal(runId(), parentRun); assert.equal(fs.realpathSync('/run'), '/run') + assert.ok(mountRows().every(row => !row.slice(6).some(field => /^(shared|master|propagate_from):/.test(field)))) + process.umask(0o022) + cmd('mount', '-t', 'tmpfs', '-o', 'mode=0755,size=12m,nosuid,nodev,noexec', 'deva-native-test', '/run') + assert.notEqual(runId(), parentRun); assert.deepEqual(fs.readdirSync('/run'), []) + try { await qualify(bundle) } finally { cmd('umount', '/run'); assert.equal(runId(), parentRun) } +} else test('compiled project reader requires a real private RO leaf mount and revokes on restart', { timeout: 90000 }, async t => { + const probe = process.platform === 'linux' && spawnSync('unshare', [...flags, '/usr/bin/true'], { env, timeout: 5000, encoding: 'utf8' }) + if (!probe || probe.status !== 0) { + const reason = `private Linux user+mount unshare unavailable: ${probe ? probe.error?.message ?? (probe.stderr.trim() || String(probe.signal)) : process.platform}` + if (process.env.DEVA_REQUIRE_MOUNT_TEST === '1') assert.fail(reason) + return t.skip(reason) + } + const original = [ns('user'), ns('mnt'), runId()] + const bundle = resolve(process.env.DEVA_TEST_SERVER ?? fileURLToPath(new URL('../out/headless/server.mjs', import.meta.url))) + assert.ok(fs.statSync(bundle).isFile(), 'build the headless production bundle first') + const child = spawn('unshare', [...flags, process.execPath, main, '--private', ...original, String(process.getuid()), bundle], { env, detached: true }) + let log = '' + for (const stream of [child.stdout, child.stderr]) stream.on('data', chunk => { log += chunk }) + const timer = setTimeout(() => { if (child.pid) process.kill(-child.pid, 'SIGKILL') }, 80000) + try { assert.deepEqual(await wait(child), { code: 0, signal: null }, log) } finally { clearTimeout(timer) } + assert.deepEqual([ns('user'), ns('mnt'), runId()], original) + t.diagnostic(log.trim()) +}) + +async function qualify(bundle) { + const root = fs.mkdtempSync('/run/deva-docs-native-'), home = join(root, 'home'), data = join(root, 'data') + assert.equal(fs.realpathSync(root), root); assert.equal(fs.statSync(root).mode & 0o777, 0o700) + fs.mkdirSync(home, { mode: 0o700 }); fs.mkdirSync(dir) + const source = join(root, 'sealed.json'), link = join(root, 'link.json'), fifo = join(root, 'fifo'), alt = join(root, 'alt.json') + const withheld = 'ungranted-secrets.md', secret = 'withheld synthetic text' + fs.writeFileSync(join(root, withheld), secret, { mode: 0o444 }); cmd('mkfifo', fifo) + const project = 'Synthetic Reading', docs = [{ name: 'Notes.MD', text: '\ufeff# 研修 🙂\r\n\t' }, { name: 'Other.txt', text: 'initial only\n' }] + const revised = [{ name: 'Revised.md', text: 'replacement only\r\n' }] + const wire = documents => Buffer.from(`\t ${JSON.stringify({ version: 1, project, documents })}\r\n`) + const raw = wire(docs), raw2 = wire(revised), sha = digest(raw), sha2 = digest(raw2) + const token = randomBytes(32).toString('base64url'), key = randomBytes(24).toString('base64url'), model = 'fixture-docs' + const drop = ['--bounding-set=-all', '--inh-caps=-all', '--ambient-caps=-all', '--no-new-privs', '--'] + const traceProbe = spawnSync('setpriv', [...drop, 'strace', '-D', '-qq', '-o', join(root, 'probe'), '/usr/bin/true'], { env, timeout: 3000, encoding: 'utf8' }) + const tracing = traceProbe.status === 0 + const traceFile = join(root, 'syscalls'), reads = /\b(?:read|readv|pread\w*|mmap)\(/ + const docIO = trace => trace.split('\n').filter(line => [dir, source, fifo, alt, withheld].some(value => line.includes(value))) + const mount = (from, to = target, ro = true) => { + cmd('mount', '--bind', from, to) + if (ro) cmd('mount', '-o', 'remount,bind,ro', to) + const rows = leaf(to); assert.equal(rows.length, 1); assert.ok(rows[0][5].split(',').includes(ro ? 'ro' : 'rw')) + const fd = fs.openSync(to, 0o10000000 | fs.constants.O_NOFOLLOW) // O_PATH also pins the FIFO without opening a reader. + try { assert.match(fs.readFileSync(`/proc/self/fdinfo/${fd}`, 'utf8'), new RegExp(`^mnt_id:\\s+${rows[0][0]}$`, 'm')) } + finally { fs.closeSync(fd) } + } + const remove = (at = target) => { if (leaf(at).length) cmd('umount', at); fs.rmSync(at, { force: true }) } + const listen = async server => { + await once(server.listen(0, '127.0.0.1'), 'listening', { signal: deadline() }); return server.address().port + } + let calls = 0, service, cookie = '', exerciseChat = false + const upstream = createServer(async (req, res) => { + calls++; req.resume() + if (!exerciseChat || req.method !== 'POST' || req.url !== route('openai')) return res.writeHead(500).end() + res.writeHead(200, { 'Content-Type': 'text/event-stream' }) + const stream = modelStream(res, 'openai', model) + await stream.delta('ordinary synthetic reply'); stream.terminal(); res.end() + }) + try { + const base = `http://127.0.0.1:${await listen(upstream)}${gateway('openai')}/v1`, portProbe = createServer() + const port = await listen(portProbe); await new Promise(done => portProbe.close(done)) + const origin = `http://127.0.0.1:${port}`, listening = `Deva Web listening on ${origin}\n` + function launch(sha256, devaHome, duringRead) { + const trace = tracing ? ['strace', '-Dfqqy', '-s', '192', '-e', 'trace=%file,read,readv,pread64,preadv,preadv2,mmap,bind,listen', '-o', traceFile] : [] + fs.rmSync(traceFile, { force: true }) + const instrumentation = duringRead ? ['--import', `data:text/javascript,${encodeURIComponent(duringRead)}`] : [] + const child = spawn('setpriv', [...drop, ...trace, process.execPath, ...instrumentation, bundle], { env: { ...env, HOME: home, DEVA_HOME: devaHome, + DEVA_ORIGIN: origin, DEVA_PORT: String(port), DEVA_WEB_TOKEN: token, DEVA_MODEL: model, DEVA_MODEL_API_KEY: key, + DEVA_MODEL_BASE_URL: base, DEVA_PROJECT_DOCS_PATH: join(root, withheld), + ...(sha256 === undefined ? {} : { DEVA_PROJECT_DOCS_SHA256: sha256 }) } }) + let out = '', err = '' + child.stdout.on('data', chunk => { out += chunk }); child.stderr.on('data', chunk => { err += chunk }) + service = { child, exited: wait(child), out: () => out, err: () => err, trace: () => tracing ? fs.readFileSync(traceFile, 'utf8') : '' } + service.exited.catch(() => {}); return service + } + async function stop() { + if (!service) return + const run = service, { child, exited } = run; service = undefined + const force = setTimeout(() => child.kill('SIGKILL'), 2000) + child.kill('SIGTERM') + try { assert.deepEqual(await exited, { code: 0, signal: null }) } finally { clearTimeout(force) } + assert.equal(run.out(), listening); assert.equal(run.err(), '') + } + const boundedExit = run => Promise.race([run.exited, delay(4500, null, { ref: false })]) + const invalidHome = join(root, 'must-not-exist') + async function reject(sha256, code, label = code, duringRead) { + const run = launch(sha256, invalidHome, duringRead) + assert.deepEqual(await boundedExit(run), { code: 1, signal: null }, label) + assert.equal(run.out(), ''); assert.equal(run.err(), `Deva Web project documents: ${code}\n`, label) + assert.equal(fs.existsSync(invalidHome), false); assert.doesNotMatch(run.trace(), /^(?:\d+\s+)?(?:listen|bind)\(/m) + if (code === 'invalid_digest') assert.deepEqual(docIO(run.trace()), [], label) + if (code === 'invalid_mount') assert.ok(docIO(run.trace()).every(line => !reads.test(line)), label) + } + async function boot(sha256) { + const run = launch(sha256, data), end = deadline() + while (run.out() !== listening) { + assert.ok(run.child.exitCode === null && run.child.signalCode === null, run.err()); await delay(20, null, { signal: end }) + } + const status = fs.readFileSync(`/proc/${run.child.pid}/status`, 'utf8') + for (const cap of ['Inh', 'Prm', 'Eff', 'Bnd', 'Amb']) assert.match(status, new RegExp(`^Cap${cap}:\\s+0+$`, 'm')) + assert.match(status, /^NoNewPrivs:\s+1$/m); assert.equal(run.err(), '') + } + async function json(path, status = 200, { body, headers } = {}) { + const text = body === undefined ? undefined : JSON.stringify(body) + const response = await new Promise((done, fail) => { + const req = request(origin + path, { signal: deadline(), method: text === undefined ? 'GET' : 'POST', headers: { + Cookie: cookie, ...(text === undefined ? {} : { Origin: origin, 'Content-Type': 'application/json' }), ...headers } }, done) + req.on('error', fail).end(text) + }) + const chunks = []; for await (const chunk of response) chunks.push(chunk) + const content = Buffer.concat(chunks).toString('utf8') + assert.equal(response.statusCode, status, path) + for (const hidden of [root, target, withheld, secret, token, key, sha, sha2, base, cookie.split('=')[1]].filter(Boolean)) + assert.ok(!content.includes(hidden), 'private data in response') + const dto = response.headers['content-type']?.startsWith('application/x-ndjson') ? content.trimEnd().split('\n').map(line => JSON.parse(line)) : JSON.parse(content) + if (status >= 400) assert.deepEqual(dto, { error: { 401: 'auth', 403: 'origin', 404: 'missing', 405: 'method' }[status] }) + return [dto, response.headers] + } + const get = async (...args) => (await json(...args))[0] + const login = async () => { const [dto, headers] = await json('/api/login', 200, { body: { token } }) + assert.deepEqual(dto, { ok: true }); return headers['set-cookie'][0].split(';')[0] } + const id = /^[0-9a-f]{32}$/, detail = (generation, doc) => `${docPath}/${generation}/${doc}` + async function listing(expected) { + const [dto, headers] = await json(docPath), { generation, documents } = dto + assert.match(generation, id); assert.equal(new Set(documents.map(doc => doc.id)).size, expected.length) + assert.ok(+headers['x-deva-session-ttl-ms'] > 0 && +headers['x-deva-session-ttl-ms'] <= 28800000) + const rows = expected.map(({ name, text }, i) => ({ id: documents[i].id, name, bytes: Buffer.byteLength(text) })) + assert.deepEqual(dto, { project, generation, documents: rows }) + for (const [i, row] of rows.entries()) { + assert.match(row.id, id); assert.deepEqual(await get(detail(generation, row.id)), { generation, ...row, text: expected[i].text }) + } + return [generation, rows[0].id] + } + + fs.symlinkSync(fifo, target) + for (const value of ['', sha.toUpperCase(), `${sha}\n`]) await reject(value, 'invalid_digest') + await boot(); cookie = await login() + assert.deepEqual(await get(sessions), { model, sessions: [] }); await get(docPath, 404); await get(docPath, 404, { body: {} }) + const session = await get(sessions, 201, { body: {} }), sessionPath = `${sessions}/${session.id}` + const sessionFile = join(data, 'data', 'chats', `${session.id}.json`) + const volume = () => { + const { dev, ino, mtimeNs, ctimeNs } = fs.statSync(sessionFile, { bigint: true }) + return { dev, ino, mtimeNs, ctimeNs, bytes: fs.readFileSync(sessionFile) } + } + const state = volume(), oldIndex = { model, sessions: [{ id: session.id, title: session.title }] } + const off = service; await stop(); assert.deepEqual(docIO(off.trace()), []); assert.doesNotMatch(off.trace(), /\/(?:mountinfo|fdinfo)(?:[\/"<])/) + remove(); fs.writeFileSync(source, raw, { mode: 0o444 }); fs.writeFileSync(target, raw, { mode: 0o444 }) + await reject(sha, 'invalid_mount', 'unmounted 0444 leaf'); remove() + const dirSource = join(root, 'dir'); fs.mkdirSync(dirSource); fs.writeFileSync(join(dirSource, 'snapshot.json'), raw, { mode: 0o444 }) + mount(dirSource, dir); await reject(sha, 'invalid_mount', 'RO directory bind'); cmd('umount', dir) + fs.writeFileSync(alt, ''); mount(source, alt); fs.symlinkSync(alt, target) + await reject(sha, 'invalid_mount', 'symlink to a RO mount'); remove(); remove(alt) + fs.writeFileSync(target, ''); fs.linkSync(source, link); mount(link) + await reject(sha, 'invalid_mount', 'hardlinked RO leaf'); cmd('umount', target); fs.unlinkSync(link) + mount(fifo); await reject(sha, 'invalid_mount', 'FIFO RO leaf'); cmd('umount', target) + mount(source, target, false); await reject(sha, 'invalid_mount', 'RW exact leaf'); cmd('umount', target) + mount(source); await reject(sha2, 'digest_mismatch') + // Deterministically schedule a real mtime change on our synthetic backing inode immediately + // after its first real kernel data read. Neither file contents nor syscall results are mocked. + const modifyBacking = `import fs from 'node:fs'; import {syncBuiltinESMExports} from 'node:module'; + const target=fs.statSync(${JSON.stringify(source)}), read=fs.readSync; let once=true; + fs.readSync=function(fd,...args){ const n=read.call(fs,fd,...args), actual=fs.fstatSync(fd); + if(once && n>0 && actual.ino===target.ino && actual.dev===target.dev){once=false;fs.utimesSync(${JSON.stringify(source)},1000,1000)} return n }; + syncBuiltinESMExports();` + await reject(sha, 'mount_changed', 'file changed during verified read', modifyBacking) + assert.equal(fs.statSync(source).mtimeMs, 1_000_000); cmd('umount', target) + for (const [bytes, code] of [[Buffer.from('{}'), 'invalid_snapshot'], [Buffer.alloc(2 * 1024 * 1024 + 1, 32), 'snapshot_limit']]) { + fs.writeFileSync(alt, bytes, { mode: 0o444 }); mount(alt); await reject(digest(bytes), code); cmd('umount', target); remove(alt) + } + mount(source); await boot(sha); cookie = await login() + const startupIO = docIO(service.trace()); if (tracing) assert.ok(startupIO.some(line => reads.test(line)), 'trace observed the actual sealed read') + assert.deepEqual(await get(sessions), { ...oldIndex, projectDocs: true }) + assert.deepEqual(await get(`${sessions}/archived`), { model, sessions: [] }) + const [gen, doc] = await listing(docs), previous = detail(gen, doc) + for (const path of [docPath, previous]) { + await get(path, 401, { headers: { Cookie: 'deva_web=wrong' } }) + for (const name of ['Host', 'Origin']) await get(path, 403, { headers: { [name]: 'http://foreign.invalid' } }) + assert.equal((await json(path, 405, { body: {} }))[1].allow, 'GET') + } + await get(detail(gen, 'f'.repeat(32)), 404); await get(detail('bad', doc), 404) + fs.writeFileSync(alt, raw2, { mode: 0o444 }); fs.renameSync(alt, source) + assert.notEqual(fs.statSync(target).ino, fs.statSync(source).ino) + assert.deepEqual(await listing(docs), [gen, doc]); assert.deepEqual(await get(sessionPath), session) + const old = service; await stop(); assert.deepEqual(docIO(old.trace()), startupIO, 'browsing does not reopen or reread the snapshot') + cmd('umount', target); mount(source); await boot(sha2) + await get(docPath, 401); await get(previous, 401); cookie = await login() + const [newGen, newDoc] = await listing(revised) + assert.notEqual(newGen, gen); assert.notEqual(newDoc, doc); await get(previous, 404); await get(detail(newGen, doc), 404) + const current = detail(newGen, newDoc); await stop(); remove(); await reject(sha2, 'invalid_mount', 'missing fixed leaf') + await boot(); await get(docPath, 401); cookie = await login() + assert.deepEqual(await get(sessions), oldIndex); await get(docPath, 404); await get(previous, 404); await get(current, 404) + assert.deepEqual(await get(sessionPath), session); assert.deepEqual(volume(), state); assert.equal(calls, 0) + exerciseChat = true + const turn = await get(`${sessionPath}/turns`, 200, { body: { text: 'ordinary synthetic turn', revision: session.revision, turnId: randomUUID() } }) + assert.deepEqual(turn, [{ type: 'delta', text: 'ordinary synthetic reply' }, { type: 'done', reason: 'complete' }]) + assert.equal(calls, 1); assert.equal((await get(sessionPath)).messages.length, 2); await stop() + console.log(`native Linux mount matrix and restart/revoke passed; syscall trace ${tracing ? 'asserted' : `unavailable (${traceProbe.error?.message ?? (traceProbe.stderr.trim() || traceProbe.status)})`}`) + } finally { + if (service) { service.child.kill('SIGKILL'); await service.exited } + upstream.closeAllConnections(); if (upstream.listening) await new Promise(done => upstream.close(done)) + for (const path of [target, alt, dir]) if (leaf(path).length) cmd('umount', path) + } +} diff --git a/apps/desktop/test/project-documents.test.mjs b/apps/desktop/test/project-documents.test.mjs new file mode 100644 index 00000000..8b52f460 --- /dev/null +++ b/apps/desktop/test/project-documents.test.mjs @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { fileURLToPath } from 'node:url' +import { build } from 'vite' + +const entry = fileURLToPath(new URL('../src/headless/project-documents.ts', import.meta.url)) +const { output } = await build({ configFile: false, logLevel: 'silent', build: { ssr: entry, write: false, + rollupOptions: { output: { format: 'es', inlineDynamicImports: true } } } }) +const { projectDocumentResponses: publish, PROJECT_DOCS: root } = await import(`data:text/javascript;base64,${Buffer.from(output[0].code).toString('base64')}`) +const snapshot = documents => ({ version: 1, project: 'Fixture', documents, totalTextBytes: documents.reduce((sum, d) => sum + d.bytes, 0) }) +const document = (name, text) => ({ name, text, bytes: Buffer.byteLength(text) }) +const content = value => { assert.equal(value.bytes, Buffer.byteLength(value.json)); return JSON.parse(value.json) } + +test('a bounded process-local publication separates its metadata from the explicitly selected text', () => { + assert.equal(publish(undefined), undefined) + const source = Array.from({ length: 8 }, (_, i) => document(`part-${i}.md`, `${i}` + '\t'.repeat(32767))) + const first = publish(snapshot(source)), list = first(root), { project, generation, documents } = content(list) + assert.ok(list.bytes <= 32 * 1024); assert.equal(project, 'Fixture'); assert.match(generation, /^[0-9a-f]{32}$/u) + assert.equal(documents.length, source.length); assert.equal(new Set(documents.map(row => row.id)).size, source.length) + for (const [i, { id, name, bytes }] of documents.entries()) { + assert.match(id, /^[0-9a-f]{32}$/u); assert.deepEqual(documents[i], { id, name: source[i].name, bytes: source[i].bytes }) + const detail = first(`${root}/${generation}/${id}`) + assert.ok(detail.bytes <= 200 * 1024); assert.deepEqual(content(detail), { generation, id, name, bytes, text: source[i].text }) + assert.equal(first(`${root}/${generation}/${name}`), undefined) + } + const next = publish(snapshot(source)), nextList = content(next(root)); assert.notEqual(nextList.generation, generation) + assert.equal(next(`${root}/${generation}/${documents[0].id}`), undefined) + assert.equal(next(`${root}/${nextList.generation}/${documents[0].id}`), undefined) + assert.equal(first(`${root}?list`), undefined) +}) From 7964ff099159fdb67c644845bc3fe5755c17a923 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 18:00:48 +0800 Subject: [PATCH 3/4] =?UTF-8?q?feat(web):=20=E6=89=8B=E5=8A=A8=E9=A2=84?= =?UTF-8?q?=E8=A7=88=E5=B7=B2=E5=8F=91=E5=B8=83=E7=9A=84=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E8=B5=84=E6=96=99=20/=20preview=20published=20project=20docume?= =?UTF-8?q?nts=20on=20demand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/headless/web/main.tsx | 12 +- .../desktop/src/headless/web/project-docs.css | 72 +++++ .../desktop/src/headless/web/project-docs.tsx | 276 ++++++++++++++++++ 3 files changed, 357 insertions(+), 3 deletions(-) create mode 100644 apps/desktop/src/headless/web/project-docs.css create mode 100644 apps/desktop/src/headless/web/project-docs.tsx diff --git a/apps/desktop/src/headless/web/main.tsx b/apps/desktop/src/headless/web/main.tsx index eefa1114..7cbd6980 100644 --- a/apps/desktop/src/headless/web/main.tsx +++ b/apps/desktop/src/headless/web/main.tsx @@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client' import { ComposerAction } from '../../renderer/src/redesign/ComposerAction' import { normalizeSessionTitle } from '../../shared/session-title' import type { TextAttachment } from '../text-file' +import { notifyProjectDocsAuthChange, ProjectDocs } from './project-docs' import { SessionButton, TitleEditor, type TitleEdit } from './session-organizer' import { attachmentIssue, TextAttachmentCard } from './text-attachment' import { readTextAttachment } from './read-text-file' @@ -13,7 +14,7 @@ import './web.css' type Row = { id: string; title: string; archived?: true } type Message = { role: 'user'; text: string; attachment?: TextAttachment } | { role: 'assistant'; text: string } type View = Row & { messages: Message[]; revision: number; active: string | null } -type Index = { sessions: Row[]; model: string } +type Index = { sessions: Row[]; model: string; projectDocs?: true } type Mutation = 'title' | 'archive' | 'restore' type DraftFile = { key: number; name: string; size: number; attachment?: TextAttachment } type Scope = { @@ -110,6 +111,7 @@ function App() { try { if (token !== undefined) { await request('/api/login', { token }) + notifyProjectDocsAuthChange() token = undefined setIndex(undefined) } @@ -312,8 +314,11 @@ function Chat({ initial, signOut }: { initial: Index; signOut: (didExpire: boole const s = scope.current setNotice('') try { - if (kind === 'logout') { await get('/api/logout', {}); leave(false) } - else { + if (kind === 'logout') { + await get('/api/logout', {}) + notifyProjectDocsAuthChange() + leave(false) + } else { const next = await get(sessionsPath, {}) if (current(s)) { saved(select(), next); void library.reload() } } @@ -491,6 +496,7 @@ function Chat({ initial, signOut }: { initial: Index; signOut: (didExpire: boole

{view?.title || t('Chat', '对话')}

+ {initial.projectDocs === true && leave(true)} />} {view && !readOnly && !edit && } {view && !archived && !view.archived && ({ wall: Date.now(), monotonic: performance.now() }) +const at = (start: Time, delay: number): Time => ({ wall: start.wall + delay, monotonic: start.monotonic + delay }) +const remaining = (end: Time) => Math.min(end.wall - Date.now(), end.monotonic - performance.now()) + +function channel() { + try { return new BroadcastChannel(authChannel) } catch { return undefined } +} + +export function notifyProjectDocsAuthChange() { + const bus = channel() + try { bus?.postMessage(authChanged) } catch { /* Advisory browser-local signal. */ } + finally { bus?.close() } +} + +function hasKeys(value: unknown, ...keys: string[]): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) && + Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key)) +} + +const validId = (id: unknown): id is string => typeof id === 'string' && id.length === 32 && !/[^0-9a-f]/u.test(id) +const validBytes = (bytes: unknown): bytes is number => typeof bytes === 'number' && + Number.isInteger(bytes) && bytes >= 1 && bytes <= MAX_TEXT_ATTACHMENT_BYTES + +function parseList(value: unknown): Snapshot | undefined { + if (!hasKeys(value, 'project', 'generation', 'documents')) return + const { project, generation, documents } = value + if (!isProjectDocsLabel(project) || !validId(generation) || !Array.isArray(documents) || + documents.length < 1 || documents.length > MAX_PROJECT_DOCUMENTS) return + const items: Item[] = [], names = new Set(), ids = new Set() + let total = 0 + for (const item of documents as unknown[]) { + if (!hasKeys(item, 'id', 'name', 'bytes') || !validId(item.id) || !isTextAttachmentName(item.name) || !validBytes(item.bytes)) return + const name = item.name.normalize('NFC').toLowerCase() + total += item.bytes + if (total > MAX_PROJECT_TEXT_BYTES || ids.has(item.id) || names.has(name)) return + ids.add(item.id); names.add(name) + items.push({ id: item.id, name: item.name, bytes: item.bytes }) + } + return { project, generation, documents: items } +} + +function parseDetail(value: unknown, generation: string, item: Item): string | undefined { + if (!hasKeys(value, 'generation', 'id', 'name', 'bytes', 'text') || value.generation !== generation || + value.id !== item.id || value.name !== item.name || value.bytes !== item.bytes || typeof value.text !== 'string' || + textAttachmentProblem({ name: item.name, text: value.text }) || encoder.encode(value.text).length !== item.bytes) return + return value.text +} + +function ttl(response: Response) { + const raw = response.headers.get('X-Deva-Session-Ttl-Ms') + const ms = raw && /^[1-9][0-9]{0,7}$/u.test(raw) ? Number(raw) : 0 + return ms <= maxTtl ? ms : 0 +} + +async function readJson(response: Response, limit: number): Promise { + const type = response.headers.get('Content-Type')?.split(';', 1)[0].trim().toLowerCase() + if (type !== 'application/json' || !response.body || Number(response.headers.get('Content-Length')) > limit) throw new Error() + const reader = response.body.getReader() + const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) + let raw = '', bytes = 0 + try { + while (true) { + const chunk = await reader.read() + if (chunk.done) return JSON.parse(raw + decoder.decode()) + bytes += chunk.value.byteLength + if (bytes > limit) throw new Error() + raw += decoder.decode(chunk.value, { stream: true }) + } + } finally { void reader.cancel().catch(() => {}) } +} + +function clearSelection(dialog: HTMLDialogElement | null) { + const selection = document.getSelection() + if (selection && (dialog?.contains(selection.anchorNode) || dialog?.contains(selection.focusNode))) selection.removeAllRanges() +} + +export function ProjectDocs({ t, session, disabled, onExpire }: { + t: Translate; session: AbortSignal; disabled: boolean; onExpire: () => void +}) { + const [view, setView] = useState(null) + const dialog = useRef(null) + const opener = useRef(null) + const closeButton = useRef(null) + const backButton = useRef(null) + const reloadButton = useRef(null) + const returnRow = useRef() + const pending = useRef() + const lease = useRef