container.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { createHash, randomBytes } from 'node:crypto'
  2. import { spawn } from 'node:child_process'
  3. import { mkdir, realpath, chmod, lstat, rm, readFile } from 'node:fs/promises'
  4. import { join, resolve, posix, dirname, basename } from 'node:path'
  5. import { z } from 'zod'
  6. import {recoverWorkspace} from './workspaceRecovery.js'
  7. export const COMPUTER_WORKSPACE = '/home/cua/workspace'
  8. export const CUA_DRIVER = '/usr/local/libexec/openmausbot/cua-driver'
  9. export const CUA_SOCKET = '/run/user/1000/openmausbot-cua.sock'
  10. const managedLabel='cn.samien.yaoyao.computer', runnerLabel='cn.samien.yaoyao.runner', specLabel='cn.samien.yaoyao.computer-spec', ownerLabel='cn.samien.yaoyao.computer-owner'
  11. const mib=1024*1024
  12. export interface CommandResult {stdout:string;stderr:string}
  13. export interface SkillInstallation {namespace:string;revision:string;files:Record<string,string>}
  14. export type ContainerCommand=(runtime:'docker'|'podman',args:string[],options?:{timeout?:number;signal?:AbortSignal;input?:Buffer})=>Promise<CommandResult>
  15. const command:ContainerCommand=(runtime,args,options={})=>new Promise((resolveResult,reject)=>{
  16. const child=spawn(runtime,args,{stdio:'pipe',signal:options.signal}),out:Buffer[]=[],err:Buffer[]=[]
  17. let bytes=0,failure:Error|undefined
  18. const timer=setTimeout(()=>{failure=Object.assign(new Error('电脑命令超时'),{killed:true});child.kill('SIGTERM')},options.timeout??15000)
  19. const collect=(target:Buffer[],chunk:Buffer)=>{bytes+=chunk.length;if(bytes>8*mib){failure=Object.assign(new Error('电脑输出超过限制'),{killed:true});child.kill('SIGTERM')}else target.push(chunk)}
  20. child.stdout.on('data',chunk=>collect(out,Buffer.from(chunk)));child.stderr.on('data',chunk=>collect(err,Buffer.from(chunk)))
  21. child.once('error',error=>{failure=error});child.stdin.on('error',()=>{})
  22. child.once('close',code=>{clearTimeout(timer);const result={stdout:Buffer.concat(out).toString(),stderr:Buffer.concat(err).toString()};if(failure||code!==0)reject(Object.assign(failure??new Error('电脑命令失败'),{...result,...(!failure?{code}:{} )}));else resolveResult(result)})
  23. child.stdin.end(options.input)
  24. })
  25. const schema=z.object({
  26. network:z.enum(['none','public-proxy']).default('none'),
  27. id:z.string().uuid(),ownerKey:z.string().min(1).max(256),
  28. imageId:z.string().regex(/^sha256:[a-f0-9]{64}$/),
  29. cpus:z.number().int().min(1).max(8).default(2),memoryMiB:z.number().int().min(1024).max(16384).default(4096),
  30. cwd:z.string().max(4096).refine(value=>!/[\u0000-\u001f,]/.test(value)&&posix.isAbsolute(value)&&posix.normalize(value)===value&&value!=='/'&&!/^\/(?:proc|sys|dev|run|tmp|etc|usr|bin|sbin)(?:\/|$)/.test(value)&&value!=='/home/cua','电脑工作目录不受支持').default(COMPUTER_WORKSPACE),
  31. pids:z.number().int().min(64).max(1024).default(512),
  32. }).strict()
  33. export type ComputerSpecification=z.input<typeof schema>
  34. type Spec=z.output<typeof schema>
  35. export interface ComputerState {id:string;containerId:string;running:boolean;workspace:string;isolation:'container'|'vm'}
  36. export interface ComputerProvider {
  37. releaseFence?(spec:ComputerSpecification,keepRunning?:boolean):Promise<void>
  38. renewFence?(spec:ComputerSpecification):Promise<void>
  39. validateSpecification(spec:ComputerSpecification):ComputerSpecification
  40. readonly capabilities:{isolation:'container'|'vm';shell:boolean;desktop:boolean;persistentWorkspace:boolean;sharedDesktop:boolean;snapshots:boolean;network:'none'|'public-proxy'}
  41. inspect(spec:ComputerSpecification):Promise<ComputerState|undefined>
  42. ensure(spec:ComputerSpecification,authorize:()=>void):Promise<ComputerState>
  43. stop(spec:ComputerSpecification):Promise<void>
  44. remove(spec:ComputerSpecification):Promise<void>
  45. execute(spec:ComputerSpecification,argv:string[],options:{authorize():void;signal?:AbortSignal;timeout?:number;input?:Buffer}):Promise<CommandResult>
  46. health(spec:ComputerSpecification,authorize:()=>void):Promise<unknown>
  47. }
  48. export class ComputerError extends Error { constructor(readonly code:string,message:string){super(message)} }
  49. const digest=(value:unknown)=>createHash('sha256').update(JSON.stringify(value)).digest('hex')
  50. const capabilities=(values:unknown)=>Array.isArray(values)?values.map(value=>String(value).toUpperCase().replace(/^CAP_/, '')).sort():[]
  51. /** A private container per environment. No tools, filesystem operations or
  52. * process execution fall back to the host. Remote hosts run their own Runner. */
  53. export class ContainerComputerProvider implements ComputerProvider {
  54. readonly fixedCapacity:boolean=false
  55. private queue=new Map<string,Promise<unknown>>()
  56. readonly capabilities={isolation:'container',shell:true,desktop:true,persistentWorkspace:true,sharedDesktop:false,snapshots:false,network:'none'} as const
  57. constructor(readonly runtime:'docker'|'podman',readonly runnerId:string,readonly home:string,readonly run:ContainerCommand=command,readonly environment:NodeJS.ProcessEnv=process.env) {
  58. z.string().uuid().parse(runnerId)
  59. if(!['docker','podman'].includes(runtime))throw new ComputerError('runtime_unsupported','电脑运行时不受支持')
  60. }
  61. async verifyRuntime() {
  62. if(this.runtime==='docker') {
  63. const endpoint=this.environment.DOCKER_HOST||JSON.parse((await this.run('docker',['context','inspect','--format','{{json .Endpoints.docker.Host}}'])).stdout)
  64. if(typeof endpoint!=='string'||!(/^(?:unix|npipe):\/\//.test(endpoint)))throw new ComputerError('computer_remote_engine','远程 Docker 引擎请在目的电脑安装 Runner')
  65. }else{
  66. const connections=JSON.parse((await this.run('podman',['system','connection','list','--format','json'])).stdout)
  67. const endpoint=this.environment.CONTAINER_HOST||connections.find((entry:any)=>entry.Default)?.URI
  68. if(endpoint){const url=new URL(endpoint);if(url.protocol!=='unix:'&&!['127.0.0.1','localhost','[::1]'].includes(url.hostname))throw new ComputerError('computer_remote_engine','远程 Podman 引擎请在目的电脑安装 Runner')}
  69. }
  70. }
  71. validateSpecification(value:ComputerSpecification):Spec {
  72. const parsed=schema.safeParse(value)
  73. if(!parsed.success)throw new ComputerError('computer_spec_invalid','电脑环境配置无效')
  74. return parsed.data
  75. }
  76. private name(spec:Spec){return `yaoyao-computer-${digest([this.runnerId,spec.id]).slice(0,24)}`}
  77. private labels(spec:Spec){return {[managedLabel]:spec.id,[runnerLabel]:this.runnerId,[ownerLabel]:digest(spec.ownerKey),[specLabel]:digest(spec)}}
  78. private serial<T>(spec:Spec,action:()=>Promise<T>):Promise<T> {
  79. const result=(this.queue.get(spec.id)??Promise.resolve()).catch(()=>{}).then(action)
  80. this.queue.set(spec.id,result)
  81. void result.finally(()=>{if(this.queue.get(spec.id)===result)this.queue.delete(spec.id)}).catch(()=>{})
  82. return result
  83. }
  84. private async workspace(spec:Spec) {
  85. const base=resolve(this.home,'computer-workspaces')
  86. await mkdir(base,{recursive:true,mode:0o700})
  87. const canonical=await realpath(base),path=join(canonical,spec.id)
  88. await recoverWorkspace(canonical,spec.id)
  89. if(/[,\n\r\0]/.test(path))throw new ComputerError('computer_path_invalid','电脑数据目录包含不支持的字符')
  90. await mkdir(path,{recursive:true,mode:0o700})
  91. if(await realpath(path)!==path)throw new ComputerError('computer_path_unsafe','电脑工作区不能指向其他目录')
  92. if(process.platform!=='win32')await chmod(path,0o700)
  93. return path
  94. }
  95. private async inspectRaw(name:string):Promise<any|undefined> {
  96. try {const result=await this.run(this.runtime,['inspect',name]);return JSON.parse(result.stdout)[0]}
  97. catch(error){
  98. if(/no such (?:object|container)|no container with name or ID/i.test(String((error as any).stderr??'')))return undefined
  99. throw error
  100. }
  101. }
  102. private assertOwned(spec:Spec,detail:any) {
  103. if(!detail||!/^[a-f0-9]{64}$/.test(String(detail.Id))||Object.entries(this.labels(spec)).filter(([key])=>key!==specLabel).some(([key,value])=>detail.Config?.Labels?.[key]!==value))
  104. throw new ComputerError('computer_owner_mismatch','电脑实例不属于当前执行节点或配置已变化')
  105. }
  106. private assertConfiguration(spec:Spec,detail:any,workspace:string) {
  107. this.assertOwned(spec,detail)
  108. const host=detail.HostConfig??{},expectedCaps=this.runtime==='podman'?['SETGID','SETUID','SYS_CHROOT']:['SETGID','SETUID']
  109. const nanoCPUs=host.NanoCpus??(host.CpuPeriod>0?host.CpuQuota/host.CpuPeriod*1e9:0)
  110. const noPrivilege=(host.SecurityOpt??[]).some((value:string)=>/^no-new-privileges(?::true)?$/.test(value))
  111. const ports=Object.entries(host.PortBindings??{}),mounts=detail.Mounts??[]
  112. const destinations=spec.cwd===COMPUTER_WORKSPACE?[COMPUTER_WORKSPACE]:[COMPUTER_WORKSPACE,spec.cwd]
  113. if(detail.Config?.Labels?.[specLabel]!==digest(spec)||detail.Image!==spec.imageId||host.Privileged!==false||host.Memory!==spec.memoryMiB*mib||host.MemorySwap!==spec.memoryMiB*mib
  114. ||nanoCPUs!==spec.cpus*1e9||host.PidsLimit!==spec.pids||host.IpcMode!=='private'||host.CgroupnsMode!=='private'
  115. ||host.NetworkMode!=='none'||host.PidMode==='host'||host.UsernsMode==='host'||host.UTSMode==='host'
  116. ||!noPrivilege||(host.SecurityOpt??[]).some((value:string)=>/unconfined/.test(value))
  117. ||JSON.stringify(capabilities(host.CapAdd))!==JSON.stringify(expectedCaps)||!capabilities(host.CapDrop).includes('ALL')
  118. ||(host.Devices??[]).length||(host.DeviceRequests??[]).length||host.RestartPolicy?.Name!=='no'
  119. ||mounts.length!==destinations.length||mounts.some((mount:any)=>mount.Type!=='bind'||mount.Source!==workspace||!destinations.includes(mount.Destination)||mount.RW!==true)||new Set(mounts.map((mount:any)=>mount.Destination)).size!==destinations.length
  120. ||ports.length!==0)
  121. throw new ComputerError('computer_configuration_unsafe','电脑实例的隔离、资源或数据目录不符合要求,请先停止并核对')
  122. }
  123. private state(spec:Spec,detail:any,workspace:string):ComputerState {
  124. this.assertConfiguration(spec,detail,workspace)
  125. if(Object.values(detail.NetworkSettings?.Ports??{}).some(bindings=>Array.isArray(bindings)&&bindings.length))throw new ComputerError('computer_viewer_unsafe','电脑环境不能发布网络端口')
  126. return {id:spec.id,containerId:detail.Id,running:detail.State?.Running===true,workspace,isolation:'container'}
  127. }
  128. private async migratedContainer(spec:Spec,detail:any,workspace:string) {
  129. if(!detail || detail.Mounts?.every((mount:any)=>mount.Source===workspace))return detail
  130. let root=resolve(this.home)
  131. while(dirname(root)!==root&&basename(root)!=='.yaoyao')root=dirname(root)
  132. if(basename(root)!=='.yaoyao')return detail
  133. let migration
  134. try{migration=JSON.parse(await readFile(join(root,'.data-home-migration.json'),'utf8'))}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return detail;throw error}
  135. if(migration.phase!=='complete'||migration.target!==root||migration.source!==join(dirname(root),'.hermes-yaoyao'))return detail
  136. const oldWorkspace=migration.source+workspace.slice(root.length)
  137. this.assertConfiguration(spec,detail,oldWorkspace)
  138. if(detail.State?.Running)throw new ComputerError('computer_migration_busy','旧目录的虚拟机仍在运行,请停止后再迁移')
  139. // Preserve the old writable layer as a stopped backup; only the verified name changes.
  140. await this.run(this.runtime,['rename',detail.Id,`${this.name(spec)}-before-data-move-${detail.Id.slice(0,8)}`])
  141. return undefined
  142. }
  143. async inspect(value:ComputerSpecification):Promise<ComputerState|undefined> {
  144. await this.verifyRuntime()
  145. const spec=this.validateSpecification(value),workspace=await this.workspace(spec),detail=await this.migratedContainer(spec,await this.inspectRaw(this.name(spec)),workspace)
  146. return detail?this.state(spec,detail,workspace):undefined
  147. }
  148. private args(spec:Spec,workspace:string) {
  149. return ['create','--name',this.name(spec),'--hostname',this.name(spec),// The XFCE/VNC startup resolves its own hostname even without a network.
  150. '--add-host',`${this.name(spec)}:127.0.0.1`,
  151. ...Object.entries(this.labels(spec)).flatMap(([key,value])=>['--label',`${key}=${value}`]),
  152. '--restart','no','--network','none','--ipc','private','--cgroupns','private',
  153. '--memory',`${spec.memoryMiB}m`,'--memory-swap',`${spec.memoryMiB}m`,'--cpus',String(spec.cpus),'--pids-limit',String(spec.pids),
  154. '--shm-size','512m','--security-opt','no-new-privileges:true','--cap-drop','ALL','--cap-add','SETUID','--cap-add','SETGID',
  155. ...(this.runtime==='podman'?['--userns','keep-id:uid=1000,gid=1000','--user','root','--cap-add','SYS_CHROOT']:[]),
  156. ...[...new Set([COMPUTER_WORKSPACE,spec.cwd])].flatMap(destination=>['--mount',`type=bind,source=${workspace},target=${destination}${this.runtime==='podman'?',relabel=private':''}`]),
  157. ...(spec.network==='public-proxy'?['--env','HTTP_PROXY=http://127.0.0.1:3128','--env','HTTPS_PROXY=http://127.0.0.1:3128','--env','http_proxy=http://127.0.0.1:3128','--env','https_proxy=http://127.0.0.1:3128','--env','NO_PROXY=localhost,127.0.0.1,::1','--env','no_proxy=localhost,127.0.0.1,::1']:[]),
  158. '--env',`VNC_PW=${randomBytes(24).toString('base64url')}`,spec.imageId]
  159. }
  160. async ensure(value:ComputerSpecification,authorize:()=>void):Promise<ComputerState> {
  161. const spec=this.validateSpecification(value)
  162. return this.serial(spec,async()=>{
  163. authorize();await this.verifyRuntime();authorize()
  164. const workspace=await this.workspace(spec)
  165. let detail=await this.migratedContainer(spec,await this.inspectRaw(this.name(spec)),workspace)
  166. if(!detail) {
  167. const image=JSON.parse((await this.run(this.runtime,['image','inspect',spec.imageId])).stdout)[0]
  168. if(image?.Id!==spec.imageId||image.Config?.Labels?.['com.openmausbot.cua-driver']!=='0.20.0'||image.Config?.Labels?.['com.openmausbot.image-layer']!=='5')
  169. throw new ComputerError('computer_image_incompatible','电脑镜像缺少已验证的驱动,请先安装兼容镜像')
  170. authorize()
  171. const created=await this.run(this.runtime,this.args(spec,workspace))
  172. const id=created.stdout.trim()
  173. if(!/^[a-f0-9]{64}$/.test(id))throw new ComputerError('computer_creation_uncertain','电脑创建结果不确定,请核对实例')
  174. detail=await this.inspectRaw(id)
  175. }
  176. let state=this.state(spec,detail,workspace)
  177. authorize()
  178. if(!state.running)await this.run(this.runtime,['start','--',state.containerId])
  179. try {
  180. authorize();detail=await this.inspectRaw(state.containerId);state=this.state(spec,detail,workspace);authorize()
  181. if(!state.running)throw new ComputerError('computer_start_failed','电脑环境未能启动')
  182. return state
  183. }catch(error){await this.stopOwned(spec,state.containerId).catch(()=>{});throw error}
  184. })
  185. }
  186. private async stopOwned(spec:Spec,id:string) {
  187. const detail=await this.inspectRaw(id)
  188. if(!detail)return
  189. this.assertOwned(spec,detail)
  190. if(detail.State?.Running)await this.run(this.runtime,['stop','--time','10','--',id],{timeout:15000})
  191. const stopped=await this.inspectRaw(id)
  192. if(stopped?.State?.Running)throw new ComputerError('computer_stop_uncertain','尚未确认电脑环境已停止')
  193. }
  194. async stop(value:ComputerSpecification):Promise<void> {
  195. const spec=this.validateSpecification(value)
  196. return this.serial(spec,async()=>{await this.verifyRuntime();const detail=await this.inspectRaw(this.name(spec));if(detail){this.assertOwned(spec,detail);await this.stopOwned(spec,detail.Id)}})
  197. }
  198. async remove(value:ComputerSpecification):Promise<void> {
  199. const spec=this.validateSpecification(value)
  200. return this.serial(spec,async()=>{
  201. await this.verifyRuntime()
  202. const detail=await this.inspectRaw(this.name(spec));if(!detail)return
  203. this.assertOwned(spec,detail);await this.stopOwned(spec,detail.Id)
  204. await this.run(this.runtime,['rm','--',detail.Id])
  205. // Persistent workspace deletion is a separate, explicit operation.
  206. })
  207. }
  208. async execute(value:ComputerSpecification,argv:string[],options:{authorize():void;signal?:AbortSignal;timeout?:number;input?:Buffer}):Promise<CommandResult> {
  209. const spec=this.validateSpecification(value)
  210. if(!argv.length||argv.length>64||argv.some(arg=>typeof arg!=='string'||arg.includes('\0'))||argv.join('').length>65536)throw new ComputerError('computer_command_invalid','电脑命令无效或过长')
  211. return this.serial(spec,async()=>{
  212. options.authorize();if(options.signal?.aborted)throw new ComputerError('computer_cancelled','操作已停止')
  213. const state=await this.inspect(spec)
  214. if(!state?.running)throw new ComputerError('computer_not_running','电脑环境尚未运行')
  215. options.authorize()
  216. try {
  217. const result=await this.run(this.runtime,['exec',...(options.input?['-i']:[]),'--user','1000:1000','--workdir',spec.cwd,'--',state.containerId,...argv],{timeout:Math.min(60000,Math.max(1000,options.timeout??30000)),signal:options.signal,input:options.input})
  218. options.authorize();return result
  219. }catch(error){
  220. // Killing a docker exec client alone cannot prove its guest process stopped.
  221. // A cancelled or unacknowledged operation closes this private environment.
  222. if(options.signal?.aborted||(error as any).killed||typeof (error as any).code!=='number')await this.stopOwned(spec,state.containerId)
  223. throw error
  224. }
  225. })
  226. }
  227. async installSkill(value:ComputerSpecification,bundle:SkillInstallation,script:string,options:{authorize():void;signal?:AbortSignal}):Promise<{path:string;revision:string}> {
  228. const spec=this.validateSpecification(value)
  229. return this.serial(spec,async()=>{
  230. options.authorize();if(options.signal?.aborted)throw new ComputerError('computer_cancelled','操作已停止')
  231. const state=await this.inspect(spec)
  232. if(!state?.running)throw new ComputerError('computer_not_running','电脑环境尚未运行')
  233. options.authorize()
  234. const result=await this.run(this.runtime,['exec','-i','--user','0:0','--',state.containerId,'python3','-c',script,'install'],{input:Buffer.from(JSON.stringify(bundle)),signal:options.signal,timeout:30000})
  235. options.authorize();return JSON.parse(result.stdout)
  236. })
  237. }
  238. async capture(value:ComputerSpecification,authorize:()=>void):Promise<{data:string;width:number;height:number;capturedAt:number}> {
  239. const spec=this.validateSpecification(value),state=await this.inspect(spec)
  240. authorize();if(!state?.running)throw new ComputerError('computer_not_running','电脑尚未运行')
  241. const file=`/tmp/yaoyao-view-${randomBytes(12).toString('hex')}.png`
  242. const exec=(args:string[])=>this.run(this.runtime,['exec','--user','1000:1000','--',state.containerId,...args],{timeout:10000})
  243. try{
  244. await exec([CUA_DRIVER,'call','get_desktop_state','{}','--socket',CUA_SOCKET,'--screenshot-out-file',file]);authorize()
  245. const data=(await exec(['base64','-w0',file])).stdout.trim(),bytes=Buffer.from(data,'base64')
  246. if(bytes.length<24||bytes.subarray(1,4).toString()!=='PNG')throw new ComputerError('computer_frame_invalid','电脑画面无效')
  247. authorize();return {data,width:bytes.readUInt32BE(16),height:bytes.readUInt32BE(20),capturedAt:Date.now()}
  248. }finally{await exec(['rm','-f','--',file]).catch(()=>{})}
  249. }
  250. async deleteWorkspace(value:ComputerSpecification):Promise<void>{
  251. const spec=this.validateSpecification(value)
  252. if(await this.inspectRaw(this.name(spec)))throw new ComputerError('computer_busy','删除工作区前必须移除电脑实例')
  253. const base=await realpath(resolve(this.home,'computer-workspaces')).catch(error=>{if(error.code==='ENOENT')return undefined;throw error})
  254. if(!base)return
  255. const path=join(base,spec.id),info=await lstat(path).catch(error=>{if(error.code==='ENOENT')return undefined;throw error})
  256. if(!info)return
  257. if(!info.isDirectory()||info.isSymbolicLink()||await realpath(path)!==path)throw new ComputerError('computer_path_unsafe','拒绝删除非预期的电脑工作区')
  258. await rm(path,{recursive:true})
  259. }
  260. async openPipe(value:ComputerSpecification,argv:string[],authorize:()=>void){
  261. const spec=this.validateSpecification(value)
  262. authorize();const state=await this.inspect(spec);authorize()
  263. if(!state?.running)throw new ComputerError('computer_not_running','电脑环境尚未运行')
  264. return spawn(this.runtime,['exec','-i','--user','1000:1000','--workdir',spec.cwd,'--',state.containerId,...argv],{stdio:'pipe'})
  265. }
  266. async configureNetwork(value:ComputerSpecification,authorize:()=>void){
  267. const spec=this.validateSpecification(value)
  268. if(spec.network!=='public-proxy')return
  269. authorize();const state=await this.inspect(spec);authorize()
  270. if(!state?.running)throw new ComputerError('computer_not_running','电脑环境尚未运行')
  271. const script='import pathlib,json; chrome={"ProxyMode":"fixed_servers","ProxyServer":"http://127.0.0.1:3128","ProxyBypassList":"localhost;127.0.0.1;[::1]","QuicAllowed":False}; firefox={"policies":{"Proxy":{"Mode":"manual","HTTPProxy":"127.0.0.1:3128","SSLProxy":"127.0.0.1:3128","Passthrough":"localhost,127.0.0.1,::1","Locked":True},"DNSOverHTTPS":{"Enabled":False,"Locked":True}}}; paths=[("/etc/chromium/policies/managed/yaoyao.json",chrome),("/etc/opt/chrome/policies/managed/yaoyao.json",chrome),("/usr/lib/firefox/distribution/policies.json",firefox),("/usr/lib/firefox-esr/distribution/policies.json",firefox),("/opt/firefox/distribution/policies.json",firefox)]; [(pathlib.Path(p).parent.mkdir(parents=True,exist_ok=True),pathlib.Path(p).write_text(json.dumps(v))) for p,v in paths]'
  272. await this.run(this.runtime,['exec','--user','0','--',state.containerId,'python3','-c',script])
  273. authorize()
  274. }
  275. async health(value:ComputerSpecification,authorize:()=>void):Promise<unknown> {
  276. return JSON.parse((await this.execute(value,[CUA_DRIVER,'call','health_report','{}','--socket',CUA_SOCKET],{authorize})).stdout)
  277. }
  278. }