From 688a527a3a35660d353c23c5260e5d81cd23446f Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 16:58:02 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(deliveries):=20=E6=8C=89=E5=B7=B2?= =?UTF-8?q?=E7=A1=AE=E8=AE=A4=E5=9B=9E=E5=A4=8D=E5=92=8C=E6=A1=8C=E9=9D=A2?= =?UTF-8?q?=E5=8E=86=E5=8F=B2=E7=99=BB=E8=AE=B0=E4=BA=A4=E4=BB=98=20/=20de?= =?UTF-8?q?rive=20deliveries=20from=20confirmed=20replies=20and=20desktop?= =?UTF-8?q?=20history?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/chat/delivery-records-native.mjs | 173 +++++++++ .../src/chat/delivery-records-storage.mjs | 216 ++++++++++++ apps/headless/src/chat/delivery-records.mjs | 172 +++++++++ apps/headless/src/chat/text-turns.mjs | 18 +- apps/headless/test/delivery-records.test.mjs | 327 ++++++++++++++++++ 5 files changed, 904 insertions(+), 2 deletions(-) create mode 100644 apps/headless/src/chat/delivery-records-native.mjs create mode 100644 apps/headless/src/chat/delivery-records-storage.mjs create mode 100644 apps/headless/src/chat/delivery-records.mjs create mode 100644 apps/headless/test/delivery-records.test.mjs diff --git a/apps/headless/src/chat/delivery-records-native.mjs b/apps/headless/src/chat/delivery-records-native.mjs new file mode 100644 index 00000000..c623c695 --- /dev/null +++ b/apps/headless/src/chat/delivery-records-native.mjs @@ -0,0 +1,173 @@ +import { createHash } from 'node:crypto' +import { posix, win32 } from 'node:path' +import { deliveryLimitError, deliveryStorageError, parseNativeJSON } from './delivery-records-storage.mjs' + +const maxMessages = 4096 +const maxParts = 16384 +const maxDesktopGroups = 256 +const maxPaths = 20 // Original desktop present_files limit. +const maxReply = 64 * 1024 // UTF-16 units, same as the text turn writer. +const maxQuestion = 12 * 1024 +const TURN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u +export const validDeliveryTurn = value => typeof value === 'string' && value.length === 36 && TURN_ID.test(value) +const desktopId = value => typeof value === 'string' && value.length > 0 && value.length <= 256 && + !/[\u0000-\u0020\u007f-\u009f]/u.test(value) && value.isWellFormed() +export const fields = (obj, keys) => object(obj) && Object.keys(obj).length === keys.length && keys.every(key => Object.hasOwn(obj, key)) +export const object = obj => obj !== null && typeof obj === 'object' && !Array.isArray(obj) +export const digest = value => createHash('sha256').update(value).digest('hex') +export const groupId = (sid, origin, ...identity) => `d_${digest(JSON.stringify(['deva-delivery-v1', sid, origin, ...identity])).slice(0, 32)}` + +const textPart = value => fields(value, ['type', 'text']) && value.type === 'text' && typeof value.text === 'string' +const oneText = message => Array.isArray(message.content) && message.content.length === 1 && textPart(message.content[0]) + ? message.content[0].text : null + +function notice(after, { status, reason }, text) { + if (status === 'failed') return { after, kind: 'error', message: '模型回复未能完成。' } + const code = status === 'aborted' || status === 'interrupted' ? 'aborted' + : reason === 'refusal' ? (text?.trim() ? null : 'refused') + : ['empty', 'truncated', 'repeated'].includes(reason) ? reason : null + return code ? { after, kind: 'notice', code } : null +} + +/** One native user message and at most one native assistant message per receipt, + * in admission order. Require this correspondence across the entire ledger, not + * merely a nearby assistant message after a matching turn ID. */ +export function webReplies(session, ledger, attachmentIndex) { + if (!fields(ledger, ['version', 'messageCount', 'requests'])) return null + const replies = new Map() + let cursor = 0 + let notices = 0 + for (const [ordinal, row] of ledger.requests.entries()) { + const keys = ['clientRequestId', 'fingerprint', 'turnId', 'startedAt', 'status', 'reason'] + if (Object.hasOwn(row, 'model')) { + if (typeof row.model !== 'string' || row.model.length > 512) return null + keys.push('model') + } + if (!fields(row, keys) || !validDeliveryTurn(row.turnId)) return null + const user = session.messages[cursor] + if (!fields(user, ['role', 'content']) || user.role !== 'user') return null + if (!attachmentIndex?.byMessage.has(cursor)) { + const text = oneText(user) + if (!text || text.length > maxQuestion || !text.trim() || Buffer.byteLength(text) > maxQuestion) return null + } + cursor++ + const messageIndex = cursor + let text = null + const assistant = session.messages[cursor] + if (assistant?.role === 'assistant') { + if (!fields(assistant, ['role', 'content'])) return null + text = oneText(assistant) + if (text === null || !text.length || text.length > maxReply || ['running', 'interrupted'].includes(row.status)) return null + cursor++ + } + if (row.status === 'completed' && row.reason === null) { + if (!text?.trim()) return null + // Lone surrogates have no exact UTF-8 encoding. Keep the native reply visible, but not exportable. + if (text.isWellFormed()) replies.set(row.turnId, { turnId: row.turnId, messageIndex, ordinal, text }) + } else if (row.reason === 'empty' && text?.trim()) return null + const expected = notice(cursor, row, text) + if (expected) { + const recorded = session.notices?.[notices++] + const names = Object.keys(expected) + if (!fields(recorded, names) || !names.every(key => recorded[key] === expected[key])) return null + } + } + return cursor === session.messages.length && notices === (session.notices?.length ?? 0) ? replies : null +} + +function validateMessages(messages) { + return Array.isArray(messages) && messages.length <= maxMessages && messages.every(m => + object(m) && ['assistant', 'user'].includes(m.role) && (typeof m.content === 'string' || Array.isArray(m.content))) +} + +export function nativeMessages(files, sid, session) { + if (session.messages?.length > maxMessages) throw deliveryLimitError() + if (!validateMessages(session.messages)) throw deliveryStorageError() + const compacted = session.compacted + if (compacted === undefined) return session.messages + const prefix = `${sid}.compacted-` + if (!fields(compacted, ['count', 'file']) || !Number.isSafeInteger(compacted.count) || compacted.count < 1 || + typeof compacted.file !== 'string' || !compacted.file.startsWith(prefix) || + !/^[A-Za-z0-9_-]{1,128}\.jsonl$/u.test(compacted.file.slice(prefix.length)) || !compacted.file.endsWith('.jsonl')) { + throw deliveryStorageError() + } + if (compacted.count + session.messages.length > maxMessages) throw deliveryLimitError() + const text = files.readCompacted(compacted.file) + if (text === null) throw deliveryStorageError() + let start = 0 + const messages = [] + // An interrupted desktop append may leave extra lines; the main file commits only `count`. + for (let lines = 0; messages.length < compacted.count && start < text.length; lines++) { + if (lines >= maxMessages) throw deliveryLimitError() + const newline = text.indexOf('\n', start) + const end = newline < 0 ? text.length : newline + if (end !== start) messages.push(parseNativeJSON(text.slice(start, end))) + start = end + 1 + } + if (messages.length !== compacted.count || !validateMessages(messages)) throw deliveryStorageError() + return [...messages, ...session.messages] +} + +function validatedPaths(paths) { + if (!Array.isArray(paths) || paths.length === 0 || paths.length > maxPaths) return null + const unique = new Set() + for (const p of paths) { + if (typeof p !== 'string' || !p.length || p.length > 4096 || Buffer.byteLength(p) > 4096 || + /[\u0000-\u001f\u007f-\u009f]/u.test(p) || !p.isWellFormed()) return null + const absolutePosix = p.startsWith('/') && p.length > 1 && !p.endsWith('/') && posix.normalize(p) === p + const absoluteWindows = /^(?:[A-Za-z]:\\|\\\\[^.\\?][^\\]*\\[^\\]+\\)/u.test(p) && !p.endsWith('\\') && win32.normalize(p) === p + if (!absolutePosix && !absoluteWindows) return null + const identity = absoluteWindows ? p.toLowerCase() : p + if (unique.has(identity)) return null + unique.add(identity) + } + return paths.map((path, index) => ({ index, path })) +} + +export function desktopDeliveryRecords(sid, messages, delivered) { + if (!object(delivered)) return [] + if (Object.keys(delivered).length > maxParts) throw deliveryLimitError() + const uses = new Map() + const results = new Map() + const deliveries = [] + let count = 0 + const unique = (map, id, value) => map.set(id, map.has(id) ? null : value) + for (const [at, message] of messages.entries()) { + const content = message.content + if (!Array.isArray(content)) continue + if ((count += content.length) > maxParts) throw deliveryLimitError() + for (const part of content) { + if (!object(part) || typeof part.type !== 'string') throw deliveryStorageError() + if (part.type === 'tool_use' && desktopId(part.id)) { + unique(uses, part.id, at) + if (message.role === 'assistant' && part.name === 'present_files') deliveries.push({ id: part.id, at }) + } else if (part.type === 'tool_result' && desktopId(part.toolUseId)) { + unique(results, part.toolUseId, { at, part }) + } + } + } + const records = [] + const completeBatches = new Map() + function completeBatch(at) { + if (completeBatches.has(at)) return completeBatches.get(at) + const next = messages[at + 1] + const calls = messages[at].content.filter(p => p.type === 'tool_use') + const complete = next?.role === 'user' && Array.isArray(next.content) && next.content.length === calls.length && + next.content.every(p => p.type === 'tool_result') && calls.every(call => + uses.get(call.id) === at && results.get(call.id)?.at === at + 1) + completeBatches.set(at, complete) + return complete + } + // Newest first; keep the exact native order of the files within each group. + for (const { id, at } of deliveries.reverse()) { + const result = results.get(id) + if (uses.get(id) !== at || result?.at !== at + 1 || !completeBatch(at) || + (result.part.isError !== undefined && result.part.isError !== false) || + typeof result.part.content !== 'string' || !result.part.content.trim() || !Object.hasOwn(delivered, id)) continue + const entries = validatedPaths(delivered[id]) + if (!entries) continue + if (records.length >= maxDesktopGroups) throw deliveryLimitError() + records.push({ id: groupId(sid, 'desktop', id), origin: 'desktop', messageIndex: at, entries }) + } + return records +} diff --git a/apps/headless/src/chat/delivery-records-storage.mjs b/apps/headless/src/chat/delivery-records-storage.mjs new file mode 100644 index 00000000..7b24c70f --- /dev/null +++ b/apps/headless/src/chat/delivery-records-storage.mjs @@ -0,0 +1,216 @@ +import { randomBytes } from 'node:crypto' +import { + closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, openSync, readSync, realpathSync, + renameSync, unlinkSync, writeFileSync +} from 'node:fs' +import { join, resolve } from 'node:path' +import { DIRECTORY, PATH, fdPath, mountId, sameInode } from '../files/workspace-files-fd.mjs' +import { HttpError } from '../http/policy.mjs' + +const stats = { bigint: true } +const dirFlags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK +const readFlags = constants.O_RDONLY | constants.O_NONBLOCK +const writeFlags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_NONBLOCK +const uid = BigInt(process.geteuid()) +const nativeLimit = 32 * 1024 * 1024 // Full native history, including any declared compacted prefix. +const metadataLimit = 128 * 1024 // 256 ledger rows × two formats; no document bytes. +const signature = ['mode', 'uid', 'gid', 'nlink', 'size', 'mtimeNs', 'ctimeNs'] +const same = (a, b) => sameInode(a, b) && signature.every(key => a[key] === b[key]) +const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) +export const deliveryStorageError = () => new HttpError(503, 'chat_storage_unconfirmed') +export const deliveryLimitError = () => new HttpError(413, 'delivery_history_limit') +const corrupted = () => { throw deliveryStorageError() } + +function stat(path) { + try { return lstatSync(path, stats) } catch (err) { if (err?.code !== 'ENOENT') throw err; return null } +} + +const safeDir = (st, privateMode) => st?.isDirectory() && st.uid === uid && (st.mode & (privateMode ? 0o077n : 0o022n)) === 0n +const safeFile = (st, privateMode) => st?.isFile() && st.uid === uid && st.nlink === 1n && + (privateMode ? (st.mode & 0o7777n) === 0o600n : (st.mode & 0o022n) === 0n) + +/** The workbench holds its data directory's writer lock throughout this synchronous operation. + * Use directory FDs so neither native reads nor writes ever follow a replacement directory. */ +export function withDeliveryFiles(dataDir, sid, use) { + const root = resolve(dataDir) + const dirs = [] + function directory(path, privateMode) { + const named = stat(path) + if (!named) return null + if (!safeDir(named, privateMode)) corrupted() + const parent = dirs.at(-1) + const fd = openSync(path, dirFlags) + const entry = { path, fd, named, privateMode, mount: null } + dirs.push(entry) + const opened = fstatSync(fd, stats) + entry.mount = mountId(fd) + if (!safeDir(opened, privateMode) || !sameInode(named, opened) || (parent && parent.mount !== entry.mount)) corrupted() + return fdPath(fd) + } + function stableDirs() { + if (realpathSync(root) !== root) corrupted() + for (const { path, named, privateMode, mount } of dirs) { + const pin = openSync(path, DIRECTORY) + try { + const live = fstatSync(pin, stats) + if (!safeDir(live, privateMode) || !sameInode(live, named) || mountId(pin) !== mount) corrupted() + } finally { closeSync(pin) } + } + } + try { + const home = directory(root, true) + const data = home && directory(join(home, 'data'), false) + const chats = data && directory(join(data, 'chats'), false) + if (!chats) return use(null) + stableDirs() + const mount = dirs.at(-1).mount + const nativeName = `${sid}.json` + const metadataName = `${sid}.deliveries-v1` + let nativeBytes = 0 + const native = new Map() + let metadata + + function read(name, limit, privateMode) { + const path = join(chats, name) + const named = stat(path) + if (!named) return null + if (!safeFile(named, privateMode) || named.size < 1n) corrupted() + if (named.size > BigInt(limit)) throw privateMode ? deliveryStorageError() : deliveryLimitError() + // O_PATH pins the inode before a data open, even if the name races to a device/FIFO. + const pin = openSync(path, PATH) + try { + const pinned = fstatSync(pin, stats) + if (!safeFile(pinned, privateMode) || !same(named, pinned) || mountId(pin) !== mount) corrupted() + const fd = openSync(fdPath(pin), readFlags) + try { + const opened = fstatSync(fd, stats) + if (!same(pinned, opened) || mountId(fd) !== mount) corrupted() + const bytes = Buffer.allocUnsafe(Number(opened.size)) + for (let offset = 0; offset < bytes.length;) { + const count = readSync(fd, bytes, offset, bytes.length - offset, offset) + if (!count) corrupted() + offset += count + } + unchanged(name, opened) + if (!same(opened, fstatSync(fd, stats))) corrupted() + return { identity: opened, text: decoder.decode(bytes), bytes: bytes.length } + } finally { closeSync(fd) } + } finally { closeSync(pin) } + } + + function readNative(name) { + const source = read(name, nativeLimit - nativeBytes, false) + native.set(name, source?.identity ?? null) + nativeBytes += source?.bytes ?? 0 + return source + } + + function unchanged(name, expected) { + const path = join(chats, name) + if (expected === null) { + if (stat(path) !== null) corrupted() + return + } + const pin = openSync(path, PATH) + try { + if (!same(expected, fstatSync(pin, stats)) || mountId(pin) !== mount) corrupted() + } finally { closeSync(pin) } + } + + function validate() { + stableDirs() + for (const [name, identity] of native) unchanged(name, identity) + if (metadata !== undefined) unchanged(metadataName, metadata) + } + + function readMetadata() { + const file = read(metadataName, metadataLimit, true) + metadata = file?.identity ?? null + return file?.text ?? null + } + + function saveMetadata(text) { + if (metadata === undefined || Buffer.byteLength(text) > metadataLimit) corrupted() + const tmp = join(chats, `${metadataName}.${randomBytes(12).toString('hex')}.tmp`) + const fd = openSync(tmp, writeFlags, 0o600) + let pending = true + try { + fchmodSync(fd, 0o600) + writeFileSync(fd, text, 'utf8') + fsyncSync(fd) + validate() + const created = fstatSync(fd, stats) + const named = stat(tmp) + if (!safeFile(created, true) || !named || !same(created, named)) corrupted() + renameSync(tmp, join(chats, metadataName)) + pending = false + fsyncSync(dirs.at(-1).fd) + const saved = read(metadataName, metadataLimit, true) + // rename can change ctime. Still require the inode we published, exact bytes and stable readback. + if (!saved || !sameInode(saved.identity, created) || saved.text !== text) corrupted() + metadata = saved.identity + validate() + } finally { + try { + if (pending) { + const named = stat(tmp) + if (named && sameInode(named, fstatSync(fd, stats))) unlinkSync(tmp) + } + } finally { closeSync(fd) } + } + } + + const result = use({ + readMain() { + const file = readNative(nativeName) + return file && { value: parseNativeJSON(file.text), privateMode: (file.identity.mode & 0o7777n) === 0o600n || + (file.identity.mode & 0o7777n) === 0o400n } + }, + readCompacted: name => readNative(name)?.text ?? null, + readMetadata, saveMetadata + }) + validate() + return result + } finally { + for (const { fd } of dirs.reverse()) closeSync(fd) + } +} + +// Native JSON is strict about shape at the projection layer. Also reject duplicate object +// keys (JSON.parse would silently choose the last one), and bound nesting / structural work +// before comparisons with the native in-memory view. Ignore syntax inside quoted strings. +export function parseNativeJSON(text) { + const token = /["[\]{},:\\]/g + const quote = /["\\]/g + const scopes = [] + let count = 0 + for (let match; (match = token.exec(text));) { + if (++count > 1_000_000) throw deliveryLimitError() + const char = match[0] + const scope = scopes.at(-1) + if (char === '"') { + quote.lastIndex = token.lastIndex + for (;;) { + const end = quote.exec(text) + if (!end) corrupted() + if (end[0] === '"') break + quote.lastIndex++ + } + token.lastIndex = quote.lastIndex + if (scope?.key) { + const key = JSON.parse(text.slice(match.index, token.lastIndex)) + if (scope.keys.has(key)) corrupted() + scope.keys.add(key) + scope.key = false + } + } else if (char === '{' || char === '[') { + if (scopes.length >= 32) throw deliveryLimitError() + scopes.push(char === '{' ? { keys: new Set(), key: true } : null) + } else if (char === '}' || char === ']') { + scopes.pop() + } else if (char === ',' && scope) { + scope.key = true + } + } + return JSON.parse(text) +} diff --git a/apps/headless/src/chat/delivery-records.mjs b/apps/headless/src/chat/delivery-records.mjs new file mode 100644 index 00000000..9394234b --- /dev/null +++ b/apps/headless/src/chat/delivery-records.mjs @@ -0,0 +1,172 @@ +import { isDeepStrictEqual } from 'node:util' +import { HttpError } from '../http/policy.mjs' +import { desktopDeliveryRecords, digest, fields, groupId, nativeMessages, object, validDeliveryTurn, webReplies } from './delivery-records-native.mjs' +import { deliveryStorageError, parseNativeJSON, withDeliveryFiles } from './delivery-records-storage.mjs' + +const formats = new Map([['md', 'text/markdown; charset=utf-8'], ['txt', 'text/plain; charset=utf-8']]) +const missing = () => new HttpError(404, 'session_not_found') +const ineligible = () => new HttpError(404, 'reply_not_exportable') +const invalidExport = () => new HttpError(400, 'invalid_delivery_export') +const validGroupId = value => typeof value === 'string' && value.length === 34 && /^d_[0-9a-f]{32}$/u.test(value) +const revision = value => typeof value === 'string' && value.length === 64 && /^[0-9a-f]{64}$/u.test(value) +const time = value => Number.isFinite(value) && value >= 0 +const emptyIndex = () => ({ version: 1, rows: [] }) + +function exportInput(raw, validSid) { + if (!raw || ![Object.prototype, null].includes(Object.getPrototypeOf(raw)) || Reflect.ownKeys(raw).length !== 2) throw invalidExport() + const turn = Object.getOwnPropertyDescriptor(raw, 'turnId') + const format = Object.getOwnPropertyDescriptor(raw, 'format') + if (!turn?.enumerable || !format?.enumerable || !validSid(turn.value) || !formats.has(format.value)) throw invalidExport() + return { turnId: turn.value, format: format.value } +} + +function metadata(text, sid) { + if (text === null) return emptyIndex() + const index = parseNativeJSON(text) + // Atomic writer emits one canonical JSON representation. Reject duplicate keys, + // extra fields, oversized arrays, and IDs from a different session. + if (!fields(index, ['version', 'rows']) || index.version !== 1 || !Array.isArray(index.rows) || index.rows.length > 512 || + text !== JSON.stringify(index)) throw deliveryStorageError() + const ids = new Set() + for (const row of index.rows) { + if (!fields(row, ['id', 'turnId', 'format', 'messageIndex', 'revision']) || !validDeliveryTurn(row.turnId) || !formats.has(row.format) || + !Number.isSafeInteger(row.messageIndex) || row.messageIndex < 1 || row.messageIndex > 511 || !revision(row.revision) || + row.id !== groupId(sid, 'reply', row.turnId, row.format) || ids.has(row.id)) throw deliveryStorageError() + ids.add(row.id) + } + return index +} + +function replyRecord(row, reply) { + return { + id: row.id, origin: 'reply', turnId: row.turnId, messageIndex: reply.messageIndex, entries: [{ + index: 0, name: `reply-${String(reply.ordinal + 1).padStart(3, '0')}.${row.format}`, size: Buffer.byteLength(reply.text), + revision: row.revision, mime: formats.get(row.format) + }] + } +} + +function checkRows(index, replies) { + const records = [] + const stale = new Set() + const verified = new Map() + for (const [at, row] of index.rows.entries()) { + const reply = replies.get(row.turnId) + if (!reply || reply.messageIndex !== row.messageIndex || (reply.revision ??= digest(reply.text)) !== row.revision) { + stale.add(row.turnId) + continue + } + records.push({ row, reply, at }) + } + records.sort((a, b) => b.row.messageIndex - a.row.messageIndex || b.at - a.at) + for (const { row, reply } of records) { + if (!stale.has(row.turnId)) verified.set(row.id, replyRecord(row, reply)) + } + return { verified, stale } +} + +/** Dedicated synchronous delivery domain; ordinary chat snapshots and events are unchanged. + * The native writer lock is already held by the caller (the workbench owner). */ +export function createDeliveryRecords({ dataDir, validSid, ledgerKey, active, closing, blocked, cached, classify, attachedIndex, hasMedia }) { + const ambiguous = new Set() + + function view(sid, use) { + if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id') + if (closing()) throw new HttpError(503, 'chat_closed') + if (blocked(sid) || ambiguous.has(sid)) throw deliveryStorageError() + try { + return withDeliveryFiles(dataDir, sid, files => { + const source = files?.readMain() + const expected = cached(sid) + if (!source) throw expected ? deliveryStorageError() : missing() + const session = source.value + if (!object(session) || session.id !== sid || typeof session.title !== 'string' || + !time(session.createdAt) || !time(session.updatedAt)) throw deliveryStorageError() + // Desktop cache hydration may include a compacted prefix. Its read-only projection + // deliberately ignores that cache; Web writers must match the confirmed native file. + if (expected && !isDeepStrictEqual(session, Object.fromEntries(Object.entries(expected).filter(([, value]) => value !== undefined)))) { + throw deliveryStorageError() + } + const messages = nativeMessages(files, sid, session) + if (!Object.hasOwn(session, ledgerKey)) { + const ownsDeliveries = Object.hasOwn(session, 'delivered') + const records = ownsDeliveries ? desktopDeliveryRecords(sid, messages, session.delivered) : [] + const kind = ownsDeliveries || session.compacted !== undefined || classify(session) !== 'legacy_text' + ? 'unsupported_history' : 'read_only_session' + return use({ records, kind }) + } + const unsupported = () => use({ records: [], kind: 'unsupported_history' }) + if (!source.privateMode) throw deliveryStorageError() + if (session.compacted !== undefined || classify(session) !== 'text' || !hasMedia(expected ?? session, session)) return unsupported() + const replies = webReplies(session, session[ledgerKey], attachedIndex(session)) + if (!replies) return unsupported() + const index = metadata(files.readMetadata(), sid) + return use({ files, replies, index, ...checkRows(index, replies) }) + }) + } catch (error) { + if (error instanceof HttpError) throw error + throw deliveryStorageError() + } + } + + function deliverySnapshot(sid) { + return view(sid, ({ records, replies, verified, stale }) => ({ + records: records ?? [...verified.values()], + candidates: replies && !active(sid) ? [...replies.values()].reverse().filter(reply => !stale.has(reply.turnId)) + .map(({ turnId, messageIndex }) => ({ turnId, messageIndex })) : [] + })) + } + + function listDeliveryRecords(sid) { return deliverySnapshot(sid).records } + + function exportReplyDelivery(sid, raw, verifyOwner) { + if (!validSid(sid)) throw new HttpError(400, 'invalid_session_id') + const { turnId, format } = exportInput(raw, validSid) + // This callback can reenter application code. Check writer state only after it returns. + if (verifyOwner !== undefined) { + const verified = verifyOwner(sid) + if (verified === false || typeof verified?.then === 'function') throw new HttpError(401, 'unauthorized') + } + if (active(sid)) throw new HttpError(409, 'turn_in_progress') + let writing = false + try { + return view(sid, ({ files, replies, index, verified, stale, kind }) => { + if (!replies) throw new HttpError(409, kind) + if (stale.size) throw deliveryStorageError() + const reply = replies.get(turnId) + if (!reply) throw ineligible() + const id = groupId(sid, 'reply', turnId, format) + const prior = verified.get(id) + if (prior) { + if (prior.turnId !== turnId || !prior.entries[0].name.endsWith(`.${format}`)) throw deliveryStorageError() + return { created: false, record: prior } + } + if (index.rows.length >= 512) throw deliveryStorageError() + const row = { id, turnId, format, messageIndex: reply.messageIndex, revision: reply.revision ?? digest(reply.text) } + writing = true + files.saveMetadata(JSON.stringify({ ...index, rows: [...index.rows, row] })) + return { created: true, record: replyRecord(row, reply) } + }) + } catch (error) { + if (writing) ambiguous.add(sid) + throw error + } + } + + function readReplyDelivery(sid, id, index) { + if (!validSid(sid) || !validGroupId(id) || index !== 0) return null + try { + return view(sid, ({ replies, verified }) => { + const record = verified?.get(id) + if (!record) return null + const { name, revision, mime } = record.entries[0] + return { name, bytes: Buffer.from(replies.get(record.turnId).text, 'utf8'), revision, mime } + }) + } catch (error) { + if (error instanceof HttpError && [404, 413, 503].includes(error.status)) return null + throw error + } + } + + return { deliverySnapshot, listDeliveryRecords, exportReplyDelivery, readReplyDelivery } +} diff --git a/apps/headless/src/chat/text-turns.mjs b/apps/headless/src/chat/text-turns.mjs index b20c8ef4..a760c8b3 100644 --- a/apps/headless/src/chat/text-turns.mjs +++ b/apps/headless/src/chat/text-turns.mjs @@ -4,6 +4,7 @@ import { consumeModelStep, createChatStore, isValidSessionId, modelMessages } fr import { connectProvider } from '../business/model-connection.mjs' import { chatScope } from '../events/index.mjs' import { HttpError } from '../http/policy.mjs' +import { createDeliveryRecords } from './delivery-records.mjs' import { confirmPreferenceStorage, preflightPreferenceStorage } from './session-preferences-storage.mjs' import { PREFERENCES_META, checkPreferenceRevision, firstTitle, listPreferenceFields, managedModel, preferenceChanges, @@ -185,7 +186,7 @@ function appendNotice(notices, after, status, reason, text) { /** One instance per data directory and journal. The owner closes the journal after awaiting close(). * resolveRole only reads trusted library state and returns the current enabled role projection. */ -export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads }) { +export function createTextTurns({ dataDir, settings, journal, version, allowedOrigins, resolveRole, uploads, deliveries }) { if (typeof settings?.getProvider !== 'function' || !['snapshot', 'snapshotAndSubscribe', 'publishChat', 'publishSessionsChanged'] .every(fn => typeof journal?.[fn] === 'function')) throw new TypeError('Text turns require settings and an event journal') if (resolveRole !== undefined && typeof resolveRole !== 'function') throw new TypeError('resolveRole must be a function') @@ -202,12 +203,14 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr const active = new Map() const unconfirmed = new Map() // Quarantine ambiguous writes until restart; never replay a charged request. const hidden = new Set() // A failed create may leave a session only in the core's cache. + const deliverySessions = deliveries === true ? new Map() : undefined let closing function lookupSession(sid) { warned = false const s = hidden.has(sid) ? undefined : store.getSession(sid) if (s && warned) incomplete.add(s) + if (s && Object.hasOwn(s, META)) deliverySessions?.set(sid, s) return s } @@ -283,6 +286,7 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr s = store.ensureSession(id, role ? { personaId: role.id, model: role.model || undefined } : undefined) s[META] = { version: 1, messageCount: 0, requests: [] } store.saveStrict(id) + deliverySessions?.set(id, s) } catch { hidden.add(id) throw storageError() @@ -657,8 +661,18 @@ export function createTextTurns({ dataDir, settings, journal, version, allowedOr const s = lookupSession(sid) return !!s && compatibility(s) === 'text' } + const records = deliverySessions && createDeliveryRecords({ + dataDir, validSid, ledgerKey: META, + active: sid => active.has(sid), closing: () => Boolean(closing), + blocked: sid => hidden.has(sid) || unconfirmed.has(sid) || incomplete.has(deliverySessions.get(sid)), + cached: sid => deliverySessions.get(sid), classify: compatibility, attachedIndex, + hasMedia(cached, source) { + const index = attachedIndex(source) + return !index || (!mediaUnconfirmed.has(cached) && attachments.available(index)) + } + }) return Object.freeze({ create, list, attach, snapshot, send, stop, close, getPreferences, patchPreferences, - attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession + attachmentScope, describeCommittedAttachment, readCommittedAttachment, hasBrowserSession, ...records }) } diff --git a/apps/headless/test/delivery-records.test.mjs b/apps/headless/test/delivery-records.test.mjs new file mode 100644 index 00000000..2afc1a00 --- /dev/null +++ b/apps/headless/test/delivery-records.test.mjs @@ -0,0 +1,327 @@ +import assert from 'node:assert/strict' +import { createHash, randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { promises as fs } from 'node:fs' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { createChatStore } from '../dist/chat-core.mjs' +import { createTextTurns } from '../src/chat/text-turns.mjs' +import { createEventJournal, SESSIONS_SCOPE } from '../src/events/index.mjs' +import { acquireWriterLock } from '../src/runtime/writer-lock.mjs' + +const model = 'fixture:local/chat' +const groupPattern = /^d_[a-f0-9]{32}$/u +const revisionPattern = /^[a-f0-9]{64}$/u +const error = (status, code) => ({ status, code, message: code }) +const nativeLedger = '_devaHeadlessTextTurns' +const opts = { timeout: 12_000 } +const complete = (res, text, why = 'stop') => { + res.writeHead(200, { 'content-type': 'text/event-stream' }) + if (text) res.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: text }, finish_reason: null }] })}\n\n`) + res.end(`data: ${JSON.stringify({ choices: [{ index: 0, delta: {}, finish_reason: why }] })}\n\ndata: [DONE]\n\n`) +} + +async function fixture(t) { + const root = await fs.mkdtemp(join(await fs.realpath(tmpdir()), 'deva-delivery-records-')) + const dataDir = join(root, 'home') + const chats = join(dataDir, 'data', 'chats') + let release = acquireWriterLock(dataDir) + let journal, turns + const calls = [] + const responses = [] + const faults = [] + const server = createServer((req, res) => { + void (async () => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + calls.push(JSON.parse(Buffer.concat(chunks))) + await responses.shift()(res) + })().catch(e => { faults.push(e); res.destroy() }) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const origin = `http://127.0.0.1:${server.address().port}` + const settings = { async getProvider(id) { + if (id !== 'fixture') return null + return { id, enabled: true, purpose: 'llm', adapter: 'openai', apiHost: `${origin}/v1`, models: [{ id: 'local/chat', enabled: true }] } + } } + function open(deliveries = true) { + journal = createEventJournal() + turns = createTextTurns({ dataDir, settings, journal, allowedOrigins: [origin], version: 'fixture', deliveries }) + return { turns, journal } + } + t.after(async () => { + await turns?.close() + journal?.close() + release() + server.closeAllConnections() + await new Promise(resolve => server.close(resolve)) + await fs.rm(root, { recursive: true, force: true }) + assert.deepEqual(faults, []) + }) + return { + ...open(), calls, responses, root, dataDir, chats, + native: sid => join(chats, `${sid}.json`), sidecar: sid => join(chats, `${sid}.deliveries-v1`), + async restart(deliveries) { + await turns.close() + journal.close() + release() + release = acquireWriterLock(dataDir) + return open(deliveries) + } + } +} + +async function start(turns, sid, id) { + const events = [] + let finish + const done = new Promise(resolve => { finish = resolve }) + const { subscription } = turns.attach(sid, { onEvent(item) { + events.push(item.event) + if (item.event.type === 'done') finish(item) + } }) + assert.equal(subscription.status, 'subscribed') + const receipt = await turns.send({ sid, clientRequestId: id, text: 'Local QA fixture', model }) + return { ...receipt, events, done: done.finally(subscription.close) } +} + +const snapshot = (turns, sid) => turns.snapshot(sid).state + +async function turn(fx, sid, id, text, status) { + fx.responses.push(res => complete(res, text, status)) + const { turnId, done } = await start(fx.turns, sid, id) + await done + return turnId +} + +test('exports raw native UTF-8, preserves ordinary chat and replays without writes or model charges', opts, async t => { + const fx = await fixture(t) + const { turns, journal, dataDir } = fx + assert.throws(() => acquireWriterLock(dataDir), /Another writer holds/) + const sid = turns.create().id + const foreign = turns.create().id + const raw = ' # Native title\r\n\n汉字 café 𝄞 🎉\r\n\tending \n' + const turnId = await turn(fx, sid, 'done', raw) + const state = snapshot(turns, sid) + assert.deepEqual(state.messages, [{ role: 'user', content: 'Local QA fixture' }, { role: 'assistant', content: raw }]) + assert.deepEqual(turns.deliverySnapshot(sid), { records: [], candidates: [{ turnId, messageIndex: 1 }] }) + const sessionsCursor = journal.snapshot(SESSIONS_SCOPE).cursor + const nativeBefore = await fs.readFile(fx.native(sid)) + const nativeStat = await fs.stat(fx.native(sid)) + assert.throws(() => turns.exportReplyDelivery(sid, { turnId, format: 'md', bytes: 'client' }), error(400, 'invalid_delivery_export')) + assert.throws(() => turns.exportReplyDelivery(sid, { turnId, format: 'html' }), error(400, 'invalid_delivery_export')) + assert.throws(() => turns.exportReplyDelivery(foreign, { turnId, format: 'md' }), error(404, 'reply_not_exportable')) + assert.throws(() => turns.exportReplyDelivery(sid, { turnId, format: 'md' }, value => { + assert.equal(value, sid) + return false + }), error(401, 'unauthorized')) + await assert.rejects(fs.access(fx.sidecar(sid)), { code: 'ENOENT' }) + const first = turns.exportReplyDelivery(sid, { turnId, format: 'md' }) + assert.equal(first.created, true) + const id = first.record.id + const hash = createHash('sha256').update(raw).digest('hex') + assert.match(id, groupPattern) + assert.match(hash, revisionPattern) + assert.deepEqual(first.record, { id, origin: 'reply', turnId, messageIndex: 1, entries: [{ + index: 0, name: 'reply-001.md', size: Buffer.byteLength(raw), revision: hash, mime: 'text/markdown; charset=utf-8' + }] }) + const metadataStat = await fs.stat(fx.sidecar(sid)) + assert.equal(metadataStat.mode & 0o777, 0o600) + assert.deepEqual(turns.exportReplyDelivery(sid, { turnId, format: 'md' }), { ...first, created: false }) + assert.equal((await fs.stat(fx.sidecar(sid))).ino, metadataStat.ino) + const txt = turns.exportReplyDelivery(sid, { turnId, format: 'txt' }).record + assert.notEqual(txt.id, id) + assert.deepEqual(turns.listDeliveryRecords(sid), [txt, first.record]) + const expected = { name: 'reply-001.md', bytes: Buffer.from(raw), revision: hash, mime: 'text/markdown; charset=utf-8' } + assert.deepEqual(turns.readReplyDelivery(sid, id, 0), expected) + assert.equal(turns.readReplyDelivery(foreign, id, 0), null) + assert.equal(turns.readReplyDelivery(sid, id, 1), null) + assert.equal(turns.readReplyDelivery(sid, `${id}\n`, 0), null) + assert.equal(turns.readReplyDelivery(sid, id, '0'), null) + const privateIndex = JSON.parse(await fs.readFile(fx.sidecar(sid), 'utf8')) + assert.ok(privateIndex.rows.every(row => !Object.hasOwn(row, 'text') && !Object.hasOwn(row, 'bytes') && !Object.hasOwn(row, 'path'))) + assert.ok((await fs.stat(fx.sidecar(sid))).size < 512) + assert.deepEqual(await fs.readFile(fx.native(sid)), nativeBefore) + assert.equal((await fs.stat(fx.native(sid))).ino, nativeStat.ino) + assert.deepEqual(journal.snapshot(SESSIONS_SCOPE).cursor, sessionsCursor) + assert.deepEqual(snapshot(turns, sid), state) + const reopened = (await fx.restart()).turns + assert.deepEqual(reopened.listDeliveryRecords(sid), [txt, first.record]) + assert.deepEqual(reopened.exportReplyDelivery(sid, { turnId, format: 'md' }), { ...first, created: false }) + assert.deepEqual(reopened.readReplyDelivery(sid, id, 0), expected) + assert.equal(fx.calls.length, 1) + assert.deepEqual(fx.calls[0].messages, [{ role: 'system', content: 'You are a helpful general-purpose assistant. Reply in plain text.' }, + { role: 'user', content: 'Local QA fixture' }]) +}) + +test('only unambiguous completed replies qualify; active, empty, partial and failed turns stay out', opts, async t => { + const fx = await fixture(t) + const { turns } = fx + const sid = turns.create().id + const good = await turn(fx, sid, 'first', 'full') + const blank = await turn(fx, sid, 'blank', ' \n ') + const partial = await turn(fx, sid, 'partial', 'partial output', 'length') + fx.responses.push(res => res.writeHead(500).end()) + const failed = await start(turns, sid, 'failed') + await failed.done + let entered + const admitted = new Promise(resolve => { entered = resolve }) + fx.responses.push(res => { + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.write('data: {"choices":[{"index":0,"delta":{"content":"stopped partial"}}]}\n\n') + entered() + }) + const active = await start(turns, sid, 'aborted') + await admitted + assert.deepEqual(turns.deliverySnapshot(sid).candidates, []) + assert.throws(() => turns.exportReplyDelivery(sid, { turnId: good, format: 'txt' }), error(409, 'turn_in_progress')) + assert.deepEqual(turns.stop({ sid, turnId: active.turnId }), { stopped: true }) + await active.done + assert.deepEqual(turns.deliverySnapshot(sid).candidates, [{ turnId: good, messageIndex: 1 }]) + for (const turnId of [blank, partial, failed.turnId, active.turnId]) { + assert.throws(() => turns.exportReplyDelivery(sid, { turnId, format: 'txt' }), error(404, 'reply_not_exportable')) + } + const native = JSON.parse(await fs.readFile(fx.native(sid), 'utf8')) + assert.deepEqual(native[nativeLedger].requests.map(({ status, reason }) => [status, reason]), [ + ['completed', null], ['completed', 'empty'], ['completed', 'truncated'], ['failed', 'model_failed'], ['aborted', 'stopped'] + ]) + native.messages.splice(2, 1, { role: 'assistant', content: [{ type: 'text', text: 'ambiguous' }] }) + await fs.writeFile(fx.native(sid), JSON.stringify(native)) + assert.throws(() => turns.deliverySnapshot(sid), error(503, 'chat_storage_unconfirmed')) + const reopened = (await fx.restart()).turns + assert.deepEqual(reopened.deliverySnapshot(sid), { records: [], candidates: [] }) + assert.throws(() => reopened.exportReplyDelivery(sid, { turnId: good, format: 'md' }), error(409, 'unsupported_history')) + const disabled = (await fx.restart(false)).turns + assert.equal(disabled.deliverySnapshot, undefined) + assert.equal(disabled.exportReplyDelivery, undefined) +}) + +test('native and sidecar corruption fail closed without replacing evidence or serving stale bytes', opts, async t => { + const fx = await fixture(t) + const { turns } = fx + const sid = turns.create().id + const turnId = await turn(fx, sid, 'native', 'Authoritative source') + const input = { turnId, format: 'md' } + const { record } = turns.exportReplyDelivery(sid, input) + const sidecar = fx.sidecar(sid) + const correct = await fs.readFile(sidecar, 'utf8') + const elsewhere = join(fx.root, 'private-fixture') + await fs.rename(sidecar, elsewhere) + await fs.symlink(elsewhere, sidecar) + assert.equal(turns.readReplyDelivery(sid, record.id, 0), null) + assert.throws(() => turns.exportReplyDelivery(sid, input), error(503, 'chat_storage_unconfirmed')) + assert.equal(await fs.readFile(elsewhere, 'utf8'), correct) + await fs.unlink(sidecar) + await fs.rename(elsewhere, sidecar) + const duplicate = correct.replace('"version":1', '"version":1,"version":1') + await fs.writeFile(sidecar, duplicate) + assert.throws(() => turns.deliverySnapshot(sid), error(503, 'chat_storage_unconfirmed')) + assert.equal(await fs.readFile(sidecar, 'utf8'), duplicate) + await fs.writeFile(sidecar, correct) + const native = JSON.parse(await fs.readFile(fx.native(sid), 'utf8')) + native.messages[1].content[0].text = 'Swapped source' + await fs.writeFile(fx.native(sid), JSON.stringify(native)) + assert.throws(() => turns.exportReplyDelivery(sid, input), error(503, 'chat_storage_unconfirmed')) + const reopened = (await fx.restart()).turns + assert.equal(reopened.readReplyDelivery(sid, record.id, 0), null) + assert.deepEqual(reopened.deliverySnapshot(sid), { records: [], candidates: [] }) + assert.throws(() => reopened.exportReplyDelivery(sid, { turnId, format: 'txt' }), error(503, 'chat_storage_unconfirmed')) + assert.equal(await fs.readFile(sidecar, 'utf8'), correct) +}) + +test('failed strict terminal persistence never exposes unconfirmed final text', opts, async t => { + const fx = await fixture(t) + const sid = fx.turns.create().id + const obstruction = join(fx.chats, '_index.pending') + fx.responses.push(async res => { + await fs.mkdir(obstruction) + complete(res, 'Uncommitted final text') + }) + const receipt = await start(fx.turns, sid, 'bad-save') + assert.equal((await receipt.done).event.stopReason, 'error') + assert.throws(() => fx.turns.deliverySnapshot(sid), error(503, 'chat_storage_unconfirmed')) + assert.equal(JSON.parse(await fs.readFile(fx.native(sid), 'utf8'))[nativeLedger].requests[0].status, 'running') + assert.throws(() => fx.turns.exportReplyDelivery(sid, { turnId: receipt.turnId, format: 'md' }), error(503, 'chat_storage_unconfirmed')) + await fs.rmdir(obstruction) + const reopened = (await fx.restart()).turns + assert.deepEqual(reopened.deliverySnapshot(sid), { records: [], candidates: [] }) + assert.throws(() => reopened.exportReplyDelivery(sid, { turnId: receipt.turnId, format: 'md' }), error(404, 'reply_not_exportable')) + await assert.rejects(fs.access(fx.sidecar(sid)), { code: 'ENOENT' }) +}) + +const use = (id, name = 'present_files') => ({ role: 'assistant', content: [{ type: 'tool_use', id, name, input: { paths: ['/never-use-arguments.txt'] } }] }) +const result = (toolUseId, isError) => ({ role: 'user', content: [{ type: 'tool_result', toolUseId, content: '已交付 1 个文件', isError }] }) + +test('desktop projection requires an actual successful unique tool pair and the exact native sidecar', opts, async t => { + const { turns, calls, dataDir, native, sidecar, root } = await fixture(t) + const store = createChatStore({ dataDir }) + const s = store.ensureSession(randomUUID()) + const foreign = join(root, 'foreign-project', 'report.txt') // Deliberately absent; the file domain decides access later. + const other = 'C:\\Example\\QA\\summary.md' + s.messages = [ + { role: 'user', content: 'Desktop request' }, use('confirmed'), result('confirmed'), + use('failed'), result('failed', true), use('missing-table'), result('missing-table'), + use('duplicate'), result('duplicate'), use('duplicate', 'read_file'), result('duplicate'), + use('wrong-tool', 'read_file'), result('wrong-tool'), use('bad-entry'), result('bad-entry'), + use('bad-duplicate'), result('bad-duplicate'), use('second', 'present_files'), result('second', false), + use('unmatched'), { role: 'assistant', content: 'gap' }, result('unmatched'), use('partial') + ] + s.delivered = { + confirmed: [foreign, other], failed: [foreign], duplicate: [foreign], 'wrong-tool': [foreign], + 'bad-entry': [foreign, 'relative.md'], 'bad-duplicate': [foreign, foreign], second: ['/absolute/qa.pdf'], + unmatched: [foreign], partial: [foreign], 'no-use': [foreign] + } + store.saveStrict(s.id) + const peer = store.ensureSession(randomUUID()) + peer.messages = s.messages + peer.delivered = s.delivered + store.saveStrict(peer.id) + const main = await fs.readFile(native(s.id)) + const view = turns.deliverySnapshot(s.id) + assert.deepEqual(view.candidates, []) + assert.deepEqual(view.records.map(({ origin, messageIndex, entries }) => ({ origin, messageIndex, entries })), [ + { origin: 'desktop', messageIndex: 17, entries: [{ index: 0, path: '/absolute/qa.pdf' }] }, + { origin: 'desktop', messageIndex: 1, entries: [{ index: 0, path: foreign }, { index: 1, path: other }] } + ]) + for (const [at, record] of view.records.entries()) { + assert.match(record.id, groupPattern) + assert.notEqual(record.id, turns.listDeliveryRecords(peer.id)[at].id) + assert.equal(turns.readReplyDelivery(s.id, record.id, 0), null) + } + assert.equal(snapshot(turns, s.id).compatibility, 'unsupported') + assert.equal(snapshot(turns, s.id).messages, null) + assert.throws(() => turns.exportReplyDelivery(s.id, { turnId: 'confirmed', format: 'md' }), error(409, 'unsupported_history')) + assert.deepEqual(await fs.readFile(native(s.id)), main) + await assert.rejects(fs.access(sidecar(s.id)), { code: 'ENOENT' }) + assert.deepEqual(calls, []) +}) + +test('bounded native compacted prefix participates in uniqueness and is never repaired here', opts, async t => { + const { turns, native, chats, dataDir } = await fixture(t) + const writer = createChatStore({ dataDir }) + const s = writer.ensureSession(randomUUID()) + s.messages = [use('visible'), result('visible')] + s.delivered = { visible: ['/qa/visible.md'], prefix: ['/qa/prefix.txt'] } + writer.saveStrict(s.id) + const source = JSON.parse(await fs.readFile(native(s.id), 'utf8')) + const file = `${s.id}.compacted-fixture.jsonl` + const filename = join(chats, file) + source.compacted = { count: 2, file } + await fs.writeFile(native(s.id), JSON.stringify(source)) + await fs.writeFile(filename, [use('prefix'), result('prefix'), use('visible')].map(value => `${JSON.stringify(value)}\n`).join(''), { mode: 0o600 }) + const view = turns.deliverySnapshot(s.id) + assert.deepEqual(view.records.map(({ messageIndex, entries }) => [messageIndex, entries[0].path]), [[2, '/qa/visible.md'], [0, '/qa/prefix.txt']]) + source.compacted.count = 3 + await fs.writeFile(native(s.id), JSON.stringify(source)) + assert.deepEqual(turns.listDeliveryRecords(s.id).map(record => record.entries[0].path), ['/qa/prefix.txt']) + source.compacted.count = 20000 + await fs.writeFile(native(s.id), JSON.stringify(source)) + assert.throws(() => turns.deliverySnapshot(s.id), error(413, 'delivery_history_limit')) + source.compacted.count = 4 + await fs.writeFile(native(s.id), JSON.stringify(source)) + assert.throws(() => turns.deliverySnapshot(s.id), error(503, 'chat_storage_unconfirmed')) + assert.deepEqual(JSON.parse(await fs.readFile(native(s.id), 'utf8')), source) + assert.equal((await fs.stat(filename)).isFile(), true) +}) From 59d7e6f58e598ba2c047648f917bacebf063cfac Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Thu, 26 Nov 2026 16:58:02 +0800 Subject: [PATCH 2/4] =?UTF-8?q?feat(files):=20=E5=9C=A8=E6=8E=88=E6=9D=83?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E5=86=85=E6=A0=A1=E9=AA=8C=E4=BA=A4=E4=BB=98?= =?UTF-8?q?=E6=88=90=E5=93=81=20/=20verify=20delivered=20documents=20in=20?= =?UTF-8?q?explicitly=20registered=20projects?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/business/workspace-catalog.mjs | 35 +- apps/headless/src/files/delivery-files.mjs | 136 ++++ apps/headless/src/files/delivery-office.mjs | 592 ++++++++++++++++++ .../headless/src/files/workspace-files-fd.mjs | 6 + .../src/files/workspace-files-pin.mjs | 120 ++++ apps/headless/src/files/workspace-files.mjs | 121 +--- apps/headless/test/delivery-files.test.mjs | 327 ++++++++++ apps/headless/test/delivery-office.test.mjs | 158 +++++ .../fixtures/delivery-office-fixtures.mjs | 176 ++++++ 9 files changed, 1560 insertions(+), 111 deletions(-) create mode 100644 apps/headless/src/files/delivery-files.mjs create mode 100644 apps/headless/src/files/delivery-office.mjs create mode 100644 apps/headless/src/files/workspace-files-pin.mjs create mode 100644 apps/headless/test/delivery-files.test.mjs create mode 100644 apps/headless/test/delivery-office.test.mjs create mode 100644 apps/headless/test/fixtures/delivery-office-fixtures.mjs diff --git a/apps/headless/src/business/workspace-catalog.mjs b/apps/headless/src/business/workspace-catalog.mjs index 0bd1f437..ddc49213 100644 --- a/apps/headless/src/business/workspace-catalog.mjs +++ b/apps/headless/src/business/workspace-catalog.mjs @@ -1,7 +1,11 @@ import { createHash } from 'node:crypto' import { openSync, opendirSync, realpathSync } from 'node:fs' import { isAbsolute, join, relative, resolve, sep } from 'node:path' -import { DIRECTORY, close, fdPath, mountId, openAbsoluteDirectory, sameInode, stat, visibleName } from '../files/workspace-files-fd.mjs' +import { DIRECTORY, close, fdPath, mountId, openAbsoluteDirectory, sameInode, stat, validWorkspaceName, visibleName, workspacePathParts } from '../files/workspace-files-fd.mjs' + +const deliverySystemRoots = ['/boot', '/usr', '/bin', '/sbin', '/lib', '/lib64', '/var/log', '/var/cache', '/var/spool', '/var/backups'] +const privateDeliveryName = /^(?:credentials?|secrets?|private[-_ ]?keys?|api[-_ ]?keys?|(?:access[-_ ]?|refresh[-_ ]?)tokens?|id[-_](?:rsa|dsa|ecdsa|ed25519)|known_hosts|authorized_keys|passwd|shadow)(?:[._ -]|$)|\.(?:pem|key|p12|pfx|kdbx)(?:\.|$)/iu +const hiddenDeliveryName = name => privateDeliveryName.test(name) || /[\p{Cf}\p{Zl}\p{Zp}]/u.test(name) const unavailable = () => Object.assign(Error('Workspace is unavailable'), { code: 'ERR_WORKSPACE_UNAVAILABLE', status: 404, statusCode: 404 }) const validId = id => typeof id === 'string' && /^w_[a-f0-9]{32}$/.test(id) @@ -25,11 +29,18 @@ function overlapsReserved(base, path) { /** Only first-level real directories of an explicitly mounted root are choices. resolveRoot * serves memory's canonical project-key calculation; file consumers own a pinProject lease. */ export function openWorkspaceCatalog({ root, privateRoots = [] }) { - if (root == null || root === '') return Object.freeze({ list: () => [], resolveRoot: () => undefined, pinProject() { throw unavailable() }, close() {} }) + if (root == null || root === '') return Object.freeze({ + list: () => [], resolveRoot: () => undefined, resolveDeliveryPath: () => null, + pinProject() { throw unavailable() }, close() {}, + }) if (typeof root !== 'string' || !isAbsolute(root) || root.includes('\0')) throw unavailable() const base = resolve(root) const reserved = [...privateRoots, '/proc', '/dev', '/sys', '/etc', '/run', '/root'] if (base === '/' || reserved.some(path => overlapsReserved(base, path))) throw unavailable() + // Apply the extra system-directory exclusion to native deliveries only. Workspace browsing + // and project identifiers keep their existing contract. + const deliveryEnabled = !deliverySystemRoots.some(path => overlapsReserved(base, path)) + const deliveryPrefix = base + sep let fd, rootInfo, rootMount try { fd = openAbsoluteDirectory(base) @@ -89,6 +100,26 @@ export function openWorkspaceCatalog({ root, privateRoots = [] }) { if (!validId(id)) return undefined return items().find(item => item.id === id)?.path }, + // Server-read native history only. No absolute path is opened here: derive the + // catalog ID from an actual direct child. The caller must still pin that ID and + // verify every intermediate directory and leaf before claiming the item. + resolveDeliveryPath(absolute) { + if (!deliveryEnabled || typeof absolute !== 'string' || absolute.length > 4095 || + !absolute.startsWith(deliveryPrefix) || Buffer.byteLength(absolute) > 4095) return null + const split = absolute.indexOf(sep, deliveryPrefix.length) + if (split < 0) return null + const name = absolute.slice(deliveryPrefix.length, split) + const path = absolute.slice(split + 1) + const parts = workspacePathParts(path) + if (!validWorkspaceName(name) || hiddenDeliveryName(name) || !parts || parts.some(hiddenDeliveryName)) return null + let item + try { + assertRoot() + item = openChild(name) + assertRoot() + return { id: projectId(item.path, item.info), path } + } catch { return null } finally { close(item?.sub) } + }, pinProject(id) { if (!validId(id)) throw unavailable() const record = items().find(item => item.id === id) diff --git a/apps/headless/src/files/delivery-files.mjs b/apps/headless/src/files/delivery-files.mjs new file mode 100644 index 00000000..f059cf99 --- /dev/null +++ b/apps/headless/src/files/delivery-files.mjs @@ -0,0 +1,136 @@ +import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto' +import { extname } from 'node:path' +import { setImmediate } from 'node:timers/promises' +import { AVATAR_MAX_BYTES, avatarImageMime } from '../../dist/library-core.mjs' +import { officeDeliveryMime } from './delivery-office.mjs' +import { decodeUtf8 } from './workspace-files-fd.mjs' +import { assertFile, readBytes, withDirectory, withFilePin, withReadablePin } from './workspace-files-pin.mjs' + +const text = { kind: 'text', mime: 'text/plain', maxBytes: 2 * 1024 * 1024 } +const raster = mime => ({ kind: 'image', mime, maxBytes: AVATAR_MAX_BYTES }) +const jpeg = raster('image/jpeg') +const pdf = { kind: 'document', mime: 'application/pdf', maxBytes: 8 * 1024 * 1024 } +const office = (ext, subtype) => ({ ext, kind: 'document', mime: 'application/vnd.openxmlformats-officedocument.' + subtype, maxBytes: 8 * 1024 * 1024 }) +const types = new Map([ + ['.txt', text], ['.md', text], ['.csv', text], ['.json', text], + ['.png', raster('image/png')], ['.jpg', jpeg], ['.jpeg', jpeg], ['.webp', raster('image/webp')], ['.pdf', pdf], + ['.docx', office('.docx', 'wordprocessingml.document')], ['.xlsx', office('.xlsx', 'spreadsheetml.sheet')], + ['.pptx', office('.pptx', 'presentationml.presentation')], +]) +const nonText = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u +const activeTextPrefix = /^(?:#!|%PDF-|<\?xml\b|]))/iu +const keyPrefix = /^-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/u +const pdfMagic = /^%PDF-(?:1\.[0-7]|2\.0)[\r\n]/u +const revisionPattern = /^r_[0-9a-f]{64}$/u +const cacheLimit = 128 + +class DeliveryFileError extends Error { + constructor(kind, status, message) { + super(message) + this.code = `ERR_DELIVERY_FILE_${kind}` + this.status = this.statusCode = status + } +} +const invalid = () => new DeliveryFileError('INVALID', 400, 'Invalid delivery file request') +const conflict = () => new DeliveryFileError('CONFLICT', 409, 'Delivery file changed or is unavailable') +const unsupported = () => new DeliveryFileError('UNSUPPORTED', 415, 'Delivery file is not available in this format') +const equalTag = (a, b) => timingSafeEqual(Buffer.from(a), Buffer.from(b)) + +function metadata(name, type, info, status, revision = null) { + const ready = status === 'ready' + return { + name, kind: type?.kind ?? 'document', size: info && info.size <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(info.size) : null, + status, revision, canDownload: ready, canPreview: ready && type.kind === 'image', canLocate: ready, + } +} +function validateBytes(type, bytes) { + if (type === pdf) return pdfMagic.test(bytes.subarray(0, 9).toString('latin1')) ? 'ready' : 'unsupported' + if (type.ext) return officeDeliveryMime(type.ext, bytes) === type.mime ? 'ready' : 'unsupported' + if (type.kind === 'image') return avatarImageMime(bytes) === type.mime ? 'ready' : 'unsupported' + let content + try { content = decodeUtf8(bytes) } catch { return 'unsupported' } + const prefix = content.trimStart().slice(0, 1024) + if (keyPrefix.test(prefix)) return 'private' + return nonText.test(content) || activeTextPrefix.test(prefix) ? 'unsupported' : 'ready' +} + +/** Only accept paths taken from authenticated native history, never HTTP client input. */ +export function openDeliveryFiles({ catalog }) { + if (typeof catalog?.resolveDeliveryPath !== 'function' || typeof catalog?.pinProject !== 'function') { + throw TypeError('A workspace catalog is required') + } + const signingKey = randomBytes(32) + // Cache only validation outcomes/signatures, not file bytes or file descriptors. A hit + // still re-pins the named entry and checks metadata/access; all reads bypass this cache. + const settled = new Map() + function tag(domain, key, bytes) { + const signer = createHmac('sha256', signingKey).update(domain).update(key) + if (bytes) signer.update(bytes) + return signer.digest('hex').slice(0, 32) + } + function content(scope, name, pin, info, type, key, metaTag, full) { + let outcome = full ? undefined : settled.get(key) + let bytes + if (!outcome) { + // PDF is attachment-only. Its classifier and signature sample just magic plus + // the versioned inode metadata; a real download re-reads and checks all bytes. + bytes = withReadablePin(pin, info, fd => readBytes(fd, info, type === pdf && !full ? 9 : undefined), scope.project) + const status = validateBytes(type, bytes) + const signed = type === pdf ? bytes.subarray(0, 9) : bytes + outcome = { status, revision: status === 'ready' ? `r_${metaTag}${tag('content\0', key, signed)}` : null } + } + assertFile(scope, name, info) + settled.delete(key) + settled.set(key, outcome) + if (settled.size > cacheLimit) settled.delete(settled.keys().next().value) + return { ...outcome, bytes } + } + function inspectPinned(absolute, expected, variant) { + const grant = catalog.resolveDeliveryPath(absolute) + if (!grant) return null + const { id, path } = grant + const parts = path.split('/') + const name = parts.pop() + const type = types.get(extname(name).toLowerCase()) + return withDirectory(catalog, id, parts, scope => withFilePin(scope, name, ({ pin, info }) => { + if (!type || (info.mode & 0o7111n)) return { item: metadata(name, type, info, 'unsupported') } + if (info.size > type.maxBytes) return { item: metadata(name, type, info, 'too-large') } + const key = JSON.stringify([ + // The catalog ID binds the project device/inode. A directory's birth time may be + // derived from ctime on older Linux; unrelated sibling edits must not retag this file. + id, path, scope.project.mount, + info.dev, info.ino, info.birthtimeNs, info.ctimeNs, info.mtimeNs, info.size, info.mode, info.uid, info.gid, + ].map(String)) + const metaTag = tag('meta\0', key) + if (expected && !equalTag(expected.slice(2, 34), metaTag)) return null + const output = content(scope, name, pin, info, type, key, metaTag, + variant === 'download' || (variant === 'preview' && type.kind === 'image')) + if (output.status === 'private') return null + return { item: metadata(name, type, info, output.status, output.revision), id, path, type, bytes: output.bytes } + }, () => ({ item: metadata(name, type, null, 'missing') }))) + } + function lookupRevision(absolute, expected, variant) { + if (typeof expected !== 'string' || expected.length !== 66 || !revisionPattern.test(expected)) throw invalid() + let result + try { result = inspectPinned(absolute, expected, variant) } catch { throw conflict() } + if (!result?.item.revision || !equalTag(result.item.revision, expected)) throw conflict() + return result + } + return Object.freeze({ + async inspect(absolute) { + // Yield between cold metadata entries in the caller's bounded page scan. + await setImmediate() + try { return inspectPinned(absolute)?.item ?? null } catch { return null } + }, + async read(absolute, revision, variant) { + if (variant !== 'download' && variant !== 'preview') throw invalid() + const { item, type, bytes } = lookupRevision(absolute, revision, variant) + if (variant === 'preview' && !item.canPreview) throw unsupported() + return { bytes, mime: type.mime, name: item.name } + }, + async locate(absolute, revision) { + const { id, path } = lookupRevision(absolute, revision) + return { workspaceId: id, path } + }, + }) +} diff --git a/apps/headless/src/files/delivery-office.mjs b/apps/headless/src/files/delivery-office.mjs new file mode 100644 index 00000000..4083d128 --- /dev/null +++ b/apps/headless/src/files/delivery-office.mjs @@ -0,0 +1,592 @@ +import { performance } from 'node:perf_hooks' +import { inflateRawSync } from 'node:zlib' + +const MiB = 1024 * 1024 +const maxArchive = 8 * MiB +const maxExpanded = 32 * MiB +const maxEntries = 512 +const maxPart = 8 * MiB +const maxRaster = 2 * MiB +const maxMetadata = 4 * MiB +const maxManifest = 256 * 1024 +const maxRelationships = 128 * 1024 +const maxMain = 2 * MiB +const maxRatio = 250 +const maxXmlNodes = 60_000 +const maxXmlDepth = 96 +const maxAttributes = 96 +const maxPath = 240 +const maxExtra = 256 +const maxWorkMs = 250 + +const contentTypes = '[Content_Types].xml' +const rootRelationships = '_rels/.rels' +const schemas = 'http://schemas.openxmlformats.org/' +const strict = 'http://purl.oclc.org/ooxml/' +const packageTypes = `${schemas}package/2006/content-types` +const packageRels = `${schemas}package/2006/relationships` +const officeRels = `${schemas}officeDocument/2006/relationships` +const strictOfficeRels = `${strict}officeDocument/relationships` +const appType = 'application/vnd.openxmlformats-officedocument.' +const zipType = 'application/vnd.openxmlformats-package.' +const msType = 'application/vnd.ms-' +const wordType = `${appType}wordprocessingml.` +const excelType = `${appType}spreadsheetml.` +const pptType = `${appType}presentationml.` +const relsType = `${zipType}relationships+xml` +const xmlNamespace = 'http://www.w3.org/XML/1998/namespace' +const xmlnsNamespace = 'http://www.w3.org/2000/xmlns/' +const decodeUtf8 = new TextDecoder('utf-8', { fatal: true }) +const bad = Symbol('Invalid or unsupported Office package') +const requireThat = valid => { if (!valid) throw bad } +const checkTime = state => requireThat(performance.now() <= state.deadline) + +const formats = new Map([ + ['.docx', { + mime: `${wordType}document`, main: 'word/document.xml', type: `${wordType}document.main+xml`, + root: 'document', namespace: 'wordprocessingml', folder: 'word', parts: [ + [/^styles\.xml$/u, 'styles', `${wordType}styles+xml`], + [/^stylesWithEffects\.xml$/u, 'stylesWithEffects', `${msType}word.stylesWithEffects+xml`], + [/^numbering\.xml$/u, 'numbering', `${wordType}numbering+xml`], + [/^settings\.xml$/u, 'settings', `${wordType}settings+xml`], + [/^webSettings\.xml$/u, 'webSettings', `${wordType}webSettings+xml`], + [/^fontTable\.xml$/u, 'fontTable', `${wordType}fontTable+xml`], + [/^footnotes\.xml$/u, 'footnotes', `${wordType}footnotes+xml`], + [/^endnotes\.xml$/u, 'endnotes', `${wordType}endnotes+xml`], + [/^comments\.xml$/u, 'comments', `${wordType}comments+xml`], + [/^header[1-9][0-9]*\.xml$/u, 'header', `${wordType}header+xml`], + [/^footer[1-9][0-9]*\.xml$/u, 'footer', `${wordType}footer+xml`], + ], + }], + ['.xlsx', { + mime: `${excelType}sheet`, main: 'xl/workbook.xml', type: `${excelType}sheet.main+xml`, + root: 'workbook', namespace: 'spreadsheetml', folder: 'xl', parts: [ + [/^worksheets\/sheet[1-9][0-9]*\.xml$/u, 'worksheet', `${excelType}worksheet+xml`], + [/^styles\.xml$/u, 'styles', `${excelType}styles+xml`], + [/^sharedStrings\.xml$/u, 'sharedStrings', `${excelType}sharedStrings+xml`], + [/^calcChain\.xml$/u, 'calcChain', `${excelType}calcChain+xml`], + [/^tables\/table[1-9][0-9]*\.xml$/u, 'table', `${excelType}table+xml`], + [/^drawings\/drawing[1-9][0-9]*\.xml$/u, 'drawing', `${appType}drawing+xml`], + ], + }], + ['.pptx', { + mime: `${pptType}presentation`, main: 'ppt/presentation.xml', type: `${pptType}presentation.main+xml`, + root: 'presentation', namespace: 'presentationml', folder: 'ppt', parts: [ + [/^slides\/slide[1-9][0-9]*\.xml$/u, 'slide', `${pptType}slide+xml`], + [/^slideLayouts\/slideLayout[1-9][0-9]*\.xml$/u, 'slideLayout', `${pptType}slideLayout+xml`], + [/^slideMasters\/slideMaster[1-9][0-9]*\.xml$/u, 'slideMaster', `${pptType}slideMaster+xml`], + [/^notesSlides\/notesSlide[1-9][0-9]*\.xml$/u, 'notesSlide', `${pptType}notesSlide+xml`], + [/^notesMasters\/notesMaster[1-9][0-9]*\.xml$/u, 'notesMaster', `${pptType}notesMaster+xml`], + [/^handoutMasters\/handoutMaster[1-9][0-9]*\.xml$/u, 'handoutMaster', `${pptType}handoutMaster+xml`], + [/^presProps\.xml$/u, 'presProps', `${pptType}presProps+xml`], + [/^viewProps\.xml$/u, 'viewProps', `${pptType}viewProps+xml`], + [/^tableStyles\.xml$/u, 'tableStyles', `${pptType}tableStyles+xml`], + ], + }], +]) +const commonParts = new Map([ + ['docProps/core.xml', ['core', `${zipType}core-properties+xml`]], + ['docProps/app.xml', ['extended-properties', `${appType}extended-properties+xml`]], + ['docProps/custom.xml', ['custom-properties', `${appType}custom-properties+xml`]], +]) +const rasterTypes = new Map([['png', 'image/png'], ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg']]) + +const segmentIsSafe = segment => /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u.test(segment) && !segment.endsWith('.') + +function pathIsSafe(path) { + return path.length <= maxPath && (path === contentTypes || path === rootRelationships || + path.split('/').every(segmentIsSafe)) +} + +function checkExtra(bytes, start, length, local) { + requireThat(length <= maxExtra) + const end = start + length + const fields = new Set() + for (let at = start; at < end;) { + requireThat(at + 4 <= end) + const tag = bytes.readUInt16LE(at) + const size = bytes.readUInt16LE(at + 2) + at += 4 + requireThat(at + size <= end && !fields.has(tag)) + fields.add(tag) + // Only two metadata extras that cannot change names, sizes, or file types. + if (tag === 0x5455) { + requireThat(size >= 1) + const flags = bytes[at] + requireThat((flags & ~7) === 0) + const count = (flags & 1) + ((flags >> 1) & 1) + ((flags >> 2) & 1) + requireThat(size === 1 + 4 * (local ? count : flags & 1)) + } else if (tag === 0x7875) { + requireThat(size >= 5 && bytes[at] === 1) + const uidSize = bytes[at + 1] + requireThat(uidSize >= 1 && uidSize <= 8 && 3 + uidSize < size) + const gidSize = bytes[at + 2 + uidSize] + requireThat(gidSize >= 1 && gidSize <= 8 && size === 3 + uidSize + gidSize) + } else { + throw bad + } + at += size + } +} + +function readCentral(bytes, state) { + // Require a single ordinary ZIP, with no prefix, suffix, comments, or Zip64. + const end = bytes.length - 22 + requireThat(end >= 0 && bytes.readUInt32LE(end) === 0x06054b50 && bytes.readUInt32LE(end + 4) === 0 && + bytes.readUInt16LE(end + 20) === 0) + const count = bytes.readUInt16LE(end + 10) + const start = bytes.readUInt32LE(end + 16) + requireThat(count >= 3 && count <= maxEntries && count === bytes.readUInt16LE(end + 8) && + start > 0 && start + bytes.readUInt32LE(end + 12) === end) + + const entries = new Map() + const names = new Set() + let expanded = 0 + let at = start + for (let index = 0; index < count; index++) { + checkTime(state) + requireThat(at + 46 <= end && bytes.readUInt32LE(at) === 0x02014b50) + const version = bytes.readUInt16LE(at + 6) + const flags = bytes.readUInt16LE(at + 8) + const method = bytes.readUInt16LE(at + 10) + const date = bytes.readUInt32LE(at + 12) + const crc = bytes.readUInt32LE(at + 16) + const compressed = bytes.readUInt32LE(at + 20) + const size = bytes.readUInt32LE(at + 24) + const nameLength = bytes.readUInt16LE(at + 28) + const extra = bytes.readUInt16LE(at + 30) + const attrs = bytes.readUInt32LE(at + 38) + const offset = bytes.readUInt32LE(at + 42) + const next = at + 46 + nameLength + extra + requireThat(version >= 10 && version <= 20 && (flags & ~0x080e) === 0 && + (method === 8 || (method === 0 && (flags & 6) === 0 && compressed === size)) && + nameLength > 0 && nameLength <= maxPath + 1 && next <= end && + bytes.readUInt32LE(at + 32) === 0 && bytes.readUInt16LE(at + 36) <= 1 && offset < start && + size <= maxPart && compressed <= maxArchive && size <= maxRatio * compressed) + expanded += size + requireThat(expanded <= maxExpanded) + const rawName = bytes.subarray(at + 46, at + 46 + nameLength) + const name = rawName.toString('latin1') + const directory = name.endsWith('/') + const path = directory ? name.slice(0, -1) : name + const key = path.toLowerCase() + const fileType = (attrs >>> 28) & 15 + const dosAttrs = attrs & 0xffff + requireThat(pathIsSafe(path) && !names.has(key) && (dosAttrs & ~0x37) === 0 && + (fileType === 0 || fileType === (directory ? 4 : 8)) && + (directory ? (size === 0 && method === 0 && crc === 0) : (dosAttrs & 16) === 0 && size > 0)) + checkExtra(bytes, at + 46 + nameLength, extra, false) + names.add(key) + entries.set(name, { rawName, directory, offset, version, flags, method, date, crc, compressed, size }) + at = next + } + requireThat(at === end) + return { entries, start } +} + +function readLocals(bytes, entries, start, state) { + const sorted = [...entries.values()].sort((a, b) => a.offset - b.offset) + requireThat(sorted[0].offset === 0) + for (let i = 0; i < sorted.length; i++) { + checkTime(state) + const entry = sorted[i] + const { offset, version, flags, method, date, rawName, crc, compressed, size } = entry + const end = i + 1 < sorted.length ? sorted[i + 1].offset : start + requireThat(offset + 30 <= end && bytes.readUInt32LE(offset) === 0x04034b50 && + bytes.readUInt16LE(offset + 4) === version && bytes.readUInt16LE(offset + 6) === flags && + bytes.readUInt16LE(offset + 8) === method && bytes.readUInt32LE(offset + 10) === date && + bytes.readUInt16LE(offset + 26) === rawName.length) + const extra = bytes.readUInt16LE(offset + 28) + const header = offset + 30 + rawName.length + extra + const dataEnd = header + compressed + requireThat(dataEnd <= end && rawName.equals(bytes.subarray(offset + 30, offset + 30 + rawName.length))) + checkExtra(bytes, offset + 30 + rawName.length, extra, true) + const matches = pos => bytes.readUInt32LE(pos) === crc && bytes.readUInt32LE(pos + 4) === compressed && + bytes.readUInt32LE(pos + 8) === size + if (flags & 8) { + requireThat(matches(offset + 14) || (bytes.readUInt32LE(offset + 14) === 0 && + bytes.readUInt32LE(offset + 18) === 0 && bytes.readUInt32LE(offset + 22) === 0)) + requireThat((end - dataEnd === 12 && matches(dataEnd)) || (end - dataEnd === 16 && + bytes.readUInt32LE(dataEnd) === 0x08074b50 && matches(dataEnd + 4))) + } else { + requireThat(dataEnd === end && matches(offset + 14)) + } + entry.start = header + entry.end = dataEnd + } +} + +// Use a local CRC to support Node 22.0 as well as versions with zlib.crc32(). +const crcTable = Uint32Array.from({ length: 256 }, (_, i) => { + for (let bit = 0; bit < 8; bit++) i = (i >>> 1) ^ ((i & 1) ? 0xedb88320 : 0) + return i +}) + +function readStructure(bytes, entry, limit, state) { + checkTime(state) + requireThat(entry && entry.size <= limit && entry.compressed <= limit) + state.metadata += entry.size + requireThat(state.metadata <= maxMetadata) + const input = bytes.subarray(entry.start, entry.end) + let data = input + if (entry.method === 8) { + // maxOutputLength is enforced by zlib's synchronous wrapper; info confirms + // exactly one raw deflate stream consumed the entire ZIP member. + const { buffer, engine } = inflateRawSync(input, { maxOutputLength: entry.size, info: true }) + requireThat(engine.bytesWritten === input.length) + data = buffer + } + requireThat(data.length === entry.size) + let crc = 0xffffffff + for (let i = 0; i < data.length; i++) crc = (crc >>> 8) ^ crcTable[(crc ^ data[i]) & 255] + requireThat((~crc >>> 0) === entry.crc) + checkTime(state) + return data +} + +const xmlChars = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u +const whitespace = /[ \t\r\n]*/uy +const xmlName = /[A-Za-z_][A-Za-z0-9_.-]*(?::[A-Za-z_][A-Za-z0-9_.-]*)?/uy +const xmlDeclaration = /<\?xml[ \t\r\n]+version[ \t\r\n]*=[ \t\r\n]*(?:"1\.0"|'1\.0')(?:[ \t\r\n]+encoding[ \t\r\n]*=[ \t\r\n]*(?:"[Uu][Tt][Ff]-8"|'[Uu][Tt][Ff]-8'))?(?:[ \t\r\n]+standalone[ \t\r\n]*=[ \t\r\n]*(?:"(?:yes|no)"|'(?:yes|no)'))?[ \t\r\n]*\?>/uy +const entity = /&(?:amp|lt|gt|apos|quot|#[0-9]{1,7}|#x[0-9A-Fa-f]{1,6});/uy +const references = new Map([['&', '&'], ['<', '<'], ['>', '>'], ['"', '"'], [''', "'"]]) + +function xmlValue(value, decoded) { + let start = 0 + let result = '' + for (let at = value.indexOf('&'); at !== -1; at = value.indexOf('&', start)) { + entity.lastIndex = at + const match = entity.exec(value)?.[0] + requireThat(match) + let character = references.get(match) + if (character === undefined) { + const hex = match[2] === 'x' + const code = Number.parseInt(match.slice(hex ? 3 : 2, -1), hex ? 16 : 10) + requireThat(code === 9 || code === 10 || code === 13 || (code >= 32 && code <= 0xd7ff) || + (code >= 0xe000 && code <= 0xfffd) || (code >= 0x10000 && code <= 0x10ffff)) + if (decoded) character = String.fromCodePoint(code) + } + if (decoded) result += value.slice(start, at) + character + start = entity.lastIndex + } + return decoded ? result + value.slice(start) : undefined +} + +function qualified(name, bindings, attribute) { + const colon = name.indexOf(':') + if (colon === -1) return [attribute ? '' : bindings[''] ?? '', name] + const prefix = name.slice(0, colon) + const namespace = bindings[prefix] + requireThat(namespace && prefix !== 'xmlns') + return [namespace, name.slice(colon + 1)] +} + +// Parse just bounded UTF-8 XML. DTDs, custom entities and processing instructions +// have no role here; there is no entity resolver or external I/O. +function readXml(data, state, { element, strictNodes = false }) { + const xml = decodeUtf8.decode(data) + requireThat(!xmlChars.test(xml)) + const stack = [] + const base = Object.assign(Object.create(null), { xml: xmlNamespace }) + let root = false + let at = 0 + function take(pattern) { + pattern.lastIndex = at + const value = pattern.exec(xml)?.[0] + if (value !== undefined) at = pattern.lastIndex + return value + } + if (xml.startsWith('')) + xmlValue(value, false) + } + at += value.length + continue + } + if (xml.startsWith('