feat(v0.5.0): secure project previews and fix host UI compatibility

This commit is contained in:
Aisland
2026-10-27 23:09:34 +08:00
parent 6cb86b6c73
commit 56ffe0cd1c
30 changed files with 3202 additions and 1447 deletions
+36
View File
@@ -326,4 +326,40 @@ function fresh() {
ok('G. settling 过渡态保持等待')
}
// 来源:Aisland-SJL/dsh-worktable PR #16(xpeter80),head 0e35aa14636a4433c261bbac4fe818d8ab533ded。
// 模拟浏览器缩放下 CSSOM 对 px 的小数序列化,并通过真实 splitStore yield observer 验证边界。
for (const chatSide of ['left', 'right']) {
for (const externalMargin of ['marginLeft', 'marginRight', 'marginTop']) {
const { sandbox, splitStore, allEls, moInstances } = fresh()
const root = new FakeEl('DIV', 'wSkVaW_root', { phase: 'hero' }).setRect({ left: 0, top: 0, right: 969.0908203125, bottom: 800 })
const body = new FakeEl('DIV', 'wSkVaW_body')
body.style = new Proxy(new StyleProxy(), {
set(target, key, value) {
// Chromium serializes 649.0908203125px as 649.091px.
target[key] = typeof value === 'string' && /^-?[\d.]+px$/.test(value)
? Number(Number.parseFloat(value).toPrecision(6)) + 'px' : value
return true
},
})
root.appendChild(body)
allEls.push(root); sandbox.document.body.appendChild(root)
if (!splitStore.open({ ...makeSpec('zoom'), chatSide })) fail('zoom.open', 'open failed')
splitStore.setChatW(320)
const observer = moInstances.find((m) => m._target === body)
if (!observer) fail('zoom.observer', 'yield observer not installed')
const ownedMargin = chatSide === 'left' ? 'marginRight' : 'marginLeft'
if (body.style[ownedMargin] !== '649.091px') fail('zoom.fixture', body.style[ownedMargin])
observer.cb()
if (!splitStore.active) fail('zoom.self', 'own serialized write closed split')
splitStore.applyMargin()
observer.cb()
if (!splitStore.active) fail('zoom.refresh', 'repeated layout closed split')
body.style[externalMargin] = '17px'
observer.cb()
if (splitStore.active) fail('zoom.takeover', externalMargin + ' did not yield')
if (body.style.marginLeft !== '' || body.style.marginRight !== '' || body.style.marginTop !== '') fail('zoom.restore', 'original margins not restored')
ok('zoom ' + chatSide + ': self-write retained; external ' + externalMargin + ' yields')
}
}
console.log('all anchor-dom tests passed: ' + pass + '/' + pass)
+11 -1
View File
@@ -9,7 +9,17 @@ const { buildSync } = require('esbuild')
const source = buildSync({ entryPoints: [fileURLToPath(new URL('../01_content/src/client/hostTransport.ts', import.meta.url))], bundle: true, write: false, platform: 'node', format: 'cjs' }).outputFiles[0].text
const module = { exports: {} }
runInNewContext(source, { module, exports: module.exports, URL })
const { hostWebSocketUrl, worktableUpgrade } = module.exports
const { hostWebSocketUrl, hostPreviewUrl, worktableUpgrade } = module.exports
test('Desktop sandbox assets use the owned Host URL without a login token', () => {
assert.equal(hostPreviewUrl('/api/worktable/preview-static/cap/app.js', {protocol:'dsh-app:',streamBaseUrl:'http://127.0.0.1:19499'}), 'http://127.0.0.1:19499/api/worktable/preview-static/cap/app.js')
})
test('Web sandbox assets retain a relative URL; missing Desktop carrier fails closed', () => {
assert.equal(hostPreviewUrl('/api/worktable/preview-static/cap/index.html', {protocol:'https:'}), '/api/worktable/preview-static/cap/index.html')
assert.throws(() => hostPreviewUrl('/api/worktable/preview-static/cap/index.html',{protocol:'dsh-app:'}), /unavailable/)
assert.throws(() => hostPreviewUrl('/api/worktable/preview-static/cap/index.html',{protocol:'dsh-app:',streamBaseUrl:'file:///fixture'}), /Unsupported/)
assert.throws(() => hostPreviewUrl('//other.example/api',{protocol:'https:'}), /Invalid/)
})
test('Web HTTP uses its current authority and preserves encoded query', () => {
assert.equal(hostWebSocketUrl('/api/worktable/term?cwd=C%3A%2Ftest&cols=80', { href: 'http://127.0.0.1:3080/', protocol: 'http:' }), 'ws://127.0.0.1:3080/api/worktable/term?cwd=C%3A%2Ftest&cols=80')
+107
View File
@@ -0,0 +1,107 @@
import assert from 'node:assert/strict'
import { test, after, afterEach } from 'node:test'
import { createRequire } from 'node:module'
import { mkdtempSync, writeFileSync, mkdirSync, rmSync, symlinkSync, renameSync, truncateSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { pathToFileURL, fileURLToPath } from 'node:url'
const require=createRequire(new URL('../01_content/package.json',import.meta.url))
const {build}=require('esbuild')
const temp=mkdtempSync(join(tmpdir(),'wt-preview-test-'))
after(()=>rmSync(temp,{recursive:true,force:true}))
// Instrument filesystem scheduling only in the test bundle; production has no hooks.
afterEach(()=>{ delete globalThis.__wtPreviewHooks })
await build({
entryPoints:[fileURLToPath(new URL('../01_content/src/previewFiles.ts',import.meta.url))],
bundle:true,platform:'node',format:'esm',outfile:join(temp,'preview.mjs'),
plugins:[{name:'filesystem-race-fixture',setup(build){
build.onResolve({filter:/^node:fs\/promises$/},args=>args.namespace==='race-fixture'?undefined:{path:args.path,namespace:'race-fixture'})
build.onLoad({filter:/.*/,namespace:'race-fixture'},()=>({loader:'js',contents:`
import * as fs from 'node:fs/promises';
export const realpath=fs.realpath, stat=fs.stat;
export async function open(...args) {
await globalThis.__wtPreviewHooks?.beforeOpen?.();
const h=await fs.open(...args);
await globalThis.__wtPreviewHooks?.afterOpen?.();
const read=h.read.bind(h);
h.read=async(...args)=>{await globalThis.__wtPreviewHooks?.beforeRead?.();return read(...args)};
return h;
}`}))
}}],
})
const {createPreviewFiles,PREVIEW_MAX_BYTES}=await import(pathToFileURL(join(temp,'preview.mjs')).href)
const root=join(temp,'root'),outside=join(temp,'outside');mkdirSync(root);mkdirSync(outside)
writeFileSync(join(root,'index.html'),'fixture');writeFileSync(join(outside,'outside.txt'),'outside')
test('Preview reads only its canonical root, including directory indexes',async()=>{
const store=createPreviewFiles(),token=await store.mount(root)
assert.equal((await store.file(token,[])).path,join(root,'index.html'))
assert.equal(await store.file('invented-token',['index.html']),null)
for(const parts of [['..','outside','outside.txt'],['..\\outside\\outside.txt'],['/outside'],['bad\0']]) assert.equal(await store.file(token,parts),null)
symlinkSync(outside,join(root,'escape'),process.platform==='win32'?'junction':'dir')
assert.equal(await store.file(token,['escape','outside.txt']),null)
rmSync(join(root,'escape'))
})
test('Capabilities expire after idle time; revocation and disposal remove them',async()=>{
let now=0;const store=createPreviewFiles(()=>now),a=await store.mount(root)
now=29*60*1000;assert.ok(await store.file(a,['index.html']))
now+=30*60*1000;assert.equal(await store.file(a,['index.html']),null)
const b=await store.mount(root);store.revoke(b);assert.equal(await store.file(b,[]),null)
const c=await store.mount(root);store.clear();assert.equal(await store.file(c,[]),null)
})
test('Reject relative roots and bound the live capability table',async()=>{
const store=createPreviewFiles();await assert.rejects(store.mount('.'),/absolute/)
for(let i=0;i<128;i++)await store.mount(root)
await assert.rejects(store.mount(root),/Too many/)
})
test('Read content through the checked handle; HEAD omits the body and enforces the limit',async()=>{
const store=createPreviewFiles(),token=await store.mount(root)
assert.equal((await store.file(token,['index.html'])).data.toString(),'fixture')
const head=await store.file(token,['index.html'],true)
assert.equal(head.size,7);assert.equal(head.data,undefined)
const large=join(root,'large.bin');writeFileSync(large,'x');truncateSync(large,PREVIEW_MAX_BYTES+1)
await assert.rejects(store.file(token,['large.bin'],true),e=>e.status===413)
})
test('A directory replaced by a junction after path checking cannot return outside content',async()=>{
const slot=join(root,'slot'),moved=join(root,'slot-original')
mkdirSync(slot);writeFileSync(join(slot,'outside.txt'),'inside')
const store=createPreviewFiles(),token=await store.mount(root)
globalThis.__wtPreviewHooks={beforeOpen(){
delete globalThis.__wtPreviewHooks
renameSync(slot,moved);symlinkSync(outside,slot,process.platform==='win32'?'junction':'dir')
}}
try {assert.equal(await store.file(token,['slot','outside.txt']),null)}
finally {unlinkSync(slot);renameSync(moved,slot)}
})
test('Replacing the named file after open rejects the response, even with an open old handle',async()=>{
const name=join(root,'replace.txt'),old=join(root,'replace-original.txt')
writeFileSync(name,'original')
const store=createPreviewFiles(),token=await store.mount(root)
globalThis.__wtPreviewHooks={afterOpen(){
delete globalThis.__wtPreviewHooks
renameSync(name,old);writeFileSync(name,'replacement')
}}
assert.equal(await store.file(token,['replace.txt']),null)
})
test('Growth after stat cannot produce a response over 40 MiB',async()=>{
const name=join(root,'growing.bin');writeFileSync(name,'small')
const store=createPreviewFiles(),token=await store.mount(root)
globalThis.__wtPreviewHooks={beforeRead(){
delete globalThis.__wtPreviewHooks
truncateSync(name,PREVIEW_MAX_BYTES+1)
}}
await assert.rejects(store.file(token,['growing.bin']),e=>e.status===413)
})
test('Revocation during a pending read prevents the response',async()=>{
const store=createPreviewFiles(),token=await store.mount(root)
globalThis.__wtPreviewHooks={beforeRead(){
delete globalThis.__wtPreviewHooks
store.revoke(token)
}}
assert.equal(await store.file(token,['index.html']),null)
})
+132
View File
@@ -0,0 +1,132 @@
import assert from 'node:assert/strict'
import { test, after } from 'node:test'
import { createRequire } from 'node:module'
import { mkdtempSync, writeFileSync, readFileSync, mkdirSync, rmSync, existsSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { pathToFileURL, fileURLToPath } from 'node:url'
const require = createRequire(new URL('../01_content/package.json', import.meta.url))
const { buildSync } = require('esbuild')
const temp = mkdtempSync(join(tmpdir(), 'wt-auth-test-'))
after(() => rmSync(temp, { recursive: true, force: true }))
for (const [pkg, source] of Object.entries({
ws: `const {EventEmitter}=require('node:events'); exports.WebSocketServer = class {
clients=new Set();
handleUpgrade(req,socket,head,callback){
globalThis.__wtTestUpgrade=true;
if(!globalThis.__wtAllowFakeShell) throw Error('TEST: unexpected authorized upgrade');
const ws=new EventEmitter(); ws.send=()=>{}; ws.close=()=>{this.clients.delete(ws);ws.emit('close')};
ws.terminate=()=>{globalThis.__wtSocketTerminated=true;ws.close()};this.clients.add(ws);callback(ws);
}
close(){}
}`,
'node-pty': `exports.spawn = () => {
if(!globalThis.__wtAllowFakeShell)throw Error('TEST: unexpected shell');
return {onData(){},onExit(){},write(){},resize(){},kill(){globalThis.__wtShellKilled=true}};
}`,
})) {
mkdirSync(join(temp, 'node_modules', pkg), { recursive: true })
writeFileSync(join(temp, 'node_modules', pkg, 'index.js'), source)
}
const entry = fileURLToPath(new URL('../01_content/src/index.ts', import.meta.url))
buildSync({ entryPoints: [entry], bundle: true, outfile: join(temp, 'server.mjs'), platform: 'node', format: 'esm', external: ['@deepseek-ai/*', 'ws', 'node-pty'], loader: { '.css': 'text', '.html': 'text' } })
const server = await import(pathToFileURL(join(temp, 'server.mjs')).href)
const owner = { principal: { kind: 'owner' } }
function harness(connection) {
const routes = new Map(), upgrades = new Map(), disposers = []
const ctx = { get: () => connection.current, sessions: {}, logger: { info(){},warn(){} },
webServer: { register(r){ routes.set(r.path,r); return () => routes.delete(r.path) }, registerUpgrade(r){upgrades.set(r.path,r); return () => upgrades.delete(r.path)} },
effect(fn) { const d = fn(); if (typeof d === 'function') disposers.push(d) },
}
server.apply(ctx)
return { routes, upgrades, close(){for (const d of disposers.reverse()) d()} }
}
async function invoke(route, body, method = 'POST', url = route.path) {
let consumed = false
const req = { method, url, headers: {}, async *[Symbol.asyncIterator](){consumed=true;yield Buffer.from(JSON.stringify(body ?? {}))} }
const result = { status: 0, headers: {}, body: '' }
await route.handler(req, { writeHead(s,h){result.status=s;result.headers=h??{}},end(b){result.body=b?.toString()??''} })
return { ...result, consumed }
}
test('Every private HTTP route rejects unauthenticated requests before reading a body or file', async () => {
const h = harness({ current: { admit: () => ({ rejection: 401 }) } })
try {
for (const [path, route] of h.routes) {
if (path === server.HEALTH_PATH || path.endsWith('/preview-static')) continue
const r = await invoke(route, {path: join(temp,'not-created'),content:'no'})
assert.equal(r.status,401,path);assert.equal(r.consumed,false,path)
}
assert.equal(existsSync(join(temp,'not-created')),false)
} finally { h.close() }
})
test('Missing auth, exceptions, malformed admissions and non-owner API peers fail closed', async () => {
for (const [connection,status] of [[undefined,503],[{requestRejection:()=>undefined},503],[{admit(){throw Error('unavailable')}},503],[{admit:()=>null},503],[{admit:()=>({})},403],[{admit:()=>({peer:{principal:{kind:'agent'}}})},403]]) {
const h=harness({current:connection})
try { assert.equal((await invoke(h.routes.get('/api/worktable/write'),{})).status,status) } finally { h.close() }
}
})
test('An admitted owner writes normally; revocation is checked on the next request', async () => {
const connection={current:{admit:()=>({peer:owner})}}
const h=harness(connection), path=join(temp,'authorized.txt')
try {
assert.equal((await invoke(h.routes.get('/api/worktable/write'),{path,content:'authorized'})).status,200)
connection.current={admit:()=>({rejection:403})}
assert.equal((await invoke(h.routes.get('/api/worktable/write'),{path,content:'blocked'})).status,403)
assert.equal(readFileSync(path,'utf8'),'authorized')
} finally {h.close()}
})
test('0.2.0 single operator identity remains supported', async () => {
const operator={id:'isolated-operator'}
for(const connection of [{operator,admit:()=>({peer:operator})}]) {
const h=harness({current:connection})
try { assert.equal((await invoke(h.routes.get('/api/worktable/mkdir'),{})).status,400) } finally {h.close()}
}
})
test('Terminal denies before upgrading or starting a shell; no auth service also denies', async () => {
for (const [connection,status] of [[{admit:()=>({rejection:401})},401],[undefined,503]]) {
const h=harness({current:connection});let response='';globalThis.__wtTestUpgrade=false
try {
const route=h.upgrades.get('/api/worktable/term');assert.ok(route)
await route.handler({headers:{},url:route.path},{end(s){response=s}},Buffer.alloc(0))
assert.match(response,new RegExp('HTTP/1.1 '+status));assert.equal(globalThis.__wtTestUpgrade,false)
} finally {h.close()}
}
})
test('Health discloses only status; route effects and preview grants are disposed', async () => {
const h=harness({current:undefined})
assert.equal((await invoke(h.routes.get(server.HEALTH_PATH),undefined,'GET')).status,200)
h.close();assert.equal(h.routes.size,0);assert.equal(h.upgrades.size,0)
})
test('Plugin disposal terminates its shell/socket and refuses a pending upgrade', async () => {
globalThis.__wtAllowFakeShell=true;globalThis.__wtShellKilled=false;globalThis.__wtSocketTerminated=false
const h=harness({current:{admit:()=>({peer:owner})}})
try {
await h.upgrades.get('/api/worktable/term').handler({url:'/api/worktable/term?cwd='+encodeURIComponent(temp)}, {}, Buffer.alloc(0))
h.close();assert.equal(globalThis.__wtShellKilled,true);assert.equal(globalThis.__wtSocketTerminated,true)
} finally {globalThis.__wtAllowFakeShell=false}
let finish, response='';globalThis.__wtTestUpgrade=false
const pending=harness({current:{admit:()=>new Promise(resolve=>{finish=resolve})}})
const call=pending.upgrades.get('/api/worktable/term').handler({}, {end(s){response=s}}, Buffer.alloc(0))
pending.close();finish({peer:owner});await call
assert.match(response,/HTTP\/1.1 503/);assert.equal(globalThis.__wtTestUpgrade,false)
})
test('Only an authenticated owner can mint a preview; a capability is read-only and revocable', async () => {
const h=harness({current:{admit:()=>({peer:owner})}})
try {
writeFileSync(join(temp,'page.html'),'<h1>fixture</h1>')
const grant=JSON.parse((await invoke(h.routes.get('/api/worktable/preview'),{root:temp})).body)
assert.match(grant.token,/^[\w-]{32}$/)
const route=h.routes.get('/api/worktable/preview-static'), url=grant.base+'page.html'
const r=await invoke(route,undefined,'GET',url)
assert.equal(r.status,200);assert.equal(r.body,'<h1>fixture</h1>');
assert.equal((await invoke(route,undefined,'HEAD',url)).status,200);
assert.match(r.headers['content-security-policy'],/sandbox allow-scripts/)
assert.doesNotMatch(r.headers['content-security-policy'],/allow-same-origin/)
assert.equal(r.headers['referrer-policy'],'no-referrer');assert.equal(r.headers['access-control-allow-origin'],'*')
assert.equal((await invoke(route,{},'POST',url)).status,405)
await invoke(h.routes.get('/api/worktable/preview'),{revoke:grant.token})
assert.equal((await invoke(route,undefined,'GET',url)).status,404)
} finally {h.close()}
})
+226
View File
@@ -0,0 +1,226 @@
/**
* SandboxedFrame lifecycle tests.
* Transpiles the real component with esbuild and runs it with a minimal React
* hooks fixture. Network and JSX are stubbed; this is not React DOM / browser E2E.
*/
import assert from 'node:assert/strict'
import { test, after } from 'node:test'
import { createRequire } from 'node:module'
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { runInNewContext } from 'node:vm'
import { fileURLToPath } from 'node:url'
const require = createRequire(new URL('../01_content/package.json', import.meta.url))
const { buildSync } = require('esbuild')
const temp = mkdtempSync(join(tmpdir(), 'wt-sandboxed-frame-test-'))
after(() => rmSync(temp, { recursive: true, force: true }))
const componentPath = fileURLToPath(new URL('../01_content/src/client/SandboxedFrame.tsx', import.meta.url))
const bundlePath = join(temp, 'SandboxedFrame.cjs')
buildSync({
entryPoints: [componentPath], bundle: true, platform: 'node', format: 'cjs',
outfile: bundlePath, external: ['react', 'react/jsx-runtime'], jsx: 'automatic',
})
const componentCode = readFileSync(bundlePath, 'utf8')
function createHarness({ location, fetch }) {
const slots = []
let cursor = 0
let pendingEffects = []
let currentProps
let currentOutput
const jsx = (type, props) => ({ type, props: props ?? {} })
const react = {
useState(initial) {
const index = cursor++
if (!slots[index]) slots[index] = { kind: 'state', value: typeof initial === 'function' ? initial() : initial }
const slot = slots[index]
return [slot.value, value => { slot.value = typeof value === 'function' ? value(slot.value) : value }]
},
useEffect(create, deps) {
const index = cursor++
const previous = slots[index]
const same = previous?.kind === 'effect' && Array.isArray(deps) && Array.isArray(previous.deps)
&& deps.length === previous.deps.length && deps.every((value, i) => Object.is(value, previous.deps[i]))
if (!same) pendingEffects.push({ index, create, deps: Array.isArray(deps) ? [...deps] : undefined })
},
}
const module = { exports: {} }
const sandbox = {
module,
exports: module.exports,
URL,
location,
fetch,
require(id) {
if (id === 'react') return react
if (id === 'react/jsx-runtime') return { jsx, jsxs: jsx, Fragment: Symbol.for('test.fragment') }
throw new Error('unexpected external module: ' + id)
},
}
runInNewContext(componentCode, sandbox, { filename: 'SandboxedFrame.cjs' })
const { SandboxedFrame, previewTarget } = module.exports
function render(props) {
currentProps = props ?? currentProps
cursor = 0
pendingEffects = []
currentOutput = SandboxedFrame(currentProps)
for (const effect of pendingEffects) {
const previous = slots[effect.index]
if (previous?.kind === 'effect') previous.cleanup?.()
const cleanup = effect.create()
slots[effect.index] = {
kind: 'effect', deps: effect.deps,
cleanup: typeof cleanup === 'function' ? cleanup : undefined,
}
}
return currentOutput
}
function unmount() {
for (const slot of slots) if (slot?.kind === 'effect') slot.cleanup?.()
slots.length = 0
}
return { render, unmount, previewTarget, get output() { return currentOutput } }
}
const flush = async () => { for (let i = 0; i < 12; i++) await Promise.resolve() }
const siteUrl = (protocol = 'https:', host = 'dsh.example') =>
protocol + '//' + host + '/api/worktable/site/C%3A%2FProjects%2Flegacy/index.html'
const grant = token => ({ token, base: '/api/worktable/preview-static/' + token + '/' })
const response = value => ({ ok: true, status: 200, json: async () => value })
function recordingFetch(grants) {
const calls = []
const fetch = (url, init = {}) => {
const body = init.body ? JSON.parse(init.body) : {}
calls.push({ url, init, body })
if (body.revoke) return Promise.resolve({ ok: true, status: 200 })
const value = typeof grants === 'function' ? grants(body, calls.length) : grants.shift()
return Promise.resolve(typeof value?.then === 'function' ? value : response(value))
}
return { fetch, calls, revoked: () => calls.filter(call => call.body.revoke).map(call => call.body.revoke) }
}
const iframeProps = output => {
assert.equal(output?.type, 'iframe', 'expected iframe output; actual=' + JSON.stringify(output))
return output.props
}
const errorText = output => output?.props?.children?.props?.children
test('dangerous URL schemes are rejected before a preview grant is requested', async () => {
const network = recordingFetch([])
const location = { href: 'https://dsh.example/worktable', protocol: 'https:' }
const harness = createHarness({ location, fetch: network.fetch })
for (const url of ['javascript:alert(1)', 'data:text/html,unsafe', 'file:///tmp/page.html', 'blob:https://dsh.example/id', 'ftp://dsh.example/page']) {
assert.throws(() => harness.previewTarget(url, location.href), /Unsupported preview URL/)
}
harness.render({ url: 'javascript:alert(1)', reloadKey: 0 })
await flush()
const output = harness.render()
assert.equal(output.type, 'div')
assert.match(errorText(output), /Unsupported preview URL/)
assert.equal(network.calls.length, 0)
harness.unmount()
})
test('legacy site URLs request a grant for the decoded root and load the relative resource', async () => {
const token = 'a'.repeat(32)
const network = recordingFetch([grant(token)])
const location = { href: 'https://dsh.example/worktable', protocol: 'https:' }
const harness = createHarness({ location, fetch: network.fetch })
const url = 'https://dsh.example/api/worktable/site/C%3A%2FProjects%2Flegacy%20site/assets/main%20file.css?theme=dark#top'
const props = { url, title: 'legacy', reloadKey: 0 }
harness.render(props)
await flush()
const frame = iframeProps(harness.render(props))
assert.deepEqual(network.calls[0].body, { root: 'C:/Projects/legacy site' })
assert.equal(frame.src, grant(token).base + 'assets/main%20file.css?theme=dark#top')
assert.equal(frame['data-source-url'], url)
assert.equal(frame.sandbox, 'allow-scripts allow-forms allow-downloads')
harness.unmount()
assert.deepEqual(network.revoked(), [token], 'revoke calls=' + JSON.stringify(network.calls))
})
test('a grant that returns after unmount is revoked immediately', async () => {
const token = 'b'.repeat(32)
const pending = {}
pending.promise = new Promise(resolve => { pending.resolve = resolve })
const calls = []
const fetch = (url, init = {}) => {
const body = init.body ? JSON.parse(init.body) : {}
calls.push({ url, body })
return body.revoke ? Promise.resolve({ ok: true }) : pending.promise
}
const harness = createHarness({
location: { href: 'https://dsh.example/worktable', protocol: 'https:' }, fetch,
})
harness.render({ url: siteUrl(), reloadKey: 0 })
harness.unmount()
pending.resolve(response(grant(token)))
await flush()
assert.deepEqual(calls.filter(call => call.body.revoke).map(call => call.body.revoke), [token])
})
test('Desktop URL construction failure revokes the minted token immediately and only once', async () => {
const token = 'c'.repeat(32)
const network = recordingFetch([grant(token)])
const location = { href: 'dsh-app://app/worktable', protocol: 'dsh-app:' }
const harness = createHarness({ location, fetch: network.fetch })
const props = { url: siteUrl('dsh-app:', 'app'), reloadKey: 0 }
harness.render(props)
await flush()
assert.deepEqual(network.revoked(), [token])
const output = harness.render(props)
assert.equal(output.type, 'div')
assert.match(errorText(output), /Desktop Host preview URL unavailable/)
harness.unmount()
assert.deepEqual(network.revoked(), [token], 'unmount must not revoke the already-cleared token again')
})
test('reload revokes the previous token and uses only the newly issued token', async () => {
const first = 'd'.repeat(32)
const second = 'e'.repeat(32)
const network = recordingFetch([grant(first), grant(second)])
const harness = createHarness({
location: { href: 'https://dsh.example/worktable', protocol: 'https:' }, fetch: network.fetch,
})
const props = { url: siteUrl(), reloadKey: 0 }
harness.render(props)
await flush()
assert.ok(iframeProps(harness.render(props)).src.includes(first))
const reloadProps = { ...props, reloadKey: 1 }
harness.render(reloadProps)
assert.deepEqual(network.revoked(), [first], 'reload cleanup must revoke the old token before the new grant settles')
await flush()
const nextFrame = iframeProps(harness.render(reloadProps))
assert.ok(nextFrame.src.includes(second))
assert.equal(nextFrame.src.includes(first), false)
harness.unmount()
assert.deepEqual(network.revoked(), [first, second])
})
test('an unavailable preview authorization service renders an error without navigating', async () => {
const calls = []
const fetch = async (url, init = {}) => {
calls.push({ url, body: init.body ? JSON.parse(init.body) : {} })
return { ok: false, status: 503 }
}
const harness = createHarness({
location: { href: 'https://dsh.example/worktable', protocol: 'https:' }, fetch,
})
const props = { url: siteUrl(), reloadKey: 0 }
harness.render(props)
await flush()
const output = harness.render(props)
assert.equal(output.type, 'div')
assert.match(errorText(output), /Preview HTTP 503/)
assert.equal(calls.length, 1)
assert.deepEqual(calls[0].body, { root: 'C:/Projects/legacy' })
assert.equal(calls.some(call => call.body.revoke), false)
harness.unmount()
})
+2 -2
View File
@@ -90,7 +90,7 @@ function runChild(envHome, name, withOfficial = false) {
"import { homedir } from 'node:os'",
"const mod = await import(pathToFileURL(process.argv[1]).href)",
"const routes = []",
"const fakeCtx = { webServer: { register: (r) => { routes.push(r) } }, effect: () => {}, logger: { warn() {}, info() {} } }",
"const fakeCtx = { webServer: { register: (r) => { routes.push(r) } }, get: () => ({ admit: () => ({ peer: { principal: { kind: 'owner' } } }) }), effect: (fn) => fn(), logger: { warn() {}, info() {} } }",
"mod.apply(fakeCtx)",
"const route = routes.find((r) => r.path === '/api/worktable/workspaces')",
"let status = 0; let body = ''",
@@ -162,7 +162,7 @@ function runChild(envHome, name, withOfficial = false) {
"import { pathToFileURL } from 'node:url'",
"const mod = await import(pathToFileURL(process.argv[1]).href)",
"const routes = []",
"const fakeCtx = { webServer: { register: (r) => { routes.push(r) } }, effect: () => {}, logger: { warn() {}, info() {} } }",
"const fakeCtx = { webServer: { register: (r) => { routes.push(r) } }, get: () => ({ admit: () => ({ peer: { principal: { kind: 'owner' } } }) }), effect: (fn) => fn(), logger: { warn() {}, info() {} } }",
"mod.apply(fakeCtx)",
"const route = routes.find((r) => r.path === '/api/worktable/workspaces')",
"let status = 0; let body = ''",
+244
View File
@@ -0,0 +1,244 @@
/**
* WorktableSection popup regression against the actual client bundle.
* Usage: node 04_test/sidebar-popup.test.mjs [lib/client.js]
* The small React hook/JSX harness runs the exported component and its event handlers;
* it does not claim browser layout or desktop GUI coverage.
*/
import { readFileSync } from 'node:fs'
import { createContext, runInNewContext } from 'node:vm'
import { fileURLToPath } from 'node:url'
import { dirname, join, resolve } from 'node:path'
const BUNDLE = resolve(process.argv[2] ?? join(dirname(fileURLToPath(import.meta.url)), '..', '01_content', 'lib', 'client.js'))
const source = readFileSync(BUNDLE, 'utf8')
const assert = (condition, message) => {
if (!condition) throw new Error(message)
}
const Fragment = Symbol('test.fragment')
const jsx = (type, props, key) => ({ type, props: props ?? {}, key: key ?? props?.key ?? null })
function makeHooks() {
const slots = []
const effects = []
let cursor = 0
let mounted = false
const useState = (initial) => {
const i = cursor++
if (!(i in slots)) slots[i] = typeof initial === 'function' ? initial() : initial
return [slots[i], (next) => { slots[i] = typeof next === 'function' ? next(slots[i]) : next }]
}
const useRef = (initial) => {
const i = cursor++
if (!(i in slots)) slots[i] = { current: initial }
return slots[i]
}
const useMemo = (make) => { cursor++; return make() }
const useCallback = (callback) => { cursor++; return callback }
const useEffect = (effect) => { cursor++; if (!mounted) effects.push(effect) }
return {
React: { Fragment, useState, useRef, useMemo, useCallback, useEffect, useLayoutEffect: useEffect },
render(component, props) {
cursor = 0
const tree = component(props)
if (!mounted) {
mounted = true
for (const effect of effects.splice(0)) {
try { effect() } catch (error) { throw new Error('mount effect failed: ' + error.message) }
}
}
return tree
},
}
}
function fakeElement(tagName = 'div') {
return {
tagName: tagName.toUpperCase(),
className: '',
style: {},
children: [],
setAttribute(name, value) { this[name] = value },
appendChild(child) { child.parentElement = this; this.children.push(child); return child },
remove() {},
addEventListener() {},
removeEventListener() {},
getBoundingClientRect() { return { left: 24, top: 100, right: 64, bottom: 140, width: 40, height: 40 } },
getContext() {
return {
globalCompositeOperation: '',
createLinearGradient() { return { addColorStop() {} } },
fillRect() {},
getImageData() { return { data: [0, 0, 0, 255] } },
}
},
}
}
function loadComponent() {
const values = new Map([
['dsh.worktable.updateCheck.v1', '0'],
['dsh.worktable.projects.v1', JSON.stringify({
order: [], lastUsed: {}, hidden: [], nameOverrides: {}, iconOverrides: {}, removed: [],
views: {}, shortcuts: [], bindings: {}, folders: {},
layouts: [{
id: 'popup-test-layout', title: 'Popup Test', icon: '🧱', top: null,
main: [{ id: 'popup-test-pane', title: 'Pane', min: 200, content: null }],
chatWidth: { default: 320, min: 240, max: 600 },
}],
})],
])
const localStorage = {
getItem: (key) => values.has(key) ? values.get(key) : null,
setItem: (key, value) => values.set(key, String(value)),
removeItem: (key) => values.delete(key),
}
const body = fakeElement('body')
const head = fakeElement('head')
const document = {
body, head,
documentElement: fakeElement('html'),
querySelector: () => null,
querySelectorAll: () => [],
createElement: (tag) => fakeElement(tag),
addEventListener() {},
removeEventListener() {},
}
const window = {
innerWidth: 1280,
innerHeight: 900,
localStorage,
document,
__ModuleLoader__: { load: (definition) => { window.captured = definition } },
addEventListener() {},
removeEventListener() {},
dispatchEvent() {},
matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
setTimeout: () => 1,
clearTimeout() {},
setInterval: () => 1,
clearInterval() {},
open() {},
}
const hooks = makeHooks()
const jsxRuntime = { Fragment, jsx, jsxs: jsx }
const sandbox = {
window, document, localStorage,
self: window,
location: { href: 'http://localhost/', protocol: 'http:' },
navigator: { userAgent: 'node popup regression', platform: 'Win32', language: 'en-US' },
console,
atob,
btoa,
fetch: async () => ({ ok: false, status: 404, json: async () => ({}) }),
setTimeout: window.setTimeout,
clearTimeout: window.clearTimeout,
setInterval: window.setInterval,
clearInterval: window.clearInterval,
requestAnimationFrame: () => 1,
cancelAnimationFrame() {},
MutationObserver: class { observe() {} disconnect() {} },
ResizeObserver: class { observe() {} unobserve() {} disconnect() {} },
IntersectionObserver: class { observe() {} unobserve() {} disconnect() {} },
CustomEvent: class { constructor(type, init) { this.type = type; this.detail = init?.detail } },
URL, Blob, AbortController,
indexedDB: undefined,
}
createContext(sandbox)
runInNewContext(source, sandbox, { filename: BUNDLE, timeout: 20000 })
assert(typeof window.captured?.factory === 'function', 'client bundle did not register a factory')
const requireExternal = (id) => {
if (id === 'react') return hooks.React
if (id === 'react/jsx-runtime') return jsxRuntime
if (id === 'react-dom') return { createPortal: (child) => child }
if (id === 'scheduler') return {}
throw new Error('unexpected external module: ' + id)
}
const exports = window.captured.factory(requireExternal)
assert(typeof exports.WorktableSection === 'function', 'bundle did not export WorktableSection')
return { component: exports.WorktableSection, hooks, window, values }
}
function walk(node, predicate, out = []) {
if (Array.isArray(node)) { for (const child of node) walk(child, predicate, out); return out }
if (!node || typeof node !== 'object') return out
if (typeof node.type !== 'undefined' && predicate(node)) out.push(node)
walk(node.props?.children, predicate, out)
return out
}
const classHas = (node, name) => String(node.props?.className ?? '').split(/\s+/).includes(name)
const byClass = (tree, name) => walk(tree, (node) => classHas(node, name))
const click = (node, rect = fakeElement()) => {
assert(typeof node?.props?.onClick === 'function', 'target has no onClick handler')
node.props.onClick({ currentTarget: rect, target: rect, stopPropagation() {}, preventDefault() {} })
}
async function main() {
const { component, hooks, window, values } = loadComponent()
const render = (wide) => hooks.render(component, { wide, t: (key) => key })
let tree = render(false)
assert(byClass(tree, 'dsh-wt_rail').length === 1, 'collapsed rail was not rendered')
assert(byClass(tree, 'dsh-wt_add').length === 0, 'add popup unexpectedly started open')
const addFromConsole = window.__dshCustomEnv?.console?.onAdd
assert(typeof addFromConsole === 'function', 'control-room onAdd action was not exposed')
addFromConsole()
tree = render(false)
assert(byClass(tree, 'dsh-wt_add').length === 1, 'control-room add action did not render once in collapsed rail')
tree = render(true)
assert(byClass(tree, 'dsh-wt_add').length === 1, 'switching wide retained duplicate or lost add popup')
click(byClass(tree, 'dsh-wt_popBackdrop')[0])
tree = render(true)
assert(byClass(tree, 'dsh-wt_add').length === 0, 'add popup backdrop did not close')
const viewOptionsButton = walk(tree, (node) => node.type === 'button' && node.props?.['aria-label'] === 'menu.viewOptions')[0]
assert(viewOptionsButton, 'view-options control missing in wide mode')
click(viewOptionsButton)
tree = render(true)
assert(byClass(tree, 'dsh-wt_manage').length === 1, 'manage popup did not open')
tree = render(false)
assert(byClass(tree, 'dsh-wt_manage').length === 1, 'switching collapsed while popup open lost or duplicated the popup')
tree = render(true)
const layoutIcon = byClass(tree, 'dsh-wt_manageIcon').at(-1)
assert(layoutIcon, 'layout icon control missing')
click(layoutIcon)
tree = render(true)
assert(byClass(tree, 'dsh-wt_iconPop').length === 1, 'icon popup did not open once')
const iconCell = byClass(tree, 'dsh-wt_iconCell')[1]
assert(iconCell, 'icon choices missing')
const chosenIcon = iconCell.props.children
click(iconCell)
tree = render(true)
assert(byClass(tree, 'dsh-wt_iconPop').length === 0, 'choosing an icon did not close its popup')
const savedProjects = JSON.parse(values.get('dsh.worktable.projects.v1'))
assert(savedProjects.layouts[0].icon === chosenIcon, 'chosen layout icon was not persisted')
const layoutCard = byClass(tree, 'dsh-wt_layout').at(-1)
const bindButton = layoutCard && walk(layoutCard, (node) => classHas(node, 'dsh-wt_bindBtn'))[0]
assert(bindButton, 'layout binding control missing')
click(bindButton)
tree = render(true)
assert(byClass(tree, 'dsh-wt_bindPop').length === 1, 'binding popup did not open once')
click(byClass(tree, 'dsh-wt_popBackdrop').at(-1))
tree = render(true)
assert(byClass(tree, 'dsh-wt_bindPop').length === 0, 'binding popup backdrop did not close')
const deleteButton = walk(tree, (node) => node.type === 'button' && node.props?.title === 'manage.deleteLayout')[0]
assert(deleteButton, 'layout delete control missing')
click(deleteButton)
tree = render(true)
assert(walk(tree, (node) => node.props?.role === 'alertdialog').length === 1, 'delete confirmation did not open')
const cancelButton = walk(tree, (node) => node.type === 'button' && node.props?.children === 'confirm.cancel')[0]
assert(cancelButton, 'delete confirmation cancel control missing')
click(cancelButton)
tree = render(true)
assert(walk(tree, (node) => node.props?.role === 'alertdialog').length === 0, 'delete confirmation did not close')
console.log('all sidebar-popup tests passed: add, icon, binding, delete confirmation, wide/collapsed switching')
}
await main()
+197
View File
@@ -0,0 +1,197 @@
/**
* Split margin/CSSOM regression tests.
* Usage: node split-margin.test.mjs [path/to/lib/client.js]
*
* Runs the actual client bundle in isolated headless Chromium with a temporary
* profile. The fractional case uses real CSSStyleDeclaration and MutationObserver.
*/
import assert from 'node:assert/strict'
import { copyFileSync, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { spawnSync } from 'node:child_process'
import { dirname, join, resolve, sep } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { tmpdir } from 'node:os'
const testDir = dirname(fileURLToPath(import.meta.url))
const repoRoot = resolve(testDir, '..')
const bundlePath = resolve(process.argv[2] ?? join(repoRoot, '01_content', 'lib', 'client.js'))
assert.ok(existsSync(bundlePath), 'client bundle not found: ' + bundlePath)
const browserPath = process.env.DSH_TEST_CHROMIUM || [
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
].find(existsSync)
assert.ok(browserPath && existsSync(browserPath),
'Chromium not found; set DSH_TEST_CHROMIUM to an installed Chromium executable')
const browserCode = [
"const result = document.getElementById('result');",
"const lines = [];",
"const record = (name, ok, detail) => lines.push((ok ? 'PASS ' : 'FAIL ') + name + (detail ? ' (' + detail + ')' : ''));",
"const sleep = () => new Promise(resolve => setTimeout(resolve, 80));",
"const makeStub = () => {",
" const stub = function () { return makeStub(); };",
" return new Proxy(stub, {",
" get: (_target, key) => (key === Symbol.toPrimitive ? () => 'stub' : makeStub()),",
" apply: () => makeStub(),",
" construct: () => makeStub(),",
" });",
"};",
"const requireStub = id => {",
" if (id === 'react' || id === 'react/jsx-runtime') return makeStub();",
" throw new Error('unexpected external require: ' + id);",
"};",
"const makeSpec = (id, extra = {}) => Object.assign({",
" id, title: id, top: null,",
" main: [{ id: 'p1', title: 'p1', min: 200, content: null }],",
" chatWidth: { default: 320, min: 240, max: 600 },",
"}, extra);",
"function addRoot(phase, width, headerHeight = 48) {",
" const root = document.createElement('div');",
" root.dataset.phase = phase;",
" root.className = 'wSkVaW_root';",
" root.style.cssText = 'position:absolute;left:0;top:0;width:' + width + 'px;height:800px;padding:0;border:0;box-sizing:content-box;';",
" let header = null;",
" let area;",
" if (headerHeight === null) {",
" area = document.createElement('div');",
" root.appendChild(area);",
" } else {",
" header = document.createElement('div');",
" header.className = 'wSkVaW_header';",
" header.style.cssText = 'height:' + headerHeight + 'px;width:100%;';",
" area = document.createElement('div');",
" area.style.cssText = 'height:700px;width:100%;';",
" root.appendChild(header);",
" root.appendChild(area);",
" }",
" document.body.appendChild(root);",
" return { root, header, area };",
"}",
"async function runCase(name, fn) {",
" try { await fn(); record(name, true); }",
" catch (error) { record(name, false, String(error && error.message || error)); }",
" try { if (window.__splitStore && window.__splitStore.active) window.__splitStore.close(); } catch {}",
" document.querySelectorAll('[data-phase]').forEach(el => el.remove());",
" await sleep();",
"}",
"(async () => {",
" try {",
" if (!window.__captured || typeof window.__captured.factory !== 'function') throw new Error('client factory not captured');",
" window.__captured.factory(requireStub);",
" const splitStore = window.__dshWorktable && window.__dshWorktable.splitStore;",
" if (!splitStore) throw new Error('splitStore not exported');",
" window.__splitStore = splitStore;",
" document.body.style.margin = '0';",
" await runCase('A fractional CSSOM write stays open', async () => {",
" const { root, area } = addRoot('active', 1000.333);",
" if (!splitStore.open(makeSpec('split-margin-a'))) throw new Error('open failed');",
" splitStore.setChatW(splitStore.chatW + 1);",
" const colW = splitStore.geom.right - splitStore.geom.left;",
" const rawMargin = Math.max(0, colW - splitStore.chatW) + 'px';",
" const probe = document.createElement('div');",
" probe.style.marginLeft = rawMargin;",
" if (probe.style.marginLeft === rawMargin) throw new Error('fixture did not exercise CSSOM rounding: ' + rawMargin);",
" await sleep();",
" if (!splitStore.active) throw new Error('self-write closed split; raw=' + rawMargin + ', CSSOM=' + probe.style.marginLeft);",
" if (area.style.marginLeft !== probe.style.marginLeft) throw new Error('unexpected applied CSSOM value: ' + area.style.marginLeft);",
" root.remove();",
" });",
" await runCase('B top/left resizing stays open', async () => {",
" const { root } = addRoot('active', 1000.333);",
" const spec = makeSpec('split-margin-b', {",
" top: [{ id: 't1', title: 't1', min: 120, content: null }],",
" left: { id: 'l1', title: 'l1', min: 160, content: null },",
" topHeight: { default: 200, min: 80 },",
" leftWidth: { default: 260, min: 160 },",
" });",
" if (!splitStore.open(spec)) throw new Error('open failed');",
" splitStore.setTopH(201.4);",
" splitStore.setLeftW(301.4);",
" splitStore.setChatW(400);",
" await sleep();",
" if (!splitStore.active) throw new Error('resizing closed split');",
" root.remove();",
" });",
" await runCase('C external style rewrite still yields', async () => {",
" const { area } = addRoot('active', 1000);",
" if (!splitStore.open(makeSpec('split-margin-c'))) throw new Error('open failed');",
" await sleep();",
" if (!splitStore.active) throw new Error('split closed before external rewrite');",
" area.style.marginRight = '19px';",
" await sleep();",
" if (splitStore.active) throw new Error('external rewrite was not detected');",
" });",
" await runCase('D yield observer follows a new view area', async () => {",
" const old = addRoot('hero', 1000, null);",
" if (!splitStore.open(makeSpec('split-margin-d'))) throw new Error('open failed');",
" await sleep();",
" const next = addRoot('active', 1000);",
" splitStore.syncAnchor();",
" await sleep();",
" if (splitStore.root !== next.root || splitStore.viewArea !== next.area) throw new Error('syncAnchor did not move to new root');",
" if (!splitStore.active) throw new Error('split closed during re-anchor');",
" next.area.style.marginLeft = '23px';",
" await sleep();",
" if (splitStore.active) throw new Error('new view area rewrite was not observed');",
" old.root.remove();",
" });",
" await runCase('E integer geometry stays open', async () => {",
" const { root } = addRoot('active', 1000);",
" if (!splitStore.open(makeSpec('split-margin-e'))) throw new Error('open failed');",
" await sleep();",
" if (!splitStore.active) throw new Error('integer geometry closed split');",
" root.remove();",
" });",
" } catch (error) {",
" lines.push('FAIL setup (' + String(error && error.message || error) + ')');",
" }",
" result.textContent = (lines.some(line => line.startsWith('FAIL ')) ? 'FAIL|' : 'PASS|') + lines.join('|');",
"})();",
].join('\n')
const html = [
'<!doctype html><html><head><meta charset="utf-8"></head><body>',
'<pre id="result">RUNNING</pre>',
'<script>window.__ModuleLoader__ = { load: reg => { window.__captured = reg; } };</script>',
'<script src="./client.js"></script>',
'<script>',
browserCode,
'</script>',
'</body></html>',
].join('\n')
const systemTemp = realpathSync(tmpdir())
const tempDir = mkdtempSync(join(systemTemp, 'dsh-worktable-split-margin-'))
try {
const tempReal = realpathSync(tempDir)
assert.ok(tempReal.toLowerCase().startsWith(systemTemp.toLowerCase() + sep), 'temporary directory escaped system temp')
copyFileSync(bundlePath, join(tempDir, 'client.js'))
writeFileSync(join(tempDir, 'index.html'), html, 'utf8')
const browser = spawnSync(browserPath, [
'--headless=new',
'--disable-gpu',
'--disable-extensions',
'--disable-background-networking',
'--allow-file-access-from-files',
'--force-device-scale-factor=1.5',
'--no-first-run',
'--no-default-browser-check',
'--dump-dom',
'--virtual-time-budget=5000',
'--user-data-dir=' + join(tempDir, 'profile'),
pathToFileURL(join(tempDir, 'index.html')).href,
], { encoding: 'utf8', timeout: 30000, maxBuffer: 5 * 1024 * 1024 })
if (browser.error) throw browser.error
const resultMatch = /<pre id="result">([\s\S]*?)<\/pre>/.exec(browser.stdout || '')
assert.ok(resultMatch, 'Chromium did not return the test result. stderr: ' + String(browser.stderr || '').slice(-1200))
const result = resultMatch[1]
for (const line of result.split('|').slice(1)) console.log(line)
assert.ok(result.startsWith('PASS|'), 'split margin regression failed: ' + result)
assert.equal(browser.status, 0, 'Chromium exited with status ' + browser.status)
console.log('all split margin tests passed')
} finally {
const tempReal = realpathSync(tempDir)
assert.ok(tempReal.toLowerCase().startsWith(systemTemp.toLowerCase() + sep), 'refusing to remove path outside system temp')
rmSync(tempReal, { recursive: true, force: true })
}