import { createMockFacade } from './facade/mockFacade'
import { createScriptSandbox } from './facade/scriptSandbox'
type ScriptReport = { schemaVersion: 1; status: 'pass' | 'failed'; browserId: 'chrome'; crossOriginIsolated: boolean; macro?: { commands: number; replay: string; executed: number; bytes: number }; security?: { disallowedRejected: boolean; quotaRejected: boolean; noDynamicExecution: boolean; deniedCapabilities: string[] }; persistence?: { mode: string; byteLength: number; roundTrip: boolean; released: boolean }; opfs?: { markerSuite: string; commands: number; markerRemoved: boolean }; afterRelease?: { shapeCount: number; kernelReferenceCount: number }; error?: string }
const sha256 = async (bytes: Uint8Array) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes).buffer))].map((value) => value.toString(16).padStart(2, '0')).join('')
const run = async (): Promise<ScriptReport> => { const facade = createMockFacade(); const report: ScriptReport = { schemaVersion: 1, status: 'failed', browserId: 'chrome', crossOriginIsolated: globalThis.crossOriginIsolated === true }; try { if (!report.crossOriginIsolated || !navigator.storage?.getDirectory) throw new Error('Chrome script evidence requires isolated OPFS.'); await facade.project.list(); const sandbox = createScriptSandbox({ allowedCommands: ['project.list', 'geometry.createBox'], allowedCapabilities: [], maxCommands: 4, maxArgumentBytes: 512 }); sandbox.record('project.list'); sandbox.record('geometry.createBox', { width: 2, height: 3 }); const macro = sandbox.exportMacro(); const replay = sandbox.replay(sandbox.importMacro(macro)); let disallowedRejected = false; try { sandbox.record('geometry.boolean') } catch { disallowedRejected = true }; const quotaSandbox = createScriptSandbox({ maxArgumentBytes: 8 }); let quotaRejected = false; try { quotaSandbox.record('project.list', 'too-long') } catch { quotaRejected = true }; const deniedCapabilities = (['file', 'network', 'time', 'resource'] as const).filter((capability) => !sandbox.requestCapability(capability).granted); const payload = new TextEncoder().encode(macro); const stored = await facade.project.resource.put(payload, 'application/vnd.bitbybit.macro+json'); const loaded = await facade.project.resource.get(stored.hash); const roundTrip = loaded !== null && await sha256(loaded) === await sha256(payload); await facade.project.resource.release(stored.hash); const released = await facade.project.resource.get(stored.hash) === null; const directory = await navigator.storage.getDirectory(); const markerName = 'script-chrome-marker.json'; const marker = await directory.getFileHandle(markerName, { create: true }); const writable = await marker.createWritable(); await writable.write(JSON.stringify({ suite: 'SCRIPT-ALL', commands: sandbox.snapshot().commands.length })); await writable.close(); const markerPayload = JSON.parse(await (await marker.getFile()).text()) as { suite: string; commands: number }; await directory.removeEntry(markerName); let markerRemoved = false; try { await directory.getFileHandle(markerName) } catch (error) { markerRemoved = error instanceof DOMException && error.name === 'NotFoundError' }; report.macro = { commands: sandbox.snapshot().commands.length, replay: replay.status, executed: replay.executed, bytes: payload.byteLength }; report.security = { disallowedRejected, quotaRejected, noDynamicExecution: sandbox.snapshot().policy.allowedCapabilities.length === 0, deniedCapabilities }; report.persistence = { mode: facade.project.capabilities().mode, byteLength: stored.byteLength, roundTrip, released }; report.opfs = { markerSuite: markerPayload.suite, commands: markerPayload.commands, markerRemoved }; report.status = report.macro.commands === 2 && report.macro.replay === 'replayed' && report.macro.executed === 2 && report.macro.bytes > 0 && report.security.disallowedRejected && report.security.quotaRejected && report.security.noDynamicExecution && JSON.stringify(report.security.deniedCapabilities) === JSON.stringify(['file', 'network', 'time', 'resource']) && report.persistence.mode === 'sqlite-opfs' && report.persistence.roundTrip && report.persistence.released && report.opfs.markerSuite === 'SCRIPT-ALL' && report.opfs.commands === 2 && report.opfs.markerRemoved ? 'pass' : 'failed' } catch (error) { report.error = error instanceof Error ? error.stack || error.message : String(error) } finally { facade.geometry.dispose(); await new Promise((resolve) => setTimeout(resolve, 0)); const capabilities = facade.geometry.capabilities(); report.afterRelease = { shapeCount: capabilities.shapeCount, kernelReferenceCount: capabilities.kernelReferenceCount }; if (capabilities.shapeCount !== 0 || capabilities.kernelReferenceCount !== 0) { report.status = 'failed'; report.error = `${report.error ? `${report.error} ` : ''}Shape ownership gate failed.` } } return report }
run().then((report) => { ;(window as Window & { __bitbybitScriptReport?: ScriptReport }).__bitbybitScriptReport = report; document.documentElement.dataset.status = report.status; document.querySelector('#result')!.textContent = JSON.stringify(report, null, 2) }).catch((error) => { document.documentElement.dataset.status = 'failed'; document.querySelector('#result')!.textContent = error instanceof Error ? error.stack || error.message : String(error) })
export {}
