From 8ca3957e42403ae217f37ec3f284e8df9c14f1c0 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 09:16:23 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat(files):=20=E5=8F=AA=E5=9C=A8=E5=B7=B2?= =?UTF-8?q?=E6=8E=88=E6=9D=83=E7=9B=AE=E5=BD=95=E7=8B=AC=E5=8D=A0=E5=8F=91?= =?UTF-8?q?=E5=B8=83=E6=96=B0=E6=96=87=E6=A1=A3=20/=20publish=20new=20docu?= =?UTF-8?q?ments=20exclusively=20in=20a=20pinned=20workspace=20folder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/files/project-document-names.mjs | 69 ++++ .../src/files/project-document-target.mjs | 308 ++++++++++++++++++ .../project-document-target-faults.test.mjs | 217 ++++++++++++ .../test/project-document-target.test.mjs | 303 +++++++++++++++++ 4 files changed, 897 insertions(+) create mode 100644 apps/headless/src/files/project-document-names.mjs create mode 100644 apps/headless/src/files/project-document-target.mjs create mode 100644 apps/headless/test/project-document-target-faults.test.mjs create mode 100644 apps/headless/test/project-document-target.test.mjs diff --git a/apps/headless/src/files/project-document-names.mjs b/apps/headless/src/files/project-document-names.mjs new file mode 100644 index 00000000..bdb0d3f0 --- /dev/null +++ b/apps/headless/src/files/project-document-names.mjs @@ -0,0 +1,69 @@ +import { HttpError } from '../http/policy.mjs' +import { disclosurePath, sensitiveBytes } from './workspace-disclosure.mjs' +import { validWorkspaceName, workspacePathParts } from './workspace-files-fd.mjs' +import { decodeWorkspaceText } from './workspace-files.mjs' + +const status = Object.freeze({ + auth: 401, document_invalid: 400, document_read_only: 403, document_unsafe: 403, + workspace_unavailable: 404, document_exists: 409, document_changed: 409, + document_limit: 413, document_restricted: 422, document_unconfirmed: 503, +}) +export class ProjectDocumentError extends HttpError { + constructor(code) { super(status[code], code) } +} +export const rejectDocument = code => { throw new ProjectDocumentError(code) } +export const PROJECT_DOCUMENT_MAX_BYTES = 2 * 1024 * 1024 +const MAX_NAME_BYTES = 200 +const extension = /\.(?:md|txt)$/i +const windows = /[<>:"|?*\/\\]|~[0-9]+(?:\.|$)/u +const device = /^(?:aux|clock\$|con|conin\$|conout\$|nul|prn|(?:com|lpt)[0-9])(?:\s*[.]|\s*$)/iu +const invisible = /[\p{C}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u +const ambiguous = /^[.\s]|[.\s]$/u +const instruction = /^(?:agents|claude|gemini|skill|instructions|copilot-instructions|cursor-rules|codex|opencode)(?:[.]|$)/iu +const control = /^(?:dockerfile|containerfile|makefile|gnumakefile|justfile|jenkinsfile|procfile|vagrantfile|codeowners|autorun)(?:[.]|$)/iu +const executable = /\.(?:app|apk|bash|bat|bin|cmd|com|cpl|deb|desktop|dll|dmg|exe|fish|hta|html?|ini|ins|jar|js|jse|jsx|lnk|lua|mjs|msi|msp|nsh|php|pl|ps1|py|rb|reg|rpm|scr|sh|svg|sys|ts|tsx|url|vbe|vbs|wsf|zsh)(?:\s*[.]|\s*$)/iu +const extraSensitiveName = /^(?:auth|key|keyfiles?|ssh[-_ ]config)(?:[._ -]|$)/iu +const recognizableCredential = /\b(?:gh[pousr]_[a-zA-Z0-9]{30,}|github_pat_[a-zA-Z0-9_]{30,}|glpat-[a-zA-Z0-9_-]{20,}|xox[baprs]-[a-zA-Z0-9-]{20,}|sk-(?:proj-|svcacct-)?[a-zA-Z0-9_-]{24,}|(?:AKIA|ASIA)[A-Z0-9]{16})\b/u +const credentialAssignment = /^[\t ]*(?:export[\t ]+)?(?:[A-Z0-9]+_)*(?:PRIVATE_KEY|API_KEY|ACCESS_TOKEN|REFRESH_TOKEN|AUTH_TOKEN|CLIENT_SECRET|SECRET_ACCESS_KEY)[\t ]*=[\t ]*["']?[a-z0-9_+/=-]{16,}/imu + +// Conservative compatibility/case key for an advisory scan on case-sensitive mounts. +// Exact no-clobber is still enforced by the kernel at the final link operation. +export const documentNameKey = name => name.normalize('NFKC').toLowerCase().toUpperCase().trimEnd().replace(/[. ]+$/u, '') + +export function assertDocumentDisclosure(parts) { + if (parts.length && (!disclosurePath(parts.join('/')) || parts.some(part => { + const folded = part.normalize('NFKC') + return invisible.test(part) || !disclosurePath(folded) || extraSensitiveName.test(folded) + }))) rejectDocument('document_restricted') +} + +export function projectDocumentPath(input) { + const { directory, name } = input ?? {} + const parts = workspacePathParts(directory, true) + if (!parts || typeof name !== 'string' || !name.isWellFormed()) rejectDocument('document_invalid') + if (Buffer.byteLength(name) > MAX_NAME_BYTES) rejectDocument('document_limit') + if (!validWorkspaceName(name) || !extension.test(name) || invisible.test(name)) rejectDocument('document_invalid') + const folded = name.normalize('NFKC') + const stem = folded.replace(extension, '') + if (!stem || ambiguous.test(stem) || windows.test(folded) || device.test(folded)) rejectDocument('document_invalid') + if (instruction.test(stem) || control.test(stem) || executable.test(stem)) rejectDocument('document_restricted') + const segments = [...parts, name] + const path = segments.join('/') + if (!workspacePathParts(path)) rejectDocument('document_limit') + assertDocumentDisclosure(segments) + return { parts, name, path } +} + +export function projectDocumentBytes(content) { + if (typeof content !== 'string') rejectDocument('document_invalid') + if (content.length > PROJECT_DOCUMENT_MAX_BYTES || Buffer.byteLength(content) > PROJECT_DOCUMENT_MAX_BYTES) { + rejectDocument('document_limit') + } + if (!content.isWellFormed()) rejectDocument('document_invalid') + const bytes = Buffer.from(content) + if (decodeWorkspaceText(bytes) === null) rejectDocument('document_invalid') + if (sensitiveBytes(bytes) || recognizableCredential.test(content) || credentialAssignment.test(content)) { + rejectDocument('document_restricted') + } + return bytes +} diff --git a/apps/headless/src/files/project-document-target.mjs b/apps/headless/src/files/project-document-target.mjs new file mode 100644 index 00000000..3add7ddf --- /dev/null +++ b/apps/headless/src/files/project-document-target.mjs @@ -0,0 +1,308 @@ +import { randomBytes } from 'node:crypto' +import { + constants as C, fchmodSync, fsyncSync, linkSync, openSync, opendirSync, readSync, unlinkSync, writeFileSync, +} from 'node:fs' +import { isPromise } from 'node:util/types' +import { PATH, close, decodeUtf8, fdPath, mountId, sameInode, stat } from './workspace-files-fd.mjs' +import { access, pinWorkspaceDirectory } from './workspace-files-pin.mjs' +import { workspaceTextRevision } from './workspace-files.mjs' +import { + ProjectDocumentError, assertDocumentDisclosure, documentNameKey, projectDocumentBytes, projectDocumentPath, rejectDocument, +} from './project-document-names.mjs' + +const DIR_FLAGS = C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW +const STAGE_FLAGS = C.O_RDWR | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW | C.O_NONBLOCK +const MAX_SCAN = 4096 +const STAGE_PREFIX = '.project-document-' +const changed = () => rejectDocument('document_changed') +const unconfirmed = () => rejectDocument('document_unconfirmed') + +function closeQuietly(fd) { try { close(fd) } catch { /* close must not mask the outcome */ } } + +function report(error, opening = false) { + if (error instanceof ProjectDocumentError) throw error + switch (error?.code) { + case 'ERR_WORKSPACE_UNAVAILABLE': return rejectDocument('workspace_unavailable') + case 'ERR_WORKSPACE_FILE_LIMIT': case 'ENOSPC': case 'EDQUOT': case 'EFBIG': return rejectDocument('document_limit') + case 'ERR_WORKSPACE_FILE_CONFLICT': case 'ESTALE': return changed() + case 'ENOENT': return rejectDocument(opening ? 'workspace_unavailable' : 'document_changed') + case 'ERR_WORKSPACE_FILE_UNSAFE': case 'ENOTDIR': case 'ELOOP': return rejectDocument('document_unsafe') + case 'EROFS': case 'EACCES': case 'EPERM': return rejectDocument('document_read_only') + default: return unconfirmed() + } +} + +function directoryAccess(scope, writable) { + const info = stat(scope.fd) + const mode = C.R_OK | C.X_OK | (writable ? C.W_OK : 0) + const uid = process.geteuid() + const ownerMode = writable ? 0o700n : 0o500n + // access(2) checks the applicable ACL and mount. Preserve owner-mode intent + // even when the server is uid 0 or the group/other class has broader bits. + if (((uid === 0 || BigInt(uid) === info.uid) && (info.mode & ownerMode) !== ownerMode) || !access(scope.fd, info, mode)) { + rejectDocument('document_read_only') + } +} + +function assertDirectory(scope, writable) { + directoryAccess(scope, writable) + scope.assertCurrent() + directoryAccess(scope, writable) +} + +function probe(scope, name) { + try { return openSync(fdPath(scope.fd, name), PATH) } + catch (error) { if (error?.code !== 'ENOENT') throw error } +} + +function rejectExisting(scope, name) { + const fd = probe(scope, name) + try { + if (fd === undefined) return + const info = stat(fd) + if (mountId(fd) !== scope.project.mount || !info.isFile() || info.nlink !== 1n) rejectDocument('document_unsafe') + rejectDocument('document_exists') + } finally { closeQuietly(fd) } +} + +function scanAliases(scope, name, key, ownStage, installed = false) { + const directory = opendirSync(fdPath(scope.fd, '.'), { encoding: 'buffer' }) + let scanned = 0 + try { + for (let entry; (entry = directory.readSync()) !== null;) { + let spelling + try { spelling = decodeUtf8(entry.name) } catch { /* unrelated non-UTF-8 name */ } + if (ownStage !== undefined && spelling === ownStage) continue + // Reserve a slot so a newly published document still fits the ordinary workspace listing cap. + if (++scanned > MAX_SCAN - Number(!installed)) rejectDocument('document_limit') + if (spelling !== undefined && !(installed && spelling === name) && documentNameKey(spelling) === key) { + rejectExisting(scope, spelling) + } + } + } finally { directory.closeSync() } +} + +function assertAbsent(scope, name, key, ownStage) { + rejectExisting(scope, name) + scanAliases(scope, name, key, ownStage) + rejectExisting(scope, name) +} + +function verifyOwnerNow(verifyOwner) { + let verified + try { + verified = verifyOwner() + // A rejected async callback is still a synchronous authorization failure. + // Observe native rejections without running arbitrary thenables. + if (isPromise(verified)) Promise.prototype.then.call(verified, undefined, () => {}) + } catch { rejectDocument('auth') } + if (verified !== true) rejectDocument('auth') +} + +function makeStage(parent) { + for (let attempt = 0; attempt < 4; attempt++) { + const name = `${STAGE_PREFIX}${randomBytes(16).toString('hex')}.tmp` + try { return { name, fd: openSync(fdPath(parent, name), STAGE_FLAGS, 0o600) } } + catch (error) { if (error?.code !== 'EEXIST') throw error } + } + return unconfirmed() +} + +function ownFile(info, size, links) { + return info.isFile() && info.size === BigInt(size) && info.nlink === BigInt(links) && + (info.mode & 0o7777n) === 0o600n && info.uid === BigInt(process.geteuid()) +} + +function sameContents(a, b) { + return sameInode(a, b) && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid && a.size === b.size && a.mtimeNs === b.mtimeNs +} + +function sameSnapshot(a, b) { + return sameContents(a, b) && a.nlink === b.nlink && a.ctimeNs === b.ctimeNs && a.birthtimeNs === b.birthtimeNs +} + +function assertNamed(scope, name, expected) { + const fd = probe(scope, name) + try { + if (fd === undefined || mountId(fd) !== scope.project.mount || !sameSnapshot(expected, stat(fd))) changed() + } finally { closeQuietly(fd) } +} + +function readStable(fd, expected) { + const bytes = Buffer.alloc(Number(expected.size)) + let offset = 0 + while (offset < bytes.length) { + const count = readSync(fd, bytes, offset, bytes.length - offset, offset) + if (!count) changed() + offset += count + } + if (!sameSnapshot(expected, stat(fd))) changed() + return bytes +} + +function assertStage(scope, stage, prepared, bytes, links) { + const info = stat(stage.fd) + if (!ownFile(info, bytes.length, links) || !sameContents(prepared, info) || !readStable(stage.fd, info).equals(bytes)) changed() + assertNamed(scope, stage.name, info) + return info +} + +function removeStage(scope, parent, stage) { + const fd = probe(scope, stage.name) + try { + if (fd === undefined || mountId(fd) !== scope.project.mount || !sameInode(stat(stage.fd), stat(fd))) return false + // Node exposes no inode-conditional unlink. Check a held no-follow pin + // immediately before unlink; observed replacements are left untouched. + unlinkSync(fdPath(parent, stage.name)) + return true + } finally { closeQuietly(fd) } +} + +function readInstalled(scope, name, key, fd, info, writable) { + assertDirectory(scope, writable) + assertNamed(scope, name, info) + scanAliases(scope, name, key, undefined, true) + const bytes = readStable(fd, info) + assertDirectory(scope, writable) + assertNamed(scope, name, info) + return bytes +} + +/** Opt-in, single-target lease for creating a visible document in a granted project. */ +export function openProjectDocumentTarget(catalog, workspaceId, input) { + let scope, target, key + try { + target = projectDocumentPath(input) + key = documentNameKey(target.name) + if (typeof catalog?.pinProject !== 'function') rejectDocument('workspace_unavailable') + scope = pinWorkspaceDirectory(catalog, workspaceId, target.parts) + assertDocumentDisclosure([scope.project.name]) + assertDirectory(scope, true) + } catch (error) { + try { scope?.close() } catch { /* do not expose native errors */ } + report(error, true) + } + const { name, path } = target + let closed = false, busy = false, sealed = false, receipt + + function release() { + closeQuietly(receipt?.fd) + receipt = undefined + try { scope.close() } catch { /* close is idempotent and non-throwing */ } + } + function assertOpen() { if (closed) changed() } + function run(fn) { + assertOpen() + if (busy) changed() + busy = true + try { return fn() } catch (error) { report(error) } + finally { busy = false; if (closed) release() } + } + function verifyAbsent() { + return run(() => { + assertDirectory(scope, true) + assertAbsent(scope, name, key) + assertDirectory(scope, true) + assertOpen() + return true + }) + } + function publish(content, verifyOwner) { + return run(() => { + if (sealed) { if (receipt) rejectDocument('document_exists'); unconfirmed() } + const bytes = projectDocumentBytes(content) + let parent, stage, removed = false + try { + verifyOwnerNow(verifyOwner) + assertOpen() + assertDirectory(scope, true) + assertAbsent(scope, name, key) + parent = openSync(fdPath(scope.fd, '.'), DIR_FLAGS) + if (!sameInode(stat(parent), stat(scope.fd)) || mountId(parent) !== scope.project.mount) changed() + assertDirectory(scope, true) + stage = makeStage(parent) + fchmodSync(stage.fd, 0o600) + writeFileSync(stage.fd, bytes) + fsyncSync(stage.fd) + const prepared = stat(stage.fd) + if (mountId(stage.fd) !== scope.project.mount) rejectDocument('document_unsafe') + assertStage(scope, stage, prepared, bytes, 1) + + assertAbsent(scope, name, key, stage.name) + // Put the live owner check after the bounded but potentially slow alias scan. + // The callback can mutate state; only recheck pinned identities and the exact + // destination after it returns, leaving the final alias scan to readback. + verifyOwnerNow(verifyOwner) + assertOpen() + assertDirectory(scope, true) + rejectExisting(scope, name) + assertNamed(scope, stage.name, prepared) + // link(2) is no-overwrite, including for symlinks and equal existing bytes. + // Node's source operand is name-based: verify the original held inode both + // sides of this call and treat an ambiguous outcome as sealed, never undo it. + sealed = true + try { linkSync(fdPath(parent, stage.name), fdPath(parent, name)) } + catch (error) { + if (error?.code === 'EEXIST') { + const existing = probe(scope, name) + try { if (existing !== undefined && sameInode(prepared, stat(existing))) unconfirmed() } + finally { closeQuietly(existing) } + sealed = false + rejectExisting(scope, name) + rejectDocument('document_exists') + } + if (['EACCES', 'EPERM', 'EROFS'].includes(error?.code)) sealed = false + throw error + } + + verifyOwnerNow(verifyOwner) + assertOpen() + assertDirectory(scope, true) + const linked = assertStage(scope, stage, prepared, bytes, 2) + assertNamed(scope, name, linked) + if (!(removed = removeStage(scope, parent, stage))) unconfirmed() + fsyncSync(stage.fd) + fsyncSync(parent) + const installed = stat(stage.fd) + if (!ownFile(installed, bytes.length, 1) || !sameContents(prepared, installed)) unconfirmed() + const readback = readInstalled(scope, name, key, stage.fd, installed, true) + if (!readback.equals(bytes)) unconfirmed() + assertOpen() + const revision = workspaceTextRevision(path, installed, readback) + receipt = { fd: stage.fd, revision, info: installed } + return { revision } + } catch (error) { + if (sealed && !(error instanceof ProjectDocumentError && error.code === 'auth')) unconfirmed() + throw error + } finally { + if (stage && !removed) { + try { removeStage(scope, parent, stage) } catch { /* leave an unverified stage untouched */ } + } + if (stage?.fd !== receipt?.fd) closeQuietly(stage?.fd) + closeQuietly(parent) + } + }) + } + function verifyReceipt(revision) { + return run(() => { + if (!receipt) { if (sealed) unconfirmed(); changed() } + if (revision !== receipt.revision) changed() + try { + const { fd, info } = receipt + if (!sameSnapshot(info, stat(fd))) changed() + const bytes = readInstalled(scope, name, key, fd, info, false) + if (workspaceTextRevision(path, info, bytes) !== revision) changed() + assertOpen() + return true + } catch (error) { + if (error?.code === 'ERR_WORKSPACE_UNAVAILABLE') throw error + return changed() + } + }) + } + return Object.freeze({ path, verifyAbsent, publish, verifyReceipt, close() { + if (closed) return + closed = true + if (!busy) release() + } }) +} diff --git a/apps/headless/test/project-document-target-faults.test.mjs b/apps/headless/test/project-document-target-faults.test.mjs new file mode 100644 index 00000000..1c27a805 --- /dev/null +++ b/apps/headless/test/project-document-target-faults.test.mjs @@ -0,0 +1,217 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import { syncBuiltinESMExports } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { openWorkspaceCatalog } from '../src/business/workspace-catalog.mjs' +import { openProjectDocumentTarget } from '../src/files/project-document-target.mjs' +import { openWorkspaceFiles } from '../src/files/workspace-files.mjs' +import { HttpError } from '../src/http/policy.mjs' + +const owner = () => true +const code = (status, value) => error => error instanceof HttpError && error.status === status && error.code === value && error.message === value +const lost = code(503, 'document_unconfirmed') +const syntheticRevision = `r_${'0'.repeat(64)}` +const io = () => Object.assign(Error('Injected error carrying an absolute pathname and secret'), { code: 'EIO' }) +function patch(t, key, override) { + const original = fs[key] + fs[key] = override(original) + syncBuiltinESMExports() + t.after(() => { fs[key] = original; syncBuiltinESMExports() }) +} +function fixture(t, name = 'note.md') { + const base = fs.mkdtempSync(join(tmpdir(), 'deva-project-document-faults-')) + const root = join(base, 'root'); const project = join(root, 'project'); const dir = join(project, 'nested') + fs.mkdirSync(dir, { recursive: true }) + const catalog = openWorkspaceCatalog({ root }) + const id = catalog.list()[0].id + const target = openProjectDocumentTarget(catalog, id, { directory: 'nested', name }) + t.after(() => { target.close(); catalog.close(); fs.rmSync(base, { recursive: true, force: true }) }) + return { base, root, dir, target, catalog, id, filename: join(dir, name) } +} + +test('kernel no-overwrite preserves an equal-byte final created immediately before link', t => { + const { dir, filename, target } = fixture(t) + let existing + patch(t, 'linkSync', native => (source, destination) => { + fs.writeFileSync(filename, 'same', { mode: 0o644, flag: 'wx' }) + existing = fs.lstatSync(filename, { bigint: true }) + native(source, destination) + }) + assert.throws(() => target.publish('same', owner), code(409, 'document_exists')) + assert.deepEqual(fs.readdirSync(dir), ['note.md']) + const retained = fs.lstatSync(filename, { bigint: true }) + assert.equal(retained.ino, existing.ino) + assert.equal(retained.ctimeNs, existing.ctimeNs) + assert.equal(retained.mode & 0o777n, 0o644n & ~BigInt(process.umask())) + assert.throws(() => target.verifyReceipt(syntheticRevision), code(409, 'document_changed')) +}) + +test('stage fsync failure is not reported as a save and removes only the owned private stage', t => { + const { dir, target } = fixture(t) + let syncs = 0 + patch(t, 'fsyncSync', native => fd => { + if (++syncs === 1) throw io() + native(fd) + }) + assert.throws(() => target.publish('text', owner), lost) + assert.deepEqual(fs.readdirSync(dir), []) + assert.equal(target.verifyAbsent(), true) + const { revision } = target.publish('retry', owner) + assert.equal(target.verifyReceipt(revision), true) +}) + +test('parent fsync and ambiguous link errors preserve committed targets without receipts', t => { + const parentSync = fixture(t, 'fsync.md') + const lateLink = fixture(t, 'link.md') + const order = [] + patch(t, 'fsyncSync', native => fd => { + if (fs.fstatSync(fd).isDirectory() && fs.readlinkSync(`/proc/self/fd/${fd}`) === parentSync.dir) { + order.push('parent-sync') + throw io() + } + native(fd) + }) + patch(t, 'linkSync', native => (source, destination) => { + native(source, destination) + if (destination.endsWith('/link.md')) throw io() + order.push('link') + }) + for (const { target, dir, filename } of [parentSync, lateLink]) { + assert.throws(() => target.publish('left in place', owner), lost) + const installed = fs.lstatSync(filename) + assert.equal(installed.nlink, 1) + assert.equal(fs.readFileSync(filename, 'utf8'), 'left in place') + assert.throws(() => target.verifyReceipt(syntheticRevision), lost) + assert.throws(() => target.publish('retry', owner), lost) + assert.deepEqual(fs.readdirSync(dir), [target.path.split('/').at(-1)]) + assert.equal(fs.lstatSync(filename).ino, installed.ino) + } + assert.deepEqual(order, ['link', 'parent-sync']) +}) + +test('owner expiry during the final pre-link alias scan prevents any visible target', t => { + const { target, dir, filename } = fixture(t) + let active = true, calls = 0, expiredDuringScan = false + patch(t, 'opendirSync', native => (path, options) => { + const directory = native(path, options) + if (fs.realpathSync.native(path) === dir && fs.readdirSync(dir).some(name => name.startsWith('.project-document-'))) { + const read = directory.readSync.bind(directory) + directory.readSync = () => { + expiredDuringScan = true + active = false + return read() + } + } + return directory + }) + assert.throws(() => target.publish('no commit', () => { calls++; return active }), code(401, 'auth')) + assert.equal(expiredDuringScan, true) + assert.equal(calls, 2) + assert.equal(fs.existsSync(filename), false) + assert.deepEqual(fs.readdirSync(dir), []) +}) + +test('post-link auth failure retains final inode and emits only the authorization error', t => { + const { target, dir, filename } = fixture(t) + let calls = 0, inode + assert.throws(() => target.publish('published', () => { + if (++calls !== 3) return true + inode = fs.lstatSync(filename).ino + throw Error(filename) + }), code(401, 'auth')) + assert.equal(calls, 3) + assert.equal(fs.lstatSync(filename).ino, inode) + assert.equal(fs.readFileSync(filename, 'utf8'), 'published') + assert.deepEqual(fs.readdirSync(dir), ['note.md']) + assert.throws(() => target.verifyReceipt(syntheticRevision), lost) +}) + +test('a replaced private stage is preserved, including when the replacement occurs before the link', t => { + const { target, dir, filename } = fixture(t) + let calls = 0, stagePath, decoyInode + assert.throws(() => target.publish('original', () => { + if (++calls === 2) { + stagePath = join(dir, fs.readdirSync(dir).find(name => name.startsWith('.project-document-'))) + fs.renameSync(stagePath, `${stagePath}.moved`) + fs.writeFileSync(stagePath, 'unknown', { flag: 'wx' }) + decoyInode = fs.lstatSync(stagePath).ino + } + return true + }), code(409, 'document_changed')) + assert.ok(!fs.existsSync(filename)) + assert.equal(fs.lstatSync(stagePath).ino, decoyInode) + assert.equal(fs.readFileSync(stagePath, 'utf8'), 'unknown') + assert.equal(fs.readFileSync(`${stagePath}.moved`, 'utf8'), 'original') +}) + +test('after-link pathname substitutions are neither blessed nor destroyed', t => { + const { target, dir, filename } = fixture(t) + let stagePath, installed, decoy, unknown, calls = 0 + assert.throws(() => target.publish('same bytes', () => { + if (++calls === 3) { + stagePath = join(dir, fs.readdirSync(dir).find(name => name.startsWith('.project-document-'))) + installed = fs.lstatSync(filename).ino + fs.renameSync(filename, `${filename}.moved`) + fs.writeFileSync(filename, 'same bytes', { mode: 0o600, flag: 'wx' }) + decoy = fs.lstatSync(filename).ino + fs.renameSync(stagePath, `${stagePath}.moved`) + fs.symlinkSync('note.md', stagePath) + unknown = fs.lstatSync(stagePath).ino + } + return true + }), lost) + assert.equal(fs.lstatSync(`${filename}.moved`).ino, installed) + assert.equal(fs.lstatSync(`${stagePath}.moved`).ino, installed) + assert.equal(fs.lstatSync(filename).ino, decoy) + assert.equal(fs.lstatSync(stagePath).ino, unknown) + assert.equal(fs.readlinkSync(stagePath), 'note.md') + assert.equal(fs.readFileSync(filename, 'utf8'), 'same bytes') + assert.throws(() => target.verifyReceipt(syntheticRevision), lost) +}) + +test('case and normalization aliases appearing across link prevent confirmation without deleting either entry', t => { + const { target, dir, filename } = fixture(t, 'Café.txt') + const alias = join(dir, 'cafe\u0301.TXT') + patch(t, 'linkSync', native => (source, destination) => { + native(source, destination) + fs.writeFileSync(alias, 'external', { flag: 'wx' }) + }) + assert.throws(() => target.publish('user text', owner), lost) + assert.equal(fs.readFileSync(filename, 'utf8'), 'user text') + assert.equal(fs.readFileSync(alias, 'utf8'), 'external') + assert.throws(() => target.verifyReceipt(syntheticRevision), lost) + assert.deepEqual(fs.readdirSync(dir).sort(), ['Café.txt', 'cafe\u0301.TXT'].sort()) +}) + +test('post-link catalog-root replacement yields unconfirmed and never touches new tree', t => { + const { target, base, root, dir, filename } = fixture(t) + const moved = join(base, 'root-old') + let calls = 0 + assert.throws(() => target.publish('in pinned tree', () => { + if (++calls === 3) { + fs.renameSync(root, moved) + fs.mkdirSync(dir, { recursive: true }) + fs.writeFileSync(filename, 'in replacement tree') + } + return true + }), lost) + assert.equal(fs.readFileSync(filename, 'utf8'), 'in replacement tree') + const original = join(moved, 'project', target.path) + assert.equal(fs.readFileSync(original, 'utf8'), 'in pinned tree') + assert.deepEqual(fs.readdirSync(join(moved, 'project', 'nested')), ['note.md']) + assert.throws(() => target.verifyReceipt(syntheticRevision), lost) +}) + +test('synthesized birth time matches fresh workspace read after hard-link/unlink ctime changes', async t => { + const { target, catalog, id } = fixture(t) + patch(t, 'fstatSync', native => (fd, opts) => { + const info = native(fd, opts) + if (opts?.bigint) info.birthtimeNs = info.ctimeNs + return info + }) + const { revision } = target.publish('synthesized', owner) + assert.equal((await openWorkspaceFiles({ catalog }).read(id, target.path)).revision, revision) + assert.equal(target.verifyReceipt(revision), true) +}) diff --git a/apps/headless/test/project-document-target.test.mjs b/apps/headless/test/project-document-target.test.mjs new file mode 100644 index 00000000..4a1ad803 --- /dev/null +++ b/apps/headless/test/project-document-target.test.mjs @@ -0,0 +1,303 @@ +import assert from 'node:assert/strict' +import { execFileSync, spawnSync } from 'node:child_process' +import { + chmodSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, + renameSync, rmSync, symlinkSync, utimesSync, writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { openWorkspaceCatalog } from '../src/business/workspace-catalog.mjs' +import { openProjectDocumentTarget } from '../src/files/project-document-target.mjs' +import { openWorkspaceFiles, workspaceTextRevision } from '../src/files/workspace-files.mjs' +import { HttpError } from '../src/http/policy.mjs' + +const MAX_BYTES = 2 * 1024 * 1024 +const owner = () => true +const stageName = folder => readdirSync(folder).find(name => name.startsWith('.project-document-')) +const unavailableId = `w_${'0'.repeat(32)}` +const expect = (status, code) => error => { + assert.ok(error instanceof HttpError) + assert.equal(error.status, status) + assert.equal(error.code, code) + assert.equal(error.message, code) + assert.equal(error.cause, undefined) + return true +} + +function fixture(t) { + const base = mkdtempSync(join(tmpdir(), 'deva-project-document-')) + const root = join(base, 'granted'); const project = join(root, 'alpha'); const outside = join(base, 'outside') + mkdirSync(project, { recursive: true }); mkdirSync(outside) + const catalog = openWorkspaceCatalog({ root, privateRoots: [outside] }) + const id = catalog.list()[0].id + const leases = [] + t.after(() => { + for (const lease of leases) lease.close() + catalog.close() + rmSync(base, { recursive: true, force: true }) + }) + const open = (name, directory = '', source = catalog) => { + const lease = openProjectDocumentTarget(source, id, { directory, name }) + leases.push(lease) + return lease + } + return { base, root, project, outside, catalog, id, open, files: openWorkspaceFiles({ catalog, writable: true }) } +} + +test('native publish uses exact workspace revisions, mode, and bytes for BOM, CJK, mixed line endings and empty text', async t => { + const { project, open, files, id } = fixture(t) + const folder = join(project, '文档'); mkdirSync(folder) + const content = '\ufeff中文 🧭\r\nLatin: café\t\nline break: \u0085\r' + const lease = open('项目笔记.MD', '文档') + assert.equal(lease.path, '文档/项目笔记.MD') + assert.equal(lease.verifyAbsent(), true) + let calls = 0 + const previousUmask = process.umask(0o777) + let saved + try { + saved = lease.publish(content, () => { + calls++ + if (calls === 1) assert.deepEqual(readdirSync(folder), []) + if (calls === 2) assert.equal(lstatSync(join(folder, stageName(folder))).mode & 0o7777, 0o600) + if (calls === 3) assert.ok(lstatSync(join(project, lease.path)).isFile()) + return true + }) + } finally { process.umask(previousUmask) } + assert.equal(calls, 3) + assert.match(saved.revision, /^r_[0-9a-f]{64}$/) + const installed = join(project, lease.path) + const stat = lstatSync(installed, { bigint: true }) + assert.equal(stat.mode & 0o7777n, 0o600n) + assert.equal(stat.nlink, 1n) + assert.equal(stat.uid, BigInt(process.geteuid())) + assert.deepEqual(readFileSync(installed), Buffer.from(content)) + assert.equal(saved.revision, workspaceTextRevision(lease.path, stat, Buffer.from(content))) + assert.deepEqual(await files.read(id, lease.path), { path: lease.path, content, revision: saved.revision, writable: true }) + assert.equal(lease.verifyReceipt(saved.revision), true) + assert.equal(lease.verifyReceipt(saved.revision), true) + assert.deepEqual(readdirSync(folder), ['项目笔记.MD']) + assert.throws(() => lease.publish(content, owner), expect(409, 'document_exists')) + assert.throws(() => lease.verifyAbsent(), expect(409, 'document_exists')) + assert.throws(() => lease.verifyReceipt(`r_${'0'.repeat(64)}`), expect(409, 'document_changed')) + assert.deepEqual(lstatSync(installed, { bigint: true }).mtimeNs, stat.mtimeNs) + lease.close(); lease.close() + assert.throws(() => lease.verifyReceipt(saved.revision), expect(409, 'document_changed')) + for (const fd of readdirSync('/proc/self/fd')) { + let path + try { path = readlinkSync(`/proc/self/fd/${fd}`) } catch (error) { if (error.code !== 'ENOENT') throw error } + assert.notEqual(path, folder) + assert.notEqual(path, installed) + } + const empty = open('README.md') + const result = empty.publish('', owner) + assert.equal((await files.read(id, 'README.md')).revision, result.revision) + assert.equal((await files.read(id, 'README.md')).content, '') +}) + +test('name rules cover ordinary visible files, traversal, Windows aliases, controls and sensitive paths', t => { + const { open, catalog, project } = fixture(t) + const rejected = [undefined, 42, '', '.hidden.md', 'a/b.md', '../doc.txt', 'a\\b.md', 'C:doc.md', '\0.md', 'a\u0080.md', + 'a\u202e.md', 'a\u200b.md', 'a\u2028.md', 'a\ud800.md', 'a\ufe0f.md', 'a.md ', 'a.md.', ' a.md', 'a .md', 'a..md', + 'NUL.md', 'PRN.x.txt', 'con .md', 'CONIN$.md', 'LPT².txt', 'Part~1.md', 'team:a.txt', 'a*.md', 'a|b.md', 'a/b.md', + 'report.markdown', 'report.text', 'script.md.exe'] + for (const name of rejected) assert.throws(() => open(name), expect(400, 'document_invalid'), String(name)) + for (const name of ['AGENTS.md', 'CLAUDE.txt', 'gemini.MD', 'SKILL.md', 'AGENTS.override.md', 'copilot-instructions.md', + 'Dockerfile.md', 'codeowners.txt', 'script.PS1.txt', 'run.ExE.notes.md', 'script.js.md', 'private-key.txt', 'id_rsa.md', + 'api_key.txt', 'access-token.md', 'Key.txt', 'notes.pem.txt', 'CLAUDE.md']) { + assert.throws(() => open(name), expect(422, 'document_restricted'), name) + } + for (const directory of ['.', '..', '/var/tmp', '.git', '../alpha', 'a\\b', 'nested/']) { + assert.throws(() => open('note.md', directory), expect(400, 'document_invalid'), directory) + } + for (const directory of ['credentials', 'notes/api_keys', 'u\u202er']) { + assert.throws(() => open('note.md', directory), expect(422, 'document_restricted'), directory) + } + assert.throws(() => open('note.md', 'missing'), expect(404, 'workspace_unavailable')) + assert.throws(() => open('note.md', Array(16).fill('x').join('/')), expect(413, 'document_limit')) + assert.throws(() => open(`${'中'.repeat(66)}.md`), expect(413, 'document_limit')) + assert.equal(open(`${'中'.repeat(65)}xy.md`).verifyAbsent(), true) + assert.throws(() => openProjectDocumentTarget(catalog, unavailableId, { directory: '', name: 'note.md' }), expect(404, 'workspace_unavailable')) + assert.throws(() => openProjectDocumentTarget(catalog, project, { directory: '', name: 'note.md' }), expect(404, 'workspace_unavailable')) + assert.deepEqual(readdirSync(project), []) +}) + +test('byte cap and reader text validity precede stage creation; recognized credential material is restricted', async t => { + const { open, project, files, id } = fixture(t) + const target = open('content.txt') + for (const content of [null, 17, Buffer.from('bytes'), '\ud800', '\udc00', 'zero\0byte', '\u0003', '\u001b', '\u007f', '\u009f']) { + assert.throws(() => target.publish(content, () => assert.fail('unexpected authorization')), expect(400, 'document_invalid')) + } + for (const content of ['x'.repeat(MAX_BYTES + 1), 'é'.repeat(MAX_BYTES / 2 + 1)]) { + assert.throws(() => target.publish(content, owner), expect(413, 'document_limit')) + } + for (const content of ['prefix\n-----BEGIN OPENSSH PRIVATE KEY-----\n', '{"client_secret":"example"}', + `ghp_${'SampleToken'.repeat(4)}`, 'EXAMPLE_ACCESS_TOKEN=abcdefgh0123456789']) { + assert.throws(() => target.publish(content, owner), expect(422, 'document_restricted')) + } + assert.deepEqual(readdirSync(project), []) + const content = 'é'.repeat(MAX_BYTES / 2) + assert.equal(Buffer.byteLength(content), MAX_BYTES) + const { revision } = target.publish(content, owner) + assert.equal((await files.read(id, target.path)).content, content) + assert.equal(target.verifyReceipt(revision), true) +}) + +test('all existing entry types and common spelling aliases are non-adoptable', t => { + const { outside, project, open } = fixture(t) + const protectedFile = join(outside, 'kept.txt'); writeFileSync(protectedFile, 'outside') + writeFileSync(join(project, 'existing.md'), 'same') + writeFileSync(join(project, 'Café.txt'), 'alias') + writeFileSync(join(project, 'x.txt. '), 'Windows alias') + mkdirSync(join(project, 'directory.md')) + symlinkSync(protectedFile, join(project, 'linked.md')) + symlinkSync('missing', join(project, 'dangling.md')) + symlinkSync(outside, join(project, 'directory-link')) + linkSync(protectedFile, join(project, 'hard.txt')) + execFileSync('mkfifo', [join(project, 'pipe.md')]) + for (const name of ['existing.md', 'EXISTING.MD', 'cafe\u0301.TXT', 'x.txt']) { + const target = open(name) + assert.throws(() => target.verifyAbsent(), expect(409, 'document_exists')) + assert.throws(() => target.publish('same', owner), expect(409, 'document_exists')) + } + for (const name of ['directory.md', 'linked.md', 'dangling.md', 'hard.txt', 'PIPE.md']) { + const target = open(name) + assert.throws(() => target.verifyAbsent(), expect(403, 'document_unsafe')) + assert.throws(() => target.publish('same', owner), expect(403, 'document_unsafe')) + } + assert.throws(() => open('note.md', 'directory-link'), expect(403, 'document_unsafe')) + assert.throws(() => open('note.md', 'existing.md'), expect(403, 'document_unsafe')) + assert.equal(readFileSync(protectedFile, 'utf8'), 'outside') + assert.equal(stageName(project), undefined) +}) + +test('permissions and owner checkpoints run before staging and again before the visible link', t => { + const { open, project } = fixture(t) + const dir = join(project, 'editable'); mkdirSync(dir) + const target = open('gate.md', 'editable') + for (const guard of [undefined, () => false, () => { throw Error(project) }, async () => { throw Error(project) }]) { + assert.throws(() => target.publish('text', guard), expect(401, 'auth')) + } + assert.deepEqual(readdirSync(dir), []) + let calls = 0 + assert.throws(() => target.publish('text', () => ++calls < 2), expect(401, 'auth')) + assert.equal(calls, 2) + assert.deepEqual(readdirSync(dir), []) + for (const mode of [0o555, 0o300, 0o600, 0o377]) { + chmodSync(dir, mode) + try { assert.throws(() => target.publish('text', owner), expect(403, 'document_read_only')) } + finally { chmodSync(dir, 0o700) } + } + calls = 0 + assert.throws(() => target.publish('text', () => { + if (++calls === 2) chmodSync(dir, 0o500) + return true + }), expect(403, 'document_read_only')) + chmodSync(dir, 0o700) + const remaining = readdirSync(dir) + assert.ok(remaining.every(name => name.startsWith('.project-document-'))) + assert.equal(target.verifyAbsent(), true) + const closing = open('closed.md', 'editable') + assert.throws(() => closing.publish('text', () => { closing.close(); return true }), expect(409, 'document_changed')) + assert.deepEqual(readdirSync(dir), remaining) +}) + +// Node exposes no POSIX ACL API; use Linux's xattr interface when available. +const aclScript = ` +import errno, os, struct, sys +path, kind, owner = sys.argv[1:] +uid = 65533 if os.geteuid() == 65534 else 65534 +entries = [(1, int(owner), 0xffffffff), (2, 7, uid), (4, 7, 0xffffffff), + (16, 7, 0xffffffff), (32, 7, 0xffffffff)] +acl = struct.pack(' { + const { open, project } = fixture(t) + const dir = join(project, 'acl'); mkdirSync(dir) + if (!setAcl(dir, 'default', 7)) return t.skip('Python or the filesystem POSIX ACL interface is unavailable') + const target = open('note.txt', 'acl') + const { revision } = target.publish('test', owner) + assert.equal(lstatSync(join(dir, 'note.txt')).mode & 0o7777, 0o600) + const blocked = open('another.md', 'acl') + assert.equal(setAcl(dir, 'access', 5), true) + assert.equal(target.verifyReceipt(revision), true) + assert.throws(() => blocked.publish('text', owner), expect(403, 'document_read_only')) + assert.deepEqual(readdirSync(dir), ['note.txt']) + chmodSync(dir, 0o700) +}) + +test('pinned parent, project and catalog-root swaps fail before touching a substitute', t => { + const { base, root, project, open } = fixture(t) + const dir = join(project, 'nested'); mkdirSync(dir) + const moved = join(project, 'old-nested') + const lease = open('note.md', 'nested') + let calls = 0 + assert.throws(() => lease.publish('first', () => { + if (++calls === 2) { + renameSync(dir, moved); mkdirSync(dir) + writeFileSync(join(dir, 'note.md'), 'decoy') + } + return true + }), expect(409, 'document_changed')) + assert.deepEqual(readdirSync(moved), []) + assert.equal(readFileSync(join(dir, 'note.md'), 'utf8'), 'decoy') + const atProject = open('project.md') + renameSync(project, join(root, 'old-alpha')); mkdirSync(project) + assert.throws(() => atProject.verifyAbsent(), expect(404, 'workspace_unavailable')) + assert.throws(() => atProject.publish('second', owner), expect(404, 'workspace_unavailable')) + assert.deepEqual(readdirSync(project), []) + renameSync(root, join(base, 'old-root')); mkdirSync(project, { recursive: true }) + assert.throws(() => atProject.publish('third', owner), expect(404, 'workspace_unavailable')) + assert.deepEqual(readdirSync(project), []) +}) + +test('receipt rejects external metadata changes, writes, aliases and equal-byte inode substitutions', t => { + const { project, open } = fixture(t) + for (const [name, mutate] of [ + ['mtime.md', path => utimesSync(path, 1000, 1000)], + ['bytes.md', path => writeFileSync(path, 'evil')], + ['alias.md', () => writeFileSync(join(project, 'ALIAS.MD'), 'decoy')], + ['equal.md', path => { + const existing = lstatSync(path) + renameSync(path, `${path}.old`) + writeFileSync(path, 'same', { mode: 0o600 }); utimesSync(path, existing.atime, existing.mtime) + assert.notEqual(lstatSync(path).ino, existing.ino) + }], + ]) { + const target = open(name) + const { revision } = target.publish('same', owner) + mutate(join(project, name)) + assert.throws(() => target.verifyReceipt(revision), expect(409, 'document_changed'), name) + } + assert.equal(readFileSync(join(project, 'equal.md'), 'utf8'), 'same') + assert.equal(readFileSync(join(project, 'ALIAS.MD'), 'utf8'), 'decoy') +}) + +test('directory scan caps cover hidden entries and do not leave a stage', async t => { + const { project, open, files, id } = fixture(t) + const floor = join(project, 'many'); mkdirSync(floor) + for (let i = 0; i < 4095; i++) writeFileSync(join(floor, `.other-${i}`), '') + const within = open('last.md', 'many') + const { revision } = within.publish('', owner) + assert.equal(within.verifyReceipt(revision), true) + const list = await files.list(id, 'many') + assert.deepEqual(list.entries, [{ name: 'last.md', path: 'many/last.md', type: 'file' }]) + const beyond = open('overflow.md', 'many') + assert.throws(() => beyond.verifyAbsent(), expect(413, 'document_limit')) + assert.throws(() => beyond.publish('', owner), expect(413, 'document_limit')) + assert.equal(stageName(floor), undefined) +}) From b6bf5efa501a651006315576925f017526b0b648 Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 09:16:23 +0800 Subject: [PATCH 2/7] =?UTF-8?q?feat(files):=20=E7=BB=91=E5=AE=9A=E4=BA=BA?= =?UTF-8?q?=E5=B7=A5=E6=A0=B8=E5=AF=B9=E4=B8=8E=E5=88=9B=E5=BB=BA=E5=9B=9E?= =?UTF-8?q?=E6=89=A7=E5=88=B0=E7=99=BB=E5=BD=95=E5=AE=9E=E4=BE=8B=20/=20bi?= =?UTF-8?q?nd=20document=20creation=20and=20verification=20to=20the=20orig?= =?UTF-8?q?inal=20login?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/files/project-document-resources.mjs | 66 ++++ .../src/files/project-document-service.mjs | 296 +++++++++++++++ .../project-document-service-native.test.mjs | 76 ++++ .../test/project-document-service.test.mjs | 338 ++++++++++++++++++ 4 files changed, 776 insertions(+) create mode 100644 apps/headless/src/files/project-document-resources.mjs create mode 100644 apps/headless/src/files/project-document-service.mjs create mode 100644 apps/headless/test/project-document-service-native.test.mjs create mode 100644 apps/headless/test/project-document-service.test.mjs diff --git a/apps/headless/src/files/project-document-resources.mjs b/apps/headless/src/files/project-document-resources.mjs new file mode 100644 index 00000000..93bade10 --- /dev/null +++ b/apps/headless/src/files/project-document-resources.mjs @@ -0,0 +1,66 @@ +import { types } from 'node:util' +import { HttpError } from '../http/policy.mjs' +import { PROJECT_DOCUMENT_MAX_BYTES } from './project-document-names.mjs' + +const codes = new Map(Object.entries({ + auth: 401, + workspace_unavailable: 404, + document_invalid: 400, + document_read_only: 403, + document_unsafe: 403, + document_intent_missing: 404, + document_exists: 409, + document_changed: 409, + document_conflict: 409, + document_limit: 413, + document_restricted: 422, + document_busy: 429, + document_unconfirmed: 503, + document_unavailable: 503, +})) +export const fault = code => new HttpError(codes.get(code), code) +export function bridgeCode(error, fallback) { + if (error && !types.isProxy(error) && error instanceof HttpError) { + const code = ownData(error, 'code') + if (codes.has(code) && ownData(error, 'status') === codes.get(code)) return code + } + return fallback +} + +const exact = (value, length, pattern) => typeof value === 'string' && value.length === length && pattern.test(value) +export const validWorkspace = v => exact(v, 34, /^w_[\da-f]{32}$/) +export const validIntent = v => exact(v, 35, /^di_[\da-f]{32}$/) +export const validRevision = v => exact(v, 66, /^r_[\da-f]{64}$/) + +const record = value => value !== null && typeof value === 'object' && !types.isProxy(value) +export function ownData(value, key) { + if (!record(value)) return undefined + const entry = Object.getOwnPropertyDescriptor(value, key) + return entry && Object.hasOwn(entry, 'value') ? entry.value : undefined +} + +function fields(value, keys) { + if (!record(value)) throw fault('document_invalid') + const proto = Object.getPrototypeOf(value) + if ((proto !== Object.prototype && proto !== null) || Reflect.ownKeys(value).length !== keys.length) throw fault('document_invalid') + return keys.map(key => { + const entry = Object.getOwnPropertyDescriptor(value, key) + if (!entry?.enumerable || !Object.hasOwn(entry, 'value')) throw fault('document_invalid') + return entry.value + }) +} + +export const emptyBody = value => { fields(value, []) } +export function targetBody(value) { + const [directory, name] = fields(value, ['directory', 'name']) + if (typeof directory !== 'string' || typeof name !== 'string') throw fault('document_invalid') + return { directory, name } +} + +export function contentBody(value) { + const [content] = fields(value, ['content']) + if (typeof content !== 'string') throw fault('document_invalid') + if (content.length > PROJECT_DOCUMENT_MAX_BYTES || Buffer.byteLength(content, 'utf8') > PROJECT_DOCUMENT_MAX_BYTES) throw fault('document_limit') + if (!content.isWellFormed()) throw fault('document_invalid') + return content +} diff --git a/apps/headless/src/files/project-document-service.mjs b/apps/headless/src/files/project-document-service.mjs new file mode 100644 index 00000000..136d2501 --- /dev/null +++ b/apps/headless/src/files/project-document-service.mjs @@ -0,0 +1,296 @@ +import { createHash, randomBytes } from 'node:crypto' +import { performance } from 'node:perf_hooks' +import { types } from 'node:util' +import { + bridgeCode, contentBody, emptyBody, fault, ownData, targetBody, validIntent, validRevision, validWorkspace, +} from './project-document-resources.mjs' + +const MAX_PER_LOGIN = 4, MAX_ACTIVE = 16 +const ISSUE_WINDOW_MS = 10_000, ISSUE_PER_LOGIN = 12, ISSUE_GLOBAL = 48 +const changed = code => code === 'document_exists' || code === 'document_changed' +// These native errors attest that publication did not make the target visible. +const PRE_PUBLICATION = new Set(['document_invalid', 'document_read_only', 'document_unsafe', 'document_limit', 'document_restricted']) +const sameLogin = (a, b) => a.ownerId === b.ownerId && a.loginSessionId === b.loginSessionId +const quietly = action => { try { return action() } catch {} } + +function actorIdentity(actor) { + const role = ownData(actor, 'role'), ownerId = ownData(actor, 'ownerId'), loginSessionId = ownData(actor, 'loginSessionId') + if (role !== 'owner' || typeof ownerId !== 'string' || !ownerId || typeof loginSessionId !== 'string' || !loginSessionId) throw fault('auth') + return Object.freeze({ role, ownerId, loginSessionId }) +} + +// Native publication always gets a literal true, not the caller's auth metadata. +function verificationFailure(verifyOwner) { + if (typeof verifyOwner !== 'function' || types.isProxy(verifyOwner) || types.isAsyncFunction(verifyOwner)) return 'auth' + try { + const result = verifyOwner() + if (result === true || result === undefined) return null + if (types.isPromise(result)) { + // Reject accidental async auth checks and contain their rejection. + Promise.prototype.then.call(result, undefined, () => {}) + return 'auth' + } + // A synchronous auth check can return metadata. Reject thenables without invoking getters. + if (result === null || typeof result !== 'object') return 'auth' + for (let proto = result; proto !== null; proto = Object.getPrototypeOf(proto)) { + if (types.isProxy(proto)) return 'auth' + const then = Object.getOwnPropertyDescriptor(proto, 'then') + if (then) return Object.hasOwn(then, 'value') && typeof then.value !== 'function' ? null : 'auth' + } + return null + } catch (error) { + return bridgeCode(error) === 'document_unavailable' ? 'document_unavailable' : 'auth' + } +} + +/** Manual one-shot document creation. No native target is acquired until an authorized prepare. */ +export function openProjectDocumentService({ auth, openTarget, now = () => performance.now(), ttlMs = 120_000 } = {}) { + if (typeof auth?.isLoginActive !== 'function' || typeof auth?.onSessionRevoked !== 'function' || + typeof openTarget !== 'function' || types.isAsyncFunction(openTarget) || typeof now !== 'function' || + !Number.isSafeInteger(ttlMs) || ttlMs < 1 || ttlMs > 2 ** 31 - 1) throw fault('document_unavailable') + + const entries = new Map(), leases = new Set(), issuances = [] + let closed = false + + function dispose(entry) { + const target = entry.target + entry.target = null + entry.digest = entry.revision = null + try { quietly(() => ownData(target, 'close')?.call(target)) } + finally { entry.actor = null; leases.delete(entry) } + } + + function retire(entry, code) { + if (entry.failure) return + entry.failure = code + entries.delete(entry.id) + clearTimeout(entry.timer) + // A revoke can fire synchronously inside the bridge. Let its stack unwind before closing FDs. + if (!entry.running) dispose(entry) + } + + function finish(entry) { + if (!entry.running) return + entry.running = false + if (entry.failure) dispose(entry) + } + + const unsubscribe = auth.onSessionRevoked(login => { + for (const item of issuances) if (item.login === login) item.login = null + for (const entry of entries.values()) if (entry.actor.loginSessionId === login) retire(entry, 'auth') + }) + + function checkLogin(actor, entry) { + if (closed) throw fault('document_unavailable') + if (quietly(() => auth.isLoginActive(actor)) !== true) { + if (entry) retire(entry, 'auth') + for (const active of entries.values()) if (sameLogin(active.actor, actor)) retire(active, 'auth') + throw fault('auth') + } + if (closed) throw fault('document_unavailable') + } + + function authorize(actor, verifyOwner, entry) { + checkLogin(actor, entry) + const failure = verificationFailure(verifyOwner) + checkLogin(actor, entry) + if (failure) throw fault(failure) + } + + function checkpoint(entry, verifyOwner) { + authorize(entry.actor, verifyOwner, entry) + if (!entry.failure && now() >= entry.expires) retire(entry, 'document_intent_missing') + if (entry.failure) throw fault(entry.failure) + return true + } + + function armExpiry(entry) { + const left = entry.expires - now() + if (left <= 0) retire(entry, 'document_intent_missing') + else entry.timer = setTimeout(() => armExpiry(entry), Math.ceil(left)).unref() + } + + function reserve(actor, workspaceId) { + const time = now() + for (const entry of entries.values()) if (entry.expires <= time) retire(entry, 'document_intent_missing') + if (closed) throw fault('document_unavailable') + if (leases.size >= MAX_ACTIVE || [...leases].filter(entry => entry.actor && sameLogin(entry.actor, actor)).length >= MAX_PER_LOGIN) { + throw fault('document_busy') + } + while (issuances.length && time - issuances[0].time >= ISSUE_WINDOW_MS) issuances.shift() + if (issuances.length >= ISSUE_GLOBAL || issuances.filter(item => item.login === actor.loginSessionId).length >= ISSUE_PER_LOGIN) { + throw fault('document_busy') + } + issuances.push({ time, login: actor.loginSessionId }) + let id + do { id = 'di_' + randomBytes(16).toString('hex') } while (entries.has(id)) + const entry = { id, actor, workspaceId, expires: time + ttlMs, state: 'opening', running: true, target: null, revision: null, digest: null } + entries.set(id, entry) + leases.add(entry) + armExpiry(entry) + return entry + } + + function use(actor, workspaceId, intentId, verifyOwner, run) { + const identity = actorIdentity(actor) + checkLogin(identity) + const entry = validIntent(intentId) && entries.get(intentId) + if (!entry || entry.state === 'opening' || entry.workspaceId !== workspaceId || !sameLogin(entry.actor, identity)) { + authorize(identity, verifyOwner) + throw fault('document_intent_missing') + } + if (entry.running) { + authorize(identity, verifyOwner) + throw fault('document_busy') + } + entry.running = true + try { + checkpoint(entry, verifyOwner) + return run(entry, verifyOwner) + } finally { finish(entry) } + } + + function stale(entry, code) { + entry.state = 'stale' + entry.staleCode = code + entry.digest = entry.revision = null + } + + function quarantine(entry) { + entry.state = 'unconfirmed' + entry.digest = entry.revision = null + } + + function call(entry, verifyOwner, action, fallback, observe) { + checkpoint(entry, verifyOwner) + let result, failure + try { result = action() } catch (error) { failure = bridgeCode(error, fallback) } + // Once acquired, an invalidated project identifier is a lost binding, not an absent intent. + if (entry.target && failure === 'workspace_unavailable') failure = 'document_changed' + const code = observe(result, failure) + checkpoint(entry, verifyOwner) + if (code) throw fault(code) + return result + } + + function verifyAbsent(entry, verifyOwner, unconfirmed = false) { + call(entry, verifyOwner, () => entry.target.verifyAbsent(), 'document_unavailable', (result, failure) => { + const code = failure ?? (result !== true ? 'document_unavailable' : undefined) + // An unknown leaf after an ambiguous publish may be our own. It is neither a receipt nor permission to retry. + if (unconfirmed && code === 'document_exists') return + if (changed(code)) stale(entry, code) + return code + }) + } + + function verifyReceipt(entry, verifyOwner) { + call(entry, verifyOwner, () => entry.target.verifyReceipt(entry.revision), 'document_unconfirmed', (result, failure) => { + const code = failure === 'document_unavailable' ? 'document_unconfirmed' : failure ?? (result !== true ? 'document_unconfirmed' : undefined) + if (changed(code)) stale(entry, code) + else if (code) quarantine(entry) + return code + }) + } + + function prepare(actor, workspaceId, body, verifyOwner) { + const identity = actorIdentity(actor) + authorize(identity, verifyOwner) + if (!validWorkspace(workspaceId)) throw fault('workspace_unavailable') + const request = Object.freeze(targetBody(body)) + const entry = reserve(identity, workspaceId) + try { + call(entry, verifyOwner, () => { entry.target = openTarget(workspaceId, request) }, 'document_unavailable', (_, failure) => failure) + const path = ownData(entry.target, 'path') + const expectedPath = request.directory === '' ? request.name : `${request.directory}/${request.name}` + if (typeof path !== 'string' || path !== expectedPath || !['verifyAbsent', 'publish', 'verifyReceipt', 'close'].every(key => + typeof ownData(entry.target, key) === 'function')) throw fault('document_unavailable') + verifyAbsent(entry, verifyOwner) + entry.path = path + entry.state = 'prepared' + return { id: entry.id, path, ttlMs } + } catch (error) { + retire(entry, 'document_intent_missing') + finish(entry) + authorize(identity, verifyOwner) + throw error + } finally { finish(entry) } + } + + function publicationGuard(entry, verifyOwner) { + return { + verify() { + if (!entry) throw fault('document_intent_missing') + return checkpoint(entry, verifyOwner) + }, + close() { entry = verifyOwner = null }, + } + } + + function publish(entry, verifyOwner, content, digest) { + const guard = publicationGuard(entry, verifyOwner) + try { + call(entry, verifyOwner, () => entry.target.publish(content, guard.verify), 'document_unconfirmed', (result, failure) => { + const revision = ownData(result, 'revision') + if (!failure && validRevision(revision)) { + entry.state = 'created' + entry.revision = revision + entry.digest = digest + return + } + if (changed(failure)) { stale(entry, failure); return failure } + if (PRE_PUBLICATION.has(failure)) return failure + quarantine(entry) + return failure === 'auth' ? 'auth' : 'document_unconfirmed' + }) + } finally { guard.close() } + } + + function create(entry, verifyOwner, body) { + const content = contentBody(body) + if (entry.state === 'stale') throw fault(entry.staleCode) + if (entry.state === 'unconfirmed') throw fault('document_unconfirmed') + const digest = createHash('sha256').update(content, 'utf8').digest('hex') + const replayed = entry.state === 'created' + if (replayed) { + if (digest !== entry.digest) throw fault('document_conflict') + } else { + verifyAbsent(entry, verifyOwner) + publish(entry, verifyOwner, content, digest) + } + verifyReceipt(entry, verifyOwner) + return { created: true, path: entry.path, revision: entry.revision, replayed } + } + + return Object.freeze({ + prepare, + create(actor, workspaceId, intentId, body, verifyOwner) { + return use(actor, workspaceId, intentId, verifyOwner, (entry, verify) => create(entry, verify, body)) + }, + status(actor, workspaceId, intentId, body, verifyOwner) { + return use(actor, workspaceId, intentId, verifyOwner, (entry, verify) => { + emptyBody(body) + if (entry.state === 'stale') throw fault(entry.staleCode) + if (entry.state === 'created') verifyReceipt(entry, verify) + else verifyAbsent(entry, verify, entry.state === 'unconfirmed') + return { state: entry.state, path: entry.path, revision: entry.revision } + }) + }, + cancel(actor, workspaceId, intentId, body, verifyOwner) { + return use(actor, workspaceId, intentId, verifyOwner, (entry, verify) => { + emptyBody(body) + const identity = entry.actor + retire(entry, 'document_intent_missing') + finish(entry) + authorize(identity, verify) + return { closed: true } + }) + }, + close() { + if (closed) return + closed = true + quietly(() => unsubscribe()) + for (const entry of entries.values()) retire(entry, 'document_unavailable') + issuances.length = 0 + }, + }) +} diff --git a/apps/headless/test/project-document-service-native.test.mjs b/apps/headless/test/project-document-service-native.test.mjs new file mode 100644 index 00000000..ab24ffa4 --- /dev/null +++ b/apps/headless/test/project-document-service-native.test.mjs @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict' +import { existsSync } from 'node:fs' +import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import test from 'node:test' +import { openWorkspaceCatalog } from '../src/business/workspace-catalog.mjs' +import { openProjectDocumentService } from '../src/files/project-document-service.mjs' +import { openProjectDocumentTarget } from '../src/files/project-document-target.mjs' +import { HttpError } from '../src/http/policy.mjs' + +const A = Object.freeze({ role: 'owner', ownerId: 'owner', loginSessionId: 'login-A' }) +const B = Object.freeze({ ...A, loginSessionId: 'login-B' }) +const ok = () => true +const fault = (status, code) => e => e instanceof HttpError && e.status === status && e.code === code + +test('real publication reads back exact bytes; login revocation at visibility keeps file but returns zero receipts', { skip: process.platform !== 'linux' }, async t => { + const base = await realpath(tmpdir()), root = await mkdtemp(join(base, 'deva-project-document-service-')) + const { dev, ino } = await lstat(root) + const folder = join(root, 'Project', 'Notes') + const installed = join(folder, 'english.txt'), revoked = join(folder, 'during.md') + let catalog, service + t.after(async () => { + try { service?.close(); catalog?.close() } + finally { + assert.equal(dirname(root), base) + assert.equal(await realpath(root), root) + const current = await lstat(root) + assert.deepEqual([current.dev, current.ino], [dev, ino]) + await rm(root, { recursive: true }) + } + }) + await mkdir(folder, { recursive: true, mode: 0o700 }) + catalog = openWorkspaceCatalog({ root }) + const wid = catalog.list()[0].id + const active = new Set([A.loginSessionId, B.loginSessionId]) + let listener, nativeCloses = 0, nativePublishes = 0 + const revoke = actor => { active.delete(actor.loginSessionId); listener(actor.loginSessionId) } + service = openProjectDocumentService({ + auth: { isLoginActive: actor => active.has(actor.loginSessionId), onSessionRevoked(fn) { listener = fn; return () => { listener = undefined } } }, + openTarget(workspace, body) { + const target = openProjectDocumentTarget(catalog, workspace, body) + return { ...target, + publish(...args) { nativePublishes++; return target.publish(...args) }, + close() { nativeCloses++; return target.close() }, + } + }, + }) + assert.throws(() => service.prepare(A, wid, { directory: 'Notes', name: 'AGENTS.md' }, ok), fault(422, 'document_restricted')) + const live = service.prepare(A, wid, { directory: 'Notes', name: 'english.txt' }, ok) + const blocked = '{"private_key":"PRIVATE_LITERAL"}' + assert.throws(() => service.create(A, wid, live.id, { content: blocked }, ok), fault(422, 'document_restricted')) + const bytes = '\uFEFF真实 UTF-8\r\nsecond line\r\n' + const receipt = service.create(A, wid, live.id, { content: bytes }, ok) + assert.match(receipt.revision, /^r_[a-f0-9]{64}$/u) + assert.equal(receipt.replayed, false) + const before = await lstat(installed, { bigint: true }) + assert.deepEqual(await readFile(installed), Buffer.from(bytes)) + assert.deepEqual(service.create(A, wid, live.id, { content: bytes }, ok), { ...receipt, replayed: true }) + const after = await lstat(installed, { bigint: true }) + assert.deepEqual([after.ino, after.ctimeNs], [before.ino, before.ctimeNs]) + assert.equal(nativePublishes, 2, 'the rejected restricted text and the successful publish each reached native validation') + + const abandoned = service.prepare(A, wid, { directory: 'Notes', name: 'during.md' }, ok) + assert.throws(() => service.create(A, wid, abandoned.id, { content: bytes }, () => { + if (existsSync(revoked)) revoke(A) + return true + }), fault(401, 'auth')) + assert.deepEqual(await readFile(revoked), Buffer.from(bytes)) + assert.deepEqual((await readdir(folder)).sort(), ['during.md', 'english.txt']) + assert.equal(nativeCloses, 2, 'all held pins for the revoked identity were released') + assert.throws(() => service.status(B, wid, live.id, {}, ok), fault(404, 'document_intent_missing')) + assert.throws(() => service.status(B, wid, abandoned.id, {}, ok), fault(404, 'document_intent_missing')) + assert.throws(() => service.prepare(B, wid, { directory: 'Notes', name: 'during.md' }, ok), fault(409, 'document_exists')) + assert.equal(nativeCloses, 3, 'rejected prepared target closes too') +}) diff --git a/apps/headless/test/project-document-service.test.mjs b/apps/headless/test/project-document-service.test.mjs new file mode 100644 index 00000000..7c45fba2 --- /dev/null +++ b/apps/headless/test/project-document-service.test.mjs @@ -0,0 +1,338 @@ +import assert from 'node:assert/strict' +import { setTimeout as delay } from 'node:timers/promises' +import test from 'node:test' +import { HttpError } from '../src/http/policy.mjs' +import { openProjectDocumentService } from '../src/files/project-document-service.mjs' + +const WID = 'w_' + '1'.repeat(32), OTHER_WID = 'w_' + '2'.repeat(32) +const REV = 'r_' + 'a'.repeat(64) +const owner = n => Object.freeze({ role: 'owner', ownerId: 'same-owner', loginSessionId: `login-${n}` }) +const A = owner(0), B = owner(1) +const ok = () => true +const doc = (name = 'note.md') => ({ directory: 'Notes', name }) +const error = (status, code) => new HttpError(status, code) +const throws = (fn, status, code) => assert.throws(fn, e => e instanceof HttpError && e.status === status && e.code === code) + +function fixture(t, options = {}) { + const active = new Set(), listeners = new Set(), hooks = Object.create(null), files = new Map(), targets = [] + const stats = { opens: 0, absences: 0, publishes: 0, receipts: 0, closes: 0 } + const auth = { + isLoginActive: actor => actor.role === 'owner' && actor.ownerId === A.ownerId && active.has(actor.loginSessionId), + onSessionRevoked(fn) { listeners.add(fn); return () => listeners.delete(fn) }, + } + function activate(actor) { active.add(actor.loginSessionId) } + function revoke(actor) { + active.delete(actor.loginSessionId) + for (const listener of listeners) listener(actor.loginSessionId) + } + activate(A); activate(B) + const service = openProjectDocumentService({ auth, ...options, openTarget(wid, request) { + stats.opens++ + const { directory, name } = request + const path = directory === '' ? name : `${directory}/${name}`, key = `${wid}:${path}` + let closed = false, receipt + function live() { assert.equal(closed, false, 'bridge FD remained live until the callback unwound') } + const target = { path, + verifyAbsent() { + live(); stats.absences++ + hooks.absent?.(target) + live() + if (files.has(key)) throw error(409, 'document_exists') + return true + }, + publish(bytes, verify) { + live(); stats.publishes++ + assert.equal(verify(), true) + hooks.beforeLink?.(target, verify) + if (files.has(key)) throw error(409, 'document_exists') + files.set(key, (receipt = { bytes, revision: REV })) + hooks.afterLink?.(target, verify) + live() + assert.equal(verify(), true) + return { revision: REV } + }, + verifyReceipt(revision) { + live(); stats.receipts++ + hooks.receipt?.(target) + live() + if (!receipt || files.get(key) !== receipt || revision !== receipt.revision) throw error(409, 'document_changed') + return true + }, + close() { assert.equal(closed, false); closed = true; stats.closes++; hooks.close?.(target) }, + } + targets.push({ key, target }) + hooks.open?.(target) + return target + } }) + t.after(() => service.close()) + const prepare = (actor = A, workspace = WID, request = doc(), verify = ok) => service.prepare(actor, workspace, request, verify) + const create = (id, content, verify = ok) => service.create(A, WID, id, { content }, verify) + const status = (id, actor = A, workspace = WID) => service.status(actor, workspace, id, {}, ok) + const cancel = (id, actor = A) => service.cancel(actor, WID, id, {}, ok) + return { service, auth, listeners, active, activate, revoke, hooks, files, targets, stats, prepare, create, status, cancel } +} + +test('fresh receipt requires synchronous native readback and identical retries only verify', t => { + const f = fixture(t) + assert.equal(f.stats.opens, 0) + const prepared = f.prepare() + assert.deepEqual(prepared, { id: prepared.id, path: 'Notes/note.md', ttlMs: 120_000 }) + assert.match(prepared.id, /^di_[a-f0-9]{32}$/) + assert.deepEqual(f.status(prepared.id), { state: 'prepared', path: prepared.path, revision: null }) + const text = '\uFEFF项目\r\nSecond line\r\n' + const receipt = f.create(prepared.id, text) + assert.deepEqual(receipt, { created: true, path: prepared.path, revision: REV, replayed: false }) + assert.equal(f.stats.receipts, 1) + assert.deepEqual(f.create(prepared.id, text), { ...receipt, replayed: true }) + assert.equal(f.stats.publishes, 1) + assert.equal(f.stats.receipts, 2) + throws(() => f.create(prepared.id, text.replaceAll('\r\n', '\n')), 409, 'document_conflict') + assert.deepEqual(f.status(prepared.id), { state: 'created', path: prepared.path, revision: REV }) + assert.equal(f.stats.receipts, 3) + assert.deepEqual(f.cancel(prepared.id), { closed: true }) + assert.equal(f.stats.closes, 1) + assert.equal(f.files.get(f.targets[0].key).bytes, text) + throws(() => f.status(prepared.id), 404, 'document_intent_missing') +}) + +test('sibling login, workspace, and malformed intent IDs see the same missing receipt', t => { + const f = fixture(t) + const { id } = f.prepare() + for (const who of [B, { ...A, loginSessionId: 'new-session' }]) { + f.activate(who) + throws(() => f.status(id, who), 404, 'document_intent_missing') + throws(() => f.service.create(who, WID, id, { content: 'same' }, ok), 404, 'document_intent_missing') + throws(() => f.cancel(id, who), 404, 'document_intent_missing') + } + throws(() => f.status(id, A, OTHER_WID), 404, 'document_intent_missing') + throws(() => f.status(`${id}\n`), 404, 'document_intent_missing') + throws(() => f.prepare(A, `${WID}\n`), 404, 'workspace_unavailable') + assert.equal(f.stats.closes, 0) + f.revoke(A) + assert.equal(f.stats.closes, 1) + throws(() => f.status(id), 401, 'auth') + throws(() => f.status(id, B), 404, 'document_intent_missing') + assert.ok(f.prepare(B).id) +}) + +test('validates bodies without invoking getters, proxy traps, or coercion', t => { + const f = fixture(t) + const fail = () => assert.fail('request accessor or trap was invoked') + const preparedBody = { directory: '', get name() { fail() } } + const proxy = new Proxy(doc(), { ownKeys: fail, getPrototypeOf: fail, get: fail }) + for (const value of [preparedBody, proxy, null, [], 'string', { ...doc(), extra: '' }, { directory: 4, name: 'x.md' }, + { directory: '', name: { toString: fail } }, Object.create(doc())]) { + throws(() => f.prepare(A, WID, value), 400, 'document_invalid') + } + assert.equal(f.stats.opens, 0) + const { id } = f.prepare() + for (const value of [null, [], { get content() { fail() } }, { content: '\ud800' }, { content: true }, { content: '', [Symbol()]: 1 }]) { + throws(() => f.service.create(A, WID, id, value, ok), 400, 'document_invalid') + } + throws(() => f.create(id, 'é'.repeat(1024 * 1024 + 1)), 413, 'document_limit') + throws(() => f.service.cancel(A, WID, id, { get content() { fail() } }, ok), 400, 'document_invalid') + throws(() => f.service.status(A, WID, id, proxy, ok), 400, 'document_invalid') + assert.equal(f.stats.publishes, 0) + assert.equal(f.create(id, '').replayed, false) +}) + +test('requires current owner authority before acquisition and after every native call', t => { + const f = fixture(t) + for (const verify of [false, () => false, async () => true, () => Promise.reject(new Error('async denial')), + () => ({ get then() { assert.fail('then getter') } }), () => { throw Error('auth denied') }]) { + throws(() => f.prepare(A, WID, doc(), verify), 401, 'auth') + } + assert.equal(f.stats.opens, 0) + f.hooks.open = () => f.revoke(A) + throws(() => f.prepare(), 401, 'auth') + assert.equal(f.stats.absences, 0) + assert.equal(f.stats.closes, 1) + f.hooks.open = undefined + f.hooks.absent = () => f.revoke(B) + throws(() => f.prepare(B), 401, 'auth') + assert.equal(f.stats.closes, 2) + f.activate(B) + f.hooks.absent = undefined + const { id } = f.prepare(B) + f.hooks.close = () => f.revoke(B) + throws(() => f.cancel(id, B), 401, 'auth') + assert.equal(f.stats.closes, 3) +}) + +test('a foreign file with matching content cannot be acknowledged, even in a publish race', t => { + const f = fixture(t) + const draft = doc('draft.txt') + const foreign = { bytes: 'same', revision: REV } + f.files.set(`${WID}:Notes/${draft.name}`, foreign) + throws(() => f.prepare(A, WID, draft), 409, 'document_exists') + assert.equal(f.stats.closes, 1) + const { id } = f.prepare() + const { key } = f.targets.at(-1) + f.hooks.beforeLink = () => f.files.set(key, foreign) + throws(() => f.create(id, foreign.bytes), 409, 'document_exists') + assert.equal(f.files.get(key), foreign) + assert.equal(f.stats.receipts, 0) + f.files.delete(key) + throws(() => f.create(id, foreign.bytes), 409, 'document_exists') + assert.equal(f.stats.publishes, 1) +}) + +test('two logins can prepare the same empty slot; the first publication wins', t => { + const f = fixture(t) + const winner = f.prepare(A) + const second = f.prepare(B) + assert.notEqual(winner.id, second.id) + assert.equal(winner.path, second.path) + const receipt = f.create(winner.id, 'same bytes') + throws(() => f.service.create(B, WID, second.id, { content: 'same bytes' }, ok), 409, 'document_exists') + throws(() => f.status(second.id, B), 409, 'document_exists') + assert.deepEqual(f.create(winner.id, 'same bytes'), { ...receipt, replayed: true }) + assert.equal(f.stats.publishes, 1) + assert.equal(f.files.get(f.targets[0].key).bytes, 'same bytes') +}) + +test('both replacement and disappearance fence an acquired receipt; lost project becomes changed', t => { + const f = fixture(t) + const { id } = f.prepare() + const { key } = f.targets[0] + f.create(id, 'original') + const installed = f.files.get(key) + f.files.set(key, { ...installed }) + throws(() => f.status(id), 409, 'document_changed') + f.files.set(key, installed) + throws(() => f.create(id, 'original'), 409, 'document_changed') + assert.equal(f.stats.publishes, 1) + const { id: other } = f.prepare(A, WID, doc('other.md')) + f.hooks.absent = () => { throw error(404, 'workspace_unavailable') } + throws(() => f.status(other), 409, 'document_changed') +}) + +test('ambiguous publication or fresh readback quarantines: status has no revision and no retry writes', t => { + const f = fixture(t) + const { id, path } = f.prepare() + const { key } = f.targets[0] + f.hooks.afterLink = () => { throw Error('untrusted native diagnostics') } + throws(() => f.create(id, 'landed'), 503, 'document_unconfirmed') + assert.deepEqual(f.status(id), { state: 'unconfirmed', path, revision: null }) + assert.equal(f.files.get(key).bytes, 'landed') + f.files.delete(key) + assert.deepEqual(f.status(id), { state: 'unconfirmed', path, revision: null }) + throws(() => f.create(id, 'landed'), 503, 'document_unconfirmed') + throws(() => f.create(id, 'different'), 503, 'document_unconfirmed') + assert.equal(f.stats.publishes, 1) + f.hooks.afterLink = undefined + const second = f.prepare(A, WID, doc('readback.md')) + f.hooks.receipt = () => { throw Error('read interrupted') } + throws(() => f.create(second.id, 'landed'), 503, 'document_unconfirmed') + f.hooks.receipt = undefined + assert.deepEqual(f.status(second.id), { state: 'unconfirmed', path: second.path, revision: null }) + assert.equal(f.stats.publishes, 2) + f.hooks.absent = () => { throw error(409, 'document_changed') } + throws(() => f.status(second.id), 409, 'document_changed') +}) + +test('a revoke after visibility yields no receipt and does not delete the file', t => { + const f = fixture(t) + const { id } = f.prepare() + const { key } = f.targets[0] + f.hooks.afterLink = () => { + f.revoke(A) + assert.equal(f.stats.closes, 0, 'avoid closing a descriptor still in use') + } + throws(() => f.create(id, 'landed'), 401, 'auth') + assert.equal(f.files.get(key).bytes, 'landed') + assert.equal(f.stats.closes, 1) + assert.equal(f.stats.receipts, 0) + throws(() => f.status(id, B), 404, 'document_intent_missing') + throws(() => f.prepare(B), 409, 'document_exists') +}) + +test('late request-only shutdown keeps a returned receipt retryable if login is still active', t => { + const f = fixture(t) + const { id } = f.prepare() + let responseFailed = false + f.hooks.receipt = () => { responseFailed = true } + throws(() => f.create(id, 'once', () => { if (responseFailed) throw error(503, 'document_unavailable'); return true }), 503, 'document_unavailable') + f.hooks.receipt = undefined + assert.equal(f.create(id, 'once').replayed, true) + assert.equal(f.stats.publishes, 1) + assert.equal(f.stats.closes, 0) +}) + +test('in-flight intent operations are exclusive and shutdown closes once after unwind', t => { + const f = fixture(t) + const { id } = f.prepare() + f.hooks.beforeLink = (_, verify) => { + throws(() => f.create(id, 'claim'), 429, 'document_busy') + throws(() => f.cancel(id), 429, 'document_busy') + throws(() => f.status(id, B), 404, 'document_intent_missing') + assert.equal(typeof verify, 'function') + f.service.close() + assert.equal(f.stats.closes, 0) + assert.equal(f.listeners.size, 0) + verify() + } + throws(() => f.create(id, 'claim'), 503, 'document_unavailable') + assert.equal(f.stats.publishes, 1) + assert.equal(f.stats.closes, 1) + assert.equal(f.files.size, 0) + f.service.close() + assert.equal(f.stats.closes, 1) + throws(() => f.prepare(), 503, 'document_unavailable') +}) + +test('expiry releases an idle pin by timer and neither status nor replay renews TTL', { timeout: 3000 }, async t => { + const f = fixture(t, { ttlMs: 20 }) + const { id } = f.prepare() + const abort = new AbortController() + const expired = new Promise(resolve => { f.hooks.close = resolve }) + try { await Promise.race([expired, delay(2000, undefined, { signal: abort.signal }).then(() => { throw Error('idle pin leaked') })]) } + finally { abort.abort() } + assert.equal(f.stats.closes, 1) + throws(() => f.status(id), 404, 'document_intent_missing') + + let now = 0 + const g = fixture(t, { now: () => now, ttlMs: 120_000 }) + const pending = g.prepare() + now = 110_000 + g.status(pending.id) + g.create(pending.id, 'x') + now = 119_999 + assert.equal(g.create(pending.id, 'x').replayed, true) + now++ + throws(() => g.status(pending.id), 404, 'document_intent_missing') + assert.equal(g.stats.closes, 1) + assert.equal(g.files.size, 1) +}) + +test('active quota, issuance rate, and identity release have independent bounds', t => { + let now = 0 + const f = fixture(t, { now: () => now }) + const actors = Array.from({ length: 6 }, (_, i) => owner(i)) + actors.forEach(f.activate) + for (const actor of actors.slice(0, 4)) { + for (let i = 0; i < 4; i++) f.prepare(actor) + throws(() => f.prepare(actor, OTHER_WID), 429, 'document_busy') + } + throws(() => f.prepare(actors[4]), 429, 'document_busy') + assert.equal(f.stats.opens, 16) + f.revoke(B) + assert.equal(f.stats.closes, 4) + assert.ok(f.prepare(actors[4]).id) + f.service.close() + assert.equal(f.stats.closes, 17) + assert.equal(f.listeners.size, 0) + + const g = fixture(t, { now: () => now }) + for (let i = 0; i < 12; i++) g.cancel(g.prepare().id) + throws(() => g.prepare(), 429, 'document_busy') + for (const actor of actors.slice(1, 4)) { + g.activate(actor) + for (let i = 0; i < 12; i++) g.cancel(g.prepare(actor).id, actor) + } + g.activate(actors[4]) + g.revoke(B) + throws(() => g.prepare(actors[4]), 429, 'document_busy') + now = 10_000 + assert.ok(g.prepare().id) +}) From cbcaa75fd17b613a14a388b5b55b063b98aa88ea Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 09:16:23 +0800 Subject: [PATCH 3/7] =?UTF-8?q?feat(headless):=20=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E6=8E=88=E6=9D=83=E6=96=B0=E5=BB=BA=E6=96=87=E6=A1=A3=E5=B9=B6?= =?UTF-8?q?=E5=A4=8D=E6=A0=B8=E5=8E=9F=E7=94=9F=E5=86=99=E5=85=A5=20/=20ex?= =?UTF-8?q?pose=20a=20separate=20grant=20for=20verified=20native=20documen?= =?UTF-8?q?t=20creation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/headless/src/business/handlers.mjs | 18 +- apps/headless/src/business/library-routes.mjs | 6 +- apps/headless/src/cli.mjs | 9 +- .../src/files/project-document-routes.mjs | 78 ++++ apps/headless/src/http/policy.mjs | 26 +- apps/headless/src/http/session-routes.mjs | 2 +- apps/headless/src/server.mjs | 7 + .../test/project-documents-http.test.mjs | 364 ++++++++++++++++++ apps/headless/test/server-cli.test.mjs | 16 + apps/headless/test/server.test.mjs | 9 + compose.workspace-create.yaml | 6 + 11 files changed, 527 insertions(+), 14 deletions(-) create mode 100644 apps/headless/src/files/project-document-routes.mjs create mode 100644 apps/headless/test/project-documents-http.test.mjs create mode 100644 compose.workspace-create.yaml diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs index 1e22f99c..03060204 100644 --- a/apps/headless/src/business/handlers.mjs +++ b/apps/headless/src/business/handlers.mjs @@ -20,6 +20,8 @@ import { allowedModelOrigins } from './provider-fetch.mjs' import { openLibrary } from './library-routes.mjs' import { openSkillDocuments } from '../skills/documents.mjs' import { openSkillLibrary } from '../skills/store.mjs' +import { openProjectDocumentService } from '../files/project-document-service.mjs' +import { projectDocumentRoutes } from '../files/project-document-routes.mjs' import { skillLibraryRoutes } from '../skills/routes.mjs' const keyPath = /^\/api\/v1\/provider-keys\/([A-Za-z0-9_.-]{1,128})$/ @@ -53,15 +55,16 @@ async function probe(settings, supplied, opts, signal) { return connection.listModels() } -export async function openBusiness({ dataDir, vault, auth, version, allowedOrigins = [], workspaceRoot, workspaceWritable = false, privateRoots, browserRunDir, terminalRunDir, gitProjects }) { +export async function openBusiness({ dataDir, vault, auth, version, allowedOrigins = [], workspaceRoot, workspaceWritable = false, workspaceCreate = false, privateRoots, browserRunDir, terminalRunDir, gitProjects }) { const opts = { version, allowedOrigins: [...allowedModelOrigins(allowedOrigins)] } const settings = await openSettings({ dataDir, vault }) const lifetime = new AbortController() const journal = createEventJournal() let library, turns, uploads, browser, closingBrowser, git, closingGit, taskStore, preview, tasks, closingTasks - let terminalService, closingTerminals, skills, closingSkills + let terminalService, closingTerminals, skills, closingSkills, documentIntents, closingDocuments try { - library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, privateRoots, gitProjects }) + library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, workspaceCreate, privateRoots, gitProjects }) + if (library.createDocumentTarget) documentIntents = openProjectDocumentService({auth,openTarget:library.createDocumentTarget}) // Discover native documents only upon explicit owner requests (never feed this catalog to turns). const documents = openSkillDocuments({ dataDir }) skills = skillLibraryRoutes({ auth, documents, store: openSkillLibrary({ dataDir, documents, @@ -86,9 +89,10 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi } } catch (err) { journal.close() - await Promise.allSettled([skills?.close(), terminalService?.close(), git?.close(), ...(tasks ? [tasks.close()] : [preview?.close(), taskStore?.close?.()]), + await Promise.allSettled([documentIntents?.close(), skills?.close(), terminalService?.close(), git?.close(), ...(tasks ? [tasks.close()] : [preview?.close(), taskStore?.close?.()]), turns?.close(), uploads?.close(), library?.close()]); throw err } + const documentRoutes = projectDocumentRoutes(documentIntents) const terminals = terminalRoutes(terminalService) const handleGit = gitViewRoutes(git) const handleBrowser = browserRoutes(browser) @@ -97,6 +101,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi const deliveries = deliveryRoutes({ turns, files: library.deliveryFiles }) function beginShutdown() { lifetime.abort(); attachments.close() + if (!closingDocuments) { closingDocuments=documentRoutes.close();void closingDocuments.catch(()=>{}) } if (!closingSkills) { closingSkills=skills.close();void closingSkills.catch(()=>{}) } if (!closingTerminals) { closingTerminals = terminals.close(); void closingTerminals.catch(() => {}) } if (!closingTasks) { closingTasks = tasks.close(); void closingTasks.catch(() => {}) } @@ -107,13 +112,14 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi beginShutdown, capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true, browserPanel: !!browser, gitInspect: !!git, taskInspection: Boolean(tasks), deliveries: typeof turns.deliverySnapshot === 'function', - terminalViewer: Boolean(terminalService), skillLibrary: Boolean(skills), + terminalViewer: Boolean(terminalService), skillLibrary: Boolean(skills), workspaceDocumentCreate: Boolean(documentIntents), sessionWorkspaces: typeof turns.getWorkspace === 'function' && typeof turns.setWorkspace === 'function', sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }), createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }), getConfig: () => settings.getPublicConfig(), async handle(req, res, { auth, policy }) { const path = (req.url ?? '').split('?', 1)[0] + if (path.startsWith('/api/v1/workspaces/') && path.includes('/document-intents') && await documentRoutes.handle(req,res,{auth,policy})) return true if ((path === '/api/v1/skills' || path.startsWith('/api/v1/skills/')) && await skills.handle(req,res,{auth,policy})) return true if ((path === '/api/v1/terminal/profiles' || (path.startsWith('/api/v1/workspaces/') && path.includes('/terminals'))) && await terminals.handle(req,res,{auth,policy})) return true @@ -170,7 +176,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi try { await turns.close() } finally { journal.close() try { - const results = await Promise.allSettled([closingBrowser, closingGit, closingTasks, closingTerminals, closingSkills]) + const results = await Promise.allSettled([closingBrowser, closingGit, closingTasks, closingTerminals, closingSkills, closingDocuments]) if (results.some(row => row.status === 'rejected')) throw Error('Optional service shutdown unconfirmed') } finally { try { await uploads.close() } finally { await library.close() } } } diff --git a/apps/headless/src/business/library-routes.mjs b/apps/headless/src/business/library-routes.mjs index 56859128..73162d83 100644 --- a/apps/headless/src/business/library-routes.mjs +++ b/apps/headless/src/business/library-routes.mjs @@ -10,6 +10,7 @@ import { gitGrants, gitProjectNames } from '../git/access.mjs' import { openWorkspaceFiles } from '../files/workspace-files.mjs' import { workspaceFileRoutes } from '../files/workspace-routes.mjs' import { openTerminalSource } from '../terminal/source.mjs' +import { openProjectDocumentTarget } from '../files/project-document-target.mjs' import { openDeliveryFiles } from '../files/delivery-files.mjs' const rolePath = /^\/api\/v1\/personas\/([A-Za-z0-9][A-Za-z0-9_.-]{0,63})(?:\/(enabled|avatar-image))?$/ @@ -49,7 +50,8 @@ function snapshotOf(memory, scope) { return { snapshot, revision } } -export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = false, privateRoots = [], gitProjects }) { +export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = false, workspaceCreate = false, privateRoots = [], gitProjects }) { + if (typeof workspaceCreate !== 'boolean' || (workspaceCreate && (!workspaceRoot || workspaceWritable !== true))) throw new TypeError('Document creation requires a writable project root') if (typeof workspaceWritable !== 'boolean' || (workspaceWritable && !workspaceRoot)) throw new TypeError('Workspace writes require an explicit project root') const gitNames = gitProjectNames(gitProjects) if (gitNames.length && !workspaceRoot) throw new TypeError('Git inspection requires an explicit workspace root') @@ -99,6 +101,8 @@ export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = } return { workspaceFilesEnabled: Boolean(fileCommands), + // Distinct authority from update-in-place: only an explicit deployment grant can mint a new-file intent. + createDocumentTarget: workspaceCreate ? (id,fields) => openProjectDocumentTarget(catalog,id,fields) : undefined, terminalSource: workspaceRoot ? (id, path, revision) => openTerminalSource(catalog,id,path,revision) : undefined, gitGrants: approvedGit, deliveryFiles: workspaceRoot ? openDeliveryFiles({ catalog }) : undefined, diff --git a/apps/headless/src/cli.mjs b/apps/headless/src/cli.mjs index f0172c0a..0537fcf2 100644 --- a/apps/headless/src/cli.mjs +++ b/apps/headless/src/cli.mjs @@ -30,6 +30,7 @@ Options override the environment: --web-dir PATH DEVA_WEB_DIR (default apps/desktop/out/workbench, relative to the project) --workspace-root PATH DEVA_WORKSPACE_ROOT (optional mounted parent for registered projects; default none) --workspace-write DEVA_WORKSPACE_WRITE=1 (explicit permission to save an existing text file; default 0) + --workspace-create DEVA_WORKSPACE_CREATE=1 (also allow new ordinary .md/.txt documents; requires workspace writes) --browser-control-dir PATH DEVA_BROWSER_CONTROL_DIR (optional private browser-worker socket mount) --terminal-control-dir PATH DEVA_TERMINAL_CONTROL_DIR (optional dedicated private read-only TTY viewer socket mount) --git-projects JSON DEVA_GIT_PROJECTS (optional array of project names approved for read-only Git history) @@ -44,7 +45,7 @@ const runtime = { 'run-dir': str } const origin = { host: str, port: str, 'public-url': str } const flags = Object.freeze({ 'init-key': { ...paths, ...key, 'if-missing': { type: 'boolean' } }, - serve: { ...paths, ...key, ...runtime, ...origin, 'web-dir': str, 'workspace-root': str, 'workspace-write': { type: 'boolean' }, 'browser-control-dir': str, 'terminal-control-dir': str, 'git-projects': str }, + serve: { ...paths, ...key, ...runtime, ...origin, 'web-dir': str, 'workspace-root': str, 'workspace-write': { type: 'boolean' }, 'workspace-create': { type: 'boolean' }, 'browser-control-dir': str, 'terminal-control-dir': str, 'git-projects': str }, claim: { ...paths, ...runtime, ...origin }, status: { ...paths, ...runtime } }) @@ -81,9 +82,13 @@ function configuration(command, values, env) { const writeFlag = env.DEVA_WORKSPACE_WRITE ?? '0' if (!['0', '1'].includes(writeFlag)) throw Error('DEVA_WORKSPACE_WRITE must be 0 or 1') const workspaceWritable = values['workspace-write'] === true || writeFlag === '1' + const createFlag = env.DEVA_WORKSPACE_CREATE ?? '0' + if (!['0', '1'].includes(createFlag)) throw Error('DEVA_WORKSPACE_CREATE must be 0 or 1') + const workspaceCreate = values['workspace-create'] === true || createFlag === '1' + if (workspaceCreate && (!workspaceWritable || !workspaceRoot || !isAbsolute(workspaceRoot))) throw Error('Document creation requires an explicit writable workspace root') if (workspaceWritable && !workspaceRoot) throw Error('Workspace writes require an explicit workspace root') config.businessOptions = { - workspaceWritable, + workspaceWritable, workspaceCreate, ...(gitProjects ? { gitProjects } : {}), ...(terminalControl ? { terminalRunDir: workbenchPath(terminalControl, 'Terminal control directory') } : {}), ...(browserControl ? { browserRunDir: workbenchPath(browserControl, 'Browser control directory') } : {}), diff --git a/apps/headless/src/files/project-document-routes.mjs b/apps/headless/src/files/project-document-routes.mjs new file mode 100644 index 00000000..51aebba6 --- /dev/null +++ b/apps/headless/src/files/project-document-routes.mjs @@ -0,0 +1,78 @@ +import { HttpError, json, readJson } from '../http/policy.mjs' + +const collection = /^\/api\/v1\/workspaces\/(w_[a-f0-9]{32})\/document-intents(?:\/(di_[a-f0-9]{32})\/(create|status|cancel))?$/u +const codes = Object.freeze({ + auth:401, origin:403, unexpected_query:400, invalid_json:400, too_large:413, json_required:415, + document_invalid:400, document_read_only:403, document_unsafe:403, workspace_unavailable:404, + document_intent_missing:404, document_exists:409, document_changed:409, document_conflict:409, + document_limit:413, document_restricted:422, document_busy:429, document_unconfirmed:503, document_unavailable:503, +}) +const stop = () => new HttpError(503,'document_unavailable') +const exact = (value,fields) => Object.keys(value).length===fields.length && fields.every(key=>Object.hasOwn(value,key)) + +/** A human may check an empty named slot, then explicitly publish one ordinary document there. + * Filenames and document text stay in authenticated bodies. A transport error is not a reason + * to retry a creation: the same login can instead inspect the original intent's disk receipt. */ +export function projectDocumentRoutes(service) { + const active=new Set() + let closing=false,drain + async function serve(req,res,{auth,policy},path,match) { + const [,workspace,id,op]=match + let actor,prepared,published=false + try { + policy.check(req, req.method!=='GET' && req.method!=='HEAD') + if (req.url!==path) throw new HttpError(400,'unexpected_query') + if (req.method!=='POST') { json(res,405,{error:'method'},{allow:'POST',connection:'close'});return } + const cookie=policy.cookie(req) + const verify=()=>{ + const identity=auth.identify(cookie,req.headers['x-deva-csrf']) + if (!identity || identity.role!=='owner' || actor && (identity.ownerId!==actor.ownerId || identity.loginSessionId!==actor.loginSessionId)) throw new HttpError(401,'auth') + if (closing || res.destroyed) throw stop() + actor??=identity;return true + } + verify() + if (!service) throw new HttpError(403,'document_read_only') + const body=await readJson(req,op==='create'?8*1024*1024:op?128:16*1024,{uniqueMembers:true}) + verify() + const fields=op==='create'?['content']:op?[]:['directory','name'] + if (!exact(body,fields) || fields.some(field=>typeof body[field]!=='string')) throw new HttpError(400,'document_invalid') + let result, status=200 + if (!op) { + result=await service.prepare(actor,workspace,body,verify) + prepared=result.id;status=201 + } else if (op==='create') { + result=await service.create(actor,workspace,id,body,verify) + status=result.replayed?200:201 + } else if (op==='status') result=await service.status(actor,workspace,id,body,verify) + else result=await service.cancel(actor,workspace,id,body,verify) + verify();json(res,status,result);published=true + } catch(error) { + const known=error instanceof HttpError && Object.hasOwn(codes,error.code) && codes[error.code]===error.status + const code=known?error.code:error?.code==='AUTH_FAILED'?'auth':'document_unavailable' + if (!res.destroyed && !res.headersSent) json(res,codes[code],{error:code},{connection:'close'}) + } finally { + // Only unacknowledged *preparations* can be released here. A late create may have + // already linked real bytes; keep the receipt until inspection, revocation or expiry. + if (prepared && !published && auth.isLoginActive(actor)) { + try { await service.cancel(actor,workspace,prepared,{},()=>auth.isLoginActive(actor)) } catch { /* expiry/teardown owns the same handle */ } + } + } + } + return Object.freeze({ + async handle(req,res,context) { + const path=(req.url??'').split('?',1)[0],match=collection.exec(path) + if (!match || match[0]!==path) return false + if (closing || active.size>=8) { json(res,closing?503:429,{error:closing?'document_unavailable':'document_busy'},{connection:'close'});return true } + const task=serve(req,res,context,path,match);active.add(task) + try { await task } finally { active.delete(task) } + return true + }, + close() { + if (!drain) { + closing=true + drain=Promise.allSettled([...active]).then(()=>service?.close()) + } + return drain + }, + }) +} diff --git a/apps/headless/src/http/policy.mjs b/apps/headless/src/http/policy.mjs index cb470af5..0819800b 100644 --- a/apps/headless/src/http/policy.mjs +++ b/apps/headless/src/http/policy.mjs @@ -56,8 +56,24 @@ export function json(res, status, payload, headers = {}) { res.end(bytes) } +// Called only on successfully parsed JSON. Count outer object members without +// interpreting colons in strings or in nested objects. JSON.parse alone silently +// chooses the last value of a duplicated key, including differently escaped spellings. +function outerMemberCount(raw) { + let members=0, depth=0, quoted=false + for (let i=0;i limit) throw new HttpError(413, 'too_large') chunks.push(chunk) } - let body - try { body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))) } + let body,raw + try { raw=new TextDecoder('utf-8', {fatal:true}).decode(Buffer.concat(chunks));body=JSON.parse(raw) } catch { throw new HttpError(400, 'invalid_json') } - if (!body || Array.isArray(body) || typeof body !== 'object') throw new HttpError(400, 'invalid_json') + if (!body || Array.isArray(body) || typeof body !== 'object' || (uniqueMembers && outerMemberCount(raw)!==Object.keys(body).length)) { + throw new HttpError(400,'invalid_json') + } return body } diff --git a/apps/headless/src/http/session-routes.mjs b/apps/headless/src/http/session-routes.mjs index 60f82bd0..d0b99572 100644 --- a/apps/headless/src/http/session-routes.mjs +++ b/apps/headless/src/http/session-routes.mjs @@ -53,7 +53,7 @@ export function sessionRoutes({ auth, policy, version, getConfig, capabilities } deliveries: capabilities?.deliveries === true, gitInspect: capabilities?.gitInspect === true, sessionWorkspaces: capabilities?.sessionWorkspaces === true, taskInspection: capabilities?.taskInspection === true, terminalViewer: capabilities?.terminalViewer === true, - skillLibrary: capabilities?.skillLibrary === true } }) + skillLibrary: capabilities?.skillLibrary === true, workspaceDocumentCreate: capabilities?.workspaceDocumentCreate === true } }) return true } if (path === '/api/v1/auth/logout') { diff --git a/apps/headless/src/server.mjs b/apps/headless/src/server.mjs index c1c54575..2fd9cccf 100644 --- a/apps/headless/src/server.mjs +++ b/apps/headless/src/server.mjs @@ -46,6 +46,13 @@ function options(opts) { if (inside(webDir, keyFile) || [dataDir, runDir].some(dir => inside(dir, webDir) || inside(webDir, dir))) { throw Error('Web directory must be separate from private runtime paths') } + const { workspaceCreate=false, workspaceWritable=false, workspaceRoot } = opts.businessOptions ?? {} + if (typeof workspaceCreate !== 'boolean' || workspaceCreate && + (workspaceWritable !== true || typeof workspaceRoot !== 'string' || !isAbsolute(workspaceRoot) || workspaceRoot.includes('\0') || resolve(workspaceRoot) !== workspaceRoot || workspaceRoot === '/' || + [dataDir, keyFile, runDir, webDir, opts.businessOptions?.browserRunDir, opts.businessOptions?.terminalRunDir].filter(Boolean) + .some(privatePath => inside(workspaceRoot,privatePath) || inside(privatePath,workspaceRoot)))) { + throw Error('Document creation requires an explicit writable workspace root') + } const ttyDir = opts.businessOptions?.terminalRunDir if (ttyDir !== undefined) { const otherRoots = [dataDir,keyFile,runDir,webDir,opts.businessOptions?.workspaceRoot,opts.businessOptions?.browserRunDir,'/proc','/sys','/dev','/etc','/root'].filter(Boolean) diff --git a/apps/headless/test/project-documents-http.test.mjs b/apps/headless/test/project-documents-http.test.mjs new file mode 100644 index 00000000..f5db3dc0 --- /dev/null +++ b/apps/headless/test/project-documents-http.test.mjs @@ -0,0 +1,364 @@ +import assert from 'node:assert/strict' +import { randomBytes, randomUUID } from 'node:crypto' +import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises' +import { request as requestHttp } from 'node:http' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import test from 'node:test' +import { requestControl } from '../src/control/socket.mjs' +import { startWorkbench } from '../src/server.mjs' +import { initializeMasterKey } from '../src/storage/vault.mjs' + +const native = { skip: process.platform !== 'linux', timeout: 45_000 } +const intentId = /^di_[a-f0-9]{32}$/u +const revision = /^r_[a-f0-9]{64}$/u +const missingWorkspace = 'w_' + '0'.repeat(32) +const fullText = '\uFEFF项目文档\r\n第二行\r\n' +const existingText = 'original draft\n' +const directory = 'Notes' +const route = wid => `workspaces/${wid}/document-intents` +const action = (wid, intent, verb) => `${route(wid)}/${intent.id}/${verb}` + +async function fixture(t) { + const parent = await realpath(tmpdir()), root = await mkdtemp(join(parent, 'deva-doc-http-')) + const original = await lstat(root) + const opts = { dataDir: join(root, 'data'), runDir: join(root, 'run'), keyFile: join(root, 'master.key'), webDir: join(root, 'no-web'), port: 0 } + const mount = join(root, 'projects'), notes = join(mount, 'Alpha', directory), beta = join(mount, 'Beta') + const password = randomBytes(24).toString('base64url') + let app + t.after(async () => { + try { await app?.close() } finally { + const now = await lstat(root) + assert.equal(dirname(root), parent) + assert.equal(await realpath(root), root) + assert.deepEqual([now.dev, now.ino], [original.dev, original.ino]) + await rm(root, { recursive: true }) + } + }) + await mkdir(notes, { recursive: true, mode: 0o700 }) + await mkdir(beta, { mode: 0o700 }) + await writeFile(join(notes, 'original.txt'), existingText, { mode: 0o600 }) + await writeFile(join(beta, 'outside.txt'), 'sibling project\n', { mode: 0o600 }) + await symlink(beta, join(mount, 'Alpha', 'outside')) + await initializeMasterKey(opts.keyFile) + + async function boot(businessOptions = {}, observe) { + await app?.close() + const opened=observe && (await import('../src/business/handlers.mjs')).openBusiness + app = await startWorkbench({ ...opts, businessOptions, ...(observe ? {businessFactory:async options=>{ + const business=await opened(options) + return {...business,handle(req,res,context){observe(req.method,req.url);return business.handle(req,res,context)}} + }} : {}) }) + } + async function request(path, { who, method = 'POST', body = {}, headers, raw } = {}) { + const r = await fetch(`${app.origin}/api/v1/${path}`, { + method, redirect: 'error', signal: AbortSignal.timeout(8_000), + headers: { ...(who ? { cookie: who.cookie, 'x-deva-csrf': who.csrf } : {}), + ...(method === 'GET' ? {} : { origin: app.origin, 'content-type': 'application/json' }), ...headers }, + body: method === 'GET' ? undefined : raw ?? JSON.stringify(body), + }) + assert.match(r.headers.get('content-type') ?? '', /^application\/json\b/u) + return { status: r.status, body: await r.json(), cookie: r.headers.get('set-cookie')?.split(';', 1)[0] } + } + async function signedIn(claim = false) { + const body = claim ? { password, credential: (await requestControl({ runDir: opts.runDir, op: 'claim' })).credential } : { password } + const reply = await request(claim ? 'auth/claim' : 'auth/login', { body }) + assert.equal(reply.status, 200) + assert.match(reply.cookie, /^deva-workbench-local=[A-Za-z0-9_-]{43}$/u) + assert.equal(typeof reply.body.csrf, 'string') + return { cookie: reply.cookie, csrf: reply.body.csrf } + } + async function get(path, who) { + return want(request(path, { who, method: 'GET' }), 200) + } + return { opts, mount, notes, beta, boot, request, signedIn, get, get origin(){return app.origin} } +} + +async function want(pending, status, exact) { + const r = await pending + assert.equal(r.status, status, r.body?.error ?? 'unexpected HTTP status') + if (exact !== undefined) assert.deepEqual(r.body, exact) + return r.body +} + +async function ids(f, login) { + const { workspaces } = await f.get('workspaces', login) + assert.deepEqual(workspaces.map(row => row.name), ['Alpha', 'Beta']) + return workspaces.map(row => row.id) +} + +function documents(f, who, wid) { + const post = (path, body = {}, extra) => f.request(path, { who, body, ...extra }) + return { + post, + async prepare(name, dir = directory) { + const receipt = await want(post(route(wid), { directory: dir, name }), 201) + assert.deepEqual(Object.keys(receipt).sort(), ['id', 'path', 'ttlMs']) + assert.match(receipt.id, intentId) + assert.equal(receipt.path, dir ? `${dir}/${name}` : name) + assert.ok(Number.isSafeInteger(receipt.ttlMs) && receipt.ttlMs > 0) + return receipt + }, + invoke: (intent, verb, body, extra) => post(action(wid, intent, verb), body, extra), + status: (intent, state, rev = null) => want(post(action(wid, intent, 'status')), 200, { state, path: intent.path, revision: rev }), + read: path => post(`workspaces/${wid}/read`, { path }), + } +} + +async function created(doc, intent, content) { + const value = await want(doc.invoke(intent, 'create', { content }), 201) + assert.match(value.revision, revision) + assert.deepEqual(value, { created: true, path: intent.path, revision: value.revision, replayed: false }) + return value +} + +async function assertSafeFile(path, text) { + const metadata = await lstat(path) + assert.equal(metadata.isFile(), true) + assert.equal(metadata.nlink, 1) + assert.equal(metadata.mode & 0o7111, 0) + assert.deepEqual(await readFile(path), Buffer.from(text)) +} + +const readOnly = { error: 'document_read_only' } +const notFound = { error: 'document_intent_missing' } +const authError = { error: 'auth' } + +test('HTTP creation has a separate, default-off grant from registered browse and edit', native, async t => { + const f = await fixture(t) + await f.boot() + let who = await f.signedIn(true) + assert.deepEqual(await f.get('workspaces', who), { workspaces: [] }) + let boot = await f.get('bootstrap', who) + assert.equal(boot.capabilities.workspaceFiles, false) + assert.equal(boot.capabilities.workspaceDocumentCreate, false) + const prepare = wid => f.request(route(wid), { who, body: { directory, name: 'denied.md' } }) + await want(prepare(missingWorkspace), 403, readOnly) + for (const writable of [false, true]) { + await f.boot({ workspaceRoot: f.mount, workspaceWritable: writable }) + who = await f.signedIn() + const [alpha] = await ids(f, who) + boot = await f.get('bootstrap', who) + assert.equal(boot.capabilities.workspaceFiles, true) + assert.equal(boot.capabilities.workspaceDocumentCreate, false) + const doc = documents(f, who, alpha) + const current = await want(doc.read('Notes/original.txt'), 200) + assert.equal(current.writable, writable) + const content = 'edit-only fixture\n' + const saved = await doc.post(`workspaces/${alpha}/file`, { path: 'Notes/original.txt', content, revision: current.revision }, { method: 'PUT' }) + assert.equal(saved.status, writable ? 200 : 403) + await assertSafeFile(join(f.notes, 'original.txt'), writable ? content : existingText) + await want(prepare(alpha), 403, readOnly) + for (const verb of ['status', 'create', 'cancel']) { + await want(doc.invoke({ id: `di_${'0'.repeat(32)}` }, verb, verb === 'create' ? { content } : {}), 403, readOnly) + } + assert.deepEqual(await readdir(f.notes), ['original.txt']) + } + const untouched = { ...f.opts, dataDir: join(dirname(f.opts.dataDir), 'unopened-data'), runDir: join(dirname(f.opts.runDir), 'unopened-run') } + for (const businessOptions of [{ workspaceCreate: true, workspaceWritable: true }, { workspaceCreate: true, workspaceRoot: f.mount }]) { + await assert.rejects(async () => { + const unexpected = await startWorkbench({ ...untouched, businessOptions }) + await unexpected.close() + }, /Document creation requires an explicit writable workspace root/u) + await assert.rejects(lstat(untouched.dataDir), { code: 'ENOENT' }) + await assert.rejects(lstat(untouched.runDir), { code: 'ENOENT' }) + } +}) + +test('native create intents bind login, workspace, request shape and verified filesystem revision', native, async t => { + const f = await fixture(t) + await f.boot({ workspaceRoot: f.mount, workspaceWritable: true, workspaceCreate: true }) + const a = await f.signedIn(true), b = await f.signedIn() + assert.notEqual(a.cookie, b.cookie) + assert.notEqual(a.csrf, b.csrf) + const [alpha, beta] = await ids(f, a) + assert.equal((await f.get('bootstrap', a)).capabilities.workspaceDocumentCreate, true) + const doc = documents(f, a, alpha), other = documents(f, b, alpha) + const prep = { directory, name: '项目笔记.md' } + const start = extra => doc.post(route(alpha), prep, extra) + await want(start({ who: undefined }), 401, authError) + await want(start({ headers: { 'x-deva-csrf': b.csrf } }), 401, authError) + await want(start({ headers: { origin: 'https://other.invalid' } }), 403, { error: 'origin' }) + await want(start({ headers: { origin: '' } }), 403, { error: 'origin' }) + await want(doc.post(route(missingWorkspace), prep), 404, { error: 'workspace_unavailable' }) + await want(doc.post(`${route(alpha)}?version=1`, prep), 400) + await want(start({ method: 'GET' }), 405) + await want(start({ raw: '{broken' }), 400) + for (const raw of [ + '{"directory":"Notes","name":"unused.md","na\\u006de":"different.md"}', + '{"directory":{"other":"private"},"directory":"Notes","name":"unwanted.md"}', + ]) await want(start({raw}),400,{error:'invalid_json'}) + for (const extra of [{ root: f.mount }, { path: 'Notes/original.txt' }, { revision: `r_${'1'.repeat(64)}` }, { version: 1 }, { grant: beta }]) { + await want(doc.post(route(alpha), { ...prep, ...extra }), 400) + } + for (const name of ['../n.md', '/n.md', 'a/b.md', 'a\\b.md', '.concealed.md', 'script.sh', 'setup.exe', 'n.md\u0000']) { + await want(other.post(route(alpha), { directory, name }), 400, { error: 'document_invalid' }) + } + for (const dir of ['../Beta', f.notes, 'Notes/../Notes']) { + await want(other.post(route(alpha), { directory: dir, name: 'denied.md' }), 400, { error: 'document_invalid' }) + } + await want(doc.post(route(alpha), { directory: 'Missing/Child', name: 'denied.md' }), 404, { error: 'workspace_unavailable' }) + await want(doc.post(route(alpha), { directory: 'outside', name: 'denied.md' }), 403, { error: 'document_unsafe' }) + await want(doc.post(route(alpha), { directory, name: 'original.txt' }), 409, { error: 'document_exists' }) + await symlink(join(f.beta, 'outside.txt'), join(f.notes, 'symlink.md')) + await want(doc.post(route(alpha), { directory, name: 'symlink.md' }), 403, { error: 'document_unsafe' }) + await chmod(join(f.notes, 'original.txt'), 0o700) + await want(doc.post(route(alpha), { directory, name: 'original.txt' }), 409, { error: 'document_exists' }) + await chmod(join(f.notes, 'original.txt'), 0o600) + + const { session } = await want(doc.post('chats'), 200) + const scope = `chats/${session.id}/workspace`, prefs = `chats/${session.id}/preferences` + const baseline = await Promise.all([f.get(scope, a), f.get(prefs, a), f.get('settings', a)]) + assert.equal(baseline[0].workspace, null) + const intent = await doc.prepare(prep.name) + await doc.status(intent, 'prepared') + await assert.rejects(lstat(join(f.notes, prep.name)), { code: 'ENOENT' }) + for (const verb of ['status', 'cancel', 'create']) { + const body = verb === 'create' ? { content: 'other login' } : {} + await want(doc.invoke(intent, verb, body, { who: undefined }), 401, authError) + await want(doc.invoke(intent, verb, body, { who: b }), 404, notFound) + await want(doc.invoke(intent, verb, body, { headers: { 'x-deva-csrf': b.csrf } }), 401, authError) + await want(doc.invoke(intent, verb, body, { headers: { origin: 'https://other.invalid' } }), 403, { error: 'origin' }) + await want(doc.post(action(beta, intent, verb), body), 404, notFound) + await want(doc.invoke(intent, verb, { ...body, revision: 'caller-controlled' }), 400) + } + await want(doc.invoke(intent,'create',{}, {raw:'{"content":"not approved","con\\u0074ent":"replacement"}'}),400,{error:'invalid_json'}) + await want(doc.invoke(intent, 'create', { content: null }), 400) + await want(doc.invoke(intent, 'create', { content: fullText, path: 'Notes/original.txt' }), 400, { error: 'document_invalid' }) + await want(doc.invoke(intent, 'create', { content: 'binary\u0000' }), 400) + await want(doc.invoke(intent, 'create', { content: '字'.repeat(700_000) }), 413, { error: 'document_limit' }) + await want(doc.post(action(alpha, intent, 'create'), { content: fullText }, { method: 'DELETE' }), 405) + await doc.status(intent, 'prepared') + const receipt = await created(doc, intent, fullText) + const disk = join(f.notes, prep.name) + await assertSafeFile(disk, fullText) + const read = await want(doc.read(intent.path), 200) + assert.equal(read.content, fullText) + assert.equal(read.revision, receipt.revision) + await doc.status(intent, 'created', receipt.revision) + await want(doc.invoke(intent, 'create', { content: fullText }), 200, { ...receipt, replayed: true }) + await want(doc.invoke(intent, 'create', { content: 'attempted overwrite' }), 409) + await assertSafeFile(disk, fullText) + await want(doc.post(`workspaces/${alpha}/file`, { path: intent.path }, { method: 'DELETE' }), 405) + await want(doc.post(`workspaces/${alpha}/mkdir`, { path: 'new-directory' }), 404) + await want(doc.post(`workspaces/${alpha}/file`, { path: 'Notes/no-intent.txt', content: 'not created', revision: receipt.revision }, { method: 'PUT' }), 409, { error: 'conflict' }) + + // Replacing a receipt's native entry with *identical bytes* still invalidates the original receipt. + await rename(disk, join(f.notes, 'retired.md')) + await writeFile(disk, fullText, { flag: 'wx', mode: 0o600 }) + await want(doc.invoke(intent, 'status'), 409, { error: 'document_changed' }) + await want(doc.invoke(intent, 'create', { content: fullText }), 409, { error: 'document_changed' }) + assert.notEqual((await want(doc.read(intent.path), 200)).revision, receipt.revision) + await assertSafeFile(disk, fullText) + + const empty = await doc.prepare('empty.txt', '') + const emptyReceipt = await created(doc, empty, '') + await assertSafeFile(join(f.mount, 'Alpha', 'empty.txt'), '') + assert.equal((await want(doc.read(empty.path), 200)).revision, emptyReceipt.revision) + await want(doc.invoke(empty, 'cancel'), 200, { closed: true }) + await assertSafeFile(join(f.mount, 'Alpha', 'empty.txt'), '') + const canceled = await doc.prepare('abandoned.md') + await want(doc.invoke(canceled, 'cancel'), 200, { closed: true }) + await want(doc.invoke(canceled, 'status'), 404, notFound) + await want(doc.invoke(canceled, 'create', { content: 'canceled' }), 404, notFound) + await assert.rejects(lstat(join(f.notes, 'abandoned.md')), { code: 'ENOENT' }) + + // Document operations did not grant model/tool or workspace-binding authority to the conversation. + await want(doc.post(`chats/${session.id}/turns`, { clientRequestId: randomUUID(), text: 'Create a file.', model: null, + tools: [{ name: 'workspaceDocumentCreate', intent: intent.id }] }), 400, { error: 'invalid_send' }) + assert.deepEqual(await Promise.all([f.get(scope, a), f.get(prefs, a), f.get('settings', a)]), baseline) + assert.deepEqual((await f.get(`chats/${session.id}`, a)).state.messages, []) + assert.deepEqual(await readdir(f.beta), ['outside.txt']) + assert.deepEqual(await readFile(join(f.beta, 'outside.txt')), Buffer.from('sibling project\n')) + assert.deepEqual((await readdir(f.notes)).sort(), ['original.txt', 'retired.md', 'symlink.md', prep.name].sort()) + + // Restoring the original project inode after a binding change does not revive a stale receipt. + const lost = await doc.prepare('moved-project.txt') + await created(doc, lost, 'durable data') + const project = join(f.mount, 'Alpha'), moved = join(f.mount, 'Alpha-moved') + await rename(project, moved) + try { + await want(doc.invoke(lost, 'status'), 409, { error: 'document_changed' }) + } finally { await rename(moved, project) } + await want(doc.invoke(lost, 'create', { content: 'durable data' }), 409, { error: 'document_changed' }) + await assertSafeFile(join(f.notes, 'moved-project.txt'), 'durable data') + await want(doc.invoke(lost, 'cancel'), 200, { closed: true }) + + const revoked = await doc.prepare('logged-out.md') + await want(doc.post('auth/logout'), 200, { ok: true }) + await want(doc.invoke(revoked, 'create', { content: 'stale login' }), 401, authError) + await want(doc.invoke(revoked, 'status', {}, { who: b }), 404, notFound) + await want(doc.invoke(revoked, 'cancel', {}, { who: await f.signedIn() }), 404, notFound) + await assert.rejects(lstat(join(f.notes, 'logged-out.md')), { code: 'ENOENT' }) +}) + +test('revoking the original login while the create body is still arriving leaves the project untouched', native, async t => { + const f=await fixture(t), started=Promise.withResolvers();let watched + await f.boot({workspaceRoot:f.mount,workspaceWritable:true,workspaceCreate:true},(method,url)=>{ + if (method==='POST' && url===watched) started.resolve() + }) + const owner=await f.signedIn(true),peer=await f.signedIn(),[wid]=await ids(f,owner), doc=documents(f,owner,wid) + const intent=await doc.prepare('slow.txt');watched='/api/v1/'+action(wid,intent,'create') + const response=Promise.withResolvers() + const req=requestHttp(f.origin+watched,{method:'POST',agent:false,signal:AbortSignal.timeout(9000),headers:{ + cookie:owner.cookie,origin:f.origin,'content-type':'application/json','x-deva-csrf':owner.csrf, + }},res=>{ + const chunks=[];res.on('data',b=>chunks.push(b));res.once('error',response.reject) + res.once('end',()=>response.resolve({status:res.statusCode,body:JSON.parse(Buffer.concat(chunks))})) + });req.once('error',response.reject);t.after(()=>req.destroy());void response.promise.catch(()=>{}) + req.write('{"content":"first') + await Promise.race([started.promise,response.promise.then(()=>assert.fail('create answered before the body was complete'))]) + await want(doc.post('auth/logout'),200,{ok:true}) + req.end(' second"}') + assert.deepEqual(await response.promise,{status:401,body:{error:'auth'}}) + await want(doc.invoke(intent,'status',{}, {who:peer}),404,notFound) + assert.deepEqual(await readdir(f.notes),['original.txt']) +}) + +test('Linux native publication fences canonical collisions, directory replacement and lost permission', native, async t => { + const f = await fixture(t) + await f.boot({ workspaceRoot: f.mount, workspaceWritable: true, workspaceCreate: true }) + const a = await f.signedIn(true), b = await f.signedIn(), [alpha] = await ids(f, a) + const doc = documents(f, a, alpha), other = documents(f, b, alpha) + for (const [name, alternate] of [['same.md', 'same.md'], ['Case.txt', 'case.txt'], ['Café.md', 'Cafe\u0301.md']]) { + const first = await doc.prepare(name), second = await other.prepare(alternate) + assert.notEqual(first.id, second.id) + await Promise.all([doc.status(first, 'prepared'), other.status(second, 'prepared')]) + const submissions = [[doc, first, 'first\r\n'], [other, second, 'second\n']] + const results = await Promise.all(submissions.map(([owner, intent, content]) => owner.invoke(intent, 'create', { content }))) + assert.deepEqual(results.map(value => value.status).sort(), [201, 409]) + const winner = results.findIndex(value => value.status === 201) + const [owner, intent, text] = submissions[winner] + const committed = results[winner].body + assert.match(committed.revision, revision) + await owner.status(intent, 'created', committed.revision) + assert.deepEqual(results[1 - winner].body, { error: 'document_exists' }) + for (const [owner, prepared] of submissions) await want(owner.invoke(prepared, 'cancel'), 200, { closed: true }) + await assertSafeFile(join(f.notes, winner === 0 ? name : alternate), text) + if (name !== alternate) await assert.rejects(lstat(join(f.notes, winner === 0 ? alternate : name)), { code: 'ENOENT' }) + } + const occupied = await doc.prepare('late.md') + await writeFile(join(f.notes, 'late.md'), 'native publisher first\n', { flag: 'wx', mode: 0o600 }) + await want(doc.invoke(occupied, 'create', { content: 'never replace' }), 409, { error: 'document_exists' }) + await assertSafeFile(join(f.notes, 'late.md'), 'native publisher first\n') + await want(doc.invoke(occupied, 'cancel'), 200, { closed: true }) + + const oldNotes = join(f.mount, 'Alpha', 'Moved') + const originalEntries = (await readdir(f.notes)).sort() + const swapped = await doc.prepare('swapped.md') + const renamed = await doc.prepare('renamed.md') + await rename(f.notes, oldNotes) + await want(doc.invoke(renamed, 'create', { content: 'wrong directory' }), 409, { error: 'document_changed' }) + await mkdir(f.notes, { mode: 0o700 }) + await want(doc.invoke(swapped, 'create', { content: 'wrong inode' }), 409, { error: 'document_changed' }) + assert.deepEqual(await readdir(f.notes), []) + assert.deepEqual((await readdir(oldNotes)).sort(), originalEntries) + + const chmodded = await doc.prepare('private.txt') + await chmod(f.notes, 0o500) + try { + await want(doc.invoke(chmodded, 'create', { content: 'chmod in between' }), 403, readOnly) + await want(doc.post(route(alpha), { directory, name: 'blocked.txt' }), 403, readOnly) + assert.deepEqual(await readdir(f.notes), []) + } finally { await chmod(f.notes, 0o700) } +}) diff --git a/apps/headless/test/server-cli.test.mjs b/apps/headless/test/server-cli.test.mjs index bcec5822..080c6b99 100644 --- a/apps/headless/test/server-cli.test.mjs +++ b/apps/headless/test/server-cli.test.mjs @@ -82,6 +82,22 @@ test('init-key validates existing raw key permissions and preserves a populated } }) +test('new document grant needs explicit workspace writes and an absolute project root before startup', async t => { + const p=await fixture(t) + const args=['serve','--home',p.dataDir,'--master-key-file',p.keyFile] + for (const [flags, settings, expected] of [ + [[], { DEVA_WORKSPACE_CREATE:'yes' }, 'DEVA_WORKSPACE_CREATE must be 0 or 1'], + [['--workspace-root',p.root,'--workspace-create'], {}, 'Document creation requires an explicit writable workspace root'], + [['--workspace-create','--workspace-write'], {}, 'Document creation requires an explicit writable workspace root'], + [['--workspace-create','--workspace-write','--workspace-root','relative'], {}, 'Document creation requires an explicit writable workspace root'], + [[], { DEVA_WORKSPACE_CREATE:'1',DEVA_WORKSPACE_WRITE:'0',DEVA_WORKSPACE_ROOT:p.root }, 'Document creation requires an explicit writable workspace root'], + ]) { + await assert.rejects(exec(process.execPath,[cli,...args,...flags],{env:{...p.env,...settings},timeout:5000}),err=>err.code===1 && err.stderr.trim()===expected) + } + await assert.rejects(p.run('status','--workspace-create'),err=>err.code===1 && err.stderr.includes('Invalid status options')) + await assert.rejects(fs.lstat(p.dataDir),{code:'ENOENT'}) +}) + test('production serve accepts flag-over-env settings, claim is terminal-only, and SIGTERM releases socket and lock', { timeout: 25_000 }, async t => { const paths = await fixture(t) const ttyAvailable = await fs.access(script).then(() => true, () => false) diff --git a/apps/headless/test/server.test.mjs b/apps/headless/test/server.test.mjs index 045e8479..203bbecc 100644 --- a/apps/headless/test/server.test.mjs +++ b/apps/headless/test/server.test.mjs @@ -230,6 +230,15 @@ test('Unix claim, HTTP sessions, vault, and business API all use the same instan assert.equal((await http(svc, '/api/v1/bootstrap', { headers: { cookie } })).status, 401) }) +test('document creation rejects private or unconfigured project roots before touching the data volume', async t => { + const paths=await fixture(t) + for (const workspaceRoot of [undefined,'relative','/',paths.root,paths.dataDir,join(paths.dataDir,'projects'),paths.keyFile,paths.webDir,paths.runDir]) { + await assert.rejects(paths.start({businessOptions:{workspaceCreate:true,workspaceWritable:true,workspaceRoot}}),/explicit writable workspace root/) + } + await assert.rejects(paths.start({businessOptions:{workspaceCreate:'1',workspaceWritable:true,workspaceRoot:join(paths.root,'projects')}}),/explicit writable workspace root/) + await assert.rejects(fs.lstat(paths.dataDir),{code:'ENOENT'}) +}) + test('the optional terminal control mount is distinct from data, web, project and owner-control paths', async t => { const paths = await fixture(t) const workspaceRoot = join(paths.root, 'approved'), browserRunDir = join(paths.root, 'browser') diff --git a/compose.workspace-create.yaml b/compose.workspace-create.yaml new file mode 100644 index 00000000..347badef --- /dev/null +++ b/compose.workspace-create.yaml @@ -0,0 +1,6 @@ +# Optional third file, after compose.yaml and compose.workspace-edit.yaml. +# This grant is separate from updating existing text; by itself it provides no project mount. +services: + workbench: + environment: + DEVA_WORKSPACE_CREATE: "1" From f89859378ce8b987cf8967a94089293707ad5c8f Mon Sep 17 00:00:00 2001 From: Facetomyself <[GIT_EMAIL]> Date: Fri, 27 Nov 2026 09:16:23 +0800 Subject: [PATCH 4/7] =?UTF-8?q?feat(workbench):=20=E5=9C=A8=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE=E6=96=87=E4=BB=B6=E9=A1=B5=E5=AE=9A=E4=BD=8D=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E5=92=8C=E6=A0=B8=E5=AF=B9=E6=96=B0=E5=BB=BA=E8=8D=89?= =?UTF-8?q?=E7=A8=BF=20/=20reveal=20folders=20and=20review=20new=20documen?= =?UTF-8?q?t=20drafts=20in=20the=20workspace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workbench/project-document-controller.ts | 289 +++++++++++ .../workbench/project-document-transport.ts | 114 ++++ .../src/workbench/project-document-ui.tsx | 95 ++++ .../src/workbench/project-document.css | 32 ++ apps/desktop/src/workbench/text-workbench.tsx | 7 +- apps/desktop/src/workbench/transport.ts | 15 +- .../src/workbench/workspace-dialog.tsx | 99 +++- apps/desktop/src/workbench/workspace-files.ts | 222 +++++++- .../workbench/project-document-ui.test.mjs | 490 ++++++++++++++++++ scripts/workbench/task-inspection-ui.test.mjs | 2 +- scripts/workbench/terminal-view-ui.test.mjs | 2 +- 11 files changed, 1319 insertions(+), 48 deletions(-) create mode 100644 apps/desktop/src/workbench/project-document-controller.ts create mode 100644 apps/desktop/src/workbench/project-document-transport.ts create mode 100644 apps/desktop/src/workbench/project-document-ui.tsx create mode 100644 apps/desktop/src/workbench/project-document.css create mode 100644 scripts/workbench/project-document-ui.test.mjs diff --git a/apps/desktop/src/workbench/project-document-controller.ts b/apps/desktop/src/workbench/project-document-controller.ts new file mode 100644 index 00000000..f8babf19 --- /dev/null +++ b/apps/desktop/src/workbench/project-document-controller.ts @@ -0,0 +1,289 @@ +import { HttpFailure } from './transport' +import { parentOf, writableDocumentFolders, type WorkspaceFiles } from './workspace-files' +import { documentDirectory, documentPath, documentValidation, InvalidDocumentReceipt, projectDocumentWorkspaceId, type DocumentIssue, + type PreparedDocument, type ProjectDocumentTransport } from './project-document-transport' + +type Issue = DocumentIssue | 'notCreated' +type Phase = 'draft' | 'preparing' | 'prepared' | 'creating' | 'verifying' | 'unconfirmed' | 'saved' +type Draft = Readonly<{ wid: string; directory: string; name: string; content: string; issue?: Issue; uncertainPath?: string }> +type Intent = PreparedDocument & { wid: string; expires: number } +type FocusTarget = 'name' | 'status' | 'return' +export type ProjectDocumentView = { + draft?: Draft; phase?: Phase; issue?: Issue; preview?: string; savedPath?: string; + folders: string[]; canNew: boolean; retained: boolean; canReview: boolean; canCreate: boolean; canVerify: boolean; editable: boolean; + focus?: { target: FocusTarget; serial: number } +} +const emptyView: ProjectDocumentView = { folders: [], canNew: false, retained: false, canReview: false, canCreate: false, canVerify: false, editable: false } + +function issueFor(error: unknown, writing = false): Issue { + if (!(error instanceof HttpFailure)) return writing ? 'unconfirmed' : 'unavailable' + if (error.status === 401 || error.code === 'csrf_failed') return 'expired' + switch (error.status) { + case 400: return 'invalid' + case 403: return error.code === 'document_unsafe' ? 'restricted' : 'readonly' + case 404: return 'missing' + case 409: return error.code === 'document_exists' ? 'exists' : error.code === 'document_changed' ? 'changed' : 'conflict' + case 413: return 'limit' + case 422: return 'restricted' + case 429: return 'busy' + case 503: return writing ? 'unconfirmed' : 'unavailable' + default: return writing ? 'unconfirmed' : 'unavailable' + } +} + +/** Page-memory draft per authorized project. An intent, by contrast, lives only within its current review. */ +export function createProjectDocuments(files: WorkspaceFiles, api: ProjectDocumentTransport, now = Date.now) { + const listeners = new Set<() => void>() + const kept = new Map() + let open = false + let unsubscribe: (() => void) | undefined + let phase: Phase | undefined + let draft: Draft | undefined + let intent: Intent | undefined + let saved: { wid: string; path: string } | undefined + let timer: ReturnType | undefined + let focus: ProjectDocumentView['focus'] + let folderCheck: AbortController | undefined + let serial = 0 + let view = emptyView + + function folders(): string[] { + const workspace = files.snapshot() + return projectDocumentWorkspaceId(workspace.projectId) ? writableDocumentFolders(workspace).filter(documentDirectory) : [] + } + function validTarget(value: Draft): boolean { + return files.snapshot().projectId === value.wid && folders().includes(value.directory) + } + function defaultFolder(): string { + const { file, folder } = files.snapshot() + return folder ?? (file ? parentOf(file.path) : '') + } + function emit(): void { + const workspace = files.snapshot() + const choices = folders() + const current = open && !!draft && workspace.projectId === draft.wid + const scoped = current && choices.includes(draft!.directory) + const path = current && documentDirectory(draft!.directory) && !documentValidation(draft!.name, '') ? + documentPath(draft!.directory, draft!.name) : undefined + const validation = current && draft!.name ? documentValidation(draft!.name, draft!.content) : undefined + const blocked = phase === 'draft' && !!path && workspace.blockedDocumentPaths.has(path) + const status = saved?.wid === workspace.projectId ? saved : undefined + view = { + draft: current ? draft : undefined, phase: current ? phase : status ? 'saved' : undefined, + issue: current ? workspace.issue === 'expired' ? 'expired' : draft!.issue ?? (!scoped ? 'directory' : blocked ? 'unconfirmed' : validation) : undefined, + preview: path || undefined, savedPath: status?.path, folders: choices, + canNew: open && !current && choices.includes(defaultFolder()), retained: kept.has(workspace.projectId), + editable: current && !workspace.issue && (phase === 'draft' || phase === 'preparing' || phase === 'prepared'), + canReview: scoped && phase === 'draft' && !!path && !blocked && draft!.uncertainPath !== path && !validation, + canCreate: scoped && phase === 'prepared' && !!intent && intent.path === path && intent.expires > now(), + canVerify: current && !workspace.issue && !!intent && phase === 'unconfirmed', focus + } + listeners.forEach((notify) => notify()) + } + function requestFocus(target: FocusTarget): void { focus = { target, serial: ++serial } } + function keep(next: Draft): void { kept.set(next.wid, next); draft = next } + function release(wid: string, id: string): void { void api.cancel(wid, id).catch(() => {}) } + function detachIntent(): Intent | undefined { + clearTimeout(timer) + timer = undefined + const previous = intent + intent = undefined + return previous + } + function backToDraft(issue?: Issue, unconfirmed = false): void { + const previous = detachIntent() + if (!draft) return + keep({ ...draft, issue, ...(unconfirmed && previous ? { uncertainPath: previous.path } : {}) }) + phase = unconfirmed ? 'unconfirmed' : 'draft' + if (previous) { + if (!unconfirmed) files.blockDocumentPath(previous.wid, previous.path, false) + release(previous.wid, previous.id) + } + emit() + } + function dismiss(returnFocus = false): void { + folderCheck?.abort() + folderCheck = undefined + if (!returnFocus) focus = undefined + const old = draft + const previous = detachIntent() + const uncertain = previous && (phase === 'creating' || phase === 'verifying' || phase === 'unconfirmed') ? previous.path : undefined + if (old) { + if (old.name || old.content || old.uncertainPath) kept.set(old.wid, { + ...old, issue: uncertain ? 'unconfirmed' : old.issue, uncertainPath: uncertain ?? old.uncertainPath + }) + else kept.delete(old.wid) + draft = undefined + phase = undefined + } + saved = undefined + if (returnFocus) { + requestFocus('return') + // An explicit Cancel leaves ordinary browsing available while the kept draft still fences that create target. + if (old?.uncertainPath) files.blockDocumentPath(old.wid, old.uncertainPath, false) + if (previous && uncertain) files.blockDocumentPath(previous.wid, uncertain, false) + } + if (previous) release(previous.wid, previous.id) + emit() + } + function workspaceChanged(): void { + const workspace = files.snapshot() + if (saved && (saved.wid !== workspace.projectId || saved.path !== workspace.file?.path || !workspace.file.saved)) saved = undefined + if (draft && draft.wid !== workspace.projectId) { dismiss(); return } + if (draft && workspace.issue && (intent || phase === 'preparing')) { + backToDraft(workspace.issue === 'expired' ? 'expired' : 'missing', + phase === 'creating' || phase === 'verifying' || phase === 'unconfirmed') + return + } + if (draft && (phase === 'preparing' || phase === 'prepared') && !validTarget(draft)) { + backToDraft('directory') + return + } + emit() + } + function setOpen(enabled: boolean): void { + if (open === enabled) return + open = enabled + if (enabled) { unsubscribe = files.subscribe(workspaceChanged); emit() } + else { unsubscribe?.(); unsubscribe = undefined; dismiss() } + } + function begin(): void { + if (!view.canNew) return + const wid = files.snapshot().projectId + draft = kept.get(wid) ?? { wid, directory: defaultFolder(), name: '', content: '' } + saved = undefined + phase = 'draft' + requestFocus('name') + emit() + } + function update(patch: Partial>): void { + if (!draft || !view.editable || (patch.directory !== undefined && !folders().includes(patch.directory))) return + const candidate = { ...draft, ...patch } + if (candidate.directory === draft.directory && candidate.name === draft.name && candidate.content === draft.content) return + const target = documentPath(candidate.directory, candidate.name) + const previous = detachIntent() + keep({ ...candidate, issue: target === candidate.uncertainPath ? 'unconfirmed' : undefined }) + phase = 'draft' + if (candidate.uncertainPath && target !== candidate.uncertainPath) + files.blockDocumentPath(candidate.wid, candidate.uncertainPath, false) + if (previous) release(previous.wid, previous.id) + emit() + } + function expire(review: Intent): void { + if (phase === 'prepared' && intent === review) backToDraft('missing') + } + async function prepare(): Promise { + if (!draft || !view.canReview || !validTarget(draft)) return + const original = draft + const started = now() + phase = 'preparing' + emit() + try { + const result = await api.prepare(original.wid, original.directory, original.name) + if (draft !== original || phase !== 'preparing' || !open || !validTarget(original)) { release(original.wid, result.id); return } + const next = { ...result, wid: original.wid, expires: started + result.ttlMs } + if (next.expires <= now()) { release(original.wid, next.id); backToDraft('missing'); return } + intent = next + phase = 'prepared' + keep({ ...original, issue: undefined }) + timer = setTimeout(() => expire(next), next.expires - now()) + requestFocus('status') + emit() + } catch (error) { + if (error instanceof InvalidDocumentReceipt && error.id) release(original.wid, error.id) + if (draft !== original || phase !== 'preparing') return + requestFocus('status') + backToDraft(issueFor(error)) + files.reportDocumentFailure(error, original.wid) + } + } + const same = (target: Intent): boolean => open && intent === target && draft?.wid === target.wid && + files.snapshot().projectId === target.wid && !files.snapshot().issue + + async function readback(target: Intent, content: string, revision: string): Promise { + phase = 'verifying' + emit() + const confirmed = await files.verifyCreatedDocument(target.wid, target.path, content, revision, () => same(target)) + if (!same(target)) return + if (!confirmed) { phase = 'unconfirmed'; keep({ ...draft!, issue: 'unconfirmed' }); emit(); return } + detachIntent() + release(target.wid, target.id) + kept.delete(target.wid) + saved = { wid: target.wid, path: target.path } + phase = 'saved' + draft = undefined + emit() + } + function uncertain(issue: Issue): void { + if (!draft) return + phase = 'unconfirmed' + keep({ ...draft, issue }) + requestFocus('status') + emit() + } + async function create(): Promise { + if (!intent || !draft || phase !== 'prepared') return + const target = intent + if (target.expires <= now()) { expire(target); return } + if (!view.canCreate || !validTarget(draft)) return + const { content } = draft + clearTimeout(timer) + phase = 'creating' + files.blockDocumentPath(target.wid, target.path, true) + emit() + let result: Awaited> + try { + result = await api.create(target.wid, target.id, target.path, content) + } catch (error) { + if (!same(target)) return + const issue = issueFor(error, true) + if (issue === 'unconfirmed') uncertain(issue) + else { + requestFocus('status') + // Authorization or the intent TTL can lapse after publication but before the receipt. + backToDraft(issue, issue === 'expired' || issue === 'missing') + } + files.reportDocumentFailure(error, target.wid) + return + } + if (same(target)) await verifyReadback(target, content, result.revision) + } + async function verifyReadback(target: Intent, content: string, revision: string): Promise { + try { await readback(target, content, revision) } + catch (error) { + if (!same(target)) return + uncertain(issueFor(error, true)) + files.reportDocumentFailure(error, target.wid) + } + } + async function verify(): Promise { + if (!view.canVerify || !intent || !draft) return + const target = intent + const { content } = draft + phase = 'verifying' + emit() + try { + const status = await api.status(target.wid, target.id, target.path) + if (!same(target)) return + if (status.state === 'created') await verifyReadback(target, content, status.revision) + else if (status.state === 'prepared') { backToDraft('notCreated'); requestFocus('status'); emit() } + else uncertain('unconfirmed') + } catch (error) { + if (!same(target)) return + const issue = issueFor(error, true) + if (['expired', 'missing', 'readonly', 'restricted', 'changed', 'exists', 'conflict'].includes(issue)) backToDraft(issue, true) + else uncertain(issue) + files.reportDocumentFailure(error, target.wid) + } + } + function checkFolder(): Promise | undefined { + if (!draft || !open || draft.wid !== files.snapshot().projectId) return undefined + folderCheck?.abort() + folderCheck = new AbortController() + return files.revealFolder(draft.wid, draft.directory, folderCheck.signal) + } + return { snapshot: () => view, subscribe: (report: () => void) => { listeners.add(report); return () => { listeners.delete(report) } }, + setOpen, begin, update, prepare, create, verify, checkFolder, dismiss, anyDirty: () => kept.size > 0 } +} + +export type ProjectDocuments = ReturnType diff --git a/apps/desktop/src/workbench/project-document-transport.ts b/apps/desktop/src/workbench/project-document-transport.ts new file mode 100644 index 00000000..b014b259 --- /dev/null +++ b/apps/desktop/src/workbench/project-document-transport.ts @@ -0,0 +1,114 @@ +import type { Transport } from './transport' + +export const DOCUMENT_NAME_BYTES = 200 +export const DOCUMENT_BODY_BYTES = 2 * 1024 * 1024 +export const DOCUMENT_TTL = 120_000 + +const bytes = new TextEncoder() +const invisible = /[\p{C}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u +const nonText = /[\u0000-\u0008\u000e-\u001f\u007f-\u0084\u0086-\u009f\p{Cs}]/u +const workspaceId = /^w_[a-f0-9]{32}$/u +const intentId = /^di_[a-f0-9]{32}$/u +const revision = /^r_[a-f0-9]{64}$/u +const matches = (pattern: RegExp, value: unknown): value is string => typeof value === 'string' && pattern.exec(value)?.[0] === value +export const projectDocumentWorkspaceId = (value: unknown): value is string => matches(workspaceId, value) + +export type DocumentIssue = 'directory' | 'name' | 'limit' | 'invalid' | 'readonly' | 'restricted' | 'expired' | 'missing' | + 'exists' | 'changed' | 'conflict' | 'busy' | 'unavailable' | 'unconfirmed' +export type PreparedDocument = { id: string; path: string; ttlMs: number } +export type DocumentStatus = { state: 'prepared' | 'unconfirmed'; path: string; revision: null } | + { state: 'created'; path: string; revision: string } + +export function documentDirectory(path: unknown): path is string { + if (typeof path !== 'string' || path.length > 4095 || bytes.encode(path).length > 4095) return false + if (path === '') return true + const segments = path.split('/') + return segments.length <= 16 && segments.every((segment) => !!segment && !segment.startsWith('.') && + !/\\|^[A-Za-z]:/u.test(segment) && !invisible.test(segment) && bytes.encode(segment).length <= 255) +} + +export function documentValidation(name: unknown, content: unknown): 'name' | 'limit' | 'invalid' | undefined { + if (typeof name !== 'string' || name.length > DOCUMENT_NAME_BYTES || !matches(/^.+\.(md|txt)$/iu, name) || + invisible.test(name) || bytes.encode(name).length > DOCUMENT_NAME_BYTES) return 'name' + const folded = name.normalize('NFKC') + const stem = folded.replace(/\.(md|txt)$/iu, '') + if (!stem || /^[.\s]|[.\s]$/u.test(stem) || /[/\\<>:"|?*]/u.test(folded)) return 'name' + if (typeof content !== 'string') return 'invalid' + if (content.length > DOCUMENT_BODY_BYTES || bytes.encode(content).length > DOCUMENT_BODY_BYTES) return 'limit' + return nonText.test(content) ? 'invalid' : undefined +} + +export const documentPath = (directory: string, name: string): string => directory === '' ? name : `${directory}/${name}` + +function object(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {} +} + +function exact(value: Record, ...keys: string[]): boolean { + return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key)) +} + +function validPath(path: string): boolean { + if (typeof path !== 'string') return false + const slash = path.lastIndexOf('/') + const directory = slash === -1 ? '' : path.slice(0, slash) + return slash !== 0 && documentDirectory(directory) && !documentValidation(path.slice(slash + 1), '') +} + +export class InvalidDocumentReceipt extends Error { + constructor(readonly id?: string) { super('Invalid document intent receipt') } +} + +/** Owner-session JSON only; the intent ID is never used as authority for a different workspace or target. */ +export function createProjectDocumentTransport(transport: Transport, csrf: string) { + const base = (wid: string): string => { + if (!csrf || !projectDocumentWorkspaceId(wid)) throw new Error('Invalid project document request') + return `/workspaces/${wid}/document-intents` + } + const resource = (wid: string, id: string, action: 'create' | 'status' | 'cancel'): string => { + if (!matches(intentId, id)) throw new Error('Invalid project document intent') + return `${base(wid)}/${id}/${action}` + } + const post = (path: string, body: object, expectedStatus: NonNullable[4]>['expectedStatus'], keepalive = false) => + transport.request(path, 'POST', body, csrf, { referrerPolicy: 'same-origin', expectedStatus, ...(keepalive ? { keepalive: true } : {}) }) + return { + async prepare(wid: string, directory: string, name: string): Promise { + if (!documentDirectory(directory) || documentValidation(name, '')) throw new Error('Invalid project document target') + const path = documentPath(directory, name) + const result = object(await post(base(wid), { directory, name }, (status, body) => { + const prepared = object(body) + const id = matches(intentId, prepared.id) ? prepared.id : undefined + // Preserve a well-formed ID from a rejected receipt solely to release its original pin. + if (status !== 201 || !id || !exact(prepared, 'id', 'path', 'ttlMs') || prepared.path !== path || prepared.ttlMs !== DOCUMENT_TTL) + throw new InvalidDocumentReceipt(id) + return true + })) + return { id: result.id as string, path, ttlMs: DOCUMENT_TTL } + }, + async create(wid: string, id: string, path: string, content: string): Promise<{ path: string; revision: string; replayed: boolean }> { + if (!validPath(path) || documentValidation(path.slice(path.lastIndexOf('/') + 1), content)) throw new Error('Invalid project document input') + const result = object(await post(resource(wid, id, 'create'), { content }, (status, value) => + (status === 201 && object(value).replayed === false) || (status === 200 && object(value).replayed === true))) + if (!exact(result, 'created', 'path', 'revision', 'replayed') || result.created !== true || result.path !== path || + !matches(revision, result.revision) || typeof result.replayed !== 'boolean') + throw new InvalidDocumentReceipt() + return { path, revision: result.revision, replayed: result.replayed } + }, + async status(wid: string, id: string, path: string): Promise { + if (!validPath(path)) throw new Error('Invalid project document target') + const result = object(await post(resource(wid, id, 'status'), {}, 200)) + if (exact(result, 'state', 'path', 'revision') && result.path === path) { + if (result.state === 'created' && matches(revision, result.revision)) return { state: 'created', path, revision: result.revision } + if ((result.state === 'prepared' || result.state === 'unconfirmed') && result.revision === null) + return { state: result.state, path, revision: null } + } + throw new InvalidDocumentReceipt() + }, + async cancel(wid: string, id: string): Promise { + const result = object(await post(resource(wid, id, 'cancel'), {}, 200, true)) + if (!exact(result, 'closed') || result.closed !== true) throw new InvalidDocumentReceipt() + } + } +} + +export type ProjectDocumentTransport = ReturnType diff --git a/apps/desktop/src/workbench/project-document-ui.tsx b/apps/desktop/src/workbench/project-document-ui.tsx new file mode 100644 index 00000000..e6abbf16 --- /dev/null +++ b/apps/desktop/src/workbench/project-document-ui.tsx @@ -0,0 +1,95 @@ +import type { ProjectDocuments, ProjectDocumentView } from './project-document-controller' +import './project-document.css' + +const copy = { + en: { + new: 'New document', resume: 'Resume document draft', draftTitle: 'New document draft', parent: 'Folder', root: 'Project root (/)', + name: 'File name (.md or .txt)', content: 'Document text', empty: 'An empty document is allowed.', target: 'Target path', + review: 'Review', create: 'Create document', cancel: 'Cancel', verify: 'Verify create result', checkFolder: 'Reveal target folder', + draft: 'Draft only. Review checks the path without creating a file.', preparing: 'Checking target…', + prepared: 'Target checked. The file has not been created.', creating: 'Creating file…', verifying: 'Checking file and contents…', + unconfirmed: 'Create result unconfirmed. The draft has been kept.', saved: 'Document saved', + directory: 'Select a confirmed writable folder from this project.', nameIssue: 'Use an ordinary .md or .txt name, up to 200 UTF-8 bytes.', + limit: 'The name, path, or document text exceeds its size limit (text: 2 MiB).', invalid: 'The document name or text is invalid.', readonly: 'This location is read-only.', + restricted: 'This location or file name is restricted.', expired: 'Your session expired. Copy the draft before signing in again.', + missing: 'The target or review is missing or expired. The draft has been kept.', exists: 'That file already exists. Enter a different name.', + changed: 'The target folder or file changed. Review the target again.', conflict: 'The target conflicts with the reviewed location. The draft has been kept.', + busy: 'The document service is busy. Your draft is still here.', unavailable: 'The document check is unavailable. Your draft is still here.', + notCreated: 'The review reports no creation. Review again before creating.', + }, + 'zh-CN': { + new: '新建文档', resume: '继续编辑文档草稿', draftTitle: '新建文档草稿', parent: '文件夹', root: '项目根目录 (/)', + name: '文件名(.md 或 .txt)', content: '文档正文', empty: '正文可为空。', target: '目标路径', + review: '核对目标', create: '创建文档', cancel: '取消', verify: '核实创建结果', checkFolder: '定位目标文件夹', + draft: '当前仅为草稿。核对目标时仅检查路径。', preparing: '正在检查目标…', + prepared: '目标已核对,文件尚未创建。', creating: '正在创建文件…', verifying: '正在核实文件与正文…', + unconfirmed: '创建结果尚未确认,草稿已保留。', saved: '文档已保存', + directory: '请选择本项目中已确认可写的文件夹。', nameIssue: '请输入普通的 .md 或 .txt 文件名,最多 200 个 UTF-8 字节。', + limit: '文件名、路径或正文超过大小上限(正文限 2 MiB)。', invalid: '文件名或正文无效。', readonly: '此位置为只读。', + restricted: '此位置或文件名受限。', expired: '会话已过期,请在重新登录前复制草稿。', + missing: '目标或核对记录已失效或不存在,草稿已保留。', exists: '同名文件已存在,请更换文件名。', + changed: '目标文件夹或文件已变更,请重新核对。', conflict: '目标与核对时的位置冲突,草稿已保留。', + busy: '文档服务正忙,草稿已保留。', unavailable: '文档核对服务暂不可用,草稿已保留。', + notCreated: '核实结果显示文件尚未创建。创建前请重新核对目标。', + } +} as const + +type Locale = keyof typeof copy +const pending = (phase: ProjectDocumentView['phase']): boolean => phase === 'preparing' || phase === 'creating' || phase === 'verifying' + +export function ProjectDocumentNew({ view, api, locale }: { view: ProjectDocumentView; api: ProjectDocuments; locale: Locale }): React.JSX.Element | null { + const labels = copy[locale] + return view.canNew ? : null +} + +export function ProjectDocumentStatus({ view, locale }: { view: ProjectDocumentView; locale: Locale }): React.JSX.Element | null { + if (!view.phase) return null + const labels = copy[locale] + const issue = view.issue === 'name' ? 'nameIssue' : view.issue + return

+ {pending(view.phase) &&

+} + +export function ProjectDocumentDraft({ view, api, locale }: { view: ProjectDocumentView; api: ProjectDocuments; locale: Locale }): React.JSX.Element | null { + const draft = view.draft + if (!draft) return null + const labels = copy[locale] + const prepared = view.phase === 'prepared' || view.phase === 'creating' + const uncertain = view.phase === 'unconfirmed' || view.issue === 'unconfirmed' || draft.uncertainPath === view.preview && !!draft.uncertainPath + return
+ {labels.draftTitle} + + + {view.preview &&

{labels.target}: /{view.preview}

} +