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W9zjYhm1JLqKLWSib2X6LtTTfZX67TJCGCh50XhIkY9JFYqmwHYd1+JLVfTsULuHZavDw2GW8oGBdGl3vlRfIe6PblKMRMaVNLQqrOxOnqgsCuv5EzHWxEZ/wWQj8aOtENXltgUExfBtg6eGUc=
-- CEETOS_RELEASE_PAYLOAD_BEGIN
-- CeetOS installer. Generated; do not edit.
local files = {
  ["startup.lua"] = "local pendingPath,releasePath=\"/ceetos-updates/pending.lua\",\"/ceetos-updates/release.lua\"local pending if fs.exists(pendingPath)then local loader=loadfile(pendingPath)if loader then local ok,value=pcall(loader)if ok and type(value)==\"table\"then pending=value end end end local function checksum(text)local hash=2166136261 for index=1,#text do hash=(hash*31+text:byte(index))%4294967296 end return string.format(\"%08x\",hash)end local function recoveryAgent()local root,descriptor=\"/ceetos-dev/recovery\",\"/ceetos-dev/recovery/slots.lua\"local source=\"/ceetos/recovery/agent.lua\"if not fs.exists(source)then return nil end if not fs.exists(root)then fs.makeDir(root)end local slots={}if fs.exists(descriptor)then local handle=fs.open(descriptor,\"r\")if handle then slots=textutils.unserialise(handle.readAll())or{};handle.close()end end slots.active=slots.active==\"a\"and\"a\"or\"b\"local inactive=slots.active==\"a\"and\"b\"or\"a\"local input=fs.open(source,\"r\")local text=input and input.readAll()or nil if input then input.close()end if not text then return nil end local candidate=root..\"/agent-\"..inactive..\".lua\"if(slots[inactive]or\"\")~=checksum(text)and load(text,candidate,\"t\")then local temporary=candidate..\".tmp\"local output=fs.open(temporary,\"w\")if output then output.write(text);output.close();if fs.exists(candidate)then fs.delete(candidate)end;fs.move(temporary,candidate);slots[inactive]=checksum(text)end end local active=root..\"/agent-\"..slots.active..\".lua\"local fallback=root..\"/agent-\"..inactive..\".lua\"local activeSlot,fallbackSlot=slots.active,inactive local function validSlot(path,expected)if not fs.exists(path)then return false end local handle=fs.open(path,\"r\");local body=handle and handle.readAll()or nil if handle then handle.close()end return body~=nil and(expected==nil or expected==checksum(body))and load(body,path,\"t\")~=nil end if not validSlot(active,slots[slots.active])then if validSlot(fallback,slots[inactive])then active,fallback,slots.active=fallback,active,inactive activeSlot,fallbackSlot=inactive,activeSlot else return nil end end local out=fs.open(descriptor..\".tmp\",\"w\")if out then out.write(textutils.serialise(slots));out.close();if fs.exists(descriptor)then fs.delete(descriptor)end;fs.move(descriptor..\".tmp\",descriptor)end return{primary=active,fallback=validSlot(fallback,slots[fallbackSlot])and fallback or nil}end local recovery=recoveryAgent()if pending and pending.state==\"apply\"and fs.exists(releasePath)then shell.run(releasePath,\"--ceetos-apply\")elseif recovery then local ok=shell.run(recovery.primary)if ok==false and recovery.fallback then shell.run(recovery.fallback)end elseif fs.exists(\"/ceetos/startup.lua\")then shell.run(\"/ceetos/startup.lua\")else shell.run(\"shell\")end",
  ["ceetos/startup.lua"] = "local root=\"/ceetos\"local profile={id=\"desktop\"}if fs.exists(root..\"/profile.lua\")then local loader=loadfile(root..\"/profile.lua\")if loader then local ok,value=pcall(loader);if ok and type(value)==\"table\"then profile=value end end end if profile.id~=\"desktop\"and fs.exists(root..\"/server.lua\")then shell.run(root..\"/server.lua\")elseif fs.exists(root..\"/ceet.lua\")then shell.run(root..\"/ceet.lua\")else printError(\"CeetOS is incomplete; starting CraftOS shell.\")shell.run(\"shell\")end",
  ["ceetos/profile.lua"] = "return {schema=1,id=\"desktop\"}",
  ["ceetos/ceet.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local net=require(\"ceetos.lib.net\")local peripherals=require(\"ceetos.lib.peripherals\")local telemetry=require(\"ceetos.lib.telemetry\")local audit=require(\"ceetos.lib.audit\")local store=require(\"ceetos.lib.store\")local jobs=require(\"ceetos.lib.jobs\")local crafting=require(\"ceetos.lib.crafting\")local craftSources=require(\"ceetos.lib.craft_sources\")local networkIpc=require(\"ceetos.lib.network_ipc\")local updater=require(\"ceetos.lib.updater\")local profile=require(\"ceetos.lib.profile\")local cloudSync=require(\"ceetos.lib.cloud_sync\")local releaseBroker=require(\"ceetos.lib.release_broker\")local okVersion,version=pcall(require,\"ceetos.lib.version\")version=okVersion and version or{string=\"0.17.1\"}local SHELL_REPLY_PATH=\"/ceetos/data/shell-replies.lua\"local CRAFT_REPLY_PATH=\"/ceetos/data/craft-replies.lua\"local DEV_NETWORK_STATUS=\"/ceetos/data/network-status.lua\"local DEV_NETWORK_HEALTH=\"/ceetos/data/network-service.lua\"local DEV_NETWORK_IPC_DIAG=\"/ceetos/data/network-ipc-status.lua\"local JOB_INBOX=\"/ceetos/data/job-inbox.lua\"local JOB_OUTBOX=\"/ceetos/data/job-outbox.lua\"local CRAFT_STATE=\"/ceetos/data/crafting-state.lua\"local CRAFT_COMMANDS=\"/ceetos/data/crafting-commands\"local CRAFT_COMMAND_LEGACY=\"/ceetos/data/crafting-commands.lua\"local CRAFT_RECIPES=\"/ceetos/data/recipes.lua\"local PROFILE_CACHE=\"/ceetos/data/profile-cache.lua\"local lastJobTemplateSync=0 local lastProfileAdvert=0 local craftRecoveryChecked=false local function writeDevValue(path,value)if not fs.exists(\"/ceetos/data\")then fs.makeDir(\"/ceetos/data\")end local encoded,serialised=pcall(textutils.serialise,value)if not encoded then return false,tostring(serialised)end local handle=fs.open(path,\"w\")if not handle then return false,\"could not open diagnostic state file\"end handle.write(serialised);handle.close()return true end local function craftDefault()return{config={ticker=nil,requester=nil,recipeServer=nil,stockName=nil,requesterName=nil,orderAddress=\"Order\",timeout=120},sources={tickers={},requesters={},recipeServers={},updated=0},stock={},stockUpdated=0,cart={},craftMode=false,queue={},retries={},history={},sequence=0,acknowledgements={}}end local function craftState()local value=store.read(CRAFT_STATE,craftDefault())local defaults=craftDefault()for key,fallback in pairs(defaults)do if value[key]==nil then value[key]=fallback end end for key,fallback in pairs(defaults.config)do if value.config[key]==nil then value.config[key]=fallback end end if not value.config.ticker and value.config.stockName then value.config.ticker={transport=\"local\",name=value.config.stockName}end if not value.config.requester and value.config.requesterName then value.config.requester={transport=\"local\",name=value.config.requesterName}end if not craftRecoveryChecked then craftRecoveryChecked=true if value.active then local active,item=value.active,value.active.items and value.active.items[value.active.index]value.history[#value.history+1]={id=active.id,status=\"interrupted-unconfirmed\",name=item and item.name,requested=active.requested or(item and item.count),accepted=active.accepted,dispatched=active.delivered or 0,destination=active.destination,reason=\"CeetOS restarted; request was not replayed\",finished=os.epoch(\"utc\")}while#value.history>24 do table.remove(value.history,1)end value.active,value.nextRefresh,value.recoveryNotice=nil,0,\"An active Create request was interrupted and not replayed.\"store.write(CRAFT_STATE,value)end end return value end local function saveCraft(value)store.write(CRAFT_STATE,value)end local function craftRecipes()if not profile.capability(\"recipes\")then return nil,nil,\"Craft mode requires a reachable Recipe Server\"end local recipeDb=require((\"ceetos.lib.recipe_db\"))local base,databaseOrErr=recipeDb.loadBase()if not base then return nil,nil,databaseOrErr end local database,overlay=databaseOrErr,{recipes={},tags={}}if fs.exists(CRAFT_RECIPES)then local file=fs.open(CRAFT_RECIPES,\"r\");local raw=file and file.readAll()or nil if file then file.close()end local parsed,err=crafting.parseRecipeOverlay(raw or\"\")if not parsed then return nil,nil,err end overlay=parsed end return recipeDb.mergeOverlay(base,overlay.recipes),recipeDb.mergeTags(database.tags,overlay.tags),nil,overlay end local function peerSourceCandidates()local tickers,requesters={},{}for _,peer in ipairs(net.peers())do local cache=store.read(\"/ceetos/data/remote/\"..tostring(peer.id)..\".lua\",{})for _,item in ipairs(cache.peripherals or{})do local source={transport=\"peer\",peer=tostring(peer.id),name=item.name,type=item.type,mode=item.mode,label=\"Peer \"..tostring(peer.label or peer.id)..\" / \"..tostring(item.name)}local kind=tostring(item.type or\"\"):lower()if kind:find(\"stockticker\",1,true)then tickers[#tickers+1]=source elseif kind:find(\"redstonerequester\",1,true)then requesters[#requesters+1]=source end end end return tickers,requesters end local function recordProfile(peerId,body)if type(body)~=\"table\"or type(body.profile)~=\"string\"or not profile.IDS[body.profile]then return false end local cache=store.read(PROFILE_CACHE,{})cache[tostring(peerId)]={profile=body.profile,version=tostring(body.version or\"\"):sub(1,24),seen=os.epoch(\"utc\")}store.write(PROFILE_CACHE,cache)return true end local function refreshCraftSources(state,queryPeers)local tickers,requesters=craftSources.discoverLocal()local recipeServers={}local peerTickers,peerRequesters=peerSourceCandidates()for _,item in ipairs(peerTickers)do tickers[#tickers+1]=item end for _,item in ipairs(peerRequesters)do requesters[#requesters+1]=item end local profiles=store.read(PROFILE_CACHE,{})for _,peer in ipairs(net.peers())do local advertised=profiles[tostring(peer.id)]if advertised and advertised.profile==\"recipe-server\"then recipeServers[#recipeServers+1]={transport=\"peer\",peer=tostring(peer.id),label=\"Recipe Server \"..tostring(peer.label or peer.id)}end end if cloudSync.recipeOnline()then recipeServers[#recipeServers+1]={transport=\"cloud\",label=\"Cloud Recipe Server\"}end table.sort(recipeServers,function(a,b)local left,right=a.transport==\"cloud\",b.transport==\"cloud\"if left~=right then return not left end return tostring(a.label)<tostring(b.label)end)state.sources={tickers=tickers,requesters=requesters,recipeServers=recipeServers,updated=os.epoch(\"utc\")}if not state.config.recipeServer and#recipeServers>0 then local source=recipeServers[1]state.config.recipeServer={transport=source.transport,peer=source.peer,label=source.label}end if queryPeers then for _,peer in ipairs(net.peers())do net.request(peer.id,\"peripheral_list\",{},{safe=true});net.request(peer.id,\"profile_query\",{},{safe=true})end end end local function sourceAvailable(source,needle)source=craftSources.kind(source)if not source then return false end if source.transport==\"peer\"then local tickers,requesters=peerSourceCandidates()local candidates=needle==\"stockticker\"and tickers or requesters for _,candidate in ipairs(candidates)do if craftSources.key(candidate)==craftSources.key(source)then return true end end return false end return peripheral.isPresent(source.name)and tostring(peripheral.getType(source.name)or\"\"):lower():find(needle,1,true)~=nil end local function pushCraftHistory(state,row)state.history[#state.history+1]=row while#state.history>24 do table.remove(state.history,1)end end local function failCraft(state,reason)local active=state.active local message=tostring(reason or\"unspecified crafting queue failure\")state.error=message if active then local item=active.items and active.items[active.index]pushCraftHistory(state,{id=active.id,status=\"failed\",name=item and item.name,requested=item and item.count,accepted=active.accepted,delivered=active.delivered,destination=active.destination,error=message,finished=os.epoch(\"utc\")})end state.active=nil end local function cancelCraft(state)local active=state.active if not active then return false end local item=active.items and active.items[active.index]pushCraftHistory(state,{id=active.id,status=crafting.cancellationStatus(active.issued),name=item and item.name,requested=active.requested or(item and item.count),accepted=active.accepted,delivered=active.delivered or 0,remaining=active.remaining,destination=active.destination,issued=active.issued==true,reason=active.issued and\"Create package may still arrive\"or\"Cancelled before dispatch\",finished=os.epoch(\"utc\"),})state.active=nil return true end local function completeCraftItem(state)local active=state.active;active.index=active.index+1;active.plan,active.step,active.requested,active.accepted,active.delivered,active.remaining,active.deadline,active.issued,active.issuedKind,active.issuedAt,active.requesterConfigured,active.requesterStrict,active.waitingFor,active.expectedOutput,active.craftStep,active.pendingCraftRequests,active.craftBaseline,active.nextCraftDispatch,active.packageIndex,active.packageRequest,active.peerRequest,active.planRequest=nil,1,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil active.packageRemaining,active.stepAddress,active.stepRoute,active.packageCount=nil,nil,nil,nil if active.index>#active.items then state.active=nil else active.phase=\"prepare\"end end local function applyCraftCommand(state,command)local status,detail=\"ignored\",nil if auth.allowed(\"operator\")then if command.action==\"add\"and type(command.name)==\"string\"and tonumber(command.count)and command.count>0 then crafting.addToCart(state.cart,command.name,command.count);status=\"ok\"elseif command.action==\"remove\"then table.remove(state.cart,tonumber(command.index)or 0);status=\"ok\"elseif command.action==\"edit\"and state.cart[tonumber(command.index)or 0]then state.cart[tonumber(command.index)].count=math.max(1,math.floor(tonumber(command.count)or 1));status=\"ok\"elseif command.action==\"mode\"then if command.value==true and not sourceAvailable(state.config.requester,\"redstonerequester\")then detail=\"Craft mode needs an available Redstone Requester source\"else state.craftMode=command.value==true;status=\"ok\"end elseif command.action==\"destination\"and type(command.value)==\"string\"and#command.value>0 and#command.value<=64 then state.config.orderAddress=command.value;status=\"ok\"elseif command.action==\"submit\"and#state.cart>0 and not state.active then state.sequence=state.sequence+1;state.queue[#state.queue+1]={id=\"craft-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(state.sequence),items=state.cart,craftMode=state.craftMode,destination=state.config.orderAddress};state.cart,state.error={},nil;status=\"ok\"elseif command.action==\"retry\"and state.retries[tonumber(command.index)or 0]and not state.active then local retry=table.remove(state.retries,tonumber(command.index));state.queue[#state.queue+1]=retry;status=\"ok\"elseif command.action==\"cancel_active\"and state.active then cancelCraft(state);status=\"ok\"elseif command.action==\"refresh\"then state.nextRefresh,state.nextSourceRefresh=0,0;status=\"ok\"elseif command.action==\"source\"and(command.target==\"requester\"or command.target==\"recipes\")and command.value==false then if command.target==\"recipes\"then state.config.recipeServer=nil else state.config.requester,state.craftMode=nil,false end state.nextRefresh=0;status=\"ok\"elseif command.action==\"source\"and command.target==\"recipes\"then local source=type(command.value)==\"table\"and command.value or nil if source and source.transport==\"peer\"and type(source.peer)==\"string\"then state.config.recipeServer={transport=\"peer\",peer=source.peer,label=source.label};status=\"ok\"elseif source and source.transport==\"cloud\"then state.config.recipeServer={transport=\"cloud\",label=\"Cloud Recipe Server\"};status=\"ok\"else detail=\"invalid recipe server\"end elseif command.action==\"source\"and(command.target==\"ticker\"or command.target==\"requester\")then local source=craftSources.kind(command.value)if source and type(source.name)==\"string\"then state.config[command.target]=source;state.nextRefresh=0;status=\"ok\"else detail=\"invalid source\"end else detail=\"action unavailable\"end else detail=\"permission denied\"end if type(command.token)==\"string\"and#command.token<=80 then state.acknowledgements[command.token]={ok=status==\"ok\",error=detail,at=os.epoch(\"utc\")}end end local function takeCraftReply(requestId)if not requestId then return nil end store.invalidate(CRAFT_REPLY_PATH)local replies=store.read(CRAFT_REPLY_PATH,{})local reply=replies[requestId]if reply then replies[requestId]=nil;store.write(CRAFT_REPLY_PATH,replies)end return reply end local function newCraftRequestId(prefix)return prefix..\":\"..tostring(os.getComputerID())..\":\"..tostring(os.epoch(\"utc\"))..\":\"..tostring(math.random(1000,9999))end local function requestPeerCraft(source,typeName,body)local requestId=newCraftRequestId(typeName)body.request_id=requestId local ok,err=net.request(source.peer,typeName,body)return ok and requestId or nil,err end local function refreshCraftStock(state,source,now)if not source then return false,\"No Stock Ticker source selected\"end if source.transport~=\"peer\"then if not sourceAvailable(source,\"stockticker\")then return false,\"Selected Stock Ticker is unavailable\"end local ticker=peripheral.wrap(source.name)local ok,stock=pcall(ticker.stock,true)if not ok then return false,tostring(stock)end state.stock,state.stockUpdated,state.error=stock,now,nil return true end local pending=state.stockRequest if pending then local reply=takeCraftReply(pending.id)if reply then state.stockRequest=nil if not reply.ok then return false,tostring(reply.result or\"peer Stock Ticker request failed\")end state.stock,state.stockUpdated,state.error=reply.result or{},now,nil return true end if now-pending.sent>5000 then state.stockRequest=nil;return false,\"Peer Stock Ticker did not respond\"end return false,nil end local requestId,err=requestPeerCraft(source,\"craft_stock_request\",{name=source.name})if not requestId then return false,err end state.stockRequest={id=requestId,sent=now}return false,nil end local function consumeCraftCommands(state)if auth.refreshSession then auth.refreshSession()end if fs.exists(CRAFT_COMMAND_LEGACY)then store.invalidate(CRAFT_COMMAND_LEGACY)for _,command in ipairs(store.read(CRAFT_COMMAND_LEGACY,{}))do applyCraftCommand(state,command)end store.write(CRAFT_COMMAND_LEGACY,{})end if fs.exists(CRAFT_COMMANDS)and fs.isDir(CRAFT_COMMANDS)then local names=fs.list(CRAFT_COMMANDS);table.sort(names)for _,name in ipairs(names)do local path=fs.combine(CRAFT_COMMANDS,name)local handle=fs.open(path,\"r\");local raw=handle and handle.readAll()or nil if handle then handle.close()end fs.delete(path)local command=raw and textutils.unserialise(raw)or nil if type(command)==\"table\"then applyCraftCommand(state,command)end end end local count=0;for _ in pairs(state.acknowledgements)do count=count+1 end while count>32 do for key in pairs(state.acknowledgements)do state.acknowledgements[key]=nil;count=count-1;break end end end local function tickCraftQueue()local state=craftState();consumeCraftCommands(state)local now=os.epoch(\"utc\")if now>=(state.nextSourceRefresh or 0)then refreshCraftSources(state,true)state.nextSourceRefresh=now+8000 end local tickerSource,requesterSource,recipeServer=craftSources.kind(state.config.ticker),craftSources.kind(state.config.requester),state.config.recipeServer local recipes,recipeTags,recipeError,recipeOverlay=craftRecipes()state.recipes,state.recipeTags,state.recipeOverlay=recipes or{},recipeTags or{},recipeOverlay or{recipes={},tags={}}if recipeError and not recipeServer then state.error=recipeError end if not tickerSource then state.error=\"Select a Stock Ticker source\";saveCraft(state);return end if now>=(state.nextRefresh or 0)then local ok,err=refreshCraftStock(state,tickerSource,now)if not ok and err then state.error=err end state.nextRefresh=now+(state.active and 500 or 5000)end if not state.active and#state.queue>0 then state.active=table.remove(state.queue,1);state.active.index,state.active.phase,state.active.step=1,\"prepare\",1 end local active=state.active if active then local item=active.items[active.index]local timeout=(tonumber(state.config.timeout)or 120)*1000 if active.deadline and now>active.deadline and active.phase:find(\"^await_\")then local waiting=active.phase==\"await_crafted_output\"and\"recipe output in Stock Ticker\"or active.phase==\"await_package_confirmation\"and\"Stock Ticker package confirmation\"or\"Stock Ticker delivery confirmation\"failCraft(state,\"timed out waiting for \"..waiting)saveCraft(state)return end if not item then completeCraftItem(state)elseif active.phase==\"prepare\"then if active.craftMode then if recipeServer and recipeServer.transport==\"peer\"then if not active.planRequest then local requestId,err=requestPeerCraft(recipeServer,\"recipe_plan_request\",{item=item.name,quantity=item.count,stock=state.stock})if not requestId then failCraft(state,err)else active.planRequest,active.phase={id=requestId,sent=now,source=recipeServer.peer},\"await_peer_plan\"end saveCraft(state);return end elseif recipeServer and recipeServer.transport==\"cloud\"then local plan,planErr=cloudSync.recipePlan(item.name,item.count,state.stock)if not plan then failCraft(state,planErr or\"cloud Recipe Server is unavailable\")else active.plan,active.step,active.phase=plan,1,\"craft\"end else local plan,planErr=recipes and crafting.plan(recipes,state.stock,item.name,item.count,{forceRoot=true,tags=recipeTags})or nil,recipeError if not plan then failCraft(state,planErr or\"recipe database is unavailable\")else active.plan,active.step,active.phase=plan,1,\"craft\"end end else active.phase=\"deliver\"end elseif active.phase==\"await_peer_plan\"then local pending=active.planRequest;local reply=takeCraftReply(pending and pending.id)if reply then active.planRequest=nil local plan,planErr=reply.ok and crafting.validateExecutionPlan(reply.result)or nil,(reply and reply.result)if not plan then failCraft(state,planErr or\"recipe database did not return a valid plan\")else active.plan,active.step,active.phase=plan,1,\"craft\"end elseif pending and now-(pending.sent or now)>5000 then failCraft(state,\"recipe database did not respond\")end elseif active.phase==\"craft\"then local step=active.plan[active.step]if step then active.stepAddress,active.stepRoute=step.address,(step.dispatch==\"requester\"and\"Requester -> \"or\"Stock Ticker -> \")..tostring(step.address)active.packageCount=step.inputs and#step.inputs or nil end if not step then active.phase=\"deliver\"elseif step.dispatch==\"requester\"and(not requesterSource or not sourceAvailable(requesterSource,\"redstonerequester\"))then failCraft(state,\"Recipe \"..tostring(step.name)..\" needs an available Redstone Requester for Crafter\")elseif step.dispatch==\"package\"then if active.craftStep~=active.step then active.craftStep,active.packageIndex,active.craftBaseline=active.step,1,crafting.normalise(state.stock)[step.name]or 0 end local input=step.inputs and step.inputs[active.packageIndex]if not input then active.phase,active.baseline,active.waitingFor,active.expectedOutput,active.deadline=\"await_crafted_output\",active.craftBaseline,step.name,step.produced,now+timeout state.nextRefresh=0 elseif not active.packageRequest then local baseline=crafting.normalise(state.stock)[input.name]or 0 local requested=active.packageRemaining or input.count local ok,result if tickerSource.transport==\"peer\"then local requestId,err=requestPeerCraft(tickerSource,\"craft_request\",{name=tickerSource.name,destination=step.address,filters={{name=input.name,_requestCount=requested}}})if not requestId then failCraft(state,err)else active.packageRequest,active.phase={id=requestId,input=input,requested=requested,baseline=baseline,sent=now},\"await_peer_package\"end saveCraft(state);return else ok,result=peripherals.craftRequest(\"local\",tickerSource.name,step.address,{{name=input.name,_requestCount=requested}})end local accepted,acceptErr=ok and crafting.acceptedCount(result,requested)or nil,result if not accepted then failCraft(state,acceptErr or\"Stock Ticker rejected package\")else active.issued,active.issuedKind,active.issuedAt=true,\"package\",now active.packageRequest={input=input,baseline=baseline,requested=requested,accepted=accepted,remaining=requested-accepted}active.phase,active.waitingFor,active.deadline=\"await_package_confirmation\",input.name,now+timeout state.nextRefresh=0 end end else if active.craftStep~=active.step then active.craftStep,active.pendingCraftRequests,active.craftBaseline,active.nextCraftDispatch=active.step,step.batches,crafting.normalise(state.stock)[step.name]or 0,0 end if now>=(active.nextCraftDispatch or 0)then local ok,result if requesterSource.transport==\"peer\"then if not active.peerRequest then local requestId,err=requestPeerCraft(requesterSource,\"craft_recipe_request\",{name=requesterSource.name,address=step.address,batches=1,grid=step.grid})if not requestId then failCraft(state,err)else active.peerRequest,active.phase={id=requestId,kind=\"craft\",sent=now},\"await_peer_craft\"end end saveCraft(state);return else ok,result=peripherals.craftingRecipeRequest(\"local\",requesterSource.name,step.address,1,step.grid)end if not ok then failCraft(state,result)else active.issued,active.issuedKind,active.issuedAt=true,\"craft\",now active.requesterConfigured=type(result)==\"table\"and result.configured==true active.requesterStrict=type(result)==\"table\"and result.strict==true active.pendingCraftRequests=active.pendingCraftRequests-1 active.nextCraftDispatch=now+100 if active.pendingCraftRequests<=0 then active.phase,active.baseline,active.waitingFor,active.expectedOutput,active.deadline=\"await_crafted_output\",active.craftBaseline,step.name,step.produced,now+timeout active.craftStep,active.craftBaseline,active.nextCraftDispatch=nil,nil,nil state.nextRefresh=0 end end end end elseif active.phase==\"await_peer_craft\"then local reply=takeCraftReply(active.peerRequest and active.peerRequest.id)if reply then active.peerRequest=nil if not reply.ok then failCraft(state,reply.result)else local step=active.plan[active.step]active.issued,active.issuedKind,active.issuedAt=true,\"craft\",now active.pendingCraftRequests=active.pendingCraftRequests-1 active.nextCraftDispatch=now+100 if active.pendingCraftRequests<=0 then active.phase,active.baseline,active.waitingFor,active.expectedOutput,active.deadline=\"await_crafted_output\",active.craftBaseline,step.name,step.produced,now+timeout;active.craftStep,active.craftBaseline,active.nextCraftDispatch=nil,nil,nil else active.phase=\"craft\"end end elseif active.peerRequest and now-(active.peerRequest.sent or now)>5000 then failCraft(state,\"Redstone Requester did not respond\")end elseif active.phase==\"await_peer_package\"then local pending=active.packageRequest local reply=takeCraftReply(pending and pending.id)if reply then active.packageRequest=nil local accepted,err=reply.ok and crafting.acceptedCount(reply.result,pending.requested or pending.input.count)or nil,reply.result if not accepted then failCraft(state,err or\"peer Stock Ticker rejected package\")else active.issued,active.issuedKind,active.issuedAt=true,\"package\",now active.packageRequest={input=pending.input,baseline=pending.baseline,requested=pending.requested or pending.input.count,accepted=accepted,remaining=(pending.requested or pending.input.count)-accepted}active.phase,active.waitingFor,active.deadline=\"await_package_confirmation\",pending.input.name,now+timeout state.nextRefresh=0 end elseif pending and now-(pending.sent or now)>5000 then failCraft(state,\"peer Stock Ticker did not respond to package request\")end elseif active.phase==\"await_package_confirmation\"then local package=active.packageRequest if not package then failCraft(state,\"lost package confirmation state\")elseif(crafting.normalise(state.stock)[package.input.name]or 0)<=package.baseline-package.accepted then if package.remaining and package.remaining>0 then active.packageRemaining,active.packageRequest,active.phase=package.remaining,nil,\"craft\"else active.packageIndex,active.packageRemaining,active.packageRequest,active.phase=(active.packageIndex or 1)+1,nil,nil,\"craft\"end else state.nextRefresh=0 end elseif active.phase==\"await_crafted_output\"then local step=active.plan[active.step]if(crafting.normalise(state.stock)[active.waitingFor]or 0)>=active.baseline+step.produced then active.step=active.step+1;active.phase=\"craft\"else state.nextRefresh=0 end elseif active.phase==\"deliver\"then local baseline=crafting.normalise(state.stock)[item.name]or 0 local ok,result if tickerSource.transport==\"peer\"then if not active.peerRequest then local requestId,err=requestPeerCraft(tickerSource,\"craft_request\",{name=tickerSource.name,destination=active.destination,filters={{name=item.name,_requestCount=item.count}}})if not requestId then failCraft(state,err)else active.peerRequest,active.phase={id=requestId,kind=\"delivery\",baseline=baseline,sent=now},\"await_peer_delivery\"end end saveCraft(state);return else ok,result=peripherals.craftRequest(\"local\",tickerSource.name,active.destination,{{name=item.name,_requestCount=item.count}})end local accepted,acceptError if ok then accepted,acceptError=crafting.acceptedCount(result,item.count)else acceptError=result end if not accepted then failCraft(state,acceptError or result)else active.requested,active.accepted,active.delivered,active.remaining=item.count,accepted,0,item.count-accepted active.issued,active.issuedKind,active.issuedAt=true,\"delivery\",now active.phase,active.baseline,active.waitingFor,active.deadline=\"await_delivery_confirmation\",baseline,item.name,now+timeout state.nextRefresh=0 end elseif active.phase==\"await_peer_delivery\"then local reply=takeCraftReply(active.peerRequest and active.peerRequest.id)if reply then local baseline=active.peerRequest.baseline;active.peerRequest=nil local accepted,err=reply.ok and crafting.acceptedCount(reply.result,item.count)or nil,reply.result if not accepted then failCraft(state,err or\"peer Stock Ticker rejected the request\")else active.requested,active.accepted,active.delivered,active.remaining=item.count,accepted,0,item.count-accepted active.issued,active.issuedKind,active.issuedAt=true,\"delivery\",now active.phase,active.baseline,active.waitingFor,active.deadline=\"await_delivery_confirmation\",baseline,item.name,now+timeout;state.nextRefresh=0 end end elseif active.phase==\"await_delivery_confirmation\"then if(crafting.normalise(state.stock)[active.waitingFor]or 0)<=active.baseline-active.accepted then active.delivered=active.accepted local itemResult={id=active.id,status=active.remaining>0 and\"partial-dispatched\"or\"dispatched\",name=item.name,requested=active.requested,accepted=active.accepted,dispatched=active.delivered,remaining=active.remaining,destination=active.destination,finished=os.epoch(\"utc\")}pushCraftHistory(state,itemResult)if active.remaining>0 then state.sequence=state.sequence+1 state.retries[#state.retries+1]={id=\"craft-retry-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(state.sequence),items={{name=item.name,count=active.remaining}},craftMode=active.craftMode,destination=active.destination,retryOf=active.id}end completeCraftItem(state)else state.nextRefresh=0 end end end saveCraft(state)end local function craftingStatus()store.invalidate(CRAFT_STATE)local state=store.read(CRAFT_STATE,craftDefault())local active,item=state.active,state.active and state.active.items and state.active.items[state.active.index]local history=state.history or{}return{active=active and{id=active.id,phase=active.phase,name=item and item.name,requested=active.requested or(item and item.count),accepted=active.accepted,dispatched=active.delivered,remaining=active.remaining,destination=active.destination,issued=active.issued,issuedKind=active.issuedKind,requesterConfigured=active.requesterConfigured,requesterStrict=active.requesterStrict,waitingFor=active.waitingFor,expectedOutput=active.expectedOutput,pendingCraftRequests=active.pendingCraftRequests,stepAddress=active.stepAddress,stepRoute=active.stepRoute,packageIndex=active.packageIndex,packageCount=active.packageCount}or nil,queue=#(state.queue or{}),retries=#(state.retries or{}),error=state.error,recoveryNotice=state.recoveryNotice,recipeServer=state.config and state.config.recipeServer,last=history[#history],stockUpdated=state.stockUpdated,}end local function craftingPeripheralStatus()local state=craftState()refreshCraftSources(state,false)local tickerSource,requesterSource=craftSources.kind(state.config.ticker),craftSources.kind(state.config.requester)local requester=requesterSource and requesterSource.transport~=\"peer\"and peripheral.wrap(requesterSource.name)or nil local encoded=nil if requester and type(requester.getRequest)==\"function\"then local ok,value=pcall(requester.getRequest)if ok and type(value)==\"table\"then for _ in pairs(value)do encoded=(encoded or 0)+1 end end end local configuration=requester and type(requester.getConfiguration)==\"function\"and select(2,pcall(requester.getConfiguration))or nil local address=requester and type(requester.getAddress)==\"function\"and select(2,pcall(requester.getAddress))or nil return{ticker=tickerSource and{name=tickerSource.name,transport=tickerSource.transport,peer=tickerSource.peer,available=sourceAvailable(tickerSource,\"stockticker\")}or nil,requester=requesterSource and{name=requesterSource.name,transport=requesterSource.transport,peer=requesterSource.peer,available=sourceAvailable(requesterSource,\"redstonerequester\"),configuration=configuration,address=address,encodedSlots=encoded}or nil,sources=state.sources}end local function processDevNetworkCommand()local command=networkIpc.take()if type(command)~=\"table\"then return end writeDevValue(DEV_NETWORK_IPC_DIAG,{id=command.id,action=command.action,phase=\"received\",at=os.epoch(\"utc\")})local ok,result,detail=pcall(function()if command.action==\"network_status\"then return net.statusSnapshot()elseif command.action==\"route_status\"then return net.routeStatus(command.target)elseif command.action==\"network_trace\"then return net.transportTrace(command.kind)elseif command.action==\"peripheral_status\"then return{localDevices=peripherals.listLocal(),sharedDevices=peripherals.describe(),crafting=craftingPeripheralStatus()}elseif command.action==\"craft_status\"then return craftingStatus()elseif command.action==\"update_status\"then auth.require(\"operator\");return updater.status()elseif command.action==\"update_check\"then auth.require(\"operator\");return updater.check()elseif command.action==\"update_offers\"then auth.require(\"operator\");return updater.status().offers elseif command.action==\"update_install_latest\"then auth.require(\"operator\");return updater.installLatest()elseif command.action==\"update_download\"then auth.require(\"operator\");return updater.download(command.source)elseif command.action==\"update_cancel\"then auth.require(\"operator\");return updater.cancel()elseif command.action==\"update_clear_cache\"then auth.require(\"operator\");return updater.clearCache()elseif command.action==\"update_apply\"then auth.require(\"operator\")local applied,detail=updater.prepareApply()if not applied then return false,detail end return{reboot=true,detail=detail}elseif command.action==\"broker_status\"then auth.require(\"operator\");return releaseBroker.status()elseif command.action==\"broker_promote\"then auth.require(\"admin\");return releaseBroker.promote(command.ownerKey)elseif command.action==\"broker_revoke\"then auth.require(\"admin\");return releaseBroker.revoke(command.ownerKey)elseif command.action==\"broker_approve\"then auth.require(\"admin\");return releaseBroker.approve(command.session,command.phrase)elseif command.action==\"discovery_start\"then auth.require(\"operator\");return net.startDiscovery(command.mode or\"peer\",command.master or\"initiator\",command.phrase)elseif command.action==\"discovery_join\"then auth.require(\"operator\");return net.joinDiscovery(command.phrase)elseif command.action==\"discovery_confirm\"then auth.require(\"operator\");return net.confirmDiscovery()elseif command.action==\"discovery_cancel\"then auth.require(\"operator\");return net.cancelDiscovery()elseif command.action==\"remote_request\"then auth.require(\"operator\");return net.request(command.target,command.type,command.body or{})elseif command.action==\"auth_send\"then if type(command.target)~=\"string\"or type(command.type)~=\"string\"or type(command.body)~=\"table\"then return false,\"invalid authority request\"end return net.request(command.target,command.type,command.body,{safe=true,confidential=true})end error(\"unknown development network command\")end)if not ok then detail,result=result,nil elseif result==true and detail~=nil then result,detail=detail,nil elseif result==false then ok,detail=false,detail or\"network command failed\"end local replied,replyErr=networkIpc.reply(command.id,{id=command.id,ok=ok,result=ok and result or nil,error=ok and nil or tostring(detail)})if not replied then error(\"could not write network IPC result: \"..tostring(replyErr),0)end writeDevValue(DEV_NETWORK_IPC_DIAG,{id=command.id,action=command.action,phase=\"replied\",ok=ok,at=os.epoch(\"utc\")})networkIpc.prune(32)writeDevValue(DEV_NETWORK_STATUS,net.statusSnapshot())end math.randomseed(os.epoch(\"utc\"))auth.bootstrap()net.start()updater.recover()shell.setPath(\"/ceetos/bin:\"..shell.path())shell.setAlias(\"craftos-programs\",\"/rom/programs/programs.lua\")shell.setAlias(\"craftos-list\",\"/rom/programs/list.lua\")shell.setAlias(\"craftos-delete\",\"/rom/programs/delete.lua\")shell.setAlias(\"craftos-edit\",\"/rom/programs/edit.lua\")shell.setAlias(\"craftos-shell\",\"/ceetos/bin/craftos-shell.lua\")shell.setAlias(\"devices\",\"/ceetos/bin/ceetdevices.lua\")shell.setAlias(\"shareall\",\"/ceetos/bin/ceetshareall.lua\")shell.setAlias(\"unshareall\",\"/ceetos/bin/ceetunshareall.lua\")shell.setAlias(\"craft\",\"/ceetos/bin/ceetcraft.lua\")local function commandArgs(command)local result={}for token in tostring(command or\"\"):gmatch(\"%S+\")do result[#result+1]=token end return result end local function runCaptured(command)local output,old={},term.current()local capture={}function capture.write(text)output[#output+1]=tostring(text or\"\")end function capture.blit(text)output[#output+1]=tostring(text or\"\")end function capture.setCursorPos()end function capture.setCursorBlink()end setmetatable(capture,{__index=old})term.redirect(capture)local args=commandArgs(command)local ok,result=pcall(function()return shell.run(args[1],table.unpack(args,2))end)term.redirect(old)return ok,result,table.concat(output)end local function jobStatus()local state=jobs.state()local running=0;for _ in pairs(state.running or{})do running=running+1 end return{label=os.getComputerLabel(),capacity=state.capacity or 1,inFlight=running,queueDepth=#(state.queue or{}),available=true}end local function writeJobInbox(job)local inbox=store.read(JOB_INBOX,{})inbox[#inbox+1]=job while#inbox>16 do table.remove(inbox,1)end store.write(JOB_INBOX,inbox)end local function workerJobLoop()while true do store.invalidate(JOB_INBOX)local inbox=store.read(JOB_INBOX,{})local job=table.remove(inbox,1)if job then store.write(JOB_INBOX,inbox)local template=jobs.listTemplates()[job.template]local valid=template and template.revision==job.revision and template.command==job.command local ok,result,output=false,\"template mismatch\",\"\"if valid then ok,result,output=runCaptured(job.command)end local outbox=store.read(JOB_OUTBOX,{})outbox[#outbox+1]={id=job.id,controller=job.controller,ok=valid and ok and result~=false,output=output,error=valid and(ok and nil or tostring(result))or result}while#outbox>16 do table.remove(outbox,1)end store.write(JOB_OUTBOX,outbox)else sleep(0.15)end end end local function chooseWorker()local choices={}for workerId,worker in pairs(jobs.workers())do if worker.healthy and(worker.slots or 0)>0 then choices[#choices+1]=worker end end table.sort(choices,function(a,b)local aLoad,bLoad=(a.inFlight or 0)/math.max(1,a.capacity or 1),(b.inFlight or 0)/math.max(1,b.capacity or 1)if aLoad~=bLoad then return aLoad<bLoad end if(a.hops or 0)~=(b.hops or 0)then return(a.hops or 0)<(b.hops or 0)end return tostring(a.id)<tostring(b.id)end)return choices[1]end local function syncJobTemplates()if tostring(net.controller())~=tostring(os.getComputerID())then return end local payload={controller=net.controller(),templates=jobs.listTemplates()}for _,peer in ipairs(net.peers())do net.request(peer.id,\"job_sync\",payload)end end local function processJobOutbox()store.invalidate(JOB_OUTBOX)local outbox=store.read(JOB_OUTBOX,{})if#outbox==0 then return end store.write(JOB_OUTBOX,{})for _,row in ipairs(outbox)do if tostring(row.controller)==tostring(os.getComputerID())then if row.ok then pcall(jobs.complete,row.id,{output=row.output,ok=true})else pcall(jobs.fail,row.id,row.error or\"worker failed\")end else net.request(row.controller,\"job_result\",row)end end end local function dispatchJobs()if tostring(jobs.controller())~=tostring(net.controller())then jobs.setController(net.controller())end jobs.heartbeat(os.getComputerID(),jobStatus())if tostring(net.controller())~=tostring(os.getComputerID())then net.request(net.controller(),\"job_heartbeat\",jobStatus(),{safe=true})return end jobs.tick()if os.epoch(\"utc\")-lastJobTemplateSync>=10000 then syncJobTemplates();lastJobTemplateSync=os.epoch(\"utc\")end while true do local queued,worker=jobs.nextDispatch(),chooseWorker()if not queued or not worker then break end local ok,assigned=pcall(jobs.assign,queued,worker.id)if not ok then break end assigned.controller=tostring(os.getComputerID())if tostring(worker.id)==tostring(os.getComputerID())then writeJobInbox(assigned)else local sent,err=net.request(worker.id,\"job_dispatch\",assigned)if not sent then pcall(jobs.fail,assigned.id,err)end end end end local function syncAccounts()if auth.centralActive and auth.centralActive()then return end local snapshot=auth.snapshot()for _,peer in ipairs(net.directPeers())do net.request(peer.id,\"account_sync\",snapshot)end end net.publicHandler=function(packet,distance)local ok,err=pcall(function()if tostring(packet.type or\"\"):match(\"^broker_\")then return releaseBroker.handle(packet,distance)end return updater.publicPacket(packet,distance)end)if not ok then audit.log(\"system\",\"update.public_packet_error\",{error=tostring(err):sub(1,120)})end end net.handler=function(from,peer,packet)if packet.type==\"update_query\"or packet.type==\"update_offer\"or packet.type==\"update_chunk_request\"or packet.type==\"update_chunk\"then local ok,err=pcall(updater.authenticatedPacket,from,peer,packet)if not ok then audit.log(\"system\",\"update.packet_error\",{error=tostring(err):sub(1,120)})end return end if packet.type==\"announce\"then print(\"[peer] \"..from..\" is online\"..((packet.body and packet.body.label)and(\" (\"..packet.body.label..\")\")or\"\"))elseif packet.type==\"profile_query\"then net.reply(packet,\"profile_status\",{profile=profile.id(),version=version.string},{safe=true})elseif packet.type==\"profile_status\"then recordProfile(packet.origin or from,packet.body)elseif packet.type==\"peripheral_list\"then net.reply(packet,\"peripheral_list_result\",peripherals.describe(),{safe=true})elseif packet.type==\"peripheral_list_result\"then local origin=packet.origin or from local cache=store.read(\"/ceetos/data/remote/\"..origin..\".lua\",{})cache.peripherals,cache.updated=packet.body or{},os.epoch(\"utc\")store.write(\"/ceetos/data/remote/\"..origin..\".lua\",cache)elseif packet.type==\"peripheral_call\"then local body=packet.body or{}local ok,result=peripherals.call(peer.master,body.name,body.method,body.args)net.reply(packet,\"peripheral_result\",{ok=ok,result=result})elseif packet.type==\"peripheral_result\"then local origin=packet.origin or from local cache=store.read(\"/ceetos/data/remote/\"..origin..\".lua\",{})cache.last_result,cache.updated=packet.body,os.epoch(\"utc\")store.write(\"/ceetos/data/remote/\"..origin..\".lua\",cache)elseif packet.type==\"craft_stock_request\"then local body=packet.body or{}local origin=tostring(packet.origin or from)local ok,result=peripherals.call(peer.master,body.name,\"stock\",{true})net.reply(packet,\"craft_stock_result\",{request_id=body.request_id,ok=ok,result=result},{safe=true})elseif packet.type==\"craft_stock_result\"then local body=packet.body or{}if type(body.request_id)==\"string\"then local replies=store.read(CRAFT_REPLY_PATH,{})replies[body.request_id]={ok=body.ok==true,result=body.result,received=os.epoch(\"utc\"),from=packet.origin or from}store.write(CRAFT_REPLY_PATH,replies)end elseif packet.type==\"recipe_plan_request\"then local body=packet.body or{}local valid=type(body.request_id)==\"string\"and#body.request_id<=120 and type(body.item)==\"string\"and#body.item<=128 and tonumber(body.quantity)and tonumber(body.quantity)>=1 and tonumber(body.quantity)<=256 and type(body.stock)==\"table\"local stockCount=0 for _,row in pairs(type(body.stock)==\"table\"and body.stock or{})do stockCount=stockCount+1 if stockCount>512 or type(row)~=\"table\"or type(row.name or row.id)~=\"string\"or tonumber(row.count or row.amount or row.quantity or 0)==nil then valid=false;break end end local ok,result=false,\"invalid recipe plan request\"if valid then local recipes,tags,err=craftRecipes()if recipes then local plan,planErr=crafting.plan(recipes,body.stock,body.item,math.floor(tonumber(body.quantity)),{forceRoot=true,tags=tags})if plan and#plan<=96 then local encoded=textutils.serialise(plan)if#encoded<=12*1024 then ok,result=true,plan else result=\"recipe plan exceeds remote reply limit\"end else result=planErr or\"recipe plan exceeds remote reply limit\"end else result=err or\"recipe database is unavailable\"end end net.reply(packet,\"recipe_plan_result\",{request_id=body.request_id,ok=ok,result=result},{safe=true})elseif packet.type==\"recipe_plan_result\"then local body=packet.body or{}if type(body.request_id)==\"string\"then local replies=store.read(CRAFT_REPLY_PATH,{})replies[body.request_id]={ok=body.ok==true,result=body.result,received=os.epoch(\"utc\"),from=packet.origin or from}store.write(CRAFT_REPLY_PATH,replies)end elseif packet.type==\"craft_request\"then local body=packet.body or{}local origin=tostring(packet.origin or from)local allowed=net.isDirectController(from,packet)and(peer.role==\"admin\"or peer.role==\"operator\")local ok,result=false,\"craft request is not authorised\"if allowed then ok,result=peripherals.craftRequest(peer.master,body.name,body.destination,body.filters)end net.reply(packet,\"craft_result\",{request_id=body.request_id,ok=ok,result=result})elseif packet.type==\"craft_recipe_request\"then local body=packet.body or{}local origin=tostring(packet.origin or from)local allowed=net.isDirectController(from,packet)and(peer.role==\"admin\"or peer.role==\"operator\")local ok,result=false,\"craft recipe request is not authorised\"if allowed then ok,result=peripherals.craftingRecipeRequest(peer.master,body.name,body.address,body.batches,body.grid)end net.reply(packet,\"craft_result\",{request_id=body.request_id,ok=ok,result=result})elseif packet.type==\"craft_result\"then local body=packet.body or{}if type(body.request_id)==\"string\"then local replies=store.read(CRAFT_REPLY_PATH,{})replies[body.request_id]={ok=body.ok==true,result=body.result,received=os.epoch(\"utc\"),from=packet.origin or from}local count=0;for _ in pairs(replies)do count=count+1 end if count>32 then local oldest,oldestTime for key,row in pairs(replies)do if not oldestTime or(row.received or 0)<oldestTime then oldest,oldestTime=key,row.received or 0 end end if oldest then replies[oldest]=nil end end store.write(CRAFT_REPLY_PATH,replies)end elseif packet.type==\"shell_request\"then if peer.role~=\"admin\"and peer.role~=\"operator\"then return end local command=packet.body and packet.body.command if type(command)~=\"string\"or#command>240 or command:match(\"^%s*nx%s+recover\")then return end audit.log(\"peer:\"..from,\"shell.request\",{command=command,session=packet.body and packet.body.session})print(\"[remote \"..from..\"] \"..command)local ok,result,output=runCaptured(command)if packet.body and packet.body.session then net.reply(packet,\"shell_result\",{session=packet.body.session,ok=ok and result~=false,output=output,error=ok and nil or tostring(result)})end elseif packet.type==\"shell_result\"then local replies=store.read(SHELL_REPLY_PATH,{})replies[#replies+1]={from=from,body=packet.body or{},received=os.epoch(\"utc\")}while#replies>20 do table.remove(replies,1)end store.write(SHELL_REPLY_PATH,replies)elseif packet.type==\"auth_seed_request\"then net.reply(packet,\"auth_seed\",{snapshot=auth.authoritySnapshot(),request_id=packet.body and packet.body.request_id},{safe=true,confidential=true})elseif packet.type==\"auth_authority\"then local ok,err=pcall(auth.acceptAuthority,packet.body)if not ok then audit.log(\"system\",\"auth.authority_rejected\",{error=tostring(err):sub(1,120)})end elseif packet.type==\"auth_login_begin_result\"or packet.type==\"auth_login_proof_result\"or packet.type==\"auth_mutate_result\"then require((\"ceetos.lib.auth_client\")).receive(packet.body)elseif packet.type==\"account_sync\"then local changed,mergeError=auth.merge(packet.body)if changed then audit.log(\"peer:\"..from,\"accounts.sync\",{});syncAccounts()elseif mergeError then audit.log(\"peer:\"..from,\"accounts.sync_rejected\",{})end elseif packet.type==\"job_heartbeat\"then if tostring(net.controller())==tostring(os.getComputerID())then local body=packet.body or{};body.hops=1 jobs.heartbeat(from,body)end elseif packet.type==\"job_sync\"then local body=packet.body or{}if net.isDirectController(from,packet)and tostring(body.controller)==tostring(net.controller())and type(jobs.syncTemplates)==\"function\"then jobs.syncTemplates(body.controller,body.templates or{})end elseif packet.type==\"job_dispatch\"then local body=packet.body or{}if not net.isDirectController(from,packet)or tostring(body.controller)~=tostring(net.controller())then audit.log(\"peer:\"..from,\"jobs.rejected\",{reason=\"not_controller\"});return end local template=jobs.listTemplates()[body.template]if not template or template.revision~=body.revision or template.command~=body.command then audit.log(\"peer:\"..from,\"jobs.rejected\",{reason=\"template_mismatch\"});return end writeJobInbox(body)elseif packet.type==\"job_result\"then if tostring(net.controller())==tostring(os.getComputerID())then local body=packet.body or{}if body.ok then pcall(jobs.complete,body.id,{output=body.output,ok=true})else pcall(jobs.fail,body.id,body.error or\"worker failed\")end end end end local function serviceLoop()local discoveryTimer,accountTimer,jobTimer,craftTimer,updateTimer,cloudTimer=os.startTimer(2),os.startTimer(2),os.startTimer(2),os.startTimer(0.1),os.startTimer(1),os.startTimer(5)local started,lastError=os.epoch(\"utc\"),nil local function health(errorText)if errorText then lastError=tostring(errorText):sub(1,240)end writeDevValue(DEV_NETWORK_HEALTH,{started=started,lastEvent=os.epoch(\"utc\"),healthy=lastError==nil,error=lastError,ipc=networkIpc.status()})end health()while true do local event={os.pullEventRaw()}local handled,handleErr=pcall(net.handle,event)if not handled then health(handleErr)audit.log(\"system\",\"network.packet_error\",{error=tostring(handleErr):sub(1,120)})else health()end local ipcOk,ipcErr=pcall(processDevNetworkCommand)if not ipcOk then health(ipcErr)audit.log(\"system\",\"network.ipc_error\",{error=tostring(ipcErr):sub(1,120)})end if event[1]==\"timer\"and event[2]==discoveryTimer then local tickOk,tickErr=pcall(net.tick)pcall(releaseBroker.tick)if not tickOk then health(tickErr)audit.log(\"system\",\"network.tick_error\",{error=tostring(tickErr):sub(1,120)})end local snapshotOk,snapshot=pcall(net.statusSnapshot)if snapshotOk then local wrote,writeErr=writeDevValue(DEV_NETWORK_STATUS,snapshot)if not wrote then health(writeErr)audit.log(\"system\",\"network.status_persist_error\",{error=tostring(writeErr):sub(1,120)})end else health(snapshot)audit.log(\"system\",\"network.status_error\",{error=tostring(snapshot):sub(1,120)})end discoveryTimer=os.startTimer(2)end if event[1]==\"timer\"and event[2]==accountTimer then syncAccounts()if os.epoch(\"utc\")-lastProfileAdvert>=30000 then for _,peer in ipairs(net.peers())do net.request(peer.id,\"profile_status\",{profile=profile.id(),version=version.string},{safe=true})end lastProfileAdvert=os.epoch(\"utc\")end accountTimer=os.startTimer(10)end if event[1]==\"timer\"and event[2]==jobTimer then processJobOutbox()local ok,err=pcall(dispatchJobs)if not ok then audit.log(\"system\",\"jobs.scheduler_error\",{error=tostring(err)})end jobTimer=os.startTimer(2)end if event[1]==\"timer\"and event[2]==craftTimer then local ok,err=pcall(tickCraftQueue)if not ok then local state=craftState()failCraft(state,\"crafting queue service error: \"..tostring(err))saveCraft(state)audit.log(\"system\",\"crafting.queue_error\",{error=tostring(err)})end craftTimer=os.startTimer(0.1)end if event[1]==\"timer\"and event[2]==updateTimer then local ok,err=pcall(updater.tick)if not ok then health(err)audit.log(\"system\",\"update.service_error\",{error=tostring(err):sub(1,120)})end updateTimer=os.startTimer(1)end if event[1]==\"timer\"and event[2]==cloudTimer then local ok,err=pcall(cloudSync.tick)if not ok then audit.log(\"system\",\"cloud.sync_error\",{error=tostring(err):sub(1,120)})end cloudTimer=os.startTimer(5)end end end local function userDesktop()print(\"CeetOS \"..version.string..\" | computer \"..os.getComputerID()..\" -- starting Desktop\")while true do if fs.exists(\"/ceetos/data/desktop-stop\")then fs.delete(\"/ceetos/data/desktop-stop\")end local ok=shell.run(\"/ceetos/bin/ceetui.lua\")if ok==false and not fs.exists(\"/ceetos/data/desktop-stop\")then printError(\"CeetUI stopped; restarting in 2 seconds...\")sleep(2)elseif fs.exists(\"/ceetos/data/desktop-stop\")then fs.delete(\"/ceetos/data/desktop-stop\")return end end end local function recoveryHealthProof()local path=\"/ceetos-dev/recovery/transaction.lua\"if not fs.exists(path)then return end local handle=fs.open(path,\"r\");local transaction=handle and textutils.unserialise(handle.readAll())or nil if handle then handle.close()end if type(transaction)~=\"table\"or transaction.state~=\"candidate\"or transaction.expectedVersion~=version.string then return end local proof={transaction=transaction.id,version=version.string,profile=profile.id(),at=os.epoch(\"utc\")}local temporary,output=\"/ceetos-dev/recovery/candidate-health.lua.tmp\",fs.open(\"/ceetos-dev/recovery/candidate-health.lua.tmp\",\"w\")if output then output.write(textutils.serialise(proof));output.close();if fs.exists(\"/ceetos-dev/recovery/candidate-health.lua\")then fs.delete(\"/ceetos-dev/recovery/candidate-health.lua\")end;fs.move(temporary,\"/ceetos-dev/recovery/candidate-health.lua\")end end recoveryHealthProof()local function devBridgeLoop()local path=\"/ceetos-dev/connection.lua\"while true do if fs.exists(path)then local handle=fs.open(path,\"r\")local cfg=handle and textutils.unserialise(handle.readAll())or nil if handle then handle.close()end if type(cfg)==\"table\"and type(cfg.url)==\"string\"then local token=type(cfg.token)==\"string\"and cfg.token or\"\"if token~=\"\"then pcall(shell.run,\"/ceetos/bin/ceetdev.lua\",cfg.url,token,\"--background\")else pcall(shell.run,\"/ceetos/bin/ceetdev.lua\",cfg.url,\"--background\")end sleep(3)else sleep(5)end else sleep(5)end end end parallel.waitForAny(serviceLoop,workerJobLoop,userDesktop,devBridgeLoop)",
  ["ceetos/bin/nx.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local net=require(\"ceetos.lib.net\")local peripherals=require(\"ceetos.lib.peripherals\")local telemetry=require(\"ceetos.lib.telemetry\")local cloudSync=require(\"ceetos.lib.cloud_sync\")local ownerService=require(\"ceetos.lib.owner_service\")local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local jobs=require(\"ceetos.lib.jobs\")local networkIpc=require(\"ceetos.lib.network_ipc\")local args={...}local requestSequence=0 local function networkRequest(action,body)requestSequence=requestSequence+1 local request=body or{}request.id=\"nx-\"..tostring(os.getComputerID())..\"-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(requestSequence)request.action=action local submitted,submitErr=networkIpc.submit(request)if not submitted then return false,submitErr or\"CeetOS network service is unavailable\"end local deadline=os.epoch(\"utc\")+5000 while os.epoch(\"utc\")<deadline do local response=networkIpc.poll(request.id,true)if response and response.id==request.id then return response.ok==true,response.result or response.error end sleep(0.1)end return false,\"CeetOS network service did not respond\"end local function usage()print(\"CeetOS: help, gui, craft, whoami, login, logout, users, user add/edit/delete, discover, network, peers, share, unshare, peripherals, remote, jobs, update, broker, telemetry, cloud status|enroll <code>|retry|clear, owner-service, recover\")end local function requireArgs(n)if#args<n then error(\"missing argument\",0)end end local command=args[1]or\"help\"if command==\"help\"then usage()elseif command==\"gui\"then shell.run(\"ceetui\")elseif command==\"craft\"then shell.run(\"ceetcraft\",table.unpack(args,2))elseif command==\"whoami\"then print(auth.current and(auth.current.name..\" (\"..auth.current.role..\")\")or\"not logged in\")elseif command==\"login\"then requireArgs(2);term.write(\"Password: \");local pass=read(\"*\")if auth.login(args[2],pass)then print(\"Logged in.\")else printError(\"Invalid credentials.\")end elseif command==\"logout\"then auth.logout();print(\"Logged out.\")elseif command==\"users\"then auth.require(\"operator\");for _,user in ipairs(auth.list())do print(user.name..\"\\t\"..user.role)end elseif command==\"user\"and args[2]==\"add\"then auth.require(\"operator\");requireArgs(4);term.write(\"Password for \"..args[3]..\": \");local pass=read(\"*\")auth.add(args[3],args[4],pass);audit.log(auth.current.name,\"user.add\",{name=args[3],role=args[4]});print(\"User created.\")elseif command==\"user\"and args[2]==\"edit\"then auth.require(\"operator\");requireArgs(4);auth.setRole(args[3],args[4]);audit.log(auth.current.name,\"user.role\",{name=args[3],role=args[4]});print(\"User role updated.\")elseif command==\"user\"and args[2]==\"delete\"then auth.require(\"operator\");requireArgs(3);auth.remove(args[3]);audit.log(auth.current.name,\"user.delete\",{name=args[3]});print(\"User deleted.\")elseif command==\"peers\"then local ok,result=networkRequest(\"network_status\",{})if not ok then printError(result)else for _,peer in ipairs(result.peers or{})do print(peer.id..\"\\t\"..peer.role..(peer.master and\"\\tmaster\"or\"\")..(peer.routed and\"\\trouted\"or\"\"))end end elseif command==\"discover\"then auth.require(\"operator\")if args[2]==\"status\"then local ok,result=networkRequest(\"network_status\",{});if not ok then printError(result)else print(textutils.serialize(result.discovery or{}))end elseif args[2]==\"cancel\"then local ok,result=networkRequest(\"discovery_cancel\",{});if ok then print(\"Discovery cancelled.\")else printError(result)end elseif args[2]==\"join\"then local ok,result=networkRequest(\"discovery_join\",{phrase=args[3]})if not ok then printError(result)elseif type(result)==\"table\"and result.state==\"candidate\"then print(\"Matching computer found. Run 'nx discover confirm' to pair.\")else print(\"Searching for a matching discovery session.\")end elseif args[2]==\"confirm\"then local ok,err=networkRequest(\"discovery_confirm\",{});if not ok then printError(err)else print(\"Pairing confirmation sent.\")end elseif args[2]==\"start\"then requireArgs(3)local phrase=args[3];local mode=args[4]==\"master\"and\"master\"or\"peer\";local master=args[5]or\"initiator\"local ok,err=networkRequest(\"discovery_start\",{phrase=phrase,mode=mode,master=master})if not ok then printError(err)else print(\"Discovery started. Keep this phrase private and have the other computer enter it.\")end else printError(\"use discover start <phrase> [peer|master] [initiator|joiner], join <phrase>, confirm, cancel, or status\")end elseif command==\"network\"and args[2]==\"status\"then local ok,result=networkRequest(\"network_status\",{});if not ok then printError(result)else print(textutils.serialize(result.transport or{}))end elseif command==\"network\"and args[2]==\"routes\"then local ok,result=networkRequest(\"route_status\",{target=args[3]});if not ok then printError(result)else for _,route in ipairs(result or{})do print(tostring(route.id)..\" via \"..tostring(route.next)..\" / \"..tostring(route.hops)..\" hop [\"..tostring(route.health)..\"]\"..(route.reason and(\" - \"..tostring(route.reason))or\"\"))end end elseif command==\"network\"and args[2]==\"trace\"then local ok,result=networkRequest(\"network_trace\",{kind=args[3]});if not ok then printError(result)else print(textutils.serialize(result))end elseif command==\"update\"then auth.require(\"operator\")local sub=args[2]or\"status\"if sub==\"status\"then local ok,result=networkRequest(\"update_status\",{})if not ok then printError(result)else print(\"CeetOS \"..tostring(result.version)..\" | \"..tostring(result.status or\"idle\"))if result.message then print(tostring(result.message))end if result.cache then print(\"Cached release: \"..tostring(result.cache.version)..\"  \"..tostring(result.cache.fingerprint)..\"  key \"..tostring(result.cache.keyId))end if result.transfer then print(\"Download: \"..tostring(result.transfer.received or 0)..\"/\"..tostring(result.transfer.size)..\" bytes from \"..tostring(result.transfer.label or result.transfer.source))end end elseif sub==\"check\"then local ok,result=networkRequest(\"update_check\",{})if not ok then printError(result)elseif type(result)==\"table\"then print(\"Cloud offers: \"..tostring(result.cloud or 0)..\" | direct mesh query: \"..(result.direct and\"sent\"or\"unavailable\")..\" | routed queries: \"..tostring(result.routed or 0))if result.cloudError then printError(\"Cloud check failed: \"..tostring(result.cloudError))end else print(\"Signed release check started.\")end elseif sub==\"offers\"then local ok,result=networkRequest(\"update_offers\",{})if not ok then printError(result)elseif#result==0 then print(\"No newer signed releases discovered.\")else for _,offer in ipairs(result)do print(tostring(offer.id)..\"\\t\"..tostring(offer.label)..\"\\t\"..tostring(offer.version)..\"\\t\"..tostring(offer.size)..\" bytes\\t\"..tostring(offer.fingerprint)..\"\\t\"..tostring(offer.keyId)..\"\\t\"..tostring(offer.transport))end end elseif sub==\"download\"then requireArgs(3)local ok,result=networkRequest(\"update_download\",{source=args[3]})if ok then print(\"Download started. Run 'nx update status' to follow verified progress.\")else printError(result)end elseif sub==\"latest\"then local ok,result=networkRequest(\"update_install_latest\",{})if ok then print(\"Highest compatible signed release is downloading. Review it with 'nx update status', then run 'nx update apply'.\")else printError(result)end elseif sub==\"cancel\"then local ok,result=networkRequest(\"update_cancel\",{});if ok then print(\"Update download cancelled.\")else printError(result)end elseif sub==\"clear-cache\"then local ok,result=networkRequest(\"update_clear_cache\",{});if ok then print(\"Verified release cache cleared.\")else printError(result)end elseif sub==\"apply\"then local ok,status=networkRequest(\"update_status\",{})if not ok then printError(status)elseif not status.cache then printError(\"No verified signed release is cached.\")else print(\"Apply CeetOS \"..tostring(status.cache.version)..\" from verified cache\")print(\"Fingerprint: \"..tostring(status.cache.fingerprint)..\"  Key: \"..tostring(status.cache.keyId))term.write(\"Type APPLY to reboot and install locally: \")if read()~=\"APPLY\"then print(\"Cancelled.\")else local prepared,result=networkRequest(\"update_apply\",{})if not prepared then printError(result)else print(\"Verified update approved; rebooting locally.\");os.reboot()end end end else printError(\"use update status|check|offers|download <source>|latest|apply|cancel|clear-cache\")end elseif command==\"broker\"then local sub=args[2]or\"status\"if sub==\"status\"then local ok,result=networkRequest(\"broker_status\",{})if not ok then printError(result)else print(\"Release broker: \"..(result.enabled and\"enabled\"or\"disabled\")..\" | Cloud: \"..(result.enrolled and\"enrolled\"or\"not enrolled\"))for _,row in ipairs(result.pending or{})do print(\"Pending \"..row.id..\" from \"..row.label..\" (\"..row.profile..\")\")end end elseif sub==\"enable\"then auth.require(\"admin\");requireArgs(3)local ok,result=networkRequest(\"broker_promote\",{ownerKey=args[3]})if ok then print(\"This enrolled node is now a trusted release broker.\")else printError(result)end elseif sub==\"disable\"then auth.require(\"admin\");requireArgs(3)local ok,result=networkRequest(\"broker_revoke\",{ownerKey=args[3]})if ok then print(\"Release broker revoked.\")else printError(result)end elseif sub==\"approve\"then auth.require(\"admin\");requireArgs(4)local ok,result=networkRequest(\"broker_approve\",{session=args[3],phrase=args[4]})if ok then print(\"Bootstrap proof sent; waiting for the fresh computer to complete.\")else printError(result)end else printError(\"use broker status|enable <owner-key>|disable <owner-key>|approve <session> <phrase>\")end elseif command==\"pair\"then printError(\"legacy ID/code pairing is disabled. Use 'nx discover start <phrase>' and 'nx discover join <phrase>'.\")elseif command==\"share\"then auth.require(\"operator\");requireArgs(2)if args[2]==\"all\"then print(\"Shared \"..peripherals.shareAll(args[3]==\"master\"and\"master\"or\"peer\")..\" peripherals\")else peripherals.share(args[2],args[3]or\"peer\");print(\"Shared \"..args[2])end elseif command==\"unshare\"then auth.require(\"operator\");requireArgs(2)if args[2]==\"all\"then print(\"Unshared \"..peripherals.unshareAll()..\" peripherals\")else peripherals.unshare(args[2]);print(\"Unshared \"..args[2])end elseif command==\"peripherals\"then for _,p in ipairs(peripherals.describe())do print(p.name..\"\\t\"..p.type..\"\\t\"..p.mode)end elseif command==\"remote\"then auth.require(\"operator\");requireArgs(3)local peer,mode=args[2],args[3]if mode==\"peripherals\"then local ok,err=networkRequest(\"remote_request\",{target=peer,type=\"peripheral_list\",body={}});if not ok then printError(err)else print(\"Peripheral query sent. Run 'nx remote \"..peer..\" cache' after the reply arrives.\")end elseif mode==\"cache\"then local cache=store.read(\"/ceetos/data/remote/\"..peer..\".lua\",{})if not cache.peripherals then print(\"No peripheral cache for peer \"..peer..\"; run 'nx remote \"..peer..\" peripherals' first.\")else for _,p in ipairs(cache.peripherals)do print(p.name..\"\\t\"..p.type..\"\\t\"..p.mode)end end elseif mode==\"call\"then requireArgs(5)local values={}for i=6,#args do values[#values+1]=tonumber(args[i])or args[i]end local ok,err=networkRequest(\"remote_request\",{target=peer,type=\"peripheral_call\",body={name=args[4],method=args[5],args=values}})if not ok then printError(err)else print(\"Peripheral call sent; the result will be displayed and cached when it arrives.\")end else local cmd=table.concat(args,\" \",3);local ok,err=networkRequest(\"remote_request\",{target=peer,type=\"shell_request\",body={command=cmd}});if not ok then printError(err)else print(\"Request sent.\")end end elseif command==\"jobs\"then local sub=args[2]or\"status\"local function controllerOnly()auth.require(\"admin\")assert(tostring(net.controller())==tostring(os.getComputerID()),\"this computer is not the network job controller (\"..tostring(net.controller())..\")\")end if sub==\"status\"then auth.require(\"operator\")local state=jobs.state();print(\"Controller: \"..tostring(net.controller())..\" | queue: \"..#(state.queue or{}))for id,worker in pairs(jobs.workers())do print(tostring(id)..\"\\t\"..tostring(worker.inFlight or 0)..\"/\"..tostring(worker.capacity or 1)..\"\\t\"..(worker.healthy and\"healthy\"or\"stale\"))end elseif sub==\"history\"then auth.require(\"operator\")for _,item in ipairs(jobs.history())do print(item.id..\"\\t\"..item.template..\"\\t\"..item.status..\"\\t\"..tostring(item.result and(item.result.error or item.result.output)or\"\"):sub(1,100))end elseif sub==\"templates\"then auth.require(\"operator\")for name,item in pairs(jobs.listTemplates())do print(name..\"\\t\"..(item.enabled==false and\"off\"or\"on\")..\"\\t\"..(item.retrySafe and\"retry-safe\"or\"no-retry\"))end elseif sub==\"template\"and args[3]==\"add\"then controllerOnly();requireArgs(5);local commandLine=table.concat(args,\" \",5)local template=jobs.addTemplate(args[4],commandLine,{});audit.log(auth.current.name,\"jobs.template_add\",{name=template.name});print(\"Template added.\")elseif sub==\"template\"and args[3]==\"retry-safe\"then controllerOnly();requireArgs(5);jobs.setTemplateRetrySafe(args[4],args[5]==\"on\");print(\"Retry policy updated.\")elseif sub==\"template\"and args[3]==\"enable\"then controllerOnly();requireArgs(5);jobs.setTemplateEnabled(args[4],args[5]~=\"off\");print(\"Template state updated.\")elseif sub==\"run\"then controllerOnly();requireArgs(3);local job=jobs.enqueue(args[3]);print(\"Queued \"..job.id)elseif sub==\"schedule\"then controllerOnly();requireArgs(4);local schedule=jobs.schedule(args[3],tonumber(args[4]));print(\"Scheduled \"..schedule.id)elseif sub==\"cancel\"then controllerOnly();requireArgs(3);jobs.cancel(args[3]);print(\"Schedule cancelled.\")elseif sub==\"capacity\"then auth.require(\"admin\");requireArgs(3);print(\"Worker capacity: \"..jobs.setCapacity(tonumber(args[3])))elseif sub==\"controller\"then controllerOnly();requireArgs(3);print(\"Controller: \"..net.setController(args[3]))else printError(\"use jobs status|history|templates|template add <name> <fixed command>|template retry-safe <name> on|off|run <name>|schedule <name> <seconds>|cancel <id>|capacity <slots>|controller <id>\")end elseif command==\"telemetry\"then requireArgs(2)if args[2]==\"status\"then auth.require(\"operator\")local status=cloudSync.status()print(\"Telemetry: \"..(telemetry.status()and\"enabled\"or\"disabled\")..\" | enrolled \"..(status.enrolled and\"yes\"or\"no\"))print(\"Last report: \"..tostring(status.telemetryLastSuccess or\"never\")..\" | next: \"..tostring(status.telemetryNext or\"disabled\"))if status.telemetryLastError then print(\"Last telemetry error: \"..status.telemetryLastError)end elseif args[2]==\"on\"or args[2]==\"off\"then auth.require(\"admin\");telemetry.setEnabled(args[2]==\"on\");audit.log(auth.current.name,\"telemetry\",{enabled=args[2]==\"on\"});print(\"Telemetry \"..args[2])else error(\"use telemetry status, telemetry on, or telemetry off\",0)end elseif command==\"cloud\"then local sub=args[2]or\"status\"if sub==\"status\"then auth.require(\"operator\")local status=cloudSync.status()print(\"Cloud: \"..(status.enrolled and\"enrolled\"or\"not enrolled\")..\" | auth \"..(status.authOnline and\"online\"or\"offline\")..\" | recipes \"..(status.recipeOnline and\"online\"or\"offline\"))if status.node then print(\"Node: \"..status.node)end if status.lastError then print(\"Last error: \"..status.lastError)end print(\"Telemetry: \"..(status.telemetryEnabled and\"enabled\"or\"disabled\")..\" | last \"..tostring(status.telemetryLastSuccess or\"never\")..\" | next \"..tostring(status.telemetryNext or\"disabled\"))print(\"Dashboard: https://dash.ceet.uk (Cloudflare Access)\")elseif sub==\"enroll\"then auth.require(\"admin\");requireArgs(3)local status,err=cloudSync.enroll(args[3]);if not status then printError(err)else audit.log(auth.current.name,\"cloud.enroll\",{node=status.node});print(\"Cloud node enrollment saved. Background sync is enabled.\")end elseif sub==\"retry\"then auth.require(\"operator\")local ok,err=cloudSync.tick(\"manual\");if ok then print(\"Cloud sync requested.\")else printError(err)end elseif sub==\"clear\"then auth.require(\"admin\")local ok,err=cloudSync.clear();if ok then audit.log(auth.current.name,\"cloud.clear\",{});print(\"Cloud enrollment removed.\")else printError(err)end else error(\"use cloud status|enroll <one-time-code>|retry|clear\",0)end elseif command==\"owner-service\"then auth.require(\"admin\")local sub=args[2]or\"status\"if sub==\"status\"then local status=ownerService.status()print(\"Owner service: \"..(status.enabled and\"enabled\"or\"disabled\")..\" | \"..(status.provisioned and\"provisioned\"or\"sealed\"))if status.owner then print(\"Owner: \"..status.owner)end print(\"Actions: \"..table.concat(status.actions or{},\", \"))elseif sub==\"on\"or sub==\"off\"then ownerService.setEnabled(sub==\"on\")audit.log(auth.current.name,\"owner-service.enabled\",{enabled=sub==\"on\"})print(\"Owner service \"..sub..\".\")elseif sub==\"set-token\"then term.write(\"Owner-service token: \");local token=read(\"*\")term.write(\"Repeat token: \");local repeatToken=read(\"*\")assert(token==repeatToken,\"tokens do not match\")ownerService.provision(token,auth.current.name)audit.log(auth.current.name,\"owner-service.provision\",{})print(\"Owner service provisioned. Configure the same secret in CEETOS_SERVICE_TOKENS on the dashboard.\")elseif sub==\"rotate-token\"then local token=ownerService.rotate(auth.current.name)audit.log(auth.current.name,\"owner-service.rotate\",{})print(\"New owner-service token (shown once): \"..token)print(\"Update CEETOS_SERVICE_TOKENS on the dashboard before making remote requests.\")else error(\"use owner-service status|on|off|set-token|rotate-token\",0)end elseif command==\"recover\"and args[2]==\"enable\"then auth.require(\"admin\");local minutes=tonumber(args[3])or 10;assert(minutes>0 and minutes<=60,\"minutes must be 1-60\")store.write(\"/ceetos/data/recovery.lua\",{until_ts=os.epoch(\"utc\")+minutes*60000});audit.log(auth.current.name,\"recovery.enable\",{minutes=minutes});print(\"Recovery access enabled for \"..minutes..\" minutes.\")elseif command==\"recover\"and args[2]==\"reset\"then requireArgs(3)local recovery=store.read(\"/ceetos/data/recovery.lua\",{})assert((recovery.until_ts or 0)>os.epoch(\"utc\"),\"recovery window is not active\")term.write(\"New password for \"..args[3]..\": \");local pass=read(\"*\")assert(#pass>=8,\"password must contain at least 8 characters\")auth.resetPassword(args[3],pass)audit.log(\"local-recovery\",\"password.reset\",{name=args[3]})print(\"Password reset. The recovery window remains active until it expires.\")else usage()end",
  ["ceetos/bin/ceetui.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local gui=require(\"ceetos.lib.gui\")local auth=require(\"ceetos.lib.auth\")local net=require(\"ceetos.lib.net\")local peripherals=require(\"ceetos.lib.peripherals\")local telemetry=require(\"ceetos.lib.telemetry\")telemetry.markActivity(\"desktop\")local cloudSync=require(\"ceetos.lib.cloud_sync\")local audit=require(\"ceetos.lib.audit\")local store=require(\"ceetos.lib.store\")local files=require(\"ceetos.lib.files\")local clipboard=require(\"ceetos.lib.clipboard\")local networkIpc=require(\"ceetos.lib.network_ipc\")local terminalUi=require(\"ceetos.lib.terminal_ui\")local release=require(\"ceetos.lib.release_verify\")local launch={...}local state=gui.newState()local page=launch[1]==\"files\"and\"files\"or\"home\"if page==\"files\"and launch[2]and fs.exists(launch[2])then local target=launch[2]state.path=fs.isDir(target)and target or fs.getDir(target)state.selected=\"file:\"..target end local banner,targets,currentModel=nil,{},nil local remotePending=nil local function deps()return{auth=auth,net=net,peripherals=peripherals,telemetry=telemetry,cloud=cloudSync,audit=audit,files=files}end local function refresh(message,error)banner=message and{text=message,error=error}or nil currentModel=gui.model(page,deps(),state)targets=gui.draw(currentModel,state,banner)end local function prompt(label,secret)local _,height=term.getSize()term.setCursorPos(1,height);term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clearLine()term.write(label..\": \")return read(secret and\"*\"or nil)end local function fill(x,y,width,height,background)return terminalUi.fill(x,y,width,height,background)end local function choose(label,options)if#options==0 then return nil end local selected=1 local function draw()gui.draw(currentModel,state,banner)local width,height=term.getSize();local boxWidth=math.max(28,math.min(width-4,42));local x=math.max(2,math.floor((width-boxWidth)/2));local y=math.max(3,math.floor((height-math.min(#options+4,height-4))/2))fill(x,y,boxWidth,math.min(#options+4,height-4),colors.black)term.setTextColor(colors.white);term.setCursorPos(x+2,y+1);term.write(label:sub(1,boxWidth-4))for index,option in ipairs(options)do if y+index+1<height then term.setBackgroundColor(index==selected and colors.gray or colors.black);term.setTextColor(colors.white);term.setCursorPos(x+2,y+index+1);term.write(tostring(option.label or option):sub(1,boxWidth-4))end end return x,y,boxWidth end local x,y,boxWidth=draw()while true do local event,first,second,third=os.pullEvent()if event==\"key\"then local key=keys.getName(first)if key==\"up\"then selected=math.max(1,selected-1);x,y,boxWidth=draw()elseif key==\"down\"then selected=math.min(#options,selected+1);x,y,boxWidth=draw()elseif key==\"enter\"then return options[selected].value or options[selected]elseif key==\"backspace\"then return nil end elseif event==\"mouse_click\"and second>=x and second<=x+boxWidth and third>=y+2 and third<=y+#options+1 then local index=third-y-1;if options[index]then return options[index].value or options[index]end elseif event==\"term_resize\"then x,y,boxWidth=draw()end end end local networkRequestCounter=0 local function networkRequest(action,payload)networkRequestCounter=networkRequestCounter+1 local request=payload or{}request.id=\"ui-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(networkRequestCounter)request.action=action local submitted,submitErr=networkIpc.submit(request)if not submitted then return false,submitErr or\"CeetOS network service is unavailable\"end local deadline=os.epoch(\"utc\")+5000 while os.epoch(\"utc\")<deadline do local result=networkIpc.poll(request.id,true)if result and result.id==request.id then return result.ok==true,result.result or result.error end sleep(0.1)end return false,\"CeetOS network service did not respond\"end local function displayRemoteResult(result)if type(result)~=\"table\"then return tostring(result or\"\")end if result.ok==false then return tostring(result.result or result.error or\"request failed\")end local value=result.result local text=type(value)==\"table\"and textutils.serialise(value,{compact=true})or tostring(value)return terminalUi.clean(text):sub(1,240)end local function confirm(label)local function draw()gui.draw(currentModel,state,banner)local width,height=term.getSize()local boxWidth=math.min(width-4,math.max(28,#label+4))local boxHeight,x,y=6,math.floor((width-boxWidth)/2)+1,math.max(3,math.floor((height-6)/2))fill(x,y,boxWidth,boxHeight,colors.black)term.setTextColor(colors.white);term.setCursorPos(x+2,y+1);term.write(label:sub(1,boxWidth-4))local confirmX,cancelX=x+2,x+math.floor(boxWidth/2)+1 term.setBackgroundColor(colors.green);term.setTextColor(colors.black);term.setCursorPos(confirmX,y+4);term.write(\" Confirm \")term.setBackgroundColor(colors.gray);term.setTextColor(colors.white);term.setCursorPos(cancelX,y+4);term.write(\" Cancel \")term.setBackgroundColor(colors.black);term.setTextColor(colors.lightGray);term.setCursorPos(x+2,y+2);term.write(\"Click a choice or press Enter / Backspace\")term.setTextColor(colors.white)return{confirmX=confirmX,cancelX=cancelX,y=y+4}end local modal=draw()while true do local event,first,second,third=os.pullEvent()if event==\"mouse_click\"and third==modal.y then if second>=modal.confirmX and second<=modal.confirmX+8 then return true end if second>=modal.cancelX and second<=modal.cancelX+7 then return false end elseif event==\"key\"then local key=keys.getName(first)if key==\"enter\"or key==\"y\"then return true end if key==\"backspace\"or key==\"n\"then return false end elseif event==\"char\"then if first:lower()==\"y\"then return true elseif first:lower()==\"n\"then return false end elseif event==\"term_resize\"then modal=draw()end end end local function chooseRole()local roles={\"viewer\",\"operator\",\"admin\"}local function draw()local width,height=term.getSize();local boxWidth=30;local x,y=math.max(2,math.floor((width-boxWidth)/2)),math.max(3,math.floor((height-8)/2))fill(x,y,boxWidth,8,colors.black)term.setTextColor(colors.white);term.setCursorPos(x+2,y+1);term.write(\"Choose account role\")for index,roleName in ipairs(roles)do term.setBackgroundColor(index==1 and colors.gray or colors.black);term.setTextColor(colors.white);term.setCursorPos(x+2,y+index+1);term.write(\"[\"..index..\"] \"..roleName)end term.setBackgroundColor(colors.black);term.setTextColor(colors.gray);term.setCursorPos(x+2,y+6);term.write(\"Click a role or press 1-3 / Backspace\")return x,y end local x,y=draw()while true do local event,first,second,third=os.pullEvent()if event==\"char\"then local index=tonumber(first);if index and roles[index]then return roles[index]end elseif event==\"mouse_click\"and second>=x+1 and second<=x+18 and third>=y+2 and third<=y+4 then return roles[third-y-1]elseif event==\"key\"and keys.getName(first)==\"backspace\"then return nil elseif event==\"term_resize\"then x,y=draw()end end end local function values(text)local out={}for item in(text or\"\"):gmatch(\"[^,]+\")do out[#out+1]=tonumber(item)or item end return out end local function openMenu(item)local items=gui.context(item)if#items==0 then return refresh(\"No actions available for \"..tostring(item and item.label or\"item\"),true)end state.menu={items=items,selected=1}refresh()end local function cacheFor(peer)local cachePath=\"/ceetos/data/remote/\"..tostring(peer)..\".lua\"store.invalidate(cachePath)return store.read(cachePath,{}),cachePath end local function beginRemoteRequest(kind,peer,body,continueCall)networkRequestCounter=networkRequestCounter+1 local requested=os.epoch(\"utc\")local request={id=\"ui-remote-\"..tostring(requested)..\"-\"..tostring(networkRequestCounter),action=\"remote_request\",target=peer,type=kind==\"list\"and\"peripheral_list\"or\"peripheral_call\",body=body,}local sent,err=networkIpc.submit(request)if not sent then state.remoteResult={status=\"error\",error=true,peer=tostring(peer),text=err or\"CeetOS network service is unavailable\"}return false end local cache,cachePath=cacheFor(peer)remotePending={kind=kind,peer=peer,body=body,continueCall=continueCall==true,id=request.id,requested=requested,cachePath=cachePath,phase=\"dispatch\",deadline=requested+5000,cache=cache}state.remoteResult={status=\"pending\",pending=true,peer=tostring(peer),device=body and body.name,method=body and body.method,text=kind==\"list\"and\"Requesting peripheral list...\"or\"Calling remote peripheral...\"}return true end local function chooseRemoteCall(peer,cache)local choices={}for _,item in ipairs(cache.peripherals or{})do choices[#choices+1]={label=tostring(item.name)..\" (\"..tostring(item.type or\"unknown\")..\")\",value=item}end local device=choose(\"Choose peripheral\",choices);if not device then return false end local methods={};for _,method in ipairs(device.methods or{})do methods[#methods+1]={label=method,value=method}end local method=choose(\"Choose function\",methods);if not method then return false end return beginRemoteRequest(\"call\",peer.id or peer,{name=device.name,method=method,args=values(prompt(\"Arguments (comma separated)\"))})end local function pollRemoteRequest()if not remotePending then return false end local pending,now=remotePending,os.epoch(\"utc\")if now>=pending.deadline then state.remoteResult={status=\"error\",error=true,peer=tostring(pending.peer),device=pending.body and pending.body.name,method=pending.body and pending.body.method,text=pending.kind==\"list\"and\"No peripheral-list reply received\"or\"No peripheral-call reply received\"}remotePending=nil return true end if pending.phase==\"dispatch\"then local result=networkIpc.poll(pending.id,true)if result then if result.ok~=true then state.remoteResult={status=\"error\",error=true,peer=tostring(pending.peer),text=tostring(result.error or\"Remote request was rejected\")}remotePending=nil return true end pending.phase=\"reply\"return true end return false end store.invalidate(pending.cachePath)local cache=store.read(pending.cachePath,{})if cache.updated and cache.updated>=pending.requested and(pending.kind~=\"list\"or type(cache.peripherals)==\"table\")and(pending.kind~=\"call\"or cache.last_result~=nil)then remotePending=nil if pending.kind==\"list\"and pending.continueCall then state.remoteResult={status=\"ready\",peer=tostring(pending.peer),text=\"Peripheral list received. Choose a device.\"}chooseRemoteCall({id=pending.peer},cache)elseif pending.kind==\"list\"then state.remoteResult={status=\"ready\",peer=tostring(pending.peer),text=tostring(#(cache.peripherals or{}))..\" shared peripherals available\"}else local result=cache.last_result state.remoteResult={status=result and result.ok==false and\"error\"or\"complete\",error=result and result.ok==false or false,peer=tostring(pending.peer),device=pending.body and pending.body.name,method=pending.body and pending.body.method,text=displayRemoteResult(result)}end return true end return false end local function run(action)state.menu=nil if action:sub(1,5)==\"page:\"then page=action:sub(6);state.selected=nil;return refresh()end if action==\"terminal\"then term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)local ok,result=pcall(shell.run,\"/ceetos/bin/ceetshell.lua\")if not ok or result==false then return refresh(\"Terminal failed to start: \"..tostring(result or\"runtime error\"),true)end return refresh()end if action==\"crafting\"then term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)local ok,result=pcall(shell.run,\"/ceetos/bin/ceetcraft.lua\")if not ok or result==false then return refresh(\"Crafting console failed to start\",true)end return refresh()end if action==\"peripheral_view\"then state.peripheralView=true;state.selected=nil;return refresh()end if action==\"trash_open\"then state.trash=true;state.selected=nil;return refresh()end if action:sub(1,3)==\"up:\"then state.path=table.remove(state.history)or action:sub(4);state.selected=nil;return refresh()end if action:sub(1,4)==\"dir:\"then state.history[#state.history+1]=state.path;state.path=action:sub(5);state.selected=nil;return refresh()end if action:sub(1,4)==\"run:\"then if not auth.allowed(\"viewer\")then return refresh(\"Login required to run programs\",true)end local path=action:sub(5)if not files.runnable(path)then return refresh(\"This file is not a runnable Lua program\",true)end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)shell.run(\"/ceetos/bin/ceetlaunch.lua\",path)return refresh()end if action:sub(1,5)==\"edit:\"then local path=action:sub(6)term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)shell.run(\"/ceetos/bin/ceetedit.lua\",path)return refresh()end local ok,result=pcall(function()if action:sub(1,11)==\"copy_label:\"then local id=action:sub(12);local item=currentModel and gui.selected(currentModel,state)if item and item.id==id then clipboard.set(item.label or\"\");return\"Copied\"end return\"Nothing selected\"elseif action:sub(1,11)==\"copy_text:\"then clipboard.set(action:sub(12));return\"Copied\"elseif action==\"remote_result_copy\"then local result=state.remoteResult if not result or not result.text then return\"No remote result to copy\"end clipboard.set(result.text);return true elseif action==\"remote_result_clear\"then state.remoteResult=nil;return true elseif action:sub(1,7)==\"rename:\"then auth.require(\"operator\")local path,name=action:sub(8),prompt(\"New name\")if not confirm(\"Rename \"..fs.getName(path)..\" to \"..name)then return\"Cancelled\"end local target=files.rename(path,name);state.selected=\"file:\"..target;return target elseif action:sub(1,6)==\"trash:\"then auth.require(\"operator\")local path=action:sub(7)if not confirm(\"Move \"..fs.getName(path)..\" to Trash\")then return\"Cancelled\"end local id=files.moveToTrash(path);state.selected=nil;return\"Moved to Trash\"elseif action:sub(1,8)==\"restore:\"then auth.require(\"operator\")local path=files.restore(action:sub(9));return\"Restored \"..fs.getName(path)elseif action:sub(1,13)==\"delete_trash:\"then auth.require(\"operator\")if not confirm(\"Delete this Trash item permanently\")then return\"Cancelled\"end files.deleteTrash(action:sub(14));return true elseif action==\"new_folder\"then auth.require(\"operator\")local name=prompt(\"Folder name\")if not confirm(\"Create folder \"..name)then return\"Cancelled\"end return files.makeDirectory(state.path,name)elseif action==\"empty_trash\"then auth.require(\"operator\")if not confirm(\"Permanently delete all Trash items\")then return\"Cancelled\"end files.emptyTrash();return true elseif action==\"start_discovery\"then local phrase=prompt(\"Choose discovery phrase\")local mode=prompt(\"Mode (peer/master)\")local master=mode==\"master\"and prompt(\"Master side (initiator/joiner)\")or\"initiator\"if not confirm(\"Start \"..(mode==\"master\"and\"master/slave\"or\"peer\")..\" discovery with this phrase\")then return\"Cancelled\"end local ok,err=networkRequest(\"discovery_start\",{phrase=phrase,mode=mode,master=master});if ok then return\"Discovery active (waiting for join)\"end;return err elseif action==\"join_discovery\"then local phrase=prompt(\"Discovery phrase\",true);local ok,result=networkRequest(\"discovery_join\",{phrase=phrase})if not ok then return result end if type(result)==\"table\"and result.state==\"candidate\"then local candidate=result.candidate or{}local peerLabel=tostring(candidate.label or(\"Computer \"..tostring(candidate.id or\"?\")))local relationship=candidate.mode==\"master\"and\"master/slave\"or\"equal-peer\"if not confirm(\"Pair directly with \"..peerLabel..\" (\"..relationship..\")\")then return\"Pairing confirmation cancelled\"end local confirmed,confirmErr=networkRequest(\"discovery_confirm\",{})return confirmed and\"Pairing confirmation sent\"or confirmErr end return\"Searching for a matching discovery session\"elseif action==\"confirm_discovery\"then if not confirm(\"Confirm the selected direct pairing\")then return\"Cancelled\"end local ok,err=networkRequest(\"discovery_confirm\",{})return ok and\"Pairing confirmation sent\"or err elseif action==\"cancel_discovery\"then networkRequest(\"discovery_cancel\",{});return\"Discovery cancelled\"elseif action==\"discover\"then return net.discover()elseif action==\"pair_offer\"then local id,code=prompt(\"Peer ID\"),prompt(\"Pair code\",true);if not confirm(\"Send pairing offer\")then return\"Cancelled\"end;return net.offer(id,code)elseif action==\"pair_accept\"then local id,code=prompt(\"Peer ID\"),prompt(\"Pair code\",true);local peerRole=prompt(\"Role (viewer/operator/admin)\");local master=confirm(\"Is this peer the master\")if not confirm(\"Accept pairing\")then return\"Cancelled\"end;return net.accept(id,code,peerRole==\"\"and\"operator\"or peerRole,master)elseif action==\"remote_refresh\"then local live=store.read(\"/ceetos/data/network-status.lua\",{});local choices={}for _,peer in ipairs(live.peers or net.peers())do choices[#choices+1]={label=(peer.label or(\"Computer \"..peer.id))..\" (\"..peer.id..\")\",value=peer.id}end local peer=choose(\"Refresh peripherals from\",choices);if not peer then return false end return beginRemoteRequest(\"list\",peer)elseif action:sub(1,15)==\"peripheral_set:\"then local name,mode=action:match(\"^peripheral_set:(.-):(.+)$\")if mode~=\"peer\"and mode~=\"master\"then return\"Invalid sharing mode\"end local current for _,item in ipairs(peripherals.describe())do if item.name==name then current=item.mode end end if current==mode then peripherals.unshare(name);return\"Unshared \"..name end peripherals.share(name,mode);return\"Shared \"..name..(mode==\"master\"and\" (master only)\"or\" (peers)\")elseif action:sub(1,19)==\"peripheral_unshare:\"then local name=action:sub(20)peripherals.unshare(name);return\"Unshared \"..name elseif action==\"share_all:peer\"or action==\"share_all:master\"then local mode=action:sub(11)if not confirm(\"Share every detected peripheral\"..(mode==\"master\"and\" with master only\"or\" with peers\"))then return\"Cancelled\"end return\"Shared \"..peripherals.shareAll(mode)..\" peripherals\"elseif action==\"unshare_all\"then if not confirm(\"Stop sharing every peripheral\")then return\"Cancelled\"end return\"Unshared \"..peripherals.unshareAll()..\" peripherals\"elseif action==\"remote_cache\"then local live,choices=store.read(\"/ceetos/data/network-status.lua\",{}),{}for _,peer in ipairs(live.peers or net.peers())do choices[#choices+1]={label=(peer.label or(\"Computer \"..peer.id))..\" (\"..peer.id..\")\",value=peer.id}end local peer=choose(\"View cached peripherals from\",choices);if not peer then return false end local cache=cacheFor(peer)state.remoteResult={status=\"ready\",peer=tostring(peer),text=tostring(#(cache.peripherals or{}))..\" cached peripherals\"}return true elseif action==\"remote_call\"then local live,peers=store.read(\"/ceetos/data/network-status.lua\",{}),{}for _,peer in ipairs(live.peers or net.peers())do peers[#peers+1]={label=(peer.label or(\"Computer \"..peer.id))..\" (\"..peer.id..\")\",value=peer}end local peer=choose(\"Choose peer\",peers);if not peer then return false end local cache=cacheFor(peer.id)if not cache.peripherals or#cache.peripherals==0 then return beginRemoteRequest(\"list\",peer.id,nil,true)end return chooseRemoteCall(peer,cache)elseif action==\"update_check\"then auth.require(\"operator\")local checked,err=networkRequest(\"update_check\",{})if not checked then return err end if type(err)==\"table\"then if err.cloudError then return\"Cloud check failed: \"..tostring(err.cloudError)end return\"Found \"..tostring(err.cloud or 0)..\" cloud offer(s); mesh check sent to \"..tostring(err.routed or 0)..\" peer(s)\"end return\"Signed release check started\"elseif action==\"update_install_latest\"then auth.require(\"operator\")local started,err=networkRequest(\"update_install_latest\",{})return started and\"Latest compatible signed release is downloading; apply remains locally confirmed\"or err elseif action:sub(1,16)==\"update_download:\"then auth.require(\"operator\")local source=action:sub(17)local started,err=networkRequest(\"update_download\",{source=source})return started and\"Verified download started\"or err elseif action==\"update_cancel\"then auth.require(\"operator\")local cancelled,err=networkRequest(\"update_cancel\",{})return cancelled and\"Update download cancelled\"or err elseif action==\"update_clear\"then auth.require(\"operator\")if not confirm(\"Clear the verified release cache\")then return\"Cancelled\"end local cleared,err=networkRequest(\"update_clear_cache\",{})return cleared and\"Release cache cleared\"or err elseif action==\"update_apply\"then auth.require(\"operator\")local statusOk,update=networkRequest(\"update_status\",{})if not statusOk or not update.cache then return(statusOk and\"No verified release is cached\"or update)end local label=\"Apply CeetOS \"..tostring(update.cache.version)..\" (\"..tostring(update.cache.fingerprint)..\", key \"..tostring(update.cache.keyId)..\")\"if not confirm(label)then return\"Cancelled\"end local prepared,err=networkRequest(\"update_apply\",{})if not prepared then return err end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)print(\"Verified release approved. Rebooting locally...\")sleep(0.3);os.reboot()elseif action==\"telemetry_toggle\"then if not confirm(\"Change telemetry state\")then return\"Cancelled\"end;telemetry.setEnabled(not telemetry.status());audit.log(auth.current.name,\"telemetry\",{enabled=telemetry.status()});return true elseif action==\"cloud_enroll\"then auth.require(\"admin\")local code=prompt(\"One-time Cloud enrollment code\",true)if not confirm(\"Enroll this computer with auth.ceet.uk\")then return\"Cancelled\"end local enrolled,enrollErr=cloudSync.enroll(code)if not enrolled then return enrollErr end audit.log(auth.current.name,\"cloud.enroll\",{node=enrolled.node})return\"Cloud enrollment saved; syncing in the background\"elseif action==\"cloud_retry\"then auth.require(\"operator\")local synced,syncErr=cloudSync.tick(\"manual\")return synced and\"Cloud sync requested\"or syncErr elseif action==\"cloud_clear\"then auth.require(\"admin\")if not confirm(\"Remove this computer's Cloud enrollment\")then return\"Cancelled\"end local cleared,clearErr=cloudSync.clear()if cleared then audit.log(auth.current.name,\"cloud.clear\",{})end return cleared and\"Cloud enrollment removed\"or clearErr elseif action==\"login\"then return auth.login(prompt(\"User\"),prompt(\"Password\",true))elseif action==\"logout\"then if not confirm(\"Logout\")then return\"Cancelled\"end;auth.logout();return true elseif action==\"user_add\"then local name,userRole,password=prompt(\"User name\"),chooseRole(),prompt(\"Password\",true)if not userRole then return\"Cancelled\"end if not confirm(\"Create user \"..name)then return\"Cancelled\"end;auth.add(name,userRole,password);audit.log(auth.current.name,\"user.add\",{name=name,role=userRole});return true elseif action:sub(1,10)==\"user_role:\"then local name,userRole=action:match(\"^user_role:(.-):(.+)$\")if not confirm(\"Change \"..name..\" to \"..userRole)then return\"Cancelled\"end;auth.setRole(name,userRole);audit.log(auth.current.name,\"user.role\",{name=name,role=userRole});return true elseif action:sub(1,11)==\"user_reset:\"then local name,password=action:sub(12),prompt(\"New password for \"..action:sub(12),true)if not confirm(\"Reset password for \"..name)then return\"Cancelled\"end;auth.adminResetPassword(name,password);audit.log(auth.current.name,\"user.password\",{name=name});return true elseif action:sub(1,11)==\"user_delete:\"then local name=action:sub(12)if not confirm(\"Delete user \"..name)then return\"Cancelled\"end;auth.remove(name);audit.log(auth.current.name,\"user.delete\",{name=name});return true elseif action==\"recovery_enable\"then local minutes=tonumber(prompt(\"Recovery minutes (1-60)\"))or 10 if not confirm(\"Enable recovery window\")then return\"Cancelled\"end;store.write(\"/ceetos/data/recovery.lua\",{until_ts=os.epoch(\"utc\")+minutes*60000});audit.log(auth.current.name,\"recovery.enable\",{minutes=minutes});return true elseif action==\"recovery_reset\"then local recovery=store.read(\"/ceetos/data/recovery.lua\",{});assert((recovery.until_ts or 0)>os.epoch(\"utc\"),\"recovery window is not active\")local name,password=prompt(\"User name\"),prompt(\"New password\",true);if not confirm(\"Reset password for \"..name)then return\"Cancelled\"end;auth.resetPassword(name,password);audit.log(\"local-recovery\",\"password.reset\",{name=name});return true end end)if not ok then return refresh(tostring(result),true)end if result==false then return refresh(\"Request failed\",true)end return refresh()end local function activateSelected()local item=gui.selected(currentModel,state)if item and item.action then run(item.action)elseif item then refresh(\"This file cannot be opened\",true)end end local function nextEvent()while true do local event,first,second,third=os.pullEventRaw()if event~=\"terminate\"then return event,first,second,third end if auth.allowed(\"operator\")then if fs.exists(\"/ceetos/data\")then local marker=fs.open(\"/ceetos/data/desktop-stop\",\"w\")if marker then marker.write(\"terminate\");marker.close()end end return false end refresh(\"Viewer mode: Ctrl+T is disabled\",true)end end refresh()local uiTimer=os.startTimer(0.2)while true do local event,first,second,third=nextEvent()if event==false then return false end if event==\"timer\"and first==uiTimer then uiTimer=os.startTimer(0.2)if pollRemoteRequest()or page==\"updates\"then refresh()end elseif event==\"key\"then local name=keys.getName(first)if state.menu then if name==\"up\"then state.menu.selected=math.max(1,state.menu.selected-1);refresh()elseif name==\"down\"then state.menu.selected=math.min(#state.menu.items,state.menu.selected+1);refresh()elseif name==\"enter\"then run(state.menu.items[state.menu.selected].action)elseif name==\"backspace\"or name==\"m\"then state.menu=nil;refresh()end elseif name==\"q\"then if page==\"home\"then refresh(\"CeetOS Desktop stays active. Open Terminal for commands.\")else page=\"home\";state.selected=nil;refresh()end elseif name==\"r\"then refresh()elseif name==\"up\"or name==\"down\"or name==\"left\"or name==\"right\"then gui.move(currentModel,state,name);refresh()elseif name==\"enter\"then activateSelected()elseif name==\"m\"then openMenu(gui.selected(currentModel,state))elseif name==\"n\"and page==\"files\"and not state.trash then run(\"new_folder\")elseif name==\"t\"and page==\"files\"and not state.trash then run(\"trash_open\")elseif name==\"e\"and page==\"files\"and state.trash then run(\"empty_trash\")elseif name==\"backspace\"then if page==\"peripherals\"and state.peripheralView then state.peripheralView=false;state.selected=nil;refresh()elseif page==\"files\"and state.trash then state.trash=false;state.selected=nil;refresh()elseif page==\"files\"and state.path~=\"/\"then state.path=table.remove(state.history)or\"/\";state.selected=nil;refresh()else page=\"home\";state.selected=nil;refresh()end end elseif event==\"mouse_click\"then local target=terminalUi.hit(targets,second,third)if target then if target.kind==\"menu\"then run(target.item.action)elseif target.item.toggle then gui.select(currentModel,state,target.item);run(target.item.action)elseif first==2 then gui.select(currentModel,state,target.item);openMenu(target.item)elseif state.selected==target.item.id then if target.item.kind==\"account\"then openMenu(target.item)else activateSelected()end else gui.select(currentModel,state,target.item);refresh()end end elseif event==\"file_transfer\"then local ok,result=pcall(function()local transfers=first.getFiles();local imported,updated={},0 for _,transfer in ipairs(transfers)do local name=transfer.getName and transfer.getName()or\"\"local devBuild=name:match(\"^ceetos%-devbuild[%w%._%-]*%.lua$\")or name==\"ceetos-pastebin.lua\"local releaseBuild=name:match(\"^ceetos%-release[%w%._%-]*%.lua$\")or name==\"ceetos-release.lua\"if devBuild or releaseBuild then auth.require(\"operator\")local chunks={};while true do local chunk=transfer.read(8192);if not chunk then break end;chunks[#chunks+1]=chunk end local source=table.concat(chunks)if releaseBuild then local metadata,cacheErr=release.cache(source,\"file transfer\")assert(metadata,cacheErr or\"not a signed CeetOS release\")if confirm(\"Verified CeetOS \"..tostring(metadata.version)..\" received. Apply locally now\")then local prepared,applyErr=networkRequest(\"update_apply\",{})assert(prepared,applyErr or\"could not prepare update\")term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)print(\"Verified release approved. Rebooting locally...\")sleep(0.3);os.reboot()end updated=updated+1 else assert(source:find(\"CeetOS installer\",1,true)and source:find(\"local files\",1,true),\"not a CeetOS installer\")local installer=assert(load(source,name,\"t\"));installer();updated=updated+1 end else local importedFiles=files.import({transfer},\"/programs/imports\")for _,path in ipairs(importedFiles)do imported[#imported+1]=path end end end return{imported=imported,updated=updated}end)if ok then refresh()else refresh(tostring(result),true)end elseif event==\"disk\"or event==\"disk_eject\"or event==\"peripheral\"or event==\"peripheral_detach\"then if files.handleDiskEvent(event,first)then local selected=gui.selected(currentModel,state)if selected and selected.path and not fs.exists(selected.path)then state.selected=nil end refresh()end elseif event==\"term_resize\"then refresh()end end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)",
  ["ceetos/bin/ceetshell.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local history=require(\"ceetos.lib.terminal\")local clipboard=require(\"ceetos.lib.clipboard\")local inputState=require(\"ceetos.lib.input\")local terminalUi=require(\"ceetos.lib.terminal_ui\")local auth=require(\"ceetos.lib.auth\")local telemetry=require(\"ceetos.lib.telemetry\")telemetry.markActivity(\"terminal\")auth.require(\"operator\")local net=require(\"ceetos.lib.net\")local store=require(\"ceetos.lib.store\")local launch={...}local remoteId,remoteLabel,remoteSession if launch[1]==\"--remote\"and launch[2]then remoteId=tostring(launch[2]);remoteLabel=\"peer-\"..remoteId for _,peer in ipairs(net.peers())do if tostring(peer.id)==remoteId and peer.label and peer.label~=\"\"then remoteLabel=peer.label end end for _,peer in ipairs(net.seenPeers())do if tostring(peer.id)==remoteId and peer.label and peer.label~=\"\"then remoteLabel=peer.label end end remoteSession=tostring(os.epoch(\"utc\"))..\"-\"..tostring(math.random(1000,9999))end local function localLabel()return(os.getComputerLabel and os.getComputerLabel())or(\"computer-\"..tostring(os.getComputerID()))end local promptIdentity=(auth.current and auth.current.name or\"guest\")..\"@\"..(remoteLabel or localLabel())local function parse(line)local out,token,quote,escaped={},\"\",nil,false for index=1,#line do local char=line:sub(index,index)if escaped then token,escaped=token..char,false elseif char==\"\\\\\"then escaped=true elseif quote then if char==quote then quote=nil else token=token..char end elseif char=='\"'or char==\"'\"then quote=char elseif char:match(\"%s\")then if token~=\"\"then out[#out+1],token=token,\"\"end else token=token..char end end if token~=\"\"then out[#out+1]=token end return out end local function candidates(word)local result,seen={},{}local function add(value)if value and not seen[value]then result[#result+1],seen[value]=value,true end end if word:find(\"/\")then local directory,prefix=fs.getDir(word),fs.getName(word)directory=directory==\"\"and\"/\"or directory if fs.exists(directory)and fs.isDir(directory)then for _,name in ipairs(fs.list(directory))do if name:sub(1,#prefix)==prefix then add(fs.combine(directory,name))end end end else for directory in shell.path():gmatch(\"[^:]+\")do if fs.exists(directory)and fs.isDir(directory)then for _,name in ipairs(fs.list(directory))do add(name:gsub(\"%.lua$\",\"\"))end end end end return result end local function readCommand()local input,cursor,entries,index,draft,anchor,viewOffset=\"\",0,history.history(),nil,\"\",nil,0 local held=inputState.modifiers()local selection=require(\"ceetos.lib.selection\")local promptX,promptY=1,select(2,term.getCursorPos())local function draw()local width,height=term.getSize()local prompt=promptIdentity..\":~$ \"local available=math.max(1,width-#prompt)if cursor<viewOffset then viewOffset=cursor elseif cursor>viewOffset+available then viewOffset=cursor-available end viewOffset=math.max(0,math.min(math.max(0,#input-available),viewOffset))terminalUi.clearLine(promptY,colors.black);terminalUi.write(promptX,promptY,prompt,colors.lime,colors.black,width)local visible=input:sub(viewOffset+1,viewOffset+available)local lo,hi=anchor and math.min(anchor,cursor)or nil,anchor and math.max(anchor,cursor)or nil if lo and hi and lo~=hi then local from,to=math.max(lo,viewOffset),math.min(hi,viewOffset+#visible)if from<to then terminalUi.write(#prompt+1,promptY,input:sub(viewOffset+1,from),colors.white,colors.black,available)terminalUi.write(#prompt+1+from-viewOffset,promptY,input:sub(from+1,to),colors.black,colors.white,available-(from-viewOffset))terminalUi.write(#prompt+1+to-viewOffset,promptY,input:sub(to+1,viewOffset+#visible),colors.white,colors.black,available-(to-viewOffset))else terminalUi.write(#prompt+1,promptY,visible,colors.white,colors.black,available)end term.setBackgroundColor(colors.black)else terminalUi.write(#prompt+1,promptY,visible,colors.white,colors.black,available)end term.setCursorPos(math.min(width,#prompt+cursor-viewOffset+1),promptY);if term.setCursorBlink then term.setCursorBlink(true)end terminalUi.clearLine(height,colors.black);terminalUi.write(1,height,\"Cursor \"..tostring(cursor+1)..\"/\"..tostring(#input+1)..\"  |  Enter run  |  Tab complete  |  exit returns\",colors.gray,colors.black,width)term.setTextColor(colors.white);term.setCursorPos(math.min(width,#prompt+cursor-viewOffset+1),promptY)end draw()while true do local event,first,second,third=os.pullEvent()if event==\"char\"then if held.ctrl and held.shift and(first==\"c\"or first==\"C\")and anchor then local s=require(\"ceetos.lib.selection\").new({input});require(\"ceetos.lib.selection\").start(s,1,anchor);require(\"ceetos.lib.selection\").update(s,1,cursor);require(\"ceetos.lib.selection\").copy(s,clipboard)elseif held.ctrl and held.shift and(first==\"v\"or first==\"V\")then local text=clipboard.get();input=input:sub(1,cursor)..text..input:sub(cursor+1);cursor=cursor+#text;anchor=nil else if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil end;input=input:sub(1,cursor)..first..input:sub(cursor+1);cursor=cursor+#first end;draw()elseif event==\"paste\"then if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil end;input=input:sub(1,cursor)..first..input:sub(cursor+1);cursor=cursor+#first;draw()elseif event==\"key_down\"then inputState.key(held,keys.getName(first)or first)elseif event==\"key_up\"then inputState.keyUp(held,keys.getName(first)or first)elseif event==\"key\"then local key=tostring(keys.getName(first)or first or\"\"):lower()local copyShortcut=held.ctrl and held.shift and key==\"c\"local pasteShortcut=held.ctrl and held.shift and key==\"v\"if key==\"leftctrl\"or key==\"rightctrl\"or key==\"ctrl\"or key==\"leftshift\"or key==\"rightshift\"or key==\"shift\"then inputState.key(held,key);draw()elseif copyShortcut then held.ctrl,held.shift=false,false if anchor and anchor~=cursor then local s=selection.new({input});selection.start(s,1,anchor);selection.update(s,1,cursor);selection.copy(s,clipboard)end;draw()elseif pasteShortcut then held.ctrl,held.shift=false,false local text=clipboard.get();if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil end;input=input:sub(1,cursor)..text..input:sub(cursor+1);cursor=cursor+#text;draw()elseif key==\"enter\"then term.setCursorPos(1,promptY+1);return input elseif key==\"backspace\"then if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil elseif cursor>0 then input=input:sub(1,cursor-1)..input:sub(cursor+1);cursor=cursor-1 end;draw()elseif key==\"delete\"and cursor<#input then if anchor and anchor~=cursor then input=input:sub(1,math.min(anchor,cursor))..input:sub(math.max(anchor,cursor)+1);cursor=math.min(anchor,cursor);anchor=nil else input=input:sub(1,cursor)..input:sub(cursor+2)end;draw()elseif key==\"left\"then if held.shift then anchor=anchor or cursor end;cursor=math.max(0,cursor-1);if not held.shift then anchor=nil end;draw()elseif key==\"right\"then if held.shift then anchor=anchor or cursor end;cursor=math.min(#input,cursor+1);if not held.shift then anchor=nil end;draw()elseif key==\"home\"then if held.shift then anchor=anchor or cursor end;cursor=0;if not held.shift then anchor=nil end;draw()elseif key==\"end\"then if held.shift then anchor=anchor or cursor end;cursor=#input;if not held.shift then anchor=nil end;draw()elseif key==\"up\"then if#entries>0 then if not index then draft,index=input,#entries else index=math.max(1,index-1)end;input,cursor=entries[index],#entries[index];draw()end elseif key==\"down\"and index then index=index+1;input=index>#entries and draft or entries[index];if index>#entries then index=nil end;cursor=#input;draw()elseif key==\"tab\"then local word=input:match(\"([^%s]*)$\")or\"\";local matches=history.complete(word,candidates(word))if#matches==1 then input=input:sub(1,#input-#word)..matches[1];cursor=#input;draw()end end elseif event==\"mouse_click\"and first==2 and anchor and anchor~=cursor then local s=selection.new({input});selection.start(s,1,anchor);selection.update(s,1,cursor);selection.copy(s,clipboard);draw()elseif event==\"mouse_click\"and first==1 and third==promptY then local prompt=promptIdentity..\":~$ \";anchor=math.max(0,math.min(#input,viewOffset+second-#prompt-1));cursor=anchor;draw()elseif event==\"mouse_drag\"and first==1 and third==promptY then local prompt=promptIdentity..\":~$ \";cursor=math.max(0,math.min(#input,viewOffset+second-#prompt-1));draw()end end end local function banner()local width=select(1,term.getSize())term.setBackgroundColor(colors.black);term.setTextColor(colors.cyan);term.clear();terminalUi.write(1,1,\"CeetOS Terminal  |  \"..promptIdentity..\"  |  Tab complete  |  exit returns to Desktop\",colors.cyan,colors.black,width)term.setCursorPos(1,3)term.setTextColor(colors.white)end local function waitRemote()if not remoteSession then return end local timer,deadline=os.startTimer(0.2),os.epoch(\"utc\")+2000 while os.epoch(\"utc\")<deadline do local event,value=os.pullEvent()if event==\"timer\"and value==timer then local replies,pending=store.read(\"/ceetos/data/shell-replies.lua\",{}),{}for _,reply in ipairs(replies)do if reply.from==remoteId and reply.body and reply.body.session==remoteSession then if reply.body.output and reply.body.output~=\"\"then print(reply.body.output)end if not reply.body.ok and reply.body.error then printError(reply.body.error)end else pending[#pending+1]=reply end end store.write(\"/ceetos/data/shell-replies.lua\",pending)if#pending<#replies then return end timer=os.startTimer(0.2)end end printError(\"Remote command timed out\")end local function configureDevBridge(url,token)if not url or url==\"\"then printError(\"usage: ceetdev <ws://bridge:port/dev> [token]\");return end if not fs.exists(\"/ceetos-dev\")then fs.makeDir(\"/ceetos-dev\")end local handle=assert(fs.open(\"/ceetos-dev/connection.lua\",\"w\"))handle.write(textutils.serialize({url=url,token=token or\"\",auth=(token and token~=\"\")and\"token\"or\"none\"}));handle.close()print(\"Development bridge configured; connection continues in the background.\")end banner()while true do local line=readCommand()if line==nil or line==\"exit\"then break end if line==\"clear\"then banner()else local args=parse(line)if#args>0 then history.add(line)if remoteId then local ok,err=net.request(remoteId,\"shell_request\",{command=line,session=remoteSession})if not ok then printError(err)else waitRemote()end else local ok,result if args[1]==\"ceetdev\"then configureDevBridge(args[2],args[3]);ok,result=true,true else ok,result=pcall(shell.run,args[1],table.unpack(args,2))end if not ok then printError(result)elseif result==false then printError(\"Command failed\")end end end end end",
  ["ceetos/bin/ceetlaunch.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local capabilities=require(\"ceetos.lib.program_capabilities\")local disks=require(\"ceetos.lib.disks\")local audit=require(\"ceetos.lib.audit\")local telemetry=require(\"ceetos.lib.telemetry\")local args={...}local requestedPath=table.remove(args,1)assert(requestedPath and requestedPath~=\"\",\"usage: ceetlaunch <program> [args]\")if auth.refreshSession then auth.refreshSession()end local current=auth.current local actor=current and current.name or\"anonymous\"local normalized,pathErr=capabilities.normaliseProgramPath(requestedPath)if not normalized then audit.log(actor,\"program.launch_denied\",{path=tostring(requestedPath),reason=tostring(pathErr)})error(pathErr,0)end telemetry.markActivity(\"program: \"..(fs.getName(normalized)or\"program\"))local runner local removable=disks.forPath(normalized)if removable then local trusted,record=capabilities.hasPortableTrust(normalized,removable.token)if trusted and auth.allowed(\"admin\")then audit.log(actor,\"program.launch\",{path=normalized,mode=\"portable-temporary-trust\",volume=removable.key})runner=function()return shell.run(normalized,table.unpack(args))end else local chunk,sandboxRecord=capabilities.loadViewer(normalized,actor)if not chunk then audit.log(actor,\"program.launch_denied\",{path=normalized,reason=tostring(sandboxRecord),removable=removable.key})error(sandboxRecord,0)end audit.log(actor,\"program.launch\",{path=normalized,mode=\"portable-sandbox\",volume=removable.key,trust=sandboxRecord.trust,stale=sandboxRecord.stale==true})runner=function()return chunk(table.unpack(args))end end elseif auth.allowed(\"operator\")then audit.log(actor,\"program.launch\",{path=normalized,mode=\"full\",role=auth.current and auth.current.role})runner=function()return shell.run(normalized,table.unpack(args))end elseif auth.allowed(\"viewer\")then local chunk,record=capabilities.loadViewer(normalized,actor)if not chunk then audit.log(actor,\"program.launch_denied\",{path=normalized,reason=tostring(record)})error(record,0)end audit.log(actor,\"program.launch\",{path=normalized,mode=\"sandbox\",trust=record.trust,stale=record.stale==true,})runner=function()return chunk(table.unpack(args))end else audit.log(actor,\"program.launch_denied\",{path=normalized,reason=\"requires viewer\"})error(\"permission denied (requires viewer)\",0)end local child=coroutine.create(runner)local function resume(...)local ok,result=coroutine.resume(child,...)if not ok then audit.log(actor,\"program.failed\",{path=normalized,reason=\"program error\"})error(result,0)end return coroutine.status(child)==\"dead\",result end local done,result=resume()while not done do local event={os.pullEventRaw()}if event[1]==\"key\"and event[2]==keys.backspace then term.setTextColor(colors.gray)print(\"Backspace: returned to CeetOS Desktop\")return true end done,result=resume(table.unpack(event))end return result",
  ["ceetos/bin/craftos-shell.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")auth.require(\"operator\")shell.run(\"/rom/programs/shell.lua\")",
  ["ceetos/bin/ceetedit.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local editor=require(\"ceetos.lib.editor\")local clipboard=require(\"ceetos.lib.clipboard\")local inputState=require(\"ceetos.lib.input\")local terminalUi=require(\"ceetos.lib.terminal_ui\")local auth=require(\"ceetos.lib.auth\")local files=require(\"ceetos.lib.files\")local args={...}local path=args[1]assert(path and path~=\"\",\"usage: ceetedit <file>\")auth.require(\"operator\")assert(not files.isProtected(path),\"protected files must be edited with craftos-edit\")local buffer=editor.new(fs.exists(path)and files.readText(path)or\"\")local scroll,ctrl,shift=1,false,false local held=inputState.modifiers()local tokenColours={text=colors.white,comment=colors.gray,string=colors.orange,keyword=colors.purple,number=colors.cyan,builtin=colors.lightBlue}local function fitCursor(height)local visible=math.max(1,height-3)if buffer.line<scroll then scroll=buffer.line elseif buffer.line>=scroll+visible then scroll=buffer.line-visible+1 end end local function render(message)local width,height=term.getSize();fitCursor(height)term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()if width<24 or height<8 then terminalUi.minimum(\"CeetOS Editor\",\"Editor needs 24x8\",\"Resize | Ctrl+Q exit\");return end terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,\"CeetOS Editor | \"..path..(buffer.changed and\" *\"or\"\"),colors.white,colors.blue,width-2)local digits=math.max(2,#tostring(#buffer.lines));local gutter=digits+3 local lua=path:sub(-4):lower()==\".lua\"for row=2,height-1 do local lineNumber,line=scroll+row-2,buffer.lines[scroll+row-2]if line then local selected=lineNumber==buffer.line term.setBackgroundColor(selected and colors.gray or colors.black);terminalUi.write(1,row,(\"%\"..digits..\"d \"):format(lineNumber),colors.lightGray,selected and colors.gray or colors.black,gutter-1)term.setTextColor(colors.white)local x=gutter for _,token in ipairs(editor.tokens(line,lua))do if x<width then terminalUi.write(x,row,token.text,tokenColours[token.kind]or colors.white,selected and colors.gray or colors.black,width-x+1);x=x+#token.text end end end end local range=buffer.selection and require(\"ceetos.lib.selection\").range(buffer.selection)if range then for line=range.first.line,range.last.line do local row=line-scroll+2 if row>=2 and row<height then local from=line==range.first.line and range.first.column or 0 local to=line==range.last.line and range.last.column or#(buffer.lines[line]or\"\")if to>from and gutter+from<=width then terminalUi.write(gutter+from,row,(buffer.lines[line]or\"\"):sub(from+1,to),colors.black,colors.white,width-gutter-from+1)term.setBackgroundColor(colors.black)end end end end terminalUi.clearLine(height,colors.black);terminalUi.write(1,height,message or\"Ctrl+S save | F2 save as | Ctrl+F find | Ctrl+G line | F5 run | Ctrl+Q exit\",colors.gray,colors.black,width)local cursorY=buffer.line-scroll+2 if cursorY>=2 and cursorY<height then term.setCursorPos(math.min(width,gutter+buffer.column),cursorY)end term.setTextColor(colors.white)end local function prompt(label)local _,height=term.getSize();term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.setCursorPos(1,height);term.clearLine();term.write(label..\": \");return read()end local function save(target)target=target or path local ok,err=pcall(files.writeText,target,editor.text(buffer))if ok then path,buffer.changed=target,false;return true else render(tostring(err));return false end end local function leaveChoice()if not buffer.changed then return\"discard\"end local function draw()render()local width,height=term.getSize();local boxWidth=math.max(20,math.min(32,width-2));local x,y=math.max(1,math.floor((width-boxWidth)/2)+1),math.max(2,math.floor((height-5)/2))terminalUi.fill(x,y,boxWidth,5,colors.black)terminalUi.write(x+2,y+1,\"Unsaved changes\",colors.white,colors.black,boxWidth-4)local compact=boxWidth<31 local saveText,discardText,cancelText=compact and\"[S]\"or\" Save \",compact and\"[D]\"or\" Discard \",compact and\"[C]\"or\" Cancel \"local saveX,discardX,cancelX=x+2,x+2+#saveText+2,x+2+#saveText+#discardText+4 terminalUi.write(saveX,y+3,saveText,colors.black,colors.green)terminalUi.write(discardX,y+3,discardText,colors.white,colors.red)terminalUi.write(cancelX,y+3,cancelText,colors.white,colors.gray)return{y=y+3,saveX=saveX,saveWidth=#saveText,discardX=discardX,discardWidth=#discardText,cancelX=cancelX,cancelWidth=#cancelText}end local modal=draw()while true do local event,first,second,third=os.pullEvent()if event==\"mouse_click\"and third==modal.y then if second>=modal.saveX and second<modal.saveX+modal.saveWidth then return\"save\"elseif second>=modal.discardX and second<modal.discardX+modal.discardWidth then return\"discard\"elseif second>=modal.cancelX and second<modal.cancelX+modal.cancelWidth then return\"cancel\"end elseif event==\"key\"then local key=keys.getName(first);if key==\"enter\"then return\"save\"elseif key==\"d\"then return\"discard\"elseif key==\"backspace\"then return\"cancel\"end end if event==\"term_resize\"then modal=draw()end end end render()while true do local event,first,second,third=os.pullEvent()if event==\"char\"then editor.insert(buffer,first);render()elseif event==\"paste\"then editor.insert(buffer,first);render()elseif event==\"key_up\"then local released=tostring(keys.getName(first)or first or\"\"):lower()inputState.keyUp(held,released);ctrl,shift=held.ctrl,held.shift elseif event==\"key\"then local key=tostring(keys.getName(first)or first or\"\"):lower()if key==\"leftctrl\"or key==\"rightctrl\"or key==\"ctrl\"or key==\"leftshift\"or key==\"rightshift\"or key==\"shift\"then inputState.key(held,key);ctrl,shift=held.ctrl,held.shift elseif ctrl and key==\"c\"then editor.copySelection(buffer,clipboard);ctrl,shift,held.ctrl,held.shift=false,false,false,false;render(\"Copied\")elseif ctrl and key==\"v\"then editor.insert(buffer,clipboard.get());ctrl,shift,held.ctrl,held.shift=false,false,false,false;render()elseif ctrl and key==\"s\"then save();render(\"Saved\")elseif ctrl and key==\"q\"then local choice=leaveChoice();if choice==\"save\"then if save()then break end elseif choice==\"discard\"then break else render()end end elseif ctrl and key==\"f\"then local needle=prompt(\"Find\");if not editor.find(buffer,needle)then render(\"Not found\")else render()end elseif ctrl and key==\"g\"then editor.gotoLine(buffer,prompt(\"Go to line\"));render()elseif key==\"f2\"then local target=prompt(\"Save as\");if target~=\"\"then save(target);render(\"Saved\")else render()end elseif key==\"f5\"then if not auth.allowed(\"operator\")then render(\"Operator role required to run programs\")elseif save()then term.clear();term.setCursorPos(1,1);shell.run(\"/ceetos/bin/ceetlaunch.lua\",path);render(\"Returned from program\")end elseif key==\"left\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,0,-1);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"right\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,0,1);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"up\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,-1,0);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"down\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.move(buffer,1,0);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"home\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.gotoLine(buffer,buffer.line,0);if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"end\"then if shift and not buffer.selection.anchor then editor.selectStart(buffer)end;editor.gotoLine(buffer,buffer.line,#editor.current(buffer));if shift then editor.selectTo(buffer,buffer.line,buffer.column)else editor.clearSelection(buffer)end;render()elseif key==\"pageup\"then editor.move(buffer,-10,0);render()elseif key==\"pagedown\"then editor.move(buffer,10,0);render()elseif key==\"enter\"then editor.insert(buffer,\"\\n\");render()elseif key==\"tab\"then editor.insert(buffer,\"  \");render()elseif key==\"backspace\"then if not editor.deleteSelection(buffer)then editor.backspace(buffer)end;render()elseif key==\"delete\"then if not editor.deleteSelection(buffer)then editor.delete(buffer)end;render()elseif event==\"mouse_click\"and first==2 then if buffer.selection and require(\"ceetos.lib.selection\").range(buffer.selection)then editor.copySelection(buffer,clipboard);render(\"Copied\")else editor.insert(buffer,clipboard.get());render()end elseif event==\"mouse_click\"and first==1 then local width,height=term.getSize()local digits=math.max(2,#tostring(#buffer.lines));local gutter=digits+3 local line=scroll+third-2 if third>=2 and third<height and line>=1 and line<=#buffer.lines then local column=math.max(0,math.min(#(buffer.lines[line]or\"\"),second-gutter))editor.gotoLine(buffer,line,column);editor.selectStart(buffer);render()end elseif event==\"mouse_drag\"and first==1 then local width,height=term.getSize()local digits=math.max(2,#tostring(#buffer.lines));local gutter=digits+3 local line=math.max(1,math.min(#buffer.lines,scroll+third-2))local column=math.max(0,math.min(#(buffer.lines[line]or\"\"),second-gutter))editor.selectTo(buffer,line,column);editor.gotoLine(buffer,line,column);render()elseif event==\"term_resize\"then render()end end term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear();term.setCursorPos(1,1)",
  ["ceetos/bin/edit.lua"] = "local args={...}if#args==0 then shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")else shell.run(\"/ceetos/bin/ceetedit.lua\",args[1])end",
  ["ceetos/bin/programs.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\")",
  ["ceetos/bin/files.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")",
  ["ceetos/bin/list.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")",
  ["ceetos/bin/delete.lua"] = "shell.run(\"/ceetos/bin/ceetui.lua\",\"files\")",
  ["ceetos/lib/store.lua"] = "local M={}local cache={}local function internalPath(path)return type(path)~=\"string\"or path:sub(-4)==\".new\"or path:sub(-4)==\".bak\"end local function call(fn,...)local result={pcall(fn,...)}if not result[1]then return false,tostring(result[2])end if result[2]==false then return false,tostring(result[3]or\"operation failed\")end return true,result[2],result[3]end local function exists(path)local ok,value=call(fs.exists,path)return ok and value==true end local function remove(path)if not exists(path)then return true end local ok,err=call(fs.delete,path)return ok,err end local function ensureDirectory(path)local dir=fs.getDir(path)if dir==\"\"or exists(dir)then return true end local ok,err=call(fs.makeDir,dir)return ok,err end local function readRaw(path)local ok,handleOrErr=call(fs.open,path,\"r\")if not ok or not handleOrErr then return false,nil,tostring(handleOrErr or\"could not open file\")end local handle=handleOrErr local readOk,content=call(handle.readAll)local closeOk,closeErr=call(handle.close)if not readOk then return false,nil,content end if not closeOk then return false,nil,closeErr end return true,content end local function writeRaw(path,content)local ok,handleOrErr=call(fs.open,path,\"w\")if not ok or not handleOrErr then return false,tostring(handleOrErr or\"could not open file\")end local handle=handleOrErr local writeOk,writeErr=call(handle.write,content)local closeOk,closeErr=call(handle.close)if not writeOk then return false,writeErr end if not closeOk then return false,closeErr end return true end local function move(source,destination)local ok,err=call(fs.move,source,destination)return ok,err end local function decode(raw)local ok,value=pcall(textutils.unserialise,raw)if not ok or value==nil then return false,nil,\"invalid serialised value\"end return true,value end local function readValue(path)local ok,raw,err=readRaw(path)if not ok then return false,nil,err end return decode(raw)end local function recoverValue(path)local activeOk,activeValue=false,nil if exists(path)then activeOk,activeValue=readValue(path)end if activeOk then remove(path..\".new\")remove(path..\".bak\")return true,activeValue end local backupOk,backupValue=false,nil if exists(path..\".bak\")then backupOk,backupValue=readValue(path..\".bak\")end if backupOk then if exists(path)then remove(path)end if not exists(path)then move(path..\".bak\",path)end remove(path..\".new\")return true,backupValue end remove(path..\".new\")return false,nil end local function validLines(raw)for line in(raw..\"\\n\"):gmatch(\"(.-)\\n\")do if line~=\"\"then local ok,value=pcall(textutils.unserialise,line)if not ok or value==nil then return false,\"invalid appended value\"end end end return true end local function recoverAppend(path)if exists(path)then local activeOk,raw=readRaw(path)if activeOk then local valid=validLines(raw)if valid then remove(path..\".new\")remove(path..\".bak\")return true,raw end end end if exists(path..\".bak\")then local backupOk,raw=readRaw(path..\".bak\")if backupOk and validLines(raw)then if exists(path)then remove(path)end if not exists(path)then move(path..\".bak\",path)end remove(path..\".new\")return true,raw end end remove(path..\".new\")return false,\"no valid appended value\"end local function commitRaw(path,raw,validator)local dirOk,dirErr=ensureDirectory(path)if not dirOk then return false,dirErr end local temporary,backup=path..\".new\",path..\".bak\"local removeOk,removeErr=remove(temporary)if not removeOk then return false,removeErr end local writeOk,writeErr=writeRaw(temporary,raw)if not writeOk then remove(temporary);return false,writeErr end local checkOk,checkedRaw,checkErr=readRaw(temporary)if not checkOk then remove(temporary);return false,checkErr end local valid,validErr=validator(checkedRaw)if not valid then remove(temporary);return false,validErr or\"temporary validation failed\"end local backupRemoveOk,backupRemoveErr=remove(backup)if not backupRemoveOk then remove(temporary);return false,backupRemoveErr end if exists(path)then local backupOk,backupErr=move(path,backup)if not backupOk then remove(temporary);return false,backupErr end local activateOk,activateErr=move(temporary,path)if not activateOk then if not exists(path)then move(backup,path)end remove(temporary)return false,activateErr end else local activateOk,activateErr=move(temporary,path)if not activateOk then remove(temporary);return false,activateErr end end return true end function M.readCached(path,fallback)if internalPath(path)then return fallback end local entry=cache[path]if entry~=nil then return entry.value end return M.readFresh(path,fallback)end function M.readFresh(path,fallback)if internalPath(path)then return fallback end local ok,value=recoverValue(path)if not ok then value=fallback end cache[path]={value=value}return value end function M.read(path,fallback)return M.readCached(path,fallback)end function M.writeAtomic(path,value)if internalPath(path)then return false,\"cannot write store temporary or backup path\"end if value==nil then return false,\"cannot store nil\"end local serialisedOk,raw=pcall(textutils.serialise,value,{compact=true})if not serialisedOk or type(raw)~=\"string\"then return false,tostring(raw or\"could not serialise value\")end local valid=decode(raw)if not valid then return false,\"could not validate serialised value\"end recoverValue(path)local ok,err=commitRaw(path,raw,decode)if ok then cache[path]={value=value}end return ok,err end function M.write(path,value)return M.writeAtomic(path,value)end function M.append(path,value,limits)if internalPath(path)then return false,\"cannot append to store temporary or backup path\"end if value==nil then return false,\"cannot append nil\"end local serialisedOk,line=pcall(textutils.serialise,value,{compact=true})if not serialisedOk or type(line)~=\"string\"then return false,tostring(line or\"could not serialise value\")end local valid=validLines(line..\"\\n\")if not valid then return false,\"could not validate appended value\"end local recovered,current=recoverAppend(path)if not recovered then if exists(path)or exists(path..\".bak\")then return false,current end current=\"\"end local lines={}for existing in(current..\"\\n\"):gmatch(\"(.-)\\n\")do if existing~=\"\"then lines[#lines+1]=existing end end lines[#lines+1]=line local maxEntries=limits and tonumber(limits.maxEntries)local maxBytes=limits and tonumber(limits.maxBytes)if maxEntries then maxEntries=math.max(1,math.floor(maxEntries))end if maxBytes then maxBytes=math.max(1,math.floor(maxBytes))end while maxEntries and#lines>maxEntries do table.remove(lines,1)end local raw=table.concat(lines,\"\\n\")if#raw>0 then raw=raw..\"\\n\"end while maxBytes and#raw>maxBytes and#lines>1 do table.remove(lines,1)raw=table.concat(lines,\"\\n\")..\"\\n\"end if maxBytes and#raw>maxBytes then return false,\"appended value exceeds byte limit\"end local ok,err=commitRaw(path,raw,validLines)if ok then cache[path]=nil end return ok,err end function M.readAppend(path)if internalPath(path)then return\"\"end local ok,raw=recoverAppend(path)return ok and raw or\"\"end function M.invalidate(path)cache[path]=nil end return M",
  ["ceetos/lib/profile.lua"] = "local store=require(\"ceetos.lib.store\")local M={}M.PATH=\"/ceetos/profile.lua\"M.IDS={desktop=true,[\"recipe-server\"]=true,[\"router-server\"]=true,[\"auth-server\"]=true}local cache local function normalise(value)if type(value)~=\"table\"then value={}end local id=tostring(value.id or value.profile or\"desktop\")if not M.IDS[id]then id=\"desktop\"end return{schema=1,id=id,installedAt=tonumber(value.installedAt)or 0}end function M.current()if not cache then cache=normalise(store.read(M.PATH,{id=\"desktop\"}))end return cache end function M.id()return M.current().id end function M.is(id)return M.id()==id end function M.isServer()return M.id()~=\"desktop\"end function M.set(id)assert(M.IDS[id],\"invalid CeetOS profile\")cache={schema=1,id=id,installedAt=os.epoch(\"utc\")}return store.write(M.PATH,cache)end function M.capability(name)local id=M.id()local tableFor={desktop={desktop=true,craftingClient=true,orders=true},[\"recipe-server\"]={server=true,recipes=true,recipeImport=true,recipePlan=true},[\"router-server\"]={server=true,routing=true},[\"auth-server\"]={server=true,authAuthority=true},}return tableFor[id][name]==true end return M",
  ["ceetos/lib/auth.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local audit=require(\"ceetos.lib.audit\")local M={current=nil}local USERS=\"/ceetos/data/users.lua\"local SESSION=\"/ceetos/data/session.lua\"local TOMBSTONES=\"/ceetos/data/user-tombstones.lua\"local THROTTLE=\"/ceetos/data/login-throttle.lua\"local RECOVERY=\"/ceetos/data/recovery.lua\"local AUTHORITY=\"/ceetos/data/auth-authority.lua\"local CENTRAL_SESSION=\"/ceetos/data/auth-session.lua\"local DIRECTORY=\"/ceetos/data/auth-directory.lua\"local rank={viewer=1,operator=2,admin=3}M.SESSION_TTL_MS=8*60*60*1000 M.LOGIN_THROTTLE={failures=5,windowMs=5*60*1000,lockMs=60*1000,maxEntries=64}local configuredWorkFactor=password.DEFAULT_WORK_FACTOR local sessionPathDelete local function now()return os.epoch(\"utc\")end local function accountName(name)return type(name)==\"string\"and name:match(\"^[%w_%-]+$\")and#name<=32 end local function users()store.invalidate(USERS);return store.read(USERS,{})end local function save(value)return store.write(USERS,value)end local function tombstones()store.invalidate(TOMBSTONES);return store.read(TOMBSTONES,{})end local function saveTombstones(value)return store.write(TOMBSTONES,value)end local function authority()store.invalidate(AUTHORITY)local value=store.read(AUTHORITY,nil)return type(value)==\"table\"and value.active==true and type(value.id)==\"string\"and value or nil end function M.authority()return authority()end function M.centralActive()return authority()~=nil end local function centralDirectory()store.invalidate(DIRECTORY)local value=store.read(DIRECTORY,{})return type(value)==\"table\"and type(value.users)==\"table\"and value or{users={}}end function M.acceptAuthority(record)assert(type(record)==\"table\"and type(record.id)==\"string\"and#record.id<=64,\"invalid auth authority\")local public={schema=1,active=true,id=record.id,term=math.max(0,math.floor(tonumber(record.term)or 0)),revision=math.max(0,math.floor(tonumber(record.revision)or 0)),seen=now()}assert(store.write(AUTHORITY,public),\"could not save auth authority\")if type(record.directory)==\"table\"then assert(store.write(DIRECTORY,{schema=1,revision=public.revision,users=record.directory}),\"could not save account directory\")end local loaded,profile=pcall(require,\"ceetos.lib.profile\")if not loaded or not profile.is(\"auth-server\")then if fs.exists(USERS)then fs.delete(USERS)end if fs.exists(TOMBSTONES)then fs.delete(TOMBSTONES)end sessionPathDelete()end return public end function M.updateDirectory(directory,revision)if type(directory)~=\"table\"then return false,\"invalid account directory\"end return store.write(DIRECTORY,{schema=1,revision=math.max(0,math.floor(tonumber(revision)or 0)),users=directory})end function M.saveCentralSession(value)if type(value)~=\"table\"or not accountName(value.name)or type(value.role)~=\"string\"then return false,\"invalid central session\"end local session={sessionVersion=3,name=value.name,role=value.role,token=value.token,issued=value.issued,expires=value.expires,accountRevision=value.accountRevision,authority=value.authority}if type(session.token)~=\"string\"or#session.token<16 then return false,\"invalid central session token\"end store.write(CENTRAL_SESSION,session)M.current=nil return true end local function safeAudit(action,detail)pcall(audit.log,\"auth\",action,detail or{})end local function stamp(account)account.updated=now()account.origin=tostring(os.getComputerID())account.revision=math.max(0,math.floor(tonumber(account.revision)or 0))+1 return account end local function makeAccount(role,plainPassword,context)local record,err=password.record(plainPassword,password.newSalt(context),configuredWorkFactor)assert(record,err)record.role=role return stamp(record)end sessionPathDelete=function()if fs.exists(SESSION)then fs.delete(SESSION)end store.invalidate(SESSION)end local function saveSession()if M.current==nil then sessionPathDelete();return end local durable={sessionVersion=2,name=M.current.name,nonce=M.current.nonce,issued=M.current.issued,expires=M.current.expires,accountRevision=M.current.accountRevision,}store.write(SESSION,durable)end local function makeSession(name,account)local issued=now()M.current={name=name,role=account.role,nonce=password.newSalt(\"session:\"..name),issued=issued,expires=issued+M.SESSION_TTL_MS,accountRevision=tonumber(account.revision)or 0,}saveSession()return M.current end local function liveAccount(name)local all=users()return all[name],all end local function normaliseSession(saved,account)if type(saved)~=\"table\"or not account or account.disabled then return nil end if saved.sessionVersion==2 then local issued,expires,revision=tonumber(saved.issued),tonumber(saved.expires),tonumber(saved.accountRevision)if type(saved.nonce)~=\"string\"or#saved.nonce<16 or not issued or not expires or not revision then return nil end if expires<=now()or revision~=(tonumber(account.revision)or 0)then return nil end return{name=saved.name,role=account.role,nonce=saved.nonce,issued=issued,expires=expires,accountRevision=revision}end if saved.sessionVersion==nil and type(saved.role)==\"string\"then return\"legacy\"end return nil end function M.refreshSession()local central=authority()if central then store.invalidate(CENTRAL_SESSION)local saved=store.read(CENTRAL_SESSION,nil)local entry=type(saved)==\"table\"and centralDirectory().users[saved.name]or nil if type(saved)~=\"table\"or saved.sessionVersion~=3 or saved.authority~=central.id or type(saved.token)~=\"string\"or(tonumber(saved.expires)or 0)<=now()or type(entry)~=\"table\"or entry.disabled==true or saved.accountRevision~=entry.revision then M.current=nil if fs.exists(CENTRAL_SESSION)then fs.delete(CENTRAL_SESSION)end return nil end M.current={name=saved.name,role=entry.role,nonce=saved.token,issued=saved.issued,expires=saved.expires,accountRevision=saved.accountRevision,authority=central.id,central=true}return M.current end store.invalidate(SESSION)local saved=store.read(SESSION,nil)if type(saved)~=\"table\"or not accountName(saved.name)then M.current=nil;return nil end local account=liveAccount(saved.name)local session=normaliseSession(saved,account)if session==\"legacy\"then return makeSession(saved.name,account)end if not session then M.current=nil sessionPathDelete()return nil end M.current=session return M.current end local function throttleState()store.invalidate(THROTTLE)local data=store.read(THROTTLE,{})return type(data)==\"table\"and data or{}end local function saveThrottle(data)local entries={}for name,entry in pairs(data)do if accountName(name)and type(entry)==\"table\"and type(entry.last)==\"number\"then entries[#entries+1]={name=name,last=entry.last}end end table.sort(entries,function(a,b)return a.last>b.last end)local kept={}for index,entry in ipairs(entries)do if index<=M.LOGIN_THROTTLE.maxEntries then kept[entry.name]=data[entry.name]end end store.write(THROTTLE,kept)end local function locked(name)if not accountName(name)then return false end local entry=throttleState()[name]return entry and(tonumber(entry.lockedUntil)or 0)>now()or false end local function noteFailure(name,reason)if not accountName(name)then return end local data,entry,time=throttleState(),nil,now()entry=data[name]or{failures=0,first=time}if time-(tonumber(entry.first)or 0)>M.LOGIN_THROTTLE.windowMs then entry.failures,entry.first=0,time end entry.failures=math.max(0,math.floor(tonumber(entry.failures)or 0))+1 entry.last=time if entry.failures>=M.LOGIN_THROTTLE.failures then entry.lockedUntil=time+M.LOGIN_THROTTLE.lockMs end data[name]=entry saveThrottle(data)safeAudit(\"login.failure\",{account=name,reason=reason or\"invalid\",throttled=(entry.lockedUntil or 0)>time})end local function clearFailures(name)local data=throttleState()if data[name]~=nil then data[name]=nil;saveThrottle(data)end end function M.throttleStatus(name)local entry=accountName(name)and throttleState()[name]or nil if not entry then return{failures=0,lockedUntil=0}end return{failures=tonumber(entry.failures)or 0,lockedUntil=tonumber(entry.lockedUntil)or 0}end function M.setPasswordWorkFactor(value)local work,err=password.normaliseWorkFactor(value)assert(work,err)configuredWorkFactor=work return work end function M.passwordWorkFactor()return configuredWorkFactor end function M.bootstrap(initialPassword)if authority()then return false end local all=users()if next(all)then return false end local plainPassword=initialPassword if plainPassword==nil then term.write(\"Create CeetOS admin password: \");plainPassword=read(\"*\")end local account=makeAccount(\"admin\",plainPassword,\"admin\")all.admin=account assert(save(all),\"could not save administrator account\")makeSession(\"admin\",account)safeAudit(\"bootstrap\",{account=\"admin\"})return true end function M.login(name,plainPassword)if authority()then local client=require((\"ceetos.lib.auth_client\"))return client.login(name,plainPassword)end if not accountName(name)or type(plainPassword)~=\"string\"then noteFailure(name,\"invalid\")return false,\"invalid credentials\"end if locked(name)then safeAudit(\"login.failure\",{account=name,reason=\"throttled\",throttled=true})return false,\"too many failed attempts; try again later\"end local account,all=liveAccount(name)if not account or account.disabled then noteFailure(name,\"invalid\")return false,\"invalid credentials\"end local valid,state=password.verify(account,plainPassword)if not valid then noteFailure(name,\"invalid\")return false,\"invalid credentials\"end if state==\"legacy\"then local upgraded=makeAccount(account.role,plainPassword,\"upgrade:\"..name)upgraded.updated=account.updated or upgraded.updated upgraded.origin=account.origin or upgraded.origin upgraded.revision=math.max(tonumber(account.revision)or 0,upgraded.revision)stamp(upgraded)all[name]=upgraded assert(save(all),\"could not upgrade password record\")account=upgraded safeAudit(\"password.upgraded\",{account=name})end clearFailures(name)makeSession(name,account)safeAudit(\"login.success\",{account=name})return true end function M.logout()M.current=nil sessionPathDelete()if fs.exists(CENTRAL_SESSION)then fs.delete(CENTRAL_SESSION)end end function M.add(name,role,plainPassword)if authority()then assert(rank[role]and accountName(name),\"invalid user or role\")local record,err=makeAccount(role,plainPassword,\"central:\"..name)assert(record,err)return require((\"ceetos.lib.auth_client\")).mutate(\"add\",{name=name,role=role,record=record})end M.require(\"operator\")assert(rank[role],\"invalid role\")if role==\"admin\"then M.require(\"admin\")end assert(accountName(name),\"invalid user name\")local all=users()assert(not all[name],\"user exists\")all[name]=makeAccount(role,plainPassword,name)assert(save(all),\"could not save user\")safeAudit(\"user.add\",{account=name,role=role})end local function adminCount(all)local count=0 for _,account in pairs(all)do if account.role==\"admin\"and not account.disabled then count=count+1 end end return count end function M.setRole(name,role)if authority()then return require((\"ceetos.lib.auth_client\")).mutate(\"role\",{name=name,role=role})end M.require(\"operator\")assert(accountName(name)and rank[role],\"invalid user or role\")local all,account=users(),users()[name]assert(account,\"unknown user\")if role==\"admin\"or account.role==\"admin\"then M.require(\"admin\")end assert(not(M.current and M.current.name==name),\"cannot change the active account role\")assert(not(account.role==\"admin\"and role~=\"admin\"and adminCount(all)<=1),\"cannot remove the last administrator\")account.role=role stamp(account)all[name]=account assert(save(all),\"could not save account role\")safeAudit(\"user.role\",{account=name,role=role})end function M.setDisabled(name,disabled)if authority()then return require((\"ceetos.lib.auth_client\")).mutate(\"disable\",{name=name,disabled=disabled==true})end M.require(\"admin\")assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]assert(account,\"unknown user\")assert(not(M.current and M.current.name==name),\"cannot disable the active account\")if disabled then assert(not(account.role==\"admin\"and adminCount(all)<=1),\"cannot disable the last administrator\")end account.disabled=disabled==true stamp(account)all[name]=account assert(save(all),\"could not save account state\")safeAudit(\"user.disabled\",{account=name,disabled=account.disabled})end function M.remove(name)if authority()then return require((\"ceetos.lib.auth_client\")).mutate(\"remove\",{name=name})end M.require(\"operator\")assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]assert(account,\"unknown user\")if account.role==\"admin\"then M.require(\"admin\")end assert(not(M.current and M.current.name==name),\"cannot delete the active account\")assert(not(account.role==\"admin\"and adminCount(all)<=1),\"cannot delete the last administrator\")all[name]=nil local removed=tombstones()removed[name]=now()assert(saveTombstones(removed),\"could not save account tombstone\")assert(save(all),\"could not remove account\")safeAudit(\"user.remove\",{account=name})end local function recoveryActive()store.invalidate(RECOVERY)local recovery=store.read(RECOVERY,{})return type(recovery)==\"table\"and(tonumber(recovery.until_ts)or 0)>now()end local function setPassword(name,plainPassword)assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]assert(account,\"unknown user\")local replacement=makeAccount(account.role,plainPassword,\"reset:\"..name)replacement.updated=account.updated or replacement.updated replacement.origin=account.origin or replacement.origin replacement.revision=math.max(tonumber(account.revision)or 0,replacement.revision)replacement.disabled=account.disabled==true stamp(replacement)all[name]=replacement assert(save(all),\"could not save password\")if M.current and M.current.name==name then M.current=nil;sessionPathDelete()end safeAudit(\"password.reset\",{account=name})return true end function M.resetPassword(name,plainPassword)if authority()then local account=centralDirectory().users[name];assert(account,\"unknown user\")local record,err=makeAccount(account.role,plainPassword,\"central-reset:\"..name);assert(record,err)return require((\"ceetos.lib.auth_client\")).mutate(\"reset\",{name=name,record=record})end if not M.allowed(\"admin\")and not recoveryActive()then error(\"permission denied (requires admin or active recovery window)\",2)end return setPassword(name,plainPassword)end function M.adminResetPassword(name,plainPassword)if authority()then local account=centralDirectory().users[name];assert(account,\"unknown user\")local record,err=makeAccount(account.role,plainPassword,\"central-reset:\"..name);assert(record,err)return require((\"ceetos.lib.auth_client\")).mutate(\"reset\",{name=name,record=record})end M.require(\"operator\")local account=users()[name]assert(account,\"unknown user\")if account.role==\"admin\"then M.require(\"admin\")end return setPassword(name,plainPassword)end function M.allowed(role)if not rank[role]then return false end local current=M.refreshSession()return current~=nil and rank[current.role]>=rank[role]end function M.require(role)if not M.allowed(role)then error(\"permission denied (requires \"..tostring(role)..\")\",2)end end function M.list()local out={}local source=authority()and centralDirectory().users or users()for name,account in pairs(source)do out[#out+1]={name=name,role=account.role,disabled=account.disabled==true,revision=account.revision}end table.sort(out,function(a,b)return a.name<b.name end)return out end function M.snapshot()if authority()then return{users={},tombstones={},source=tostring(os.getComputerID()),schema=3,central=true}end return M.authoritySnapshot()end function M.authoritySnapshot()local copy={users={},tombstones={},source=tostring(os.getComputerID()),schema=2}for name,account in pairs(users())do copy.users[name]={role=account.role,salt=account.salt,verifier=account.verifier,passwordVersion=account.passwordVersion,scheme=account.scheme,workFactor=account.workFactor,revision=tonumber(account.revision)or 0,disabled=account.disabled==true,updated=account.updated or 0,origin=account.origin or copy.source,}end for name,removed in pairs(tombstones())do copy.tombstones[name]=removed end return copy end local function validIncomingPassword(account)if password.isModern(account)then local work=password.normaliseWorkFactor(account.workFactor)return work~=nil and type(account.verifier)==\"string\"and#account.verifier==64 and account.verifier:match(\"^[0-9a-f]+$\")~=nil end return type(account.salt)==\"string\"and#account.salt>0 and#account.salt<=256 and type(account.verifier)==\"string\"and account.verifier:match(\"^[0-9a-fA-F]+$\")~=nil and#account.verifier==8 end function M.merge(snapshot,authoritySeed)if authority()and authoritySeed~=true then return false,\"distributed account sync is disabled by central authority\"end if type(snapshot)~=\"table\"or type(snapshot.users)~=\"table\"then return false,\"invalid account sync\"end local all,removed,changed=users(),tombstones(),false for name,deletedAt in pairs(snapshot.tombstones or{})do if accountName(name)and type(deletedAt)==\"number\"and deletedAt>(removed[name]or 0)then local localAccount=all[name]if not localAccount or(localAccount.updated or 0)<=deletedAt then all[name],removed[name],changed=nil,deletedAt,true end end end for name,account in pairs(snapshot.users)do if accountName(name)and type(account)==\"table\"and rank[account.role]and validIncomingPassword(account)then local updated=tonumber(account.updated)or 0 local localAccount,incomingOrigin=all[name],tostring(account.origin or snapshot.source or\"\")local localOrigin=localAccount and tostring(localAccount.origin or os.getComputerID())or\"\"local wins=not localAccount or updated>(localAccount.updated or 0)or(updated==(localAccount.updated or 0)and incomingOrigin~=\"\"and incomingOrigin<localOrigin)if(removed[name]==nil or updated>removed[name])and wins then all[name]={role=account.role,salt=account.salt,verifier=account.verifier,passwordVersion=account.passwordVersion,scheme=account.scheme,workFactor=account.workFactor,revision=math.max(0,math.floor(tonumber(account.revision)or 0)),disabled=account.disabled==true,updated=updated,origin=incomingOrigin,}changed=true end end end if changed then assert(save(all),\"could not save account sync\")assert(saveTombstones(removed),\"could not save account tombstones\")M.refreshSession()end return changed end function M.authorityAccount(name)if not accountName(name)then return nil end return users()[name]end function M.authorityDirectory()local out={}for name,account in pairs(users())do out[name]={role=account.role,disabled=account.disabled==true,revision=tonumber(account.revision)or 0}end return out end function M.authorityMutate(action,fields)fields=type(fields)==\"table\"and fields or{}local name=fields.name assert(accountName(name),\"invalid user name\")local all,account=users(),users()[name]if action==\"add\"then assert(not account,\"user exists\")assert(rank[fields.role],\"invalid role\")local record=fields.record assert(type(record)==\"table\"and password.isModern(record),\"central account mutation requires a verifier record\")record.role,record.disabled=fields.role,false;all[name]=stamp(record);assert(save(all),\"could not save user\")elseif action==\"role\"then assert(account and rank[fields.role],\"unknown user or invalid role\")if account.role==\"admin\"and fields.role~=\"admin\"then local admins=0;for _,candidate in pairs(all)do if candidate.role==\"admin\"and not candidate.disabled then admins=admins+1 end end assert(admins>1,\"cannot demote the last active admin\")end account.role=fields.role;stamp(account);all[name]=account;assert(save(all),\"could not save role\")elseif action==\"disable\"then if account and account.role==\"admin\"and fields.disabled==true then local admins=0;for _,candidate in pairs(all)do if candidate.role==\"admin\"and not candidate.disabled then admins=admins+1 end end assert(admins>1,\"cannot disable the last active admin\")end assert(account,\"unknown user\");account.disabled=fields.disabled==true;stamp(account);all[name]=account;assert(save(all),\"could not save user state\")elseif action==\"remove\"then assert(account,\"unknown user\")if account.role==\"admin\"and not account.disabled then local admins=0;for _,candidate in pairs(all)do if candidate.role==\"admin\"and not candidate.disabled then admins=admins+1 end end assert(admins>1,\"cannot remove the last active admin\")end all[name]=nil;local removed=tombstones();removed[name]=now();assert(saveTombstones(removed),\"could not save tombstone\");assert(save(all),\"could not remove user\")elseif action==\"reset\"then assert(account,\"unknown user\")local replacement=fields.record assert(type(replacement)==\"table\"and password.isModern(replacement),\"central password reset requires a verifier record\")replacement.role,replacement.disabled=account.role,account.disabled==true;all[name]=stamp(replacement);assert(save(all),\"could not save password\")else error(\"unsupported account mutation\")end safeAudit(\"authority.\"..action,{account=name})return M.authorityDirectory()end M.refreshSession()return M",
  ["ceetos/lib/password.lua"] = "local M={}M.SCHEME=\"pbkdf2-hmac-sha256\"M.PASSWORD_VERSION=2 M.DEFAULT_WORK_FACTOR=256 M.MIN_WORK_FACTOR=64 M.MAX_WORK_FACTOR=2048 M.MIN_LENGTH=8 M.MAX_LENGTH=128 local MOD=4294967296 local band,bor,bxor,bnot=bit32.band,bit32.bor,bit32.bxor,bit32.bnot local rshift,lshift=bit32.rshift,bit32.lshift local unpack=table.unpack or unpack local K={0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2,}local initial={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,}local function add(...)local value=0 for i=1,select(\"#\",...)do value=(value+(select(i,...)or 0))%MOD end return value end local function rrotate(value,amount)if bit32.rrotate then return bit32.rrotate(value,amount)end return bor(rshift(value,amount),lshift(value,32-amount))end local function word(bytes,index)return bytes:byte(index)*16777216+bytes:byte(index+1)*65536+bytes:byte(index+2)*256+bytes:byte(index+3)end local function packWord(value)return string.char(band(rshift(value,24),0xff),band(rshift(value,16),0xff),band(rshift(value,8),0xff),band(value,0xff))end local function sha256Raw(value)local bitLength=#value*8 value=value..string.char(0x80)value=value..string.rep(\"\\0\",(56-(#value%64))%64)value=value..packWord(math.floor(bitLength/MOD))..packWord(bitLength%MOD)local h={unpack(initial)}for offset=1,#value,64 do if#value>16384 and offset>1 and((offset-1)/64)%128==0 and type(sleep)==\"function\"then sleep(0)end local w={}for i=1,16 do w[i]=word(value,offset+(i-1)*4)end for i=17,64 do local x,y=w[i-15],w[i-2]local s0=bxor(rrotate(x,7),rrotate(x,18),rshift(x,3))local s1=bxor(rrotate(y,17),rrotate(y,19),rshift(y,10))w[i]=add(w[i-16],s0,w[i-7],s1)end local a,b,c,d,e,f,g,hh=unpack(h)for i=1,64 do local s1=bxor(rrotate(e,6),rrotate(e,11),rrotate(e,25))local choice=bxor(band(e,f),band(bnot(e),g))local t1=add(hh,s1,choice,K[i],w[i])local s0=bxor(rrotate(a,2),rrotate(a,13),rrotate(a,22))local majority=bxor(band(a,b),band(a,c),band(b,c))local t2=add(s0,majority)hh,g,f,e,d,c,b,a=g,f,e,add(d,t1),c,b,a,add(t1,t2)end h[1],h[2],h[3],h[4]=add(h[1],a),add(h[2],b),add(h[3],c),add(h[4],d)h[5],h[6],h[7],h[8]=add(h[5],e),add(h[6],f),add(h[7],g),add(h[8],hh)end local result={}for i=1,8 do result[i]=packWord(h[i])end return table.concat(result)end local function hmac(key,message)if#key>64 then key=sha256Raw(key)end key=key..string.rep(\"\\0\",64-#key)local inner,outer={},{}for i=1,64 do local byte=key:byte(i)inner[i],outer[i]=string.char(bxor(byte,0x36)),string.char(bxor(byte,0x5c))end return sha256Raw(table.concat(outer)..sha256Raw(table.concat(inner)..message))end local function xorBytes(left,right)local out={}for i=1,#left do out[i]=string.char(bxor(left:byte(i),right:byte(i)))end return table.concat(out)end local function cooperate(round)if round%32~=0 or not(os and os.queueEvent and os.pullEvent)then return end os.queueEvent(\"ceetos_password_yield\")os.pullEvent(\"ceetos_password_yield\")end local function toHex(value)return(value:gsub(\".\",function(byte)return string.format(\"%02x\",byte:byte())end))end local function constantEqual(left,right)if type(left)~=\"string\"or type(right)~=\"string\"then return false end local differing=bxor(#left,#right)local length=math.max(#left,#right)for i=1,length do differing=bor(differing,bxor(left:byte(i)or 0,right:byte(i)or 0))end return differing==0 end function M.hmacSha256(key,message)if type(key)~=\"string\"or type(message)~=\"string\"then return nil,\"HMAC key and message must be strings\"end return toHex(hmac(key,message))end function M.sha256(value)if type(value)~=\"string\"then return nil,\"SHA-256 input must be a string\"end return toHex(sha256Raw(value))end function M.constantTimeEqual(left,right)return constantEqual(left,right)end function M.legacyDigest(value)local h=2166136261 for i=1,#value do h=bxor(h,value:byte(i))h=(h*16777619)%MOD end return string.format(\"%08x\",h)end function M.normaliseWorkFactor(value)value=tonumber(value)if not value or value%1~=0 then return nil,\"invalid password work factor\"end if value<M.MIN_WORK_FACTOR or value>M.MAX_WORK_FACTOR then return nil,\"password work factor must be \"..M.MIN_WORK_FACTOR..\"-\"..M.MAX_WORK_FACTOR end return value end function M.policy(password)if type(password)~=\"string\"then return false,\"password is required\"end if#password<M.MIN_LENGTH or#password>M.MAX_LENGTH then return false,\"password must contain \"..M.MIN_LENGTH..\"-\"..M.MAX_LENGTH..\" characters\"end if password:find(\"[%z\\1-\\31\\127]\")then return false,\"password contains control characters\"end return true end function M.derive(password,salt,workFactor)local work,err=M.normaliseWorkFactor(workFactor)if not work then return nil,err end if type(password)~=\"string\"or type(salt)~=\"string\"or#salt<16 or#salt>256 then return nil,\"invalid password record\"end local block=string.char(0,0,0,1)local value=hmac(password,salt..block)local result=value for _=2,work do value=hmac(password,value)result=xorBytes(result,value)cooperate(_)end return toHex(result)end local saltCounter=0 function M.newSalt(context)saltCounter=saltCounter+1 local now=os.epoch and os.epoch(\"utc\")or 0 local computer=os.getComputerID and os.getComputerID()or 0 local label=os.getComputerLabel and os.getComputerLabel()or\"\"local random=math.random and math.random(0,2147483647)or 0 return toHex(sha256Raw(table.concat({tostring(now),tostring(computer),tostring(label),tostring(context or\"\"),tostring(saltCounter),tostring(random)},\":\"))):sub(1,32)end function M.record(password,salt,workFactor)local valid,err=M.policy(password)if not valid then return nil,err end local work,workErr=M.normaliseWorkFactor(workFactor or M.DEFAULT_WORK_FACTOR)if not work then return nil,workErr end salt=salt or M.newSalt()local verifier,deriveErr=M.derive(password,salt,work)if not verifier then return nil,deriveErr end return{passwordVersion=M.PASSWORD_VERSION,scheme=M.SCHEME,salt=salt,verifier=verifier,workFactor=work,}end function M.isModern(record)return type(record)==\"table\"and record.passwordVersion==M.PASSWORD_VERSION and record.scheme==M.SCHEME end function M.verify(record,password)if type(record)~=\"table\"or type(password)~=\"string\"or type(record.salt)~=\"string\"or type(record.verifier)~=\"string\"then return false,\"invalid password record\"end if M.isModern(record)then local verifier,err=M.derive(password,record.salt,record.workFactor)if not verifier then return false,err end return constantEqual(record.verifier,verifier),nil end return constantEqual(record.verifier,M.legacyDigest(record.salt..password)),\"legacy\"end return M",
  ["ceetos/lib/release_keys.lua"] = "return{algorithm=\"lamport-sha256-v1\",roots={[\"desktop-release-0.16.9\"]={public=\"ChZ8CGkSeQAnvNfH8J9J2icSLBS8zDCZctujdf24kgnS9wLo1bEOC9dQhPr611gx4dnDEo4nvTcbBLo32v4j6CG/IVO8qEiQSn0jt+eZzabgYMmTjx7JE3szwlIMGRrlWUvLztYb3dL105pl4LHJOAEl3CS7dm+RA+X/BmVJ7S6iQFIU3FsWOzjIa03d51AtnyjR9ETddkNS3vvUIUj+C6JC03XJcz+f39cd1Ad6cS8a+KSgmvCszWInigJm/Vcu9EbM0faFMIs5yIUcWgTcuyo44+45scFbhE9Xj67dgCX2FSoqzJLTXWs/Z+PtVqlUkLzRgp2YzALiWW2lTMMsSRC5yLSyZFv+ixnaD6URnS3l0ZMAmigv8fH3msKQ26fk3MuFNyz66Yz6cZV25ISsRf5vDvNQBhmvyTU0OetXhJNuSQe2kQL9yVb3ukmNSrEUskl0xhxUY7tdKQGRFVgYh9V4EwX3pRt3keOWPxTQ6y3PLZ1AkS3evzvjfdSvjp3pYhHve5Y9uulHq9Smi3Ews1PaijXphWWKl/uGGn/QYmXln3MM0o+MbFbxqCtRYiFJ3FQw3CRnuNuQ3XTzzKaa5K67unx4GxuoenWEdCl7cuFxV/VMWPZ4niZ4UnEnFf1sWooj/SRMT645E8FzAmd1ObuaztTutVVWFKIEfigYafD49GANJRRS9V4vmvMQykZhwX1HoU3p3H+c9OsPLA/oP1JKVdZbO3CpFcWAzafwU/54qGTMTU3sY9mJvnUkISMYaqxDV1kR52bGsKv4vvdHg27gaGCRiLCZgJaGOqwdJKWc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A+SJWZYwRnH6p3qwoG19X8W2+ORCJxmhfUBcck1v7RvDzm2E1IJVrvS5uYy7A12/0yQncf62lk8cFtHqQ4CliuXUbstRzfHj/IJhPY+ftL61u/xTCdDPPO5DZ+RZ3N9M89olddp0zRwwhHrEfwBrH7kvEncMryA2N+jDp+I9KC6b4b2fZ3nlGGOTL+rPauHs3odDAg0kd1cBJ1M9Bd6CtgEyvx1CojmuL85sTOAH8W53JhUE9IbW+3+aNCM3nAxlg8iuCba4ogtbBnY5Lz24/6rm5/CusioUv/hGPng6rPz1pRaMy1VudmR/r+EUn9vDKIP9X8OwQ/dPyq0HbBNkZ7+9JbQjwNvpooSapHtz3bS3k3K3/oMyF8kncrySquw1upHqmp5vUqB7jFtovfx8rK7x1jrx3GX1edP9w9tDmb0VUjWsAG3reEugC4rCPJWm6FtSGBliWUN9FKbZFQRZU/yy8OD47ET2U9mbMvUGRi+WdoZEJsqNpGmMmj5Y9RdwXm/F3UIwBhM0+2eNxIKClpY7dFcELcgs7zUki46CbjQdCc8ysVCbH97RPuW76S2/lP30NL2xtQPK8IQ4T2zTB3vnx37oM/NcY0Kekkff6D0RUk2EuIURPx5XYK2oHt6syY+nZQgQ0oqxtNn2Fv8w6K8tdDTo/QYyeWCtVW7zBLkliUDUxZd6lfIPA6pv6EXrhqSmA6gQEzRhpCPlnCd6P4FK+w4Wuz871mpcT9Ph66cZcsygVuaNTlRYSVp+HOsZuMAPcxNC/lNB9JpRhUHXpRhpQlkKswdOtzN0YQORXegtWVZmFuaD9D1txq8Po2M9Hx/bEMYVVn/GcVGwN0f4aSQ==\",profile=\"desktop\"},},}",
  ["ceetos/lib/release_verify.lua"] = "local password=require(\"ceetos.lib.password\")local roots=require(\"ceetos.lib.release_keys\")local profile=require(\"ceetos.lib.profile\")local M={}M.CACHE_ROOT=\"/ceetos-updates\"M.CACHE_FILE=\"/ceetos-updates/release.lua\"M.META_FILE=\"/ceetos-updates/cache.lua\"M.PART_FILE=\"/ceetos-updates/release.part\"M.PENDING_FILE=\"/ceetos-updates/pending.lua\"M.MAX_PACKAGE_BYTES=1024*1024 M.MAX_MANIFEST_BYTES=48*1024 M.CHUNK_BYTES=3072 M.KEY_PARTS=256 local alphabet=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"local decodeMap={}for i=1,#alphabet do decodeMap[alphabet:sub(i,i)]=i-1 end local function read(path)if not fs.exists(path)or fs.isDir(path)then return nil end local handle=fs.open(path,\"r\")if not handle then return nil end local value=handle.readAll();handle.close()return value end local function write(path,value)local parent=fs.getDir(path)if parent~=\"\"and not fs.exists(parent)then fs.makeDir(parent)end local temporary=path..\".tmp\"if fs.exists(temporary)then fs.delete(temporary)end local handle=assert(fs.open(temporary,\"w\"),\"could not create temporary release state\")handle.write(value);handle.close()if fs.exists(path)then fs.delete(path)end fs.move(temporary,path)end local function encode(value)local out,index={},1 while index<=#value do local a,b,c=value:byte(index,index+2)local n=(a or 0)*65536+(b or 0)*256+(c or 0)out[#out+1]=alphabet:sub(math.floor(n/262144)%64+1,math.floor(n/262144)%64+1)out[#out+1]=alphabet:sub(math.floor(n/4096)%64+1,math.floor(n/4096)%64+1)out[#out+1]=b and alphabet:sub(math.floor(n/64)%64+1,math.floor(n/64)%64+1)or\"=\"out[#out+1]=c and alphabet:sub(n%64+1,n%64+1)or\"=\"index=index+3 end return table.concat(out)end local function decode(value)if type(value)~=\"string\"or#value%4~=0 or#value>M.MAX_MANIFEST_BYTES*2 then return nil,\"invalid base64\"end local out={}for index=1,#value,4 do local a,b,c,d=value:sub(index,index),value:sub(index+1,index+1),value:sub(index+2,index+2),value:sub(index+3,index+3)if not decodeMap[a]or not decodeMap[b]or(c~=\"=\"and not decodeMap[c])or(d~=\"=\"and not decodeMap[d])then return nil,\"invalid base64\"end if(c==\"=\"and d~=\"=\")or((c==\"=\"or d==\"=\")and index+3~=#value)then return nil,\"invalid base64 padding\"end local n=decodeMap[a]*262144+decodeMap[b]*4096+(decodeMap[c]or 0)*64+(decodeMap[d]or 0)out[#out+1]=string.char(math.floor(n/65536)%256)if c~=\"=\"then out[#out+1]=string.char(math.floor(n/256)%256)end if d~=\"=\"then out[#out+1]=string.char(n%256)end end return table.concat(out)end local function unhex(value)if type(value)~=\"string\"or#value%2~=0 or value:find(\"[^%x]\")then return nil end return(value:gsub(\"..\",function(pair)return string.char(tonumber(pair,16))end))end local function semver(value)if type(value)~=\"string\"then return nil end local major,minor,patch=value:match(\"^(%d+)%.(%d+)%.(%d+)$\")if not major then return nil end return tonumber(major),tonumber(minor),tonumber(patch)end function M.compareVersions(left,right)local a,b,c=semver(left);local x,y,z=semver(right)if not a or not x then return nil,\"invalid semantic version\"end if a~=x then return a<x and-1 or 1 end if b~=y then return b<y and-1 or 1 end if c~=z then return c<z and-1 or 1 end return 0 end local function canonical(manifest)if manifest._legacyProfile==true then return table.concat({\"ceetos-release-v1\",tostring(manifest.channel),tostring(manifest.version),tostring(manifest.size),tostring(manifest.digest),tostring(manifest.key_id),tostring(manifest.next_key_id),tostring(manifest.next_public),},\"|\")end return table.concat({\"ceetos-release-v2\",tostring(manifest.channel),tostring(manifest.profile),tostring(manifest.version),tostring(manifest.size),tostring(manifest.digest),tostring(manifest.key_id),tostring(manifest.next_key_id),tostring(manifest.next_public),},\"|\")end local function unpackKey(value)local raw,err=decode(value)if not raw or#raw~=M.KEY_PARTS*2*32 then return nil,err or\"invalid public key\"end local parts={}for index=1,M.KEY_PARTS*2 do parts[index]=raw:sub((index-1)*32+1,index*32)end return parts end function M.validPublicKey(value)return unpackKey(value)end local function lookupKey(keyId)local saved=M.trustedKeys()local value=saved[keyId]if value then return unpackKey(value)end value=roots.roots and roots.roots[keyId]if type(value)==\"table\"and type(value.public)==\"string\"then value=value.public end return unpackKey(value)end local function bitAt(digest,index)local byte=digest:byte(math.floor((index-1)/8)+1)return bit32.band(bit32.rshift(byte,7-((index-1)%8)),1)end local function decodeSignature(value)local raw,err=decode(value)if not raw or#raw~=M.KEY_PARTS*32 then return nil,err or\"invalid signature\"end local parts={}for index=1,M.KEY_PARTS do parts[index]=raw:sub((index-1)*32+1,index*32)end return parts end local function verifySignature(manifest,signature)if roots.algorithm~=\"lamport-sha256-v1\"then return false,\"unsupported release signing algorithm\"end local public,publicErr=lookupKey(manifest.key_id)local parts,signatureErr=decodeSignature(signature)if not public or not parts then local prefix=not public and\"invalid release public key: \"or\"invalid release signature: \"return false,prefix..tostring(publicErr or signatureErr or\"unknown release key\")end local digest=unhex(password.sha256(canonical(manifest))or\"\")if not digest then return false,\"could not hash release manifest\"end for index=1,M.KEY_PARTS do local expected=public[(index-1)*2+bitAt(digest,index)+1]local candidate=unhex(password.sha256(parts[index])or\"\")if not candidate or not password.constantTimeEqual(candidate,expected)then return false,\"invalid release signature\"end end return true end local function validateManifest(manifest)if type(manifest)~=\"table\"or manifest.channel~=\"release\"then return nil,\"only signed release packages are accepted\"end if manifest.profile==nil then manifest.profile,manifest._legacyProfile=\"desktop\",true end if type(manifest.profile)~=\"string\"or not profile.IDS[manifest.profile]then return nil,\"invalid release profile\"end if not semver(manifest.version)or type(manifest.size)~=\"number\"or manifest.size<1 or manifest.size>M.MAX_PACKAGE_BYTES then return nil,\"invalid release manifest size or version\"end if type(manifest.digest)~=\"string\"or#manifest.digest~=64 or manifest.digest:find(\"[^%x]\")then return nil,\"invalid release digest\"end if type(manifest.key_id)~=\"string\"or#manifest.key_id<1 or#manifest.key_id>64 then return nil,\"invalid release key id\"end if type(manifest.next_key_id)~=\"string\"or#manifest.next_key_id<1 or#manifest.next_key_id>64 then return nil,\"invalid next release key id\"end local nextKey=unpackKey(manifest.next_public)if not nextKey then return nil,\"invalid successor release key\"end return manifest end function M.parse(source)if type(source)~=\"string\"or#source>M.MAX_PACKAGE_BYTES then return nil,\"release package is too large\"end local encodedManifest,encodedSignature=source:match(\"^%-%- CEETOS_RELEASE_MANIFEST:([^\\r\\n]+)[\\r\\n]+%-%- CEETOS_RELEASE_SIGNATURE:([^\\r\\n]+)\")if not encodedManifest then encodedManifest,encodedSignature=source:match(\"^%-%- CeetOS signed release%. Generated; do not edit%.[\\r\\n]+%-%- CEETOS_RELEASE_MANIFEST:([^\\r\\n]+)[\\r\\n]+%-%- CEETOS_RELEASE_SIGNATURE:([^\\r\\n]+)\")end local first=source:find(\"%-%- CEETOS_RELEASE_PAYLOAD_BEGIN[\\r\\n]+\")if not encodedManifest or not encodedSignature or not first then return nil,\"not a signed CeetOS release package\"end local decoded,decodeErr=decode(encodedManifest)if not decoded then return nil,\"invalid release manifest encoding: \"..tostring(decodeErr)end local loader=load(\"return \"..decoded,\"=release-manifest\",\"t\",{})if not loader then return nil,\"invalid release manifest\"end local ok,manifest=pcall(loader)if not ok then return nil,\"invalid release manifest\"end local valid,manifestErr=validateManifest(manifest)if not valid then return nil,manifestErr end local start=source:find(\"\\n\",first)+1 local finish=start+valid.size-1 local payload=source:sub(start,finish)local suffix=source:sub(finish+1)if suffix~=\"\\n-- CEETOS_RELEASE_PAYLOAD_END\\n\"and suffix~=\"\\n-- CEETOS_RELEASE_PAYLOAD_END\"and suffix~=\"\\r\\n-- CEETOS_RELEASE_PAYLOAD_END\\r\\n\"and suffix~=\"\\r\\n-- CEETOS_RELEASE_PAYLOAD_END\"then return nil,\"release payload boundary mismatch\"end if#payload~=valid.size or not password.constantTimeEqual(password.sha256(payload)or\"\",valid.digest)then return nil,\"release payload digest mismatch\"end local signed,signatureErr=verifySignature(valid,encodedSignature)if not signed then return nil,signatureErr end return{manifest=valid,signature=encodedSignature,payload=payload,source=source}end function M.trustedKeys()local raw=read(M.CACHE_ROOT..\"/trusted-keys.lua\")if not raw then return{}end local loader=load(raw,\"=trusted-release-keys\",\"t\",{})if not loader then return{}end local ok,value=pcall(loader)return ok and type(value)==\"table\"and value or{}end local function saveKeys(value)local encoded=textutils.serialise(value,{compact=true})write(M.CACHE_ROOT..\"/trusted-keys.lua\",\"return \"..encoded)end function M.metadata()local raw=read(M.META_FILE)if not raw then return nil end local loader=load(raw,\"=release-cache\",\"t\",{})if not loader then return nil end local ok,value=pcall(loader)return ok and type(value)==\"table\"and value or nil end function M.cache(source,provider)local package,err=M.parse(source)if not package then return nil,err end if fs.exists(M.CACHE_ROOT)and fs.isDir(M.CACHE_ROOT)then if fs.exists(M.PART_FILE)then fs.delete(M.PART_FILE)end elseif not fs.exists(M.CACHE_ROOT)then fs.makeDir(M.CACHE_ROOT)end write(M.CACHE_FILE,package.source)local metadata={schema=2,channel=package.manifest.channel,profile=package.manifest.profile,version=package.manifest.version,size=package.manifest.size,digest=package.manifest.digest,keyId=package.manifest.key_id,nextKeyId=package.manifest.next_key_id,source=provider and tostring(provider)or\"local\",cachedAt=os.epoch(\"utc\"),}write(M.META_FILE,\"return \"..textutils.serialise(metadata,{compact=true}))local keys=M.trustedKeys();keys[package.manifest.next_key_id]=package.manifest.next_public;saveKeys(keys)return metadata end function M.promotePart(path,provider)if type(path)~=\"string\"or path~=M.PART_FILE then return nil,\"invalid release staging path\"end local source=read(path)local package,err=M.parse(source)if not package then return nil,err end if not fs.exists(M.CACHE_ROOT)then fs.makeDir(M.CACHE_ROOT)end if fs.exists(M.CACHE_FILE)then fs.delete(M.CACHE_FILE)end fs.move(M.PART_FILE,M.CACHE_FILE)local metadata={schema=2,channel=package.manifest.channel,profile=package.manifest.profile,version=package.manifest.version,size=package.manifest.size,digest=package.manifest.digest,keyId=package.manifest.key_id,nextKeyId=package.manifest.next_key_id,source=provider and tostring(provider)or\"local\",cachedAt=os.epoch(\"utc\"),}write(M.META_FILE,\"return \"..textutils.serialise(metadata,{compact=true}))M.adopt(package)return metadata end function M.adopt(package)if type(package)~=\"table\"or type(package.manifest)~=\"table\"then return false,\"invalid verified package\"end local keys=M.trustedKeys()keys[package.manifest.next_key_id]=package.manifest.next_public saveKeys(keys)return true end function M.cachedPackage()local source,metadata=read(M.CACHE_FILE),M.metadata()if not source then return nil end local package,err=M.parse(source)if not package then return nil,err end if not metadata then metadata={schema=2,channel=package.manifest.channel,profile=package.manifest.profile,version=package.manifest.version,size=package.manifest.size,digest=package.manifest.digest,keyId=package.manifest.key_id,nextKeyId=package.manifest.next_key_id,source=\"local installer\",cachedAt=os.epoch(\"utc\"),}write(M.META_FILE,\"return \"..textutils.serialise(metadata,{compact=true}))end M.adopt(package)return package,metadata end function M.clear()if fs.exists(M.PART_FILE)then fs.delete(M.PART_FILE)end if fs.exists(M.CACHE_FILE)then fs.delete(M.CACHE_FILE)end if fs.exists(M.META_FILE)then fs.delete(M.META_FILE)end return true end function M.encode(value)return encode(value)end function M.decode(value)return decode(value)end function M.canonical(manifest)return canonical(manifest)end return M",
  ["ceetos/lib/updater.lua"] = "local store=require(\"ceetos.lib.store\")local release=require(\"ceetos.lib.release_verify\")local version=require(\"ceetos.lib.version\")local net=require(\"ceetos.lib.net\")local profile=require(\"ceetos.lib.profile\")local M={}local STATE_PATH=\"/ceetos/data/update-status.lua\"local OFFER_LIMIT,HISTORY_LIMIT=20,16 local BEACON_INTERVAL,REQUEST_TIMEOUT,REQUEST_LIMIT=30000,3500,3 local MAX_OFFER_AGE=5*60*1000 local CLOUD_RELEASE_ORIGIN=\"https://releases.ceet.uk\"local CLOUD_MANIFEST_URL=CLOUD_RELEASE_ORIGIN..\"/manifest.json\"local CLOUD_SOURCE_ID=\"cloud.releases.ceet.uk\"local state=nil local lastBeacon,lastCacheRead=0,0 local cached=nil local function now()return os.epoch(\"utc\")end local function localId()return tostring(os.getComputerID())end local function localLabel()return os.getComputerLabel()or(\"Computer \"..localId())end local function defaults()return{schema=1,offers={},history={},revision=0,status=\"idle\",message=nil,transfer=nil,cache=nil}end local function loadState()if state then return state end state=store.read(STATE_PATH,defaults())for key,value in pairs(defaults())do if state[key]==nil then state[key]=value end end state.offers=type(state.offers)==\"table\"and state.offers or{}state.history=type(state.history)==\"table\"and state.history or{}return state end local function save()local value=loadState()value.revision=(tonumber(value.revision)or 0)+1 store.write(STATE_PATH,value)end local function record(kind,fields)local value=loadState()local row={at=now(),kind=tostring(kind):sub(1,48)}for key,item in pairs(fields or{})do if key~=\"data\"and key~=\"source\"and key~=\"signature\"then row[key]=item end end value.history[#value.history+1]=row while#value.history>HISTORY_LIMIT do table.remove(value.history,1)end end local function setStatus(status,message)local value=loadState()value.status,value.message=status,message and tostring(message):sub(1,180)or nil end local function validId(value)return type(value)==\"string\"and value:match(\"^[%w_%-%.]+$\")and#value<=96 end local function releaseFilename(profileId,releaseVersion)if profileId==\"desktop\"then return\"desktop/ceetos-release\"..releaseVersion..\".lua\"end return profileId..\"/ceetos-\"..profileId..\"-release\"..releaseVersion..\".lua\"end local function readHttp(url,limit)if not http or type(http.get)~=\"function\"then return nil,\"HTTP is unavailable; enable it to check releases.ceet.uk\"end local ok,response,requestErr=pcall(http.get,url,{[\"Accept\"]=\"application/json\"})if not ok or not response then return nil,tostring(requestErr or\"release server request failed\")end local chunks,total={},0 while true do local part=response.read(math.min(4096,limit-total+1))if not part or part==\"\"then break end total=total+#part if total>limit then pcall(response.close);return nil,\"release server response is too large\"end chunks[#chunks+1]=part end pcall(response.close)return table.concat(chunks)end local function validOffer(body)if type(body)~=\"table\"or type(body.version)~=\"string\"or type(body.size)~=\"number\"or type(body.digest)~=\"string\"or type(body.keyId)~=\"string\"or type(body.profile)~=\"string\"then return nil,\"malformed release offer\"end if body.profile~=profile.id()then return nil,\"release profile does not match this installation\"end local compare=release.compareVersions(body.version,version.string)if compare==nil then return nil,\"invalid release version\"end if body.size<1 or body.size>release.MAX_PACKAGE_BYTES then return nil,\"invalid release size\"end if#body.digest~=64 or body.digest:find(\"[^%x]\")then return nil,\"invalid release digest\"end if#body.keyId<1 or#body.keyId>64 then return nil,\"invalid release key ID\"end local filename=body.filename if filename~=nil and filename~=releaseFilename(body.profile,body.version)then return nil,\"invalid release filename\"end return{profile=body.profile,version=body.version,size=math.floor(body.size),digest=body.digest:lower(),keyId=body.keyId,filename=filename,fingerprint=body.digest:sub(1,16),newer=compare>0}end local function refreshCached()local timestamp=now()if cached and timestamp-lastCacheRead<5000 then return cached end lastCacheRead=timestamp local value=loadState()local previous=value.cache and(tostring(value.cache.version)..\":\"..tostring(value.cache.digest))or nil local package,metadata=release.cachedPackage()if package and package.manifest.profile==profile.id()then cached={package=package,metadata=metadata,offer={version=package.manifest.version,size=#package.source,digest=package.manifest.digest,profile=package.manifest.profile,keyId=package.manifest.key_id,fingerprint=package.manifest.digest:sub(1,16),}}value.cache={profile=package.manifest.profile,version=package.manifest.version,size=#package.source,digest=package.manifest.digest,keyId=package.manifest.key_id,fingerprint=package.manifest.digest:sub(1,16),source=metadata and metadata.source or\"local\",verifiedAt=timestamp}else cached=nil value.cache=nil end local current=value.cache and(tostring(value.cache.version)..\":\"..tostring(value.cache.digest))or nil if current~=previous then save()end return cached end local function providerOffer()local available=refreshCached()if not available then return nil end return{version=available.offer.version,size=available.offer.size,digest=available.offer.digest,profile=available.offer.profile,keyId=available.offer.keyId,label=localLabel(),id=localId(),}end local function upsertOffer(source,body,transport,distance)source=tostring(source)if source==localId()then return false,\"ignored own release offer\"end local offer,err=validOffer(body)if not offer then return false,err end if not offer.newer then return false,\"offered release is not newer\"end local value=loadState()local key=source..\":\"..offer.version..\":\"..offer.digest:sub(1,16)value.offers[key]={id=source,label=tostring(body.label or(\"Computer \"..source)):sub(1,96),version=offer.version,profile=offer.profile,size=offer.size,digest=offer.digest,fingerprint=offer.fingerprint,keyId=offer.keyId,filename=offer.filename,transport=transport,distance=tonumber(distance),seen=now(),key=key,}local rows={}for entryKey,item in pairs(value.offers)do rows[#rows+1]={key=entryKey,seen=tonumber(item.seen)or 0}end table.sort(rows,function(a,b)return a.seen>b.seen end)while#rows>OFFER_LIMIT do value.offers[table.remove(rows).key]=nil end setStatus(\"offers\",\"Signed release \"..offer.version..\" available from \"..tostring(body.label or source))record(\"offer\",{id=source,version=offer.version,transport=transport,distance=distance})save()return true end local function checkCloudManifest()local raw,readErr=readHttp(CLOUD_MANIFEST_URL,release.MAX_MANIFEST_BYTES)if not raw then return 0,readErr end local ok,catalogue=pcall(textutils.unserialiseJSON,raw)if not ok or type(catalogue)~=\"table\"or catalogue.schema~=1 or type(catalogue.releases)~=\"table\"or#catalogue.releases>OFFER_LIMIT then return 0,\"invalid signed-release catalogue\"end local count=0 for index=1,#catalogue.releases do local entry=catalogue.releases[index]if type(entry)==\"table\"and entry.profile==profile.id()then local accepted=upsertOffer(CLOUD_SOURCE_ID,entry,\"cloud\")if accepted then count=count+1 end end end return count end local function offers()local value,timestamp,rows=loadState(),now(),{}for key,item in pairs(value.offers)do if type(item)==\"table\"and timestamp-(tonumber(item.seen)or 0)<=MAX_OFFER_AGE then rows[#rows+1]=item else value.offers[key]=nil end end table.sort(rows,function(left,right)local compare=release.compareVersions(left.version,right.version)or 0 if compare~=0 then return compare>0 end return tostring(left.id)<tostring(right.id)end)return rows end local function findOffer(source)source=tostring(source)for _,item in ipairs(offers())do if item.key==source or tostring(item.id)==source then return item end end return nil,\"release source is unavailable; run update check first\"end local function removePart()if fs.exists(release.PART_FILE)then fs.delete(release.PART_FILE)end end local function appendPart(data)local handle,err=fs.open(release.PART_FILE,\"a\")if not handle then return false,err or\"could not open update staging file\"end handle.write(data);handle.close()return true end local function cachedSource()local available=refreshCached()return available and available.package and available.package.source end local function transferRequest(transfer)local length=math.min(release.CHUNK_BYTES,transfer.size-transfer.offset+1)if length<1 then return false,\"transfer is already complete\"end transfer.awaiting,transfer.requestedAt=true,now()local body={transfer=transfer.id,offset=transfer.offset,length=length}local sent,err if transfer.transport==\"routed\"then sent,err=net.request(transfer.source,\"update_chunk_request\",body,{safe=true})else sent,err=net.publicSend(transfer.source,\"update_chunk_request\",body)end if not sent then transfer.awaiting=false;return false,err end return true end local function beginDownload(source)local offer,err=findOffer(source)if not offer then return false,err end local compare=release.compareVersions(offer.version,version.string)if not compare or compare<=0 then return false,\"refusing a downgrade or current release\"end local free=fs.getFreeSpace and fs.getFreeSpace(\"/\")or nil if type(free)==\"number\"and free<offer.size+4096 then return false,\"not enough free space for one verified release cache\"end removePart()release.clear();cached=nil local value=loadState()if offer.transport==\"cloud\"then setStatus(\"downloading\",\"Downloading signed release \"..offer.version..\" from releases.ceet.uk\")save()local sourceText,readErr=readHttp(CLOUD_RELEASE_ORIGIN..\"/\"..tostring(offer.filename or\"\"),release.MAX_PACKAGE_BYTES)if not sourceText then setStatus(\"error\",readErr);record(\"download_failed\",{id=CLOUD_SOURCE_ID,error=readErr});save();return false,readErr end local parsed,parseErr=release.parse(sourceText)if not parsed or parsed.manifest.profile~=offer.profile or parsed.manifest.version~=offer.version or parsed.manifest.digest:lower()~=offer.digest or parsed.manifest.key_id~=offer.keyId then local reason=parseErr or\"verified package did not match selected release offer\"setStatus(\"error\",reason);record(\"download_failed\",{id=CLOUD_SOURCE_ID,error=reason});save();return false,reason end local metadata,cacheErr=release.cache(sourceText,\"releases.ceet.uk\")if not metadata then setStatus(\"error\",cacheErr);record(\"download_failed\",{id=CLOUD_SOURCE_ID,error=cacheErr});save();return false,cacheErr end cached=nil;refreshCached()setStatus(\"downloaded\",\"Verified release \"..metadata.version..\" is ready for local confirmation\")record(\"download_verified\",{id=CLOUD_SOURCE_ID,version=metadata.version,digest=metadata.digest:sub(1,16)})save()return true,metadata end value.transfer={id=\"update-\"..localId()..\"-\"..tostring(now())..\"-\"..tostring(math.random(1000,9999)),source=tostring(offer.id),label=offer.label,transport=offer.transport==\"routed\"and\"routed\"or\"direct\",profile=offer.profile,version=offer.version,size=offer.size,digest=offer.digest,keyId=offer.keyId,offset=1,received=0,retries=0,awaiting=false,started=now(),}setStatus(\"downloading\",\"Downloading signed release \"..offer.version..\" from \"..offer.label)record(\"download_started\",{id=offer.id,version=offer.version,transport=value.transfer.transport})local sent,sendErr=transferRequest(value.transfer)if not sent then value.transfer=nil;setStatus(\"error\",sendErr);record(\"download_failed\",{id=offer.id,error=sendErr})end save()return sent,sendErr end local function finishTransfer(transfer)local handle=fs.open(release.PART_FILE,\"r\")local source=handle and handle.readAll()or nil if handle then handle.close()end if not source or#source~=transfer.size then return false,\"download size did not match offer\"end local parsed,parseErr=release.parse(source)if not parsed then return false,parseErr end if parsed.manifest.profile~=profile.id()or parsed.manifest.profile~=transfer.profile or parsed.manifest.version~=transfer.version or parsed.manifest.digest:lower()~=transfer.digest:lower()or parsed.manifest.key_id~=transfer.keyId then return false,\"verified package did not match selected release offer\"end local metadata,promoteErr=release.promotePart(release.PART_FILE,transfer.label)if not metadata then return false,promoteErr end cached=nil;refreshCached()local value=loadState();value.transfer=nil setStatus(\"downloaded\",\"Verified release \"..metadata.version..\" is ready for local confirmation\")record(\"download_verified\",{id=transfer.source,version=metadata.version,digest=metadata.digest:sub(1,16)})save()return true,metadata end local function acceptChunk(source,body,transport)local value,transfer=loadState(),loadState().transfer if not transfer or transfer.transport~=transport or tostring(source)~=tostring(transfer.source)then return false,\"unexpected update chunk\"end if type(body)~=\"table\"or body.transfer~=transfer.id or math.floor(tonumber(body.offset)or 0)~=transfer.offset or type(body.data)~=\"string\"then return false,\"malformed update chunk\"end local remaining=transfer.size-transfer.offset+1 if#body.data<1 or#body.data>math.min(release.CHUNK_BYTES,remaining)then return false,\"invalid update chunk length\"end local ok,err=appendPart(body.data)if not ok then transfer.awaiting=false;setStatus(\"error\",err);record(\"download_failed\",{error=err});save();return false,err end transfer.offset,transfer.received,transfer.awaiting,transfer.retries=transfer.offset+#body.data,(transfer.received or 0)+#body.data,false,0 if transfer.offset>transfer.size then local complete,result=finishTransfer(transfer)if not complete then removePart();value.transfer=nil;setStatus(\"error\",result);record(\"download_failed\",{id=source,error=result});save()end return complete,result end local sent,sendErr=transferRequest(transfer)if not sent then setStatus(\"error\",sendErr);record(\"download_failed\",{id=source,error=sendErr});value.transfer=nil;removePart()end save()return sent,sendErr end local function serveChunk(target,body,routed,request)if type(body)~=\"table\"or not validId(body.transfer)or math.floor(tonumber(body.offset)or 0)<1 or math.floor(tonumber(body.length)or 0)<1 or tonumber(body.length)>release.CHUNK_BYTES then return false,\"invalid update chunk request\"end local source=cachedSource()if not source then return false,\"no verified newer signed release is cached\"end local offset,length=math.floor(body.offset),math.floor(body.length)if offset>#source then return false,\"requested update offset is beyond package\"end local data=source:sub(offset,math.min(#source,offset+length-1))local response={transfer=body.transfer,offset=offset,data=data}if routed then return net.reply(request,\"update_chunk\",response,{safe=true})end return net.publicSend(target,\"update_chunk\",response)end function M.publicPacket(packet,distance)local source,body=tostring(packet.from),packet.body or{}if packet.type==\"update_query\"then if body.profile~=profile.id()then return false,\"release profile does not match this installation\"end local offer=providerOffer()local compare=offer and release.compareVersions(offer.version,body.version or\"\")if offer and compare and compare>0 then net.publicSend(source,\"update_offer\",offer)end return elseif packet.type==\"update_offer\"then return upsertOffer(source,body,\"direct\",distance)elseif packet.type==\"update_chunk_request\"then return serveChunk(source,body,false)elseif packet.type==\"update_chunk\"then return acceptChunk(source,body,\"direct\")end end function M.authenticatedPacket(from,peer,packet)local body=packet.body or{}if packet.type==\"update_query\"then if body.profile~=profile.id()then return false,\"release profile does not match this installation\"end local offer=providerOffer()local compare=offer and release.compareVersions(offer.version,body.version or\"\")if offer and compare and compare>0 then return net.reply(packet,\"update_offer\",offer,{safe=true})end elseif packet.type==\"update_offer\"then return upsertOffer(from,body,\"routed\")elseif packet.type==\"update_chunk_request\"then return serveChunk(from,body,true,packet)elseif packet.type==\"update_chunk\"then return acceptChunk(from,body,\"routed\")end end function M.check()local value=loadState()for key in pairs(value.offers)do value.offers[key]=nil end setStatus(\"checking\",\"Looking for newer signed releases\")local cloudOffers,cloudErr=checkCloudManifest()local sent,err=net.publicBroadcast(\"update_query\",{version=version.string,profile=profile.id()})local routed=0 for _,peer in ipairs(net.peers())do if not peer.rekeyRequired then local ok=net.request(peer.id,\"update_query\",{version=version.string,profile=profile.id()},{safe=true})if ok then routed=routed+1 end end end if cloudErr then setStatus(\"warning\",\"Cloud release check failed: \"..tostring(cloudErr):sub(1,120))elseif cloudOffers==0 and not(sent or routed>0)then setStatus(\"idle\",\"No newer signed release is available\")elseif cloudOffers>0 then setStatus(\"offers\",tostring(cloudOffers)..\" signed cloud release offer\"..(cloudOffers==1 and\"\"or\"s\")..\" available\")end record(\"check\",{cloud=cloudOffers,direct=sent==true,routed=routed,cloudError=cloudErr,error=sent and nil or err})save()if cloudErr and not sent and routed==0 then return false,cloudErr end return true,{cloud=cloudOffers,direct=sent==true,routed=routed,cloudError=cloudErr}end function M.download(source)return beginDownload(source)end function M.installLatest()local checked,err=M.check()if not checked then return false,err end local rows=offers()if#rows==0 then return false,\"no newer compatible signed release is available\"end table.sort(rows,function(a,b)local comparison=release.compareVersions(a.version,b.version)or 0 return comparison==0 and tostring(a.id)<tostring(b.id)or comparison>0 end)return beginDownload(rows[1].id)end function M.cancel()local value=loadState()if not value.transfer then return false,\"no update transfer is active\"end record(\"download_cancelled\",{id=value.transfer.source,version=value.transfer.version})value.transfer=nil;removePart();setStatus(\"cancelled\",\"Update download cancelled\");save()return true end function M.clearCache()local value=loadState()if value.transfer then return false,\"cancel the active download first\"end release.clear();cached=nil;value.cache=nil;setStatus(\"idle\",\"Verified release cache cleared\");record(\"cache_cleared\");save()return true end function M.prepareApply()local package,metadata=release.cachedPackage()if not package then return false,metadata or\"no verified signed release is cached\"end local compare=release.compareVersions(package.manifest.version,version.string)if not compare or compare<=0 then return false,\"cached release is not newer than this CeetOS installation\"end if package.manifest.profile~=profile.id()then return false,\"cached release profile does not match this installation\"end local marker={schema=2,state=\"apply\",profile=package.manifest.profile,version=package.manifest.version,digest=package.manifest.digest,keyId=package.manifest.key_id,approvedAt=now()}store.write(release.PENDING_FILE,marker)local value=loadState();setStatus(\"applying\",\"Applying verified release \"..package.manifest.version..\" after reboot\");record(\"apply_approved\",{version=package.manifest.version,digest=package.manifest.digest:sub(1,16),keyId=package.manifest.key_id});save()return true,{version=package.manifest.version,fingerprint=package.manifest.digest:sub(1,16),keyId=package.manifest.key_id}end function M.recover()local marker=store.read(release.PENDING_FILE,nil)if type(marker)~=\"table\"or marker.state~=\"verify\"then return end local value=loadState()if marker.version==version.string and(marker.profile==nil or marker.profile==profile.id())then if fs.exists(release.PENDING_FILE)then fs.delete(release.PENDING_FILE)end setStatus(\"applied\",\"Verified release \"..version.string..\" is now active\")record(\"apply_verified\",{version=version.string})else setStatus(\"error\",\"Update installed but running version did not match \"..tostring(marker.version))record(\"apply_version_mismatch\",{expected=marker.version,actual=version.string})end save()end function M.tick()local value,timestamp=loadState(),now()local offer=providerOffer()if offer and timestamp-lastBeacon>=BEACON_INTERVAL then net.publicBroadcast(\"update_offer\",offer)lastBeacon=timestamp end local transfer=value.transfer if transfer and transfer.awaiting and timestamp-(transfer.requestedAt or timestamp)>=REQUEST_TIMEOUT then transfer.awaiting,transfer.retries=false,(transfer.retries or 0)+1 if transfer.retries>REQUEST_LIMIT then record(\"download_timeout\",{id=transfer.source,version=transfer.version})value.transfer=nil;removePart();setStatus(\"error\",\"Update source timed out\");save()else local sent,err=transferRequest(transfer)if not sent then value.transfer=nil;removePart();setStatus(\"error\",err);record(\"download_failed\",{id=transfer.source,error=err});save()end end end end function M.status()local value=loadState()return{profile=profile.id(),version=version.string,status=value.status,message=value.message,revision=value.revision,offers=offers(),transfer=value.transfer,cache=value.cache,history=value.history,cacheRoot=release.CACHE_ROOT,maxPackageBytes=release.MAX_PACKAGE_BYTES,}end return M",
  ["ceetos/lib/release_broker.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local crypto=require(\"ceetos.lib.mesh_crypto\")local cloud=require(\"ceetos.lib.cloud\")local net=require(\"ceetos.lib.net\")local profile=require(\"ceetos.lib.profile\")local M={}local PATH,LIMIT,LIFE=\"/ceetos/data/release-broker.lua\",8,120000 local pending={}local function now()return os.epoch(\"utc\")end local function localId()return tostring(os.getComputerID())end local function localLabel()return os.getComputerLabel()or(\"Computer \"..localId())end local function clean(v,n)return type(v)==\"string\"and#v>0 and#v<=n and not v:find(\"[%z\\1-\\31\\127]\")end local function state()local value=store.read(PATH,{})return{schema=1,enabled=value.enabled==true,promotedAt=tonumber(value.promotedAt)}end local function save(value)return store.write(PATH,value)end local function key(session,target,targetNonce,phrase)return password.hmacSha256(phrase,table.concat({\"ceetos/release-broker/v1\",session,target,localId(),targetNonce},\"|\"))end local function mac(secret,label,value)return password.hmacSha256(secret,label..\"|\"..value)end local function expiry()return now()+LIFE end local function pendingCount()local count=0 for _,row in pairs(pending)do if row.expires>now()then count=count+1 end end return count end function M.status()local value,cloudState=state(),cloud.publicStatus()local rows={}for id,row in pairs(pending)do if row.expires>now()then rows[#rows+1]={id=id,target=row.target,label=row.label,profile=row.profile,expires=row.expires,state=row.state}end end table.sort(rows,function(a,b)return a.expires<b.expires end)return{enabled=value.enabled,enrolled=cloudState.enrolled,pending=rows}end function M.promote(ownerKey)if not clean(ownerKey,256)then return false,\"owner enrollment key is required\"end local result,err=cloud.call(\"auth\",\"/v1/broker/promote\",{ownerKey=ownerKey})if not result then return false,err end save({schema=1,enabled=true,promotedAt=now()})return true,result end function M.revoke(ownerKey)if not clean(ownerKey,256)then return false,\"owner enrollment key is required\"end local result,err=cloud.call(\"auth\",\"/v1/broker/revoke\",{ownerKey=ownerKey})if not result then return false,err end save({schema=1,enabled=false})for id in pairs(pending)do pending[id]=nil end return true,result end function M.handle(packet)local body,source=packet.body or{},tostring(packet.from or\"\")if packet.type==\"broker_query\"then if not state().enabled or not cloud.publicStatus().enrolled then return end if not clean(body.session,96)or not clean(body.nonce,128)or not clean(body.profile,32)or not clean(body.label,96)or body.profile~=profile.id()then return end if pendingCount()>=LIMIT and not pending[body.session]then return end pending[body.session]={session=body.session,target=source,targetNonce=body.nonce,profile=body.profile,label=body.label,expires=expiry(),state=\"waiting\"}return net.publicSend(source,\"broker_offer\",{session=body.session,broker=localId(),label=localLabel(),profile=profile.id(),expires=pending[body.session].expires})elseif packet.type==\"broker_proof\"then local row=pending[body.session]if not row or row.expires<=now()or row.target~=source or row.state~=\"challenged\"or not clean(body.proof,128)then return end if not password.constantTimeEqual(row.expected,body.proof)then pending[body.session]=nil;return net.publicSend(source,\"broker_reject\",{session=body.session,reason=\"phrase proof rejected\"})end local result,err=cloud.call(\"auth\",\"/v1/broker/enroll\",{session=row.session,targetComputerId=row.target,targetLabel=row.label,targetProfile=row.profile,expires=row.expires})if not result or type(result.node)~=\"table\"then pending[body.session]=nil;return net.publicSend(source,\"broker_reject\",{session=body.session,reason=tostring(err or\"cloud provisioning failed\"):sub(1,96)})end local aad=\"ceetos/release-broker/grant/v1|\"..row.session..\"|\"..row.target..\"|\"..localId()local nonce=crypto.nonce(row.key,1,aad)local envelope=nonce and crypto.seal(row.key,nonce,aad,textutils.serialise({node=result.node,urls=cloud.publicStatus().urls}))pending[body.session]=nil if not envelope then return net.publicSend(source,\"broker_reject\",{session=body.session,reason=\"could not secure enrollment\"})end return net.publicSend(source,\"broker_grant\",{session=body.session,broker=localId(),envelope=envelope})end end function M.approve(session,phrase)local row=pending[tostring(session or\"\")]if not row or row.expires<=now()then return false,\"bootstrap session is unavailable or expired\"end if not clean(phrase,128)then return false,\"invalid bootstrap phrase\"end row.key=key(row.session,row.target,row.targetNonce,phrase)row.brokerNonce=password.newSalt(\"broker:\"..row.session)row.expected=mac(row.key,\"proof\",row.brokerNonce)row.state,row.expires=\"challenged\",expiry()local challenge=mac(row.key,\"challenge\",row.brokerNonce)local sent,err=net.publicSend(row.target,\"broker_challenge\",{session=row.session,broker=localId(),nonce=row.brokerNonce,mac=challenge,expires=row.expires})if not sent then row.state=\"waiting\";return false,err end return true end function M.tick()for id,row in pairs(pending)do if row.expires<=now()then pending[id]=nil end end end return M",
  ["ceetos/lib/broker_bootstrap.lua"] = "local password=require(\"ceetos.lib.password\")local crypto=require(\"ceetos.lib.mesh_crypto\")local M={}local CHANNEL,LIFE=45731,120 local function label()return os.getComputerLabel()or(\"Computer \"..tostring(os.getComputerID()))end local function valid(v,n)return type(v)==\"string\"and#v>0 and#v<=n end local function modem()for _,name in ipairs(peripheral.getNames())do if peripheral.getType(name)==\"modem\"then local wrapped=peripheral.wrap(name)if wrapped and wrapped.isWireless and wrapped.isWireless()then return wrapped end end end end local function random(context)return password.newSalt(context..\":\"..tostring(os.epoch(\"utc\")))end function M.enroll(profile)local link=modem()if not link then return nil,\"No wireless modem is attached; a trusted release broker must be directly reachable.\"end link.open(CHANNEL)local session,target,targetNonce=random(\"session\"),tostring(os.getComputerID()),random(\"target\")local phrase=random(\"phrase\"):sub(1,20)print(\"Trusted broker enrollment required.\")print(\"On an enrolled broker run: nx broker approve \"..session..\" \"..phrase)link.transmit(CHANNEL,CHANNEL,{protocol=\"ceetos/update/1\",type=\"broker_query\",from=target,to=\"0\",body={session=session,nonce=targetNonce,profile=profile,label=label()}})local deadline,broker,linkKey=os.epoch(\"utc\")+LIFE*1000,nil,nil while os.epoch(\"utc\")<deadline do local timer=os.startTimer(2)local event={os.pullEventRaw()}if event[1]==\"timer\"and event[2]==timer then link.transmit(CHANNEL,CHANNEL,{protocol=\"ceetos/update/1\",type=\"broker_query\",from=target,to=\"0\",body={session=session,nonce=targetNonce,profile=profile,label=label()}})elseif event[1]==\"modem_message\"and event[3]==CHANNEL and type(event[5])==\"table\"then local packet,body=event[5],event[5].body or{}if packet.protocol==\"ceetos/update/1\"and tostring(packet.to)==target and body.session==session then if packet.type==\"broker_offer\"then broker=tostring(body.broker)elseif packet.type==\"broker_challenge\"and broker and tostring(body.broker)==broker and valid(body.nonce,128)and valid(body.mac,128)then linkKey=password.hmacSha256(phrase,table.concat({\"ceetos/release-broker/v1\",session,target,broker,targetNonce},\"|\"))if password.constantTimeEqual(password.hmacSha256(linkKey,\"challenge|\"..body.nonce),body.mac)then link.transmit(CHANNEL,CHANNEL,{protocol=\"ceetos/update/1\",type=\"broker_proof\",from=target,to=broker,body={session=session,proof=password.hmacSha256(linkKey,\"proof|\"..body.nonce)}})end elseif packet.type==\"broker_grant\"and linkKey and tostring(body.broker)==broker then local aad=\"ceetos/release-broker/grant/v1|\"..session..\"|\"..target..\"|\"..broker local opened=crypto.open(linkKey,body.envelope,aad)local grant=opened and textutils.unserialise(opened)if type(grant)==\"table\"and type(grant.node)==\"table\"and valid(grant.node.id,96)and valid(grant.node.secret,192)then return grant end elseif packet.type==\"broker_reject\"then return nil,tostring(body.reason or\"broker rejected enrollment\")end end end end return nil,broker and\"Broker did not complete enrollment in time.\"or\"No trusted release broker answered. Installation was not changed.\"end return M",
  ["ceetos/lib/mesh_crypto.lua"] = "local password=require(\"ceetos.lib.password\")local M={}local band,bor,bxor=bit32.band,bit32.bor,bit32.bxor local lshift,rshift=bit32.lshift,bit32.rshift local MOD32,LIMB=4294967296,67108864 local function add32(...)local n=0 for i=1,select(\"#\",...)do n=(n+(select(i,...)or 0))%MOD32 end return n end local function rotl(v,bits)return bor(lshift(v,bits),rshift(v,32-bits))end local function le32(data,index)local a,b,c,d=data:byte(index,index+3)return(a or 0)+(b or 0)*256+(c or 0)*65536+(d or 0)*16777216 end local function put32(value)value=value%MOD32 return string.char(value%256,math.floor(value/256)%256,math.floor(value/65536)%256,math.floor(value/16777216)%256)end local function le64(value)value=math.max(0,math.floor(tonumber(value)or 0))local low,high=value%MOD32,math.floor(value/MOD32)%MOD32 return put32(low)..put32(high)end local function hexToRaw(value)if type(value)~=\"string\"or#value%2~=0 or value:find(\"[^%x]\")then return nil end return(value:gsub(\"..\",function(pair)return string.char(tonumber(pair,16))end))end local function rawToHex(value)return(value:gsub(\".\",function(byte)return string.format(\"%02x\",byte:byte())end))end local function xorBytes(left,right)local out={}for i=1,#left do out[i]=string.char(bxor(left:byte(i),right:byte(i)))end return table.concat(out)end local function quarter(x,a,b,c,d)x[a]=add32(x[a],x[b]);x[d]=rotl(bxor(x[d],x[a]),16)x[c]=add32(x[c],x[d]);x[b]=rotl(bxor(x[b],x[c]),12)x[a]=add32(x[a],x[b]);x[d]=rotl(bxor(x[d],x[a]),8)x[c]=add32(x[c],x[d]);x[b]=rotl(bxor(x[b],x[c]),7)end local function chachaBlock(key,counter,nonce)local state={0x61707865,0x3320646e,0x79622d32,0x6b206574}for i=1,8 do state[4+i]=le32(key,(i-1)*4+1)end state[13],state[14],state[15],state[16]=counter%MOD32,le32(nonce,1),le32(nonce,5),le32(nonce,9)local x={}for i=1,16 do x[i]=state[i]end for _=1,10 do quarter(x,1,5,9,13);quarter(x,2,6,10,14);quarter(x,3,7,11,15);quarter(x,4,8,12,16)quarter(x,1,6,11,16);quarter(x,2,7,12,13);quarter(x,3,8,9,14);quarter(x,4,5,10,15)end local out={}for i=1,16 do out[i]=put32(add32(x[i],state[i]))end return table.concat(out)end local function chachaXor(key,nonce,counter,plaintext)local out,position={},1 while position<=#plaintext do local block=chachaBlock(key,counter,nonce)local part=plaintext:sub(position,position+63)out[#out+1]=xorBytes(part,block:sub(1,#part))position,counter=position+#part,(counter+1)%MOD32 end return table.concat(out)end local function poly1305(message,key)local function zero(length)local out={};for i=1,length do out[i]=0 end;return out end local function normalise(value)local carry=0 for i=1,#value do local n=(value[i]or 0)+carry value[i],carry=n%256,math.floor(n/256)end while carry>0 do value[#value+1],carry=carry%256,math.floor(carry/256)end return value end local function add(left,right)local out=zero(math.max(#left,#right)+1)for i=1,#left do out[i]=out[i]+left[i]end for i=1,#right do out[i]=out[i]+right[i]end return normalise(out)end local function multiply(left,right)local out=zero(#left+#right+1)for i=1,#left do for j=1,#right do out[i+j-1]=out[i+j-1]+left[i]*right[j]end end return normalise(out)end local function high130(value)local out={}for i=1,#value-16 do local low=value[i+16]or 0 local high=value[i+17]or 0 out[i]=math.floor(low/4)+(high%4)*64 end return normalise(out)end local function hasHigh(value)if#value>17 then for i=18,#value do if value[i]~=0 then return true end end end return(value[17]or 0)>=4 end local function reduce(value)while hasHigh(value)do local low,high=zero(17),high130(value)for i=1,17 do low[i]=value[i]or 0 end low[17]=low[17]%4 for i=1,#high do high[i]=high[i]*5 end value=add(low,high)end local prime={251}for i=2,16 do prime[i]=255 end prime[17]=3 local greater=false for i=17,1,-1 do if(value[i]or 0)~=prime[i]then greater=(value[i]or 0)>prime[i];break end end if greater then local borrow=0 for i=1,17 do local n=(value[i]or 0)-prime[i]-borrow if n<0 then n,borrow=n+256,1 else borrow=0 end value[i]=n end end return value end local r,h=zero(17),zero(17)for i=1,16 do r[i]=key:byte(i)end r[4],r[8],r[12],r[16]=band(r[4],15),band(r[8],15),band(r[12],15),band(r[16],15)r[5],r[9],r[13]=band(r[5],252),band(r[9],252),band(r[13],252)for at=1,#message,16 do local part,n=message:sub(at,at+15),zero(17)for i=1,#part do n[i]=part:byte(i)end n[#part+1]=1 h=reduce(multiply(add(h,n),r))end local pad,out,carry={},{},0 for i=1,16 do pad[i]=key:byte(i+16)end for i=1,16 do local n=(h[i]or 0)+pad[i]+carry out[i],carry=n%256,math.floor(n/256)end return string.char(table.unpack(out))end local function padded(value)return value..string.rep(\"\\0\",(16-(#value%16))%16)end local function derive(linkKey)local raw=hexToRaw(password.hmacSha256(linkKey,\"ceetos/mesh/aead-key/v1\")or\"\")return raw end function M.nonce(linkKey,counter,context)local raw=hexToRaw(password.hmacSha256(linkKey,\"ceetos/mesh/aead-nonce/v1|\"..tostring(counter)..\"|\"..tostring(context or\"\"))or\"\")return raw and raw:sub(1,12)or nil end function M.seal(linkKey,nonce,aad,plaintext)if type(linkKey)~=\"string\"or type(nonce)~=\"string\"or#nonce~=12 or type(aad)~=\"string\"or type(plaintext)~=\"string\"then return nil,\"invalid mesh envelope input\"end local key=derive(linkKey);if not key or#key~=32 then return nil,\"could not derive mesh envelope key\"end local polyKey=chachaBlock(key,0,nonce):sub(1,32)local ciphertext=chachaXor(key,nonce,1,plaintext)local tag=poly1305(padded(aad)..padded(ciphertext)..le64(#aad)..le64(#ciphertext),polyKey)return{nonce=rawToHex(nonce),ciphertext=rawToHex(ciphertext),tag=rawToHex(tag)}end function M.open(linkKey,envelope,aad)if type(linkKey)~=\"string\"or type(envelope)~=\"table\"or type(aad)~=\"string\"then return nil,\"invalid mesh envelope\"end local nonce,ciphertext,tag=hexToRaw(envelope.nonce or\"\"),hexToRaw(envelope.ciphertext or\"\"),hexToRaw(envelope.tag or\"\")if not nonce or#nonce~=12 or not ciphertext or not tag or#tag~=16 then return nil,\"invalid mesh envelope encoding\"end local key=derive(linkKey);if not key or#key~=32 then return nil,\"could not derive mesh envelope key\"end local polyKey=chachaBlock(key,0,nonce):sub(1,32)local expected=rawToHex(poly1305(padded(aad)..padded(ciphertext)..le64(#aad)..le64(#ciphertext),polyKey))if not password.constantTimeEqual(expected,envelope.tag)then return nil,\"mesh envelope authentication failed\"end return chachaXor(key,nonce,1,ciphertext)end function M.selfTest()local key=hexToRaw(\"85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b\")local tag=poly1305(\"Cryptographic Forum Research Group\",key)return rawToHex(tag)==\"a8061dc1305136c6c22b8baf0c0127a9\"end return M",
  ["ceetos/lib/audit.lua"] = "local store=require(\"ceetos.lib.store\")local M={}local PATH=\"/ceetos/data/audit.log\"M.LIMITS={maxEntries=250,maxBytes=64*1024}function M.log(actor,action,detail)return store.append(PATH,{ts=os.epoch(\"utc\"),actor=actor or\"system\",action=action,detail=detail,},M.LIMITS)end function M.recent(limit)limit=math.max(1,math.min(50,tonumber(limit)or 10))local raw=store.readAppend(PATH)local result={}for line in(raw..\"\\n\"):gmatch(\"(.-)\\n\")do if line~=\"\"then local entry=textutils.unserialise(line)if entry then result[#result+1]=entry if#result>limit then table.remove(result,1)end end end end return result end return M",
  ["ceetos/lib/net.lua"] = "local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local password=require(\"ceetos.lib.password\")local meshCrypto=require(\"ceetos.lib.mesh_crypto\")local M={handler=nil,publicHandler=nil}local PATH=\"/ceetos/data/network.lua\"local SECURITY_PATH=\"/ceetos/data/network-security.lua\"local SEEN_PATH=\"/ceetos/data/seen-peers.lua\"local CHANNEL,PROTOCOL=45731,\"ceetos/2\"local PUBLIC_UPDATE_PROTOCOL=\"ceetos/update/1\"local PUBLIC_UPDATE_TYPES={update_query=true,update_offer=true,update_chunk_request=true,update_chunk=true,broker_query=true,broker_offer=true,broker_challenge=true,broker_proof=true,broker_grant=true,broker_reject=true,}local DISCOVERY_CHANNEL=CHANNEL local DISCOVERY_TTL,ROUTE_TTL,PACKET_TTL=120000,120000,8 local DISCOVERY_INTERVAL,PAIR_RETRY,ROUTE_INTERVAL=2000,2000,15000 local MESH_BEACON_INTERVAL,MESH_FULL_INTERVAL=15000,30000 local PROBE_INTERVAL,PROBE_DEGRADED,PROBE_OFFLINE,PROBE_RECOVERY=5000,3,6,10000 local ROUTE_CANDIDATE_LIMIT,ROUTE_BUCKET_LIMIT=4,96 local SAFE_READ_WINDOW,SAFE_READ_LIMIT=1000,16 local MAX_PACKET_STRING,MAX_PACKET_TABLE,MAX_PACKET_DEPTH=8192,128,6 local COUNTER_RESERVATION,MAX_RX_EPOCHS,MAX_REVERSE_ROUTES=64,3,128 local routes,discovered,confirmations,seenPackets,reverseRoutes={},{},{},{},{}local routeSequence,lastRouteAdvertisement,routesDirty=0,0,false local discovery,lastDiscovery=nil,{state=\"inactive\"}local security={tx={},rx={}}local autoEdges,linkHealth,meshOffers,meshSeen,advertisedRoutes,meshEnrollmentSends={},{},{},{},{},{}local lastMeshBeacon,lastMeshFull,meshDirty=0,0,false local transport={modem=false,wireless=false,name=nil,channels={},lastTransmit=nil,lastReceive=nil,lastDistance=nil,lastError=nil,rejected=0,}local traces={discovery={},routing={},transport={}}local TRACE_LIMIT=48 local MESH_STATE_LIMIT=128 local rejectPacket local function now()return os.epoch(\"utc\")end local function id()return tostring(os.getComputerID())end local function label()return os.getComputerLabel()or(\"Computer \"..id())end local function isBroadcast(value)return tostring(value)==\"0\"end local function isForUs(value)return tostring(value)==id()end local function copy(value,depth)if type(value)~=\"table\"then return value end if(depth or 0)>MAX_PACKET_DEPTH then return nil end local out={}for k,v in pairs(value)do out[k]=copy(v,(depth or 0)+1)end return out end local function trace(kind,phase,fields)local bucket=traces[kind]or traces.transport local row={time=now(),phase=phase}for key,value in pairs(fields or{})do if key~=\"phrase\"and key~=\"proof\"and key~=\"key\"and key~=\"secret\"and key~=\"mac\"and key~=\"packet\"and key~=\"tag\"then row[key]=value end end bucket[#bucket+1]=row while#bucket>TRACE_LIMIT do table.remove(bucket,1)end end local function read(path,fallback)if store.invalidate then store.invalidate(path)end return store.read(path,fallback)end local function config()local value=read(PATH,{peers={},channel=CHANNEL})value.peers=type(value.peers)==\"table\"and value.peers or{}value.channel=tonumber(value.channel)or CHANNEL return value end local function save(value)local ok,err=store.write(PATH,value)if ok==false then error(err or\"could not save network configuration\",0)end end local function migrateV1Links()local value,changed=config(),false for _,peer in pairs(value.peers)do if peer.protocol~=2 or peer.rekeyRequired or type(peer.key)~=\"string\"or#peer.key<32 then peer.protocol,peer.rekeyRequired,peer.key=1,true,nil peer.secret=nil changed=true end end if changed then save(value)end return value end local function activePeer(value,peerId)local peer=value.peers[tostring(peerId)]if peer and peer.protocol==2 and peer.rekeyRequired~=true and type(peer.key)==\"string\"and#peer.key>=32 then return peer end return nil end local function activeLink(value,peerId)local manual=activePeer(value,peerId)if manual then return manual,\"direct\"end local edge=autoEdges[tostring(peerId)]if edge and type(edge.key)==\"string\"and#edge.key>=32 and(edge.expires or 0)>now()then return edge,\"mesh\"end return nil end local function healthFor(peerId)peerId=tostring(peerId)local state=linkHealth[peerId]if not state then state={state=\"healthy\",successes=0,misses=0,lastAuthenticated=now(),stableSince=now(),inFlight=0}linkHealth[peerId]=state end return state end local function linkState(peerId)return healthFor(peerId).state or\"healthy\"end local function currentInFlight(state,timestamp)state.inFlightUntil=type(state.inFlightUntil)==\"table\"and state.inFlightUntil or{}local kept={}for _,expires in ipairs(state.inFlightUntil)do if expires>timestamp then kept[#kept+1]=expires end end state.inFlightUntil,state.inFlight=kept,#kept return state.inFlight end local function markInFlight(state)local timestamp=now()currentInFlight(state,timestamp)state.inFlightUntil[#state.inFlightUntil+1]=timestamp+SAFE_READ_WINDOW table.sort(state.inFlightUntil)while#state.inFlightUntil>SAFE_READ_LIMIT do table.remove(state.inFlightUntil,1)end state.inFlight=#state.inFlightUntil end local function linkUsable(value,peerId,allowDegraded)if not activeLink(value,peerId)then return false end local state=linkState(peerId)return state==\"healthy\"or(allowDegraded and state==\"degraded\")end local function touchLink(peerId,distance,source)local state,timestamp=healthFor(peerId),now()state.lastAuthenticated,state.lastDistance,state.lastSource=timestamp,distance,source or\"traffic\"state.misses,state.awaiting,state.probeToken=0,false,nil state.loss=math.max(0,(state.loss or 0)*0.5)if state.state~=\"healthy\"then state.successes=(state.successes or 0)+1 if state.successes>=2 then state.state,state.stableSince,state.recoveredAt=\"healthy\",timestamp,timestamp routesDirty=true trace(\"routing\",\"link_recovered\",{peer=peerId,source=source})end else state.successes=math.min(2,(state.successes or 0)+1)end end local function allDirectLinks(value)local out,seen={},{}for peerId in pairs(value.peers)do if activePeer(value,peerId)then out[#out+1],seen[peerId]=tostring(peerId),true end end for peerId,edge in pairs(autoEdges)do if not seen[peerId]and edge.expires>now()then out[#out+1]=tostring(peerId)end end table.sort(out,function(a,b)return tonumber(a)<tonumber(b)end)return out end local function remember(peer,peerLabel,extra)local value=read(SEEN_PATH,{})local old=value[tostring(peer)]or{}old.label,old.seen=peerLabel or old.label or(\"Computer \"..tostring(peer)),now()if extra then for key,item in pairs(extra)do if key~=\"tag\"and key~=\"proof\"then old[key]=item end end end value[tostring(peer)]=old store.write(SEEN_PATH,value)end local function modem(requireWireless)local candidates,used={},{}local sides=rs and rs.getSides and rs.getSides()or{}for _,name in ipairs(sides)do if peripheral.getType(name)==\"modem\"and not used[name]then candidates[#candidates+1],used[name]=name,true end end if peripheral.getNames then for _,name in ipairs(peripheral.getNames())do if peripheral.getType(name)==\"modem\"and not used[name]then candidates[#candidates+1],used[name]=name,true end end end local fallback for _,name in ipairs(candidates)do local wrapped=peripheral.wrap(name)if wrapped then fallback=fallback or wrapped local ok,wireless=pcall(function()return not wrapped.isWireless or wrapped.isWireless()end)if ok and wireless then return wrapped end end end return requireWireless and nil or fallback end local function modems()local out,seen={},{}local function add(name)if not seen[name]and peripheral.getType(name)==\"modem\"then local wrapped=peripheral.wrap(name)if wrapped then out[#out+1],seen[name]={name=name,modem=wrapped},true end end end for _,name in ipairs(rs and rs.getSides and rs.getSides()or{})do add(name)end for _,name in ipairs(peripheral.getNames and peripheral.getNames()or{})do add(name)end return out end local function wirelessModems()local out={}for _,item in ipairs(modems())do local ok,wireless=pcall(function()return not item.modem.isWireless or item.modem.isWireless()end)if ok and wireless then out[#out+1]=item end end return out end local function openChannels(value)local channels={value.channel or CHANNEL}if channels[1]~=DISCOVERY_CHANNEL then channels[#channels+1]=DISCOVERY_CHANNEL end transport.channels=channels local all=modems()if#all==0 then transport.lastError=\"no modem attached\";trace(\"transport\",\"modem_missing\");return channels end for _,item in ipairs(all)do for _,channel in ipairs(channels)do local ok,err=pcall(item.modem.open,channel)if not ok then transport.lastError=tostring(err)trace(\"transport\",\"channel_open_failed\",{channel=channel,error=transport.lastError,modem=item.name})end end end return channels end local function canonical(value,depth)depth=depth or 0 local kind=type(value)if kind==\"nil\"then return\"n\"end if kind==\"boolean\"then return value and\"b1\"or\"b0\"end if kind==\"number\"then if value~=value or value==math.huge or value==-math.huge then return nil,\"invalid numeric packet value\"end return\"d\"..string.format(\"%.17g\",value)..\";\"end if kind==\"string\"then if#value>MAX_PACKET_STRING then return nil,\"packet string exceeds limit\"end return\"s\"..tostring(#value)..\":\"..value end if kind~=\"table\"then return nil,\"unsupported packet value\"end if depth>=MAX_PACKET_DEPTH then return nil,\"packet nesting exceeds limit\"end local entries={}for key,item in pairs(value)do if#entries>=MAX_PACKET_TABLE then return nil,\"packet table exceeds limit\"end local encodedKey,keyErr=canonical(key,depth+1);if not encodedKey then return nil,keyErr end local encodedValue,valueErr=canonical(item,depth+1);if not encodedValue then return nil,valueErr end entries[#entries+1]=encodedKey..\"=\"..encodedValue end table.sort(entries)return\"t\"..tostring(#entries)..\"{\"..table.concat(entries,\",\")..\"}\"end local function packetMaterial(packet)return canonical({protocol=packet.protocol,type=packet.type,from=packet.from,to=packet.to,origin=packet.origin,destination=packet.destination,ttl=packet.ttl,request_id=packet.request_id,timestamp=packet.timestamp,reply_to=packet.reply_to,auth=packet.auth and{epoch=packet.auth.epoch,counter=packet.auth.counter}or nil,confidential=packet.confidential==true,body=packet.body,})end local function confidentialAad(packet)return table.concat({\"ceetos/confidential/v1\",tostring(packet.type),tostring(packet.origin),tostring(packet.destination),tostring(packet.request_id)},\"|\")end local function sealBody(peer,packet)local encoded=textutils.serialise(packet.body or{},{compact=true})if#encoded>6144 then return nil,\"confidential payload exceeds limit\"end local nonce=meshCrypto.nonce(peer.key,password.newSalt(\"confidential:\"..tostring(packet.request_id)),confidentialAad(packet))if not nonce then return nil,\"could not create confidential nonce\"end local envelope,err=meshCrypto.seal(peer.key,nonce,confidentialAad(packet),encoded)if not envelope then return nil,err end return{envelope=envelope}end local function openBody(peer,packet)if type(packet.body)~=\"table\"or type(packet.body.envelope)~=\"table\"then return nil,\"malformed confidential envelope\"end local decoded,err=meshCrypto.open(peer.key,packet.body.envelope,confidentialAad(packet))if not decoded or#decoded>6144 then return nil,err or\"invalid confidential payload\"end local ok,value=pcall(textutils.unserialise,decoded)if not ok or type(value)~=\"table\"then return nil,\"invalid confidential payload\"end return value end local function loadSecurity()security=read(SECURITY_PATH,{tx={},rx={}})security.tx=type(security.tx)==\"table\"and security.tx or{}security.rx=type(security.rx)==\"table\"and security.rx or{}end local function saveSecurity()local ok,err=store.write(SECURITY_PATH,security)if ok==false then error(err or\"could not persist peer replay state\",0)end end local function counter(peerId)local key=tostring(peerId)local tx=security.tx[key]if not tx then tx={epoch=password.newSalt(\"peer-tx:\"..key),reserved=0};security.tx[key]=tx end tx.next=tonumber(tx.next)or((tonumber(tx.reserved)or 0)+1)if tx.next>(tonumber(tx.reserved)or 0)then tx.reserved=tx.next+COUNTER_RESERVATION-1 saveSecurity()end local value=tx.next;tx.next=value+1 return tx.epoch,value end local function verifyReplay(from,auth)if type(auth)~=\"table\"or type(auth.epoch)~=\"string\"or#auth.epoch<16 or#auth.epoch>128 then return false,\"invalid packet epoch\"end local sequence=tonumber(auth.counter)if not sequence or sequence<1 or sequence%1~=0 then return false,\"invalid packet counter\"end local key=tostring(from)local row=security.rx[key]or{epochs={}}row.epochs=type(row.epochs)==\"table\"and row.epochs or{}local old=tonumber(row.epochs[auth.epoch])if old and sequence<=old then return false,\"replayed packet counter\"end row.epochs[auth.epoch]=sequence local order={}for epoch,max in pairs(row.epochs)do order[#order+1]={epoch=epoch,max=tonumber(max)or 0}end table.sort(order,function(a,b)return a.max>b.max end)while#order>MAX_RX_EPOCHS do row.epochs[table.remove(order).epoch]=nil end security.rx[key]=row saveSecurity()return true end local function newRequestId()return id()..\":\"..password.newSalt(\"peer-request\")end local function sign(peerId,peer,packet)local epoch,sequence=counter(peerId)packet.auth={epoch=epoch,counter=sequence}local material,err=packetMaterial(packet)if not material then return false,err end local mac,macErr=password.hmacSha256(peer.key,material)if not mac then return false,macErr end packet.auth.mac=mac return true end local function verifyPacket(packet,value)if type(packet)~=\"table\"then return false,\"packet is not a table\"end if packet.protocol~=PROTOCOL then return false,packet.protocol==\"ceetos/1\"and\"v1 packet rejected; rekey required\"or\"invalid packet protocol\"end if type(packet.type)~=\"string\"or#packet.type==0 or#packet.type>64 then return false,\"invalid packet type\"end if type(packet.from)~=\"string\"and type(packet.from)~=\"number\"then return false,\"invalid packet sender\"end local from=tostring(packet.from)local peer=activeLink(value,from)if not peer then return false,\"sender is not an active direct or mesh peer\"end if not isForUs(packet.to)then return false,\"packet addressed to another hop\"end if type(packet.origin)~=\"string\"and type(packet.origin)~=\"number\"then return false,\"invalid packet origin\"end if type(packet.destination)~=\"string\"and type(packet.destination)~=\"number\"then return false,\"invalid packet destination\"end if type(packet.request_id)~=\"string\"or#packet.request_id==0 or#packet.request_id>128 then return false,\"invalid packet request ID\"end if packet.reply_to~=nil and(type(packet.reply_to)~=\"string\"or#packet.reply_to==0 or#packet.reply_to>128)then return false,\"invalid reply correlation ID\"end local ttl=tonumber(packet.ttl)if not ttl or ttl%1~=0 or ttl<1 or ttl>PACKET_TTL then return false,\"invalid packet TTL\"end local timestamp=tonumber(packet.timestamp)if not timestamp or math.abs(now()-timestamp)>ROUTE_TTL then return false,\"stale packet timestamp\"end if type(packet.auth)~=\"table\"or type(packet.auth.mac)~=\"string\"or#packet.auth.mac~=64 then return false,\"missing packet MAC\"end local receivedMac=packet.auth.mac packet.auth.mac=nil local material,materialErr=packetMaterial(packet)packet.auth.mac=receivedMac if not material then return false,materialErr end local expected,macErr=password.hmacSha256(peer.key,material)if not expected or not password.constantTimeEqual(expected,receivedMac)then return false,macErr or\"invalid packet MAC\"end local replayOk,replayErr=verifyReplay(from,packet.auth)if not replayOk then return false,replayErr end return true,peer end local function routeBucket(targetId)local bucket=routes[tostring(targetId)]if bucket and bucket.next then bucket={candidates={{next=tostring(bucket.next),hops=tonumber(bucket.hops)or PACKET_TTL,expires=tonumber(bucket.expires)or 0,label=bucket.label,mode=bucket.mode,masterId=bucket.masterId,legacy=true,loss=1,}},primary=tostring(bucket.next),changedAt=now(),reason=\"legacy route\"}routes[tostring(targetId)]=bucket end if not bucket then bucket={candidates={},changedAt=now(),reason=\"new\"}routes[tostring(targetId)]=bucket end bucket.candidates=type(bucket.candidates)==\"table\"and bucket.candidates or{}return bucket end local function candidateHealth(candidate)local state=healthFor(candidate.next)local rank=state.state==\"healthy\"and 0 or(state.state==\"degraded\"and 1 or 2)return rank,state end local function directCandidate(value,targetId)local link,kind=activeLink(value,targetId)if link then return{next=targetId,hops=1,expires=now()+ROUTE_TTL,kind=kind,direct=true,label=link.label,mode=link.mode,masterId=link.masterId}end end local function validCandidates(targetId,value)local timestamp,out,seen=now(),{},{}local direct=directCandidate(value,targetId)if direct then out[#out+1],seen[direct.next..\":\"..direct.kind]=direct,true end local bucket=routes[tostring(targetId)]if bucket then for _,candidate in ipairs(routeBucket(targetId).candidates)do local key=tostring(candidate.next)..\":\"..tostring(candidate.kind or\"route\")if not seen[key]and candidate.expires>timestamp and candidate.hops>=1 and candidate.hops<=PACKET_TTL and activeLink(value,candidate.next)then out[#out+1],seen[key]=candidate,true end end end return out end local function compareCandidates(a,b)local ar,ah=candidateHealth(a)local br,bh=candidateHealth(b)if ar~=br then return ar<br end if(a.hops or PACKET_TTL)~=(b.hops or PACKET_TTL)then return(a.hops or PACKET_TTL)<(b.hops or PACKET_TTL)end if(ah.loss or 0)~=(bh.loss or 0)then return(ah.loss or 0)<(bh.loss or 0)end if(ah.rtt or 0)~=(bh.rtt or 0)then return(ah.rtt or 0)<(bh.rtt or 0)end return tostring(a.next)<tostring(b.next)end local function primaryCandidate(targetId,value,safe)local candidates=validCandidates(targetId,value)if#candidates==0 then return nil end table.sort(candidates,compareCandidates)local target,bucket,selected=tostring(targetId),routeBucket(targetId),candidates[1]local existing for _,item in ipairs(candidates)do if tostring(item.next)==tostring(bucket.primary)then existing=item;break end end if existing then local oldRank,newRank=candidateHealth(existing),candidateHealth(selected)if oldRank<newRank then selected=existing elseif oldRank==newRank and oldRank==0 and(selected.hops or 99)<(existing.hops or 99)then local health=healthFor(selected.next)if(health.successes or 0)<2 or(health.recoveredAt and now()-(health.stableSince or now())<PROBE_RECOVERY)then selected=existing end end end if safe then local rank,_,choices=candidateHealth(selected),nil,{}for _,item in ipairs(candidates)do local itemRank=candidateHealth(item)if itemRank==rank and item.hops==selected.hops then choices[#choices+1]=item end end if#choices>1 then table.sort(choices,function(a,b)local ah,bh=healthFor(a.next),healthFor(b.next)local aLoad,bLoad=currentInFlight(ah,now()),currentInFlight(bh,now())if aLoad~=bLoad then return aLoad<bLoad end return tostring(a.next)<tostring(b.next)end)selected=choices[1]end end if bucket.primary~=tostring(selected.next)then bucket.primary,bucket.changedAt,bucket.reason=tostring(selected.next),now(),existing and\"health/hop selection\"or\"initial selection\"trace(\"routing\",\"route_selected\",{destination=target,next=selected.next,hops=selected.hops,reason=bucket.reason})end return selected end local function nextHop(target,safe)local candidate=primaryCandidate(target,config(),safe)if candidate then local health=healthFor(candidate.next)if safe then markInFlight(health)end health.lastSelected=now()return candidate.next,candidate end routes[tostring(target)]=nil end local function transmit(items,channel,packet)if#items==0 then return false,\"no compatible modem attached\"end local sent,lastError=false,nil for _,item in ipairs(items)do local ok,err=pcall(item.modem.transmit,channel,channel,packet)if ok then sent=true else lastError=tostring(err)end end if not sent then transport.lastError=lastError or\"modem transmit failed\"end return sent,transport.lastError end local function send(target,input,forcedHop)local hop=forcedHop or nextHop(target,input.routeSafe==true and input.balanceSafe==true)if not hop then return false,\"peer is unreachable or requires rekey\"end local value,peer=config(),activeLink(config(),hop)if not peer then return false,\"direct route is unavailable\"end local packet=copy(input)packet.auth,packet.protocol,packet.from,packet.to=nil,PROTOCOL,id(),hop packet.origin,packet.destination=tostring(packet.origin or id()),tostring(packet.destination or target)packet.ttl=math.floor(tonumber(packet.ttl)or PACKET_TTL)packet.timestamp=now()if packet.ttl<1 or packet.ttl>PACKET_TTL then return false,\"invalid packet TTL\"end if type(packet.request_id)~=\"string\"or#packet.request_id==0 then packet.request_id=newRequestId()end if packet.confidential==true then local sealed,sealErr=sealBody(peer,packet)if not sealed then return false,sealErr end packet.body=sealed end local signed,signErr=sign(hop,peer,packet)if not signed then return false,signErr end openChannels(value)local links=wirelessModems()if#links==0 then return false,\"no wireless modem attached\"end local sent,err=transmit(links,value.channel or CHANNEL,packet)if not sent then trace(\"transport\",\"transmit_failed\",{type=packet.type,to=hop,error=err});return false,err end transport.lastTransmit,transport.lastError=now(),nil healthFor(hop).lastTransmit=now()trace(\"routing\",\"packet_sent\",{type=packet.type,to=hop,destination=packet.destination,links=#links})return true end local function rememberReverse(packet,previousHop)if type(packet)~=\"table\"or type(packet.request_id)~=\"string\"or#packet.request_id==0 then return false end local requestId,origin=packet.request_id,tostring(packet.origin)local existing=reverseRoutes[requestId]if existing and(existing.previous~=tostring(previousHop)or existing.origin~=origin)then return false,\"reverse route collision\"end reverseRoutes[requestId]={previous=tostring(previousHop),origin=origin,expires=now()+ROUTE_TTL}local entries={}for key,route in pairs(reverseRoutes)do entries[#entries+1]={id=key,expires=route.expires or 0}end table.sort(entries,function(a,b)return a.expires<b.expires end)while#entries>MAX_REVERSE_ROUTES do reverseRoutes[table.remove(entries,1).id]=nil end return true end local function broadcast(packet)local links=wirelessModems()if#links==0 then transport.lastError=\"no wireless modem attached\";trace(\"discovery\",\"wireless_missing\");return false,transport.lastError end local out=copy(packet)out.protocol,out.from,out.to=PROTOCOL,id(),0 out.timestamp=now()openChannels(config())local sent,err=transmit(links,DISCOVERY_CHANNEL,out)if not sent then trace(\"discovery\",\"transmit_failed\",{type=out.type,error=err});return false,err end transport.lastTransmit,transport.lastError=now(),nil trace(\"discovery\",out.type==\"discover\"and\"announcement_sent\"or\"discovery_packet_sent\",{type=out.type})return true end local function publicTransmit(target,typeName,body)if not PUBLIC_UPDATE_TYPES[typeName]then return false,\"invalid public update packet type\"end local encoded,encodeErr=canonical(body or{})if not encoded then return false,encodeErr or\"invalid public update body\"end local links=wirelessModems()if#links==0 then transport.lastError=\"no wireless modem attached\";return false,transport.lastError end openChannels(config())local packet={protocol=PUBLIC_UPDATE_PROTOCOL,type=typeName,from=id(),to=tostring(target),timestamp=now(),request_id=newRequestId(),body=body or{},}local sent,err=transmit(links,DISCOVERY_CHANNEL,packet)if not sent then transport.lastError=err or\"public update transmit failed\"trace(\"transport\",\"public_update_transmit_failed\",{type=typeName,to=target,error=transport.lastError})return false,transport.lastError end transport.lastTransmit,transport.lastError=now(),nil trace(\"transport\",\"public_update_sent\",{type=typeName,to=target,bytes=#encoded})return true end function M.publicSend(target,typeName,body)if tostring(target)==\"0\"or tostring(target)==\"\"then return false,\"public update target must be a computer ID\"end return publicTransmit(target,typeName,body)end function M.publicBroadcast(typeName,body)return publicTransmit(\"0\",typeName,body)end local function handshake(target,packet)local links=wirelessModems()if#links==0 then transport.lastError=\"no wireless modem attached\";return false,transport.lastError end local out=copy(packet)out.protocol,out.from,out.to,out.timestamp=PROTOCOL,id(),tostring(target),now()out.destination,out.ttl=tostring(target),1 openChannels(config())local sent,err=transmit(links,config().channel or CHANNEL,out)if not sent then trace(\"discovery\",\"handshake_transmit_failed\",{type=out.type,to=target,error=err});return false,err end transport.lastTransmit=now()trace(\"discovery\",out.type..\"_sent\",{to=target})return true end local function phraseTag(phrase,sessionId,hostId)return password.hmacSha256(phrase,\"ceetos/discovery/v2|\"..sessionId..\"|\"..tostring(hostId))end local function joinProof(phrase,sessionId,hostId,joinerId,nonce)return password.hmacSha256(phrase,\"ceetos/pair/join/v2|\"..sessionId..\"|\"..tostring(hostId)..\"|\"..tostring(joinerId)..\"|\"..nonce)end local function confirmProof(phrase,sessionId,hostId,joinerId,nonce,mode,master)return password.hmacSha256(phrase,\"ceetos/pair/confirm/v2|\"..sessionId..\"|\"..tostring(hostId)..\"|\"..tostring(joinerId)..\"|\"..nonce..\"|\"..tostring(mode)..\"|\"..tostring(master or\"\"))end local function linkKey(phrase,sessionId,hostId,joinerId,nonce)return password.derive(phrase,\"ceetos/link/v2|\"..sessionId..\"|\"..tostring(hostId)..\"|\"..tostring(joinerId)..\"|\"..nonce,64)end local function keyId(key)local value=password.hmacSha256(key,\"ceetos/key-id/v2\")return value and value:sub(1,16)or\"\"end local function activeSession()return discovery and(discovery.state==\"hosting\"or discovery.state==\"searching\"or discovery.state==\"candidate\"or discovery.state==\"confirming\")end local function setLast(state,message)lastDiscovery={state=state,message=message,at=now()}end local function persistPair(peerId,key,metadata,masterId)local value=config()value.peers[tostring(peerId)]={protocol=2,rekeyRequired=false,key=key,keyId=keyId(key),role=\"operator\",mode=metadata.mode or\"peer\",master=tostring(masterId or\"\")==id(),masterId=tostring(masterId or\"\"),label=metadata.label,}save(value)remember(peerId,metadata.label,{mode=metadata.mode,masterId=masterId})routes[tostring(peerId)]=nil routesDirty=true audit.log(\"local\",\"peer.rekeyed\",{peer=peerId,mode=metadata.mode})end local function markRejected(reason)if discovery then discovery=nil end setLast(\"cancelled\",reason)end local function discoveryAnnouncement()if not discovery or discovery.state~=\"hosting\"then return false,\"no active host discovery\"end return broadcast({type=\"discover\",session=discovery.id,tag=discovery.tag,label=discovery.label,mode=discovery.mode,master=discovery.masterSide,expires=discovery.expires,})end local function queueConfirmation(peerId,host)confirmations[host.id]=host local sent,err=handshake(peerId,{type=\"pair_confirm\",session=host.id,nonce=host.joinNonce,proof=host.confirmProof,label=host.label,mode=host.mode,master=host.masterId,})host.lastSent,host.retries=now(),0 if not sent then host.error=err end return sent,err end local function expireState(timestamp)if discovery and discovery.expires<=timestamp then local old=discovery.state discovery=nil setLast(\"expired\",old==\"searching\"and\"no matching discovery announcement received\"or\"discovery session expired\")trace(\"discovery\",\"session_expired\",{previous=old})end end local function boundMap(value,limit,timestamp)local entries={}for key,row in pairs(value)do entries[#entries+1]={key=key,at=type(row)==\"number\"and row or(type(row)==\"table\"and(row.expires or row.time or row.seen or row.lastAuthenticated or 0)or 0)}end table.sort(entries,function(a,b)if a.at~=b.at then return a.at<b.at end return tostring(a.key)<tostring(b.key)end)while#entries>limit do value[table.remove(entries,1).key]=nil end end local function pruneRouteBuckets(timestamp)local value=config()local entries={}for peerId,bucket in pairs(routes)do local latest=tonumber(bucket.changedAt)or 0 for _,candidate in ipairs(type(bucket.candidates)==\"table\"and bucket.candidates or{})do latest=math.max(latest,tonumber(candidate.expires)or 0)end entries[#entries+1]={peer=peerId,latest=latest}end table.sort(entries,function(a,b)if a.latest~=b.latest then return a.latest<b.latest end return tostring(a.peer)<tostring(b.peer)end)while#entries>ROUTE_BUCKET_LIMIT do local old=table.remove(entries,1)routes[old.peer],routesDirty=nil,true trace(\"routing\",\"route_bucket_evicted\",{destination=old.peer})end for peerId,state in pairs(linkHealth)do if not activeLink(value,peerId)and not routes[peerId]then linkHealth[peerId]=nil end end for peerId in pairs(advertisedRoutes)do if not activeLink(value,peerId)then advertisedRoutes[peerId]=nil end end boundMap(meshOffers,MESH_STATE_LIMIT,timestamp)boundMap(meshSeen,MESH_STATE_LIMIT,timestamp)end local function controller(value)value=value or config()if value.controller and tostring(value.controller)~=\"\"then local chosen=tostring(value.controller)if chosen==id()or activeLink(value,chosen)then return chosen end local known=routes[chosen]if known then if known.expires and known.expires>now()then return chosen end if type(known.candidates)==\"table\"then for _,candidate in ipairs(known.candidates)do if(candidate.expires or 0)>now()and activeLink(value,candidate.next)then return chosen end end end end trace(\"routing\",\"controller_unreachable\",{controller=chosen})end local selected=tonumber(id())or 0 for peerId in pairs(value.peers)do if activePeer(value,peerId)then local n=tonumber(peerId);if n and n<selected then selected=n end end end for peerId,route in pairs(routes)do local reachable=route.expires and route.expires>now()if type(route.candidates)==\"table\"then reachable=false for _,candidate in ipairs(route.candidates)do if(candidate.expires or 0)>now()then reachable=true;break end end end if reachable then local n=tonumber(peerId);if n and n<selected then selected=n end end end return tostring(selected)end local function meshConfig(value)value=value or config()local mesh=value.mesh if type(mesh)==\"table\"and type(mesh.id)==\"string\"and#mesh.id>=16 and type(mesh.root)==\"string\"and#mesh.root>=32 and tonumber(mesh.epoch)then return mesh end return nil end local function meshMaterial(packet)return canonical({protocol=packet.protocol,type=packet.type,from=packet.from,to=packet.to,mesh=packet.mesh,epoch=packet.epoch,nonce=packet.nonce,offer=packet.offer,timestamp=packet.timestamp})end local function meshTag(mesh,packet)local material=meshMaterial(packet)return material and password.hmacSha256(mesh.root,material)or nil end local function meshPacket(typeName,target,fields)local value,mesh=config(),meshConfig()if not mesh then return false,\"mesh enrollment is pending\"end local packet=copy(fields or{})packet.protocol,packet.type,packet.from,packet.to=PROTOCOL,typeName,id(),target and tostring(target)or 0 packet.mesh,packet.epoch,packet.timestamp=mesh.id,mesh.epoch,now()packet.tag=meshTag(mesh,packet)if not packet.tag then return false,\"could not authenticate mesh packet\"end openChannels(value)local links=wirelessModems()if#links==0 then return false,\"no wireless modem attached\"end local sent,err=transmit(links,value.channel or CHANNEL,packet)if sent then trace(\"routing\",typeName..\"_sent\",{to=packet.to,mesh=mesh.id:sub(1,8)})end return sent,err end local function deriveAutoEdge(mesh,peerId,firstNonce,secondNonce)local left,right=tostring(id()),tostring(peerId)if left>right then left,right=right,left end return password.hmacSha256(mesh.root,\"ceetos/mesh-edge/v1|\"..tostring(mesh.epoch)..\"|\"..left..\"|\"..right..\"|\"..tostring(firstNonce)..\"|\"..tostring(secondNonce))end local function ownsMeshOffer(peerId)local ours,theirs=tonumber(id()),tonumber(peerId)if ours and theirs then return ours<theirs end return tostring(id())<tostring(peerId)end local function installAutoEdge(mesh,peerId,firstNonce,secondNonce,peerLabel)peerId=tostring(peerId)local value=config()if activePeer(value,peerId)then return false,\"manual direct link already exists\"end local key=deriveAutoEdge(mesh,peerId,firstNonce,secondNonce)if not key then return false,\"could not derive mesh edge\"end autoEdges[peerId]={key=key,label=peerLabel,mesh=mesh.id,epoch=mesh.epoch,expires=now()+ROUTE_TTL,firstNonce=firstNonce,secondNonce=secondNonce}local state=healthFor(peerId)state.state,state.successes,state.misses,state.lastAuthenticated,state.stableSince=\"healthy\",2,0,now(),now()routesDirty,meshDirty=true,true trace(\"routing\",\"mesh_edge_active\",{peer=peerId,mesh=mesh.id:sub(1,8)})return true end local function meshEnrollmentAad(from,to,meshId,epoch,nonceCounter)return canonical({protocol=PROTOCOL,type=\"mesh_enroll\",from=tostring(from),to=tostring(to),mesh=meshId,epoch=tonumber(epoch),counter=tonumber(nonceCounter)})end local function sendEnrollment(peerId)local value,mesh,peer=config(),meshConfig(),activePeer(config(),peerId)if not mesh or not peer then return false,\"mesh or direct link unavailable\"end local _,nonceCounter=counter(peerId)local aad=meshEnrollmentAad(id(),peerId,mesh.id,mesh.epoch,nonceCounter)local nonce=meshCrypto.nonce(peer.key,nonceCounter,\"mesh-enroll|\"..id()..\"|\"..tostring(peerId))local plaintext=textutils.serialise({id=mesh.id,epoch=mesh.epoch,root=mesh.root},{compact=true})local envelope,err=meshCrypto.seal(peer.key,nonce,aad,plaintext)if not envelope then return false,err end local sent,sendErr=send(peerId,{type=\"mesh_enroll\",body={mesh=mesh.id,epoch=mesh.epoch,counter=nonceCounter,envelope=envelope},request_id=newRequestId()},peerId)if sent then trace(\"routing\",\"mesh_enrollment_sent\",{to=peerId,epoch=mesh.epoch})end return sent,sendErr end local function acceptEnrollment(from,peer,packet)if not activePeer(config(),from)then return rejectPacket(\"mesh enrollment requires a manual direct link\",packet)end local body=packet.body if type(body)~=\"table\"or type(body.mesh)~=\"string\"or type(body.envelope)~=\"table\"or not tonumber(body.epoch)or not tonumber(body.counter)then return rejectPacket(\"malformed_mesh_enrollment\",packet)end local aad=meshEnrollmentAad(from,id(),body.mesh,body.epoch,body.counter)local plaintext,err=meshCrypto.open(peer.key,body.envelope,aad)if not plaintext then return rejectPacket(err or\"mesh enrollment authentication failed\",packet)end local ok,mesh=pcall(textutils.unserialise,plaintext)if not ok or type(mesh)~=\"table\"or mesh.id~=body.mesh or tonumber(mesh.epoch)~=tonumber(body.epoch)or type(mesh.root)~=\"string\"or#mesh.root<32 then return rejectPacket(\"invalid_mesh_enrollment\",packet)end local value,existing=config(),meshConfig()if existing and existing.id==mesh.id and tonumber(existing.epoch)>tonumber(mesh.epoch)then return end value.mesh={id=mesh.id,epoch=tonumber(mesh.epoch),root=mesh.root,enrolledAt=now(),enrolledBy=tostring(from)}save(value)meshDirty,routesDirty=true,true trace(\"routing\",\"mesh_enrolled\",{from=from,mesh=mesh.id:sub(1,8),epoch=mesh.epoch})end local function ensureMeshEnrollment(timestamp)local value,mesh=config(),meshConfig()if not mesh then if(M._meshBootstrapAt or 0)>timestamp or controller(value)~=id()then return end value.mesh={id=password.newSalt(\"mesh-id:\"..id()),root=password.newSalt(\"mesh-root:\"..id()),epoch=1,createdAt=timestamp,controller=id()}save(value);mesh,meshDirty,routesDirty=value.mesh,true,true trace(\"routing\",\"mesh_created\",{mesh=mesh.id:sub(1,8),epoch=mesh.epoch})end for _,peerId in ipairs(allDirectLinks(value))do if activePeer(value,peerId)then local previous=meshEnrollmentSends[peerId]if not previous or previous.epoch~=mesh.epoch or timestamp-previous.at>=MESH_FULL_INTERVAL then local sent=sendEnrollment(peerId)if sent then meshEnrollmentSends[peerId]={epoch=mesh.epoch,at=timestamp}end end end end end local function meshBeacon(timestamp)local mesh=meshConfig()if not mesh or timestamp-lastMeshBeacon<MESH_BEACON_INTERVAL then return end lastMeshBeacon=timestamp meshPacket(\"mesh_beacon\",nil,{nonce=password.newSalt(\"mesh-beacon:\"..id()),label=label()})end local function verifyMeshPacket(packet)local mesh=meshConfig()if not mesh or type(packet)~=\"table\"or packet.protocol~=PROTOCOL or packet.mesh~=mesh.id or tonumber(packet.epoch)~=tonumber(mesh.epoch)then return false,\"mesh membership proof failed\"end if type(packet.from)~=\"string\"and type(packet.from)~=\"number\"then return false,\"invalid mesh sender\"end if type(packet.nonce)~=\"string\"or#packet.nonce<16 or#packet.nonce>128 then return false,\"invalid mesh nonce\"end if math.abs(now()-(tonumber(packet.timestamp)or 0))>ROUTE_TTL then return false,\"stale mesh packet\"end local material,tag=meshMaterial(packet),packet.tag local expected=material and password.hmacSha256(mesh.root,material)if type(tag)~=\"string\"or not expected or not password.constantTimeEqual(expected,tag)then return false,\"invalid mesh packet tag\"end local replay=tostring(packet.from)..\"|\"..tostring(packet.type)..\"|\"..tostring(packet.nonce)..\"|\"..tostring(packet.offer or\"\")if meshSeen[replay]and meshSeen[replay]+ROUTE_TTL>now()then return false,\"replayed mesh packet\"end meshSeen[replay]=now()return true,mesh end local function handleMeshPacket(packet,distance)local valid,meshOrErr=verifyMeshPacket(packet)if not valid then return rejectPacket(meshOrErr,packet,nil,distance)end local mesh,from=meshOrErr,tostring(packet.from)if from==id()then return end if packet.type==\"mesh_beacon\"then remember(from,packet.label,{mesh=mesh.id})if not activePeer(config(),from)and not autoEdges[from]and ownsMeshOffer(from)then local nonce=password.newSalt(\"mesh-offer:\"..from)meshOffers[from]={offer=nonce,expires=now()+DISCOVERY_TTL}meshPacket(\"mesh_edge_offer\",from,{nonce=nonce,label=label()})end return end if not isForUs(packet.to)then return rejectPacket(\"mesh packet addressed to another peer\",packet,nil,distance)end if packet.type==\"mesh_edge_offer\"then if activePeer(config(),from)then return end local response=password.newSalt(\"mesh-accept:\"..from)installAutoEdge(mesh,from,packet.nonce,response,packet.label)return meshPacket(\"mesh_edge_accept\",from,{nonce=response,offer=packet.nonce,label=label()})end if packet.type==\"mesh_edge_accept\"then local offer=meshOffers[from]if not offer or offer.expires<=now()or offer.offer~=packet.offer then return rejectPacket(\"unexpected mesh edge acceptance\",packet,nil,distance)end meshOffers[from]=nil return installAutoEdge(mesh,from,offer.offer,packet.nonce,packet.label)end end local function probeLinks(timestamp)local value=config()for _,peerId in ipairs(allDirectLinks(value))do local health=healthFor(peerId)local interval=health.state==\"offline\"and PROBE_INTERVAL*3 or PROBE_INTERVAL if timestamp-(health.lastAuthenticated or 0)>=interval and timestamp-(health.lastProbe or 0)>=interval then if health.awaiting then health.misses=(health.misses or 0)+1 health.loss=math.min(1,((health.loss or 0)*3+1)/4)local nextState=health.misses>=PROBE_OFFLINE and\"offline\"or(health.misses>=PROBE_DEGRADED and\"degraded\"or health.state)if nextState~=health.state then health.state,health.successes,health.recoveredAt=nextState,0,nil trace(\"routing\",\"link_\"..nextState,{peer=peerId,misses=health.misses})end routesDirty=true end health.awaiting,health.lastProbe,health.probeToken=true,timestamp,password.newSalt(\"mesh-probe:\"..peerId)send(peerId,{type=\"mesh_probe\",body={token=health.probeToken},request_id=newRequestId()},peerId)end end end local function advertisedMembers(value,peerId,timestamp)local members={}for other,manual in pairs(value.peers)do if other~=peerId and activeLink(value,other)and linkState(other)==\"healthy\"then members[other]={label=manual.label,mode=manual.mode,masterId=manual.masterId,hops=1,kind=\"direct\"}end end for other,edge in pairs(autoEdges)do if other~=peerId and edge.expires>timestamp and linkState(other)==\"healthy\"then members[other]={label=edge.label,mode=\"peer\",hops=1,kind=\"mesh\"}end end for other in pairs(routes)do if other~=peerId and not members[other]then local candidate=primaryCandidate(other,value,false)if candidate and candidate.next~=peerId and linkState(candidate.next)==\"healthy\"then members[other]={label=candidate.label,mode=candidate.mode,masterId=candidate.masterId,hops=candidate.hops,kind=candidate.kind or\"route\"}end end end return members end local function sameAdvertisement(left,right)local leftValue,leftErr=canonical(left)local rightValue,rightErr=canonical(right)return leftValue~=nil and rightValue~=nil and not leftErr and not rightErr and leftValue==rightValue end local function advertiseRoutes(force)local timestamp,value=now(),config()if not force and not routesDirty and timestamp-lastRouteAdvertisement<ROUTE_INTERVAL then return end lastRouteAdvertisement,routesDirty=timestamp,false local full=timestamp-lastMeshFull>=MESH_FULL_INTERVAL if full then lastMeshFull=timestamp end for _,peerId in ipairs(allDirectLinks(value))do if linkUsable(value,peerId,false)then local desired,previous=advertisedMembers(value,peerId,timestamp),advertisedRoutes[peerId]or{}local members,withdrawals={},{}if full then members=desired else for target,meta in pairs(desired)do if not sameAdvertisement(meta,previous[target])then members[target]=meta end end for target in pairs(previous)do if not desired[target]then withdrawals[#withdrawals+1]=target end end end table.sort(withdrawals,function(a,b)return tostring(a)<tostring(b)end)if full or next(members)~=nil or#withdrawals>0 then routeSequence=routeSequence+1 local body={sequence=routeSequence,routeVersion=2,full=full,controller=controller(value),members=members,withdrawals=withdrawals}if send(peerId,{type=\"route_advertise\",body=body,routeSafe=true,request_id=newRequestId()})then advertisedRoutes[peerId]=copy(desired)trace(\"routing\",full and\"route_snapshot_sent\"or\"route_delta_sent\",{to=peerId,changes=(full and 0 or#withdrawals)})end end else advertisedRoutes[peerId]=nil end end end function M.start()migrateV1Links()loadSecurity()assert(meshCrypto.selfTest(),\"CeetOS mesh cryptography self-test failed\")openChannels(config())local status=M.transportStatus()trace(\"transport\",status.wireless and\"wireless_modem_detected\"or\"wireless_modem_missing\",{name=status.name})routesDirty,M._meshBootstrapAt=true,now()end function M.transportStatus()local wireless=wirelessModems()transport.modem,transport.wireless=#modems()>0,#wireless>0 transport.name=wireless[1]and wireless[1].name or nil local out=copy(transport)out.wirelessLinks,out.wirelessLinkCount={},#wireless for _,item in ipairs(wireless)do out.wirelessLinks[#out.wirelessLinks+1]=item.name end out.usesAllWirelessLinks,out.protocol=true,2 out.directPeers,out.manualDirectPeers,out.meshPeers,out.rekeyRequiredPeers,out.routedPeers=0,0,0,0,0 out.healthyLinks,out.degradedLinks,out.offlineLinks=0,0,0 local value=config()for peerId,peer in pairs(value.peers)do if activePeer(value,peerId)then out.directPeers,out.manualDirectPeers=out.directPeers+1,out.manualDirectPeers+1 elseif peer.rekeyRequired then out.rekeyRequiredPeers=out.rekeyRequiredPeers+1 end end for peerId,edge in pairs(autoEdges)do if edge.expires>now()then out.meshPeers,out.directPeers=out.meshPeers+1,out.directPeers+1 end end for peerId,health in pairs(linkHealth)do if health.state==\"healthy\"then out.healthyLinks=out.healthyLinks+1 elseif health.state==\"degraded\"then out.degradedLinks=out.degradedLinks+1 elseif health.state==\"offline\"then out.offlineLinks=out.offlineLinks+1 end end for peerId,bucket in pairs(routes)do local usable=primaryCandidate(peerId,value,false)if usable and not value.peers[peerId]and not autoEdges[peerId]then out.routedPeers=out.routedPeers+1 end end local mesh=meshConfig(value)out.mesh=mesh and{id=mesh.id:sub(1,8),epoch=mesh.epoch,enrolled=true}or{enrolled=false}out.health={healthy=out.healthyLinks,degraded=out.degradedLinks,offline=out.offlineLinks}return out end function M.transportTrace(kind)if kind==\"discovery\"or kind==\"routing\"or kind==\"transport\"then return copy(traces[kind])end return{discovery=copy(traces.discovery),routing=copy(traces.routing),transport=copy(traces.transport)}end function M.discovery()expireState(now())return copy(discovery)end function M.discoveryStatus()expireState(now())local candidate=discovery and discovery.candidate and{id=discovery.candidate.from,label=discovery.candidate.label,mode=discovery.candidate.mode,master=discovery.candidate.master,}or nil local session=discovery and{session=discovery.id,state=discovery.state,mode=discovery.mode,master=discovery.masterSide,expires=discovery.expires,retries=discovery.retries or 0,candidate=candidate and copy(candidate)or nil,}or nil local state=session and session.state or(lastDiscovery and lastDiscovery.state or\"inactive\")return{state=state,active=session~=nil,lastState=lastDiscovery and lastDiscovery.state or\"inactive\",lastMessage=lastDiscovery and lastDiscovery.message or nil,session=session,searching=session and session.state==\"searching\"or false,candidate=candidate,discovered=#M.seenPeers(),transport=M.transportStatus(),message=(discovery and discovery.error)or(lastDiscovery and lastDiscovery.message),}end function M.startDiscovery(mode,masterSide,phrase)if activeSession()then return false,\"cancel the active discovery session first\"end local normalized,phraseErr=M.normalizePhrase(phrase)if not normalized then return false,phraseErr end mode=mode==\"master\"and\"master\"or\"peer\"masterSide=masterSide==\"joiner\"and\"joiner\"or\"initiator\"local sessionId=password.newSalt(\"discovery:\"..id())discovery={id=sessionId,state=\"hosting\",phrase=normalized,tag=phraseTag(normalized,sessionId,id()),mode=mode,masterSide=masterSide,label=label(),initiator=id(),expires=now()+DISCOVERY_TTL,retries=0,lastBroadcast=0,}local sent,err=discoveryAnnouncement()if not sent then discovery=nil;setLast(\"cancelled\",err);return false,err end discovery.lastBroadcast=now()setLast(\"hosting\")return true,{state=\"hosting\",session=sessionId,expires=discovery.expires}end function M.joinDiscovery(phrase)if activeSession()then return false,\"cancel the active discovery session first\"end local normalized,phraseErr=M.normalizePhrase(phrase)if not normalized then return false,phraseErr end local candidate for _,item in pairs(discovered)do if item.expires>now()and password.constantTimeEqual(item.tag or\"\",phraseTag(normalized,item.session,item.from))then candidate=item;break end end discovery={state=\"searching\",phrase=normalized,expires=now()+DISCOVERY_TTL,retries=0,lastQuery=0}if candidate then discovery.state,discovery.candidate=\"candidate\",candidate return true,{state=\"candidate\",candidate={id=candidate.from,label=candidate.label,mode=candidate.mode,master=candidate.master}}end local sent,err=broadcast({type=\"discover_query\"})if not sent then discovery=nil;setLast(\"cancelled\",err);return false,err end discovery.lastQuery=now()setLast(\"searching\",\"waiting for matching discovery announcement\")return true,{state=\"searching\"}end function M.confirmDiscovery()if not discovery or discovery.state~=\"candidate\"or not discovery.candidate then return false,\"no discovery candidate is awaiting confirmation\"end local candidate,value=discovery.candidate,config()local existing=value.peers[tostring(candidate.from)]if existing and not existing.rekeyRequired then return false,\"computer is already a network member\"end if routes[tostring(candidate.from)]and not existing then return false,\"computer is already a routed network member\"end local nonce=password.newSalt(\"pair-join:\"..candidate.session)local proof=joinProof(discovery.phrase,candidate.session,candidate.from,id(),nonce)discovery.state,discovery.joinNonce,discovery.joinProof,discovery.lastSent,discovery.retries=\"confirming\",nonce,proof,now(),0 local sent,err=handshake(candidate.from,{type=\"pair_join\",session=candidate.session,nonce=nonce,proof=proof,label=label()})if not sent then discovery.error=err;return false,err end trace(\"discovery\",\"pair_confirmation_requested\",{peer=candidate.from})return true end function M.cancelDiscovery()if discovery and discovery.state==\"hosting\"then broadcast({type=\"discover_cancel\",session=discovery.id})end discovery=nil setLast(\"cancelled\",\"discovery cancelled\")trace(\"discovery\",\"session_cancelled\")return true end function M.normalizePhrase(value)if type(value)~=\"string\"then return nil,\"phrase is required\"end if value:find(\"[%z\\1-\\31\\127]\")then return nil,\"phrase contains control characters\"end value=value:gsub(\"^%s+\",\"\"):gsub(\"%s+$\",\"\")if#value<8 then return nil,\"phrase must be at least 8 characters\"end if#value>128 then return nil,\"phrase must be at most 128 characters\"end return value end function M.tick()local timestamp=now()expireState(timestamp)if discovery then if discovery.state==\"hosting\"and timestamp-(discovery.lastBroadcast or 0)>=math.min(30000,DISCOVERY_INTERVAL*(2^math.min(discovery.retries or 0,4)))then local sent,err=discoveryAnnouncement()discovery.lastBroadcast=timestamp discovery.retries=(discovery.retries or 0)+1 if not sent then discovery.error=err end elseif discovery.state==\"searching\"and timestamp-(discovery.lastQuery or 0)>=DISCOVERY_INTERVAL then local sent,err=broadcast({type=\"discover_query\"})discovery.lastQuery,discovery.retries=timestamp,(discovery.retries or 0)+1 if not sent then discovery.error=err end elseif discovery.state==\"confirming\"and timestamp-(discovery.lastSent or 0)>=PAIR_RETRY then local candidate=discovery.candidate local sent,err=handshake(candidate.from,{type=\"pair_join\",session=candidate.session,nonce=discovery.joinNonce,proof=discovery.joinProof,label=label()})discovery.lastSent,discovery.retries=timestamp,(discovery.retries or 0)+1 if not sent then discovery.error=err end end end for sessionId,item in pairs(discovered)do if item.expires<=timestamp then discovered[sessionId]=nil end end for sessionId,record in pairs(confirmations)do if record.expires<=timestamp then confirmations[sessionId]=nil elseif timestamp-(record.lastSent or 0)>=PAIR_RETRY then queueConfirmation(record.peer,record)end end for peerId,bucket in pairs(routes)do local kept={}for _,candidate in ipairs(routeBucket(peerId).candidates)do if candidate.expires>timestamp then kept[#kept+1]=candidate end end bucket.candidates=kept if#kept==0 and not activeLink(config(),peerId)then routes[peerId],routesDirty=nil,true end end for peerId,edge in pairs(autoEdges)do if edge.expires<=timestamp then autoEdges[peerId],routesDirty=nil,true;trace(\"routing\",\"mesh_edge_expired\",{peer=peerId})end end for key,seenAt in pairs(meshSeen)do if seenAt+ROUTE_TTL<=timestamp then meshSeen[key]=nil end end for peerId,offer in pairs(meshOffers)do if offer.expires<=timestamp then meshOffers[peerId]=nil end end for requestId,seenAt in pairs(seenPackets)do if seenAt+ROUTE_TTL<=timestamp then seenPackets[requestId]=nil end end for requestId,route in pairs(reverseRoutes)do if route.expires<=timestamp then reverseRoutes[requestId]=nil end end boundMap(meshSeen,MESH_STATE_LIMIT,timestamp)boundMap(meshOffers,MESH_STATE_LIMIT,timestamp)pruneRouteBuckets(timestamp)ensureMeshEnrollment(timestamp)meshBeacon(timestamp)probeLinks(timestamp)advertiseRoutes(false)end function M.peers()local out,value,seen={},config(),read(SEEN_PATH,{})for peerId,peer in pairs(value.peers)do out[#out+1]={id=peerId,label=peer.label or(seen[peerId]and seen[peerId].label),role=peer.role or\"operator\",mode=peer.mode or\"peer\",master=peer.master==true,masterId=peer.masterId,direct=true,active=activePeer(value,peerId)~=nil,rekeyRequired=peer.rekeyRequired==true or peer.protocol~=2,health=linkState(peerId),auto=false,}end for peerId,edge in pairs(autoEdges)do if not value.peers[peerId]and edge.expires>now()then out[#out+1]={id=peerId,label=edge.label or(seen[peerId]and seen[peerId].label),role=\"mesh\",mode=\"peer\",direct=true,auto=true,active=true,health=linkState(peerId)}end end for peerId in pairs(routes)do if not value.peers[peerId]and not autoEdges[peerId]then local route=primaryCandidate(peerId,value,false)if route then out[#out+1]={id=peerId,label=route.label or(seen[peerId]and seen[peerId].label),role=\"routed\",mode=route.mode or\"peer\",masterId=route.masterId,routed=true,hops=route.hops,next=route.next,health=linkState(route.next),alternates=#routeBucket(peerId).candidates-1}end end end table.sort(out,function(a,b)return tonumber(a.id)<tonumber(b.id)end)return out end function M.directPeers()local out={}for _,peer in ipairs(M.peers())do if peer.direct and peer.active then out[#out+1]=peer end end return out end function M.seenPeers()local out={}for peerId,item in pairs(read(SEEN_PATH,{}))do if not item.seen or item.seen+DISCOVERY_TTL*2>now()then out[#out+1]={id=peerId,label=item.label,seen=item.seen,session=item.session}end end table.sort(out,function(a,b)return tonumber(a.id)<tonumber(b.id)end)return out end function M.routeStatus(target)local value,out=config(),{}local function row(peerId)local selected=primaryCandidate(peerId,value,false)if not selected then return end local health=healthFor(selected.next)local alternates={}for _,candidate in ipairs(validCandidates(peerId,value))do if tostring(candidate.next)~=tostring(selected.next)then local state=healthFor(candidate.next)alternates[#alternates+1]={next=candidate.next,hops=candidate.hops,kind=candidate.kind or\"route\",health=state.state,loss=state.loss or 0,rtt=state.rtt,distance=state.lastDistance}end end table.sort(alternates,compareCandidates)while#alternates>ROUTE_CANDIDATE_LIMIT-1 do table.remove(alternates)end out[#out+1]={id=tostring(peerId),label=selected.label,next=selected.next,hops=selected.hops,kind=selected.kind or\"route\",health=health.state,loss=health.loss or 0,rtt=health.rtt,distance=health.lastDistance,selectedAt=routeBucket(peerId).changedAt,reason=routeBucket(peerId).reason,alternates=alternates,}end if target then row(tostring(target))else local ids,seen={},{}for peerId in pairs(value.peers)do ids[#ids+1],seen[peerId]=peerId,true end for peerId in pairs(autoEdges)do if not seen[peerId]then ids[#ids+1],seen[peerId]=peerId,true end end for peerId in pairs(routes)do if not seen[peerId]then ids[#ids+1],seen[peerId]=peerId,true end end table.sort(ids,function(a,b)return tonumber(a)<tonumber(b)end)for _,peerId in ipairs(ids)do row(peerId)end end return out end function M.statusSnapshot()return{protocol=2,transport=M.transportStatus(),discovery=M.discoveryStatus(),peers=M.peers(),routes=M.routeStatus(),trace=M.transportTrace(),controller=M.controller()}end function M.controller()return controller()end function M.isDirectController(from,packet)return tostring(from)==tostring(controller())and type(packet)==\"table\"and tostring(packet.origin or\"\")==tostring(from)end function M.setController(value)assert(tonumber(value),\"controller must be a computer ID\")local saved=config();saved.controller=tostring(value);save(saved);routesDirty=true audit.log(\"local\",\"jobs.controller\",{controller=saved.controller})return saved.controller end function M.request(target,typeName,body,options)if type(typeName)~=\"string\"or#typeName==0 or#typeName>64 then return false,\"invalid request type\"end local destination=tostring(target)local value=config()if not primaryCandidate(destination,value,options and options.safe==true)then return false,\"peer is unreachable, degraded, or requires rekey\"end return send(destination,{type=typeName,body=body or{},origin=id(),routeSafe=options and options.safe==true,balanceSafe=options and options.safe==true,confidential=options and options.confidential==true,request_id=newRequestId()})end function M.reply(request,typeName,body,options)if type(request)~=\"table\"or type(typeName)~=\"string\"or#typeName==0 or#typeName>64 then return false,\"invalid reply\"end local requestId,destination=request.request_id,tostring(request.origin or\"\")local reverse=type(requestId)==\"string\"and reverseRoutes[requestId]or nil if destination==\"\"or not reverse or reverse.expires<=now()or reverse.origin~=destination then return false,\"reverse reply route is unavailable\"end return send(destination,{type=typeName,body=body or{},origin=id(),destination=destination,reply_to=requestId,routeSafe=options and options.safe==true,confidential=options and options.confidential==true,request_id=newRequestId(),},reverse.previous)end function M.offer()return false,\"legacy pairing is disabled; use phrase discovery\"end function M.accept()return false,\"legacy pairing is disabled; use phrase discovery\"end function M.discover()return broadcast({type=\"discover_query\"})end rejectPacket=function(reason,packet,channel,distance)transport.rejected=transport.rejected+1 trace(\"transport\",\"packet_rejected\",{reason=reason,type=type(packet)==\"table\"and packet.type or nil,channel=channel,distance=distance,from=type(packet)==\"table\"and packet.from or nil})end local function handleDiscovery(packet,channel,distance)local from=tostring(packet.from)if packet.type==\"discover_cancel\"and isBroadcast(packet.to)then discovered[tostring(packet.session)]=nil trace(\"discovery\",\"cancel_received\",{from=from,distance=distance})return end if packet.type==\"discover_query\"and isBroadcast(packet.to)and discovery and discovery.state==\"hosting\"then discoveryAnnouncement()trace(\"discovery\",\"query_answered\",{from=from,distance=distance})return end if packet.type==\"discover\"and isBroadcast(packet.to)and from~=id()then if type(packet.session)~=\"string\"or#packet.session<16 or type(packet.tag)~=\"string\"or#packet.tag~=64 then return rejectPacket(\"malformed_discovery\",packet,channel,distance)end local expires=tonumber(packet.expires)or(now()+DISCOVERY_TTL)discovered[packet.session]={session=packet.session,from=from,tag=packet.tag,label=tostring(packet.label or(\"Computer \"..from)):sub(1,128),mode=packet.mode==\"master\"and\"master\"or\"peer\",master=packet.master==\"joiner\"and\"joiner\"or\"initiator\",expires=math.min(expires,now()+DISCOVERY_TTL)}remember(from,packet.label,{session=packet.session})trace(\"discovery\",\"announcement_received\",{from=from,label=packet.label,distance=distance})if discovery and discovery.state==\"searching\"and password.constantTimeEqual(packet.tag,phraseTag(discovery.phrase,packet.session,from))then local value,existing=config(),config().peers[from]if existing and not existing.rekeyRequired then markRejected(\"computer is already a direct peer\")elseif routes[from]and not existing then markRejected(\"computer is already a routed network member\")else discovery.state,discovery.candidate,discovery.error=\"candidate\",discovered[packet.session],nil setLast(\"candidate\",\"matching computer found; confirm pairing\")trace(\"discovery\",\"candidate_found\",{from=from,label=packet.label,distance=distance})end end return end end local function handlePairJoin(packet,distance)if not discovery or discovery.state~=\"hosting\"or packet.session~=discovery.id then return end local from=tostring(packet.from)local value,existing=config(),config().peers[from]if(existing and not existing.rekeyRequired)or(routes[from]and not existing)then handshake(from,{type=\"pair_reject\",session=packet.session,reason=\"already_network_member\"})trace(\"discovery\",\"pair_rejected\",{from=from,reason=\"already_network_member\"})return end if type(packet.nonce)~=\"string\"or#packet.nonce<16 or#packet.nonce>128 or type(packet.proof)~=\"string\"or#packet.proof~=64 then return rejectPacket(\"malformed_pair_join\",packet,nil,distance)end local expected=joinProof(discovery.phrase,discovery.id,id(),from,packet.nonce)if not password.constantTimeEqual(expected,packet.proof)then discovery.failures=(discovery.failures or 0)+1 if discovery.failures>=5 then markRejected(\"too many invalid pairing proofs\")end handshake(from,{type=\"pair_reject\",session=packet.session,reason=\"phrase_mismatch\"})trace(\"discovery\",\"pair_rejected\",{from=from,reason=\"phrase_mismatch\"})return end local masterId=discovery.mode==\"master\"and(discovery.masterSide==\"initiator\"and id()or from)or\"\"local key,keyErr=linkKey(discovery.phrase,discovery.id,id(),from,packet.nonce)if not key then return markRejected(keyErr)end persistPair(from,key,{mode=discovery.mode,label=packet.label},masterId)local record={id=discovery.id,peer=from,joinNonce=packet.nonce,mode=discovery.mode,masterId=masterId,label=label(),expires=now()+DISCOVERY_TTL}record.confirmProof=confirmProof(discovery.phrase,record.id,id(),from,record.joinNonce,record.mode,record.masterId)discovery=nil setLast(\"paired\",\"awaiting pairing acknowledgement\")trace(\"discovery\",\"pair_join_verified\",{from=from,distance=distance})return queueConfirmation(from,record)end local function handlePairConfirm(packet,distance)if not discovery or discovery.state~=\"confirming\"or not discovery.candidate or packet.session~=discovery.candidate.session then return end local from=tostring(packet.from)if from~=tostring(discovery.candidate.from)or packet.nonce~=discovery.joinNonce then return rejectPacket(\"unexpected_pair_confirmation\",packet,nil,distance)end local expected=confirmProof(discovery.phrase,packet.session,from,id(),discovery.joinNonce,packet.mode==\"master\"and\"master\"or\"peer\",packet.master or\"\")if not password.constantTimeEqual(expected,packet.proof or\"\")then return markRejected(\"pair confirmation proof did not match\")end local key,err=linkKey(discovery.phrase,packet.session,from,id(),discovery.joinNonce)if not key then return markRejected(err)end persistPair(from,key,{mode=packet.mode,label=packet.label},packet.master)local sessionId=packet.session discovery=nil setLast(\"paired\",\"paired with \"..tostring(packet.label or from))handshake(from,{type=\"pair_ack\",session=sessionId,proof=password.hmacSha256(key,\"ceetos/pair/ack/v2|\"..sessionId)})trace(\"discovery\",\"pair_confirmed\",{from=from,distance=distance})return true end local function handlePairAck(packet)local record=confirmations[packet.session]if not record or tostring(record.peer)~=tostring(packet.from)then return end local value,peer=config(),activePeer(config(),record.peer)if not peer then return end local expected=password.hmacSha256(peer.key,\"ceetos/pair/ack/v2|\"..packet.session)if password.constantTimeEqual(expected,packet.proof or\"\")then confirmations[packet.session]=nil setLast(\"paired\",\"paired with \"..tostring(record.peer))routesDirty=true trace(\"discovery\",\"pair_acknowledged\",{from=packet.from})end end local function handleRouteAdvertisement(from,packet)local body=packet.body if type(body)~=\"table\"or type(body.sequence)~=\"number\"or type(body.members)~=\"table\"or(body.withdrawals~=nil and type(body.withdrawals)~=\"table\")then return rejectPacket(\"malformed_route_advertisement\",packet)end local key=tostring(from)M._routeSequences=M._routeSequences or{}if(M._routeSequences[key]or-1)>=body.sequence then return end M._routeSequences[key]=body.sequence local value,changed,count=config(),false,0 if body.controller and not value.controller then value.controller,changed=tostring(body.controller),true end local announced={}for advertisedId,meta in pairs(body.members)do count=count+1 if count>MAX_PACKET_TABLE then return rejectPacket(\"route_advertisement_too_large\",packet)end local peerId=tostring(advertisedId)announced[peerId]=true if peerId~=id()and peerId~=key and type(meta)==\"table\"then local hops=math.floor(tonumber(meta.hops)or 0)+1 if hops>1 and hops<=PACKET_TTL and type(meta.label)~=\"table\"and type(meta.mode)~=\"table\"then local bucket,found=routeBucket(peerId),nil for _,candidate in ipairs(bucket.candidates)do if tostring(candidate.next)==key then found=candidate;break end end if found then local metadataChanged=found.hops~=hops or found.label~=meta.label or found.mode~=meta.mode or tostring(found.masterId or\"\")~=tostring(meta.masterId or\"\")or found.kind~=(meta.kind or\"route\")found.hops,found.expires=hops,now()+ROUTE_TTL found.label,found.mode,found.masterId,found.kind=meta.label,meta.mode,meta.masterId,meta.kind or\"route\"if metadataChanged then changed=true end else bucket.candidates[#bucket.candidates+1]={next=key,hops=hops,expires=now()+ROUTE_TTL,label=type(meta.label)==\"string\"and meta.label:sub(1,128)or nil,mode=meta.mode==\"master\"and\"master\"or\"peer\",masterId=meta.masterId and tostring(meta.masterId)or nil,kind=meta.kind==\"mesh\"and\"mesh\"or\"route\"}table.sort(bucket.candidates,compareCandidates)while#bucket.candidates>ROUTE_CANDIDATE_LIMIT do table.remove(bucket.candidates)end changed=true end end end end local withdrawals=body.withdrawals or{}for _,withdrawnId in pairs(withdrawals)do count=count+1 if count>MAX_PACKET_TABLE then return rejectPacket(\"route_advertisement_too_large\",packet)end local bucket=routes[tostring(withdrawnId)]if bucket and type(bucket.candidates)==\"table\"then local kept={}for _,candidate in ipairs(bucket.candidates)do if tostring(candidate.next)~=key then kept[#kept+1]=candidate else changed=true end end bucket.candidates=kept end end if body.full==true then for peerId,bucket in pairs(routes)do if type(bucket.candidates)==\"table\"and not announced[tostring(peerId)]then local kept={}for _,candidate in ipairs(bucket.candidates)do if tostring(candidate.next)~=key then kept[#kept+1]=candidate else changed=true end end bucket.candidates=kept end end end if changed then if value.controller then save(value)end;routesDirty=true;trace(\"routing\",\"route_table_updated\",{from=from})end end local function handleProbe(from,packet)local token=type(packet.body)==\"table\"and packet.body.token if type(token)~=\"string\"or#token<16 or#token>128 then return rejectPacket(\"malformed link probe\",packet)end touchLink(from,nil,\"probe\")return send(from,{type=\"mesh_probe_ack\",body={token=token},request_id=newRequestId()},from)end local function handleProbeAck(from,packet)local health,token=healthFor(from),type(packet.body)==\"table\"and packet.body.token if not health.awaiting or token~=health.probeToken then return rejectPacket(\"unexpected link probe acknowledgement\",packet)end local sample=math.max(0,now()-(health.lastProbe or now()))health.rtt=health.rtt and math.floor((health.rtt*3+sample)/4)or sample health.awaiting,health.misses,health.probeToken=false,0,nil touchLink(from,health.lastDistance,\"probe_ack\")end function M.handle(event)if event[1]~=\"modem_message\"then return end local channel,packet,distance=event[3],event[5],event[6]local expected=false for _,item in ipairs(transport.channels or{})do if channel==item then expected=true;break end end if not expected then return rejectPacket(\"unexpected_channel\",packet,channel,distance)end transport.lastReceive,transport.lastDistance=now(),distance if type(packet)~=\"table\"then return rejectPacket(\"packet_not_table\",packet,channel,distance)end if packet.protocol==PUBLIC_UPDATE_PROTOCOL then if channel~=DISCOVERY_CHANNEL or not PUBLIC_UPDATE_TYPES[packet.type]or type(packet.from)~=\"string\"and type(packet.from)~=\"number\"or not(isForUs(packet.to)or isBroadcast(packet.to))then return rejectPacket(\"invalid_public_update_packet\",packet,channel,distance)end local encoded,encodeErr=canonical(packet.body or{})if not encoded then return rejectPacket(\"invalid_public_update_body:\"..tostring(encodeErr),packet,channel,distance)end trace(\"transport\",\"public_update_received\",{type=packet.type,from=packet.from,distance=distance,bytes=#encoded})if M.publicHandler then return M.publicHandler(packet,distance)end return end local discoveryPacket=packet.type==\"discover\"or packet.type==\"discover_query\"or packet.type==\"discover_cancel\"local handshakePacket=packet.type==\"pair_join\"or packet.type==\"pair_confirm\"or packet.type==\"pair_ack\"or packet.type==\"pair_reject\"local meshPacketType=packet.type==\"mesh_beacon\"or packet.type==\"mesh_edge_offer\"or packet.type==\"mesh_edge_accept\"if discoveryPacket then if packet.protocol~=PROTOCOL or channel~=DISCOVERY_CHANNEL then return rejectPacket(\"invalid_discovery_transport\",packet,channel,distance)end return handleDiscovery(packet,channel,distance)end if handshakePacket then if not isForUs(packet.to)then return end if packet.protocol~=PROTOCOL or channel~=(config().channel or CHANNEL)then return rejectPacket(\"invalid_handshake_transport\",packet,channel,distance)end if packet.type==\"pair_join\"then return handlePairJoin(packet,distance)elseif packet.type==\"pair_confirm\"then return handlePairConfirm(packet,distance)elseif packet.type==\"pair_ack\"then return handlePairAck(packet)elseif packet.type==\"pair_reject\"and discovery then markRejected(\"pairing rejected: \"..tostring(packet.reason or\"remote peer rejected it\"));return end return end if meshPacketType then if packet.protocol~=PROTOCOL or channel~=(config().channel or CHANNEL)then return rejectPacket(\"invalid mesh transport\",packet,channel,distance)end if packet.type~=\"mesh_beacon\"and not isForUs(packet.to)then return end return handleMeshPacket(packet,distance)end if not isForUs(packet.to)then return end local value=config()local valid,peerOrReason=verifyPacket(packet,value)if not valid then return rejectPacket(peerOrReason,packet,channel,distance)end local peer,from=peerOrReason,tostring(packet.from)if packet.confidential==true then local opened,openErr=openBody(peer,packet)if not opened then return rejectPacket(openErr or\"could not open confidential packet\",packet,channel,distance)end packet.body=opened end touchLink(from,distance,\"authenticated_packet\")if autoEdges[from]then autoEdges[from].expires=now()+ROUTE_TTL end trace(\"routing\",\"packet_received\",{type=packet.type,from=from,destination=packet.destination,distance=distance})if packet.type==\"mesh_enroll\"then return acceptEnrollment(from,peer,packet)end if packet.type==\"mesh_probe\"then return handleProbe(from,packet)end if packet.type==\"mesh_probe_ack\"then return handleProbeAck(from,packet)end if packet.type==\"route_advertise\"then return handleRouteAdvertisement(from,packet)end if packet.reply_to and packet.destination and tostring(packet.destination)~=id()then local reverse=reverseRoutes[packet.reply_to]if not reverse or reverse.expires<=now()or reverse.origin~=tostring(packet.destination)then return rejectPacket(\"reverse reply route unavailable\",packet,channel,distance)end local requestId=tostring(packet.request_id or\"\")if seenPackets[requestId]then return trace(\"routing\",\"forward_duplicate\",{from=from,type=packet.type})end seenPackets[requestId]=now()if(tonumber(packet.ttl)or 0)<=1 then return rejectPacket(\"TTL exhausted\",packet,channel,distance)end packet.ttl=packet.ttl-1 trace(\"routing\",\"reverse_reply_forwarded\",{from=from,to=reverse.previous,type=packet.type})return send(packet.destination,packet,reverse.previous)end if packet.destination and tostring(packet.destination)~=id()then local requestId=tostring(packet.request_id or\"\")if requestId==\"\"or seenPackets[requestId]then return trace(\"routing\",\"forward_duplicate\",{from=from,type=packet.type})end seenPackets[requestId]=now()local remembered,rememberErr=rememberReverse(packet,from)if not remembered then return rejectPacket(rememberErr or\"could not record reverse route\",packet,channel,distance)end if(tonumber(packet.ttl)or 0)<=1 then return rejectPacket(\"TTL exhausted\",packet,channel,distance)end packet.ttl=packet.ttl-1 return send(packet.destination,packet)end local requestId=tostring(packet.request_id or\"\")if requestId==\"\"then return rejectPacket(\"missing request ID\",packet,channel,distance)end if seenPackets[requestId]then return trace(\"routing\",\"destination_duplicate\",{from=from,type=packet.type})end seenPackets[requestId]=now()local remembered,rememberErr=rememberReverse(packet,from)if not remembered then return rejectPacket(rememberErr or\"could not record reverse route\",packet,channel,distance)end packet.authenticatedHop,packet.originVerified=from,false if M.handler then return M.handler(from,peer,packet)end end return M",
  ["ceetos/lib/network_ipc.lua"] = "local store=require(\"ceetos.lib.store\")local M={}local ROOT=\"/ceetos/data/network-ipc\"local COMMANDS=ROOT..\"/commands\"local RESULTS=ROOT..\"/results\"local function ensure(path)if not fs.exists(path)then fs.makeDir(path)end end local function safeId(value)return type(value)==\"string\"and value:match(\"^[%w_%-%.]+$\")and#value<=160 end local function path(directory,requestId)return fs.combine(directory,requestId..\".lua\")end function M.submit(request)if type(request)~=\"table\"or not safeId(request.id)then return false,\"invalid IPC request ID\"end ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)local target=path(COMMANDS,request.id)if fs.exists(target)then return false,\"IPC request already exists\"end return store.write(target,request)end function M.take()ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)local names=fs.list(COMMANDS)table.sort(names)for _,name in ipairs(names)do local requestId=name:match(\"^([%w_%-%.]+)%.lua$\")if requestId and safeId(requestId)then local target=fs.combine(COMMANDS,name)store.invalidate(target)local request=store.readFresh(target,nil)fs.delete(target)if type(request)==\"table\"and request.id==requestId then return request end end end end function M.reply(requestId,value)if not safeId(requestId)or type(value)~=\"table\"then return false,\"invalid IPC result\"end ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)return store.write(path(RESULTS,requestId),value)end function M.poll(requestId,consume)if not safeId(requestId)then return nil,\"invalid IPC request ID\"end local target=path(RESULTS,requestId)if not fs.exists(target)then return nil end local handle=fs.open(target,\"r\")if not handle then return nil end local raw=handle.readAll()handle.close()local ok,result=pcall(textutils.unserialise,raw)if not ok or type(result)~=\"table\"or result.id~=requestId then return nil,\"invalid IPC result\"end if consume then fs.delete(target)end return result end function M.prune(limit)ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)limit=math.max(1,math.floor(tonumber(limit)or 32))local names={}for _,name in ipairs(fs.list(RESULTS))do if name:match(\"^[%w_%-%.]+%.lua$\")then names[#names+1]=name end end table.sort(names)while#names>limit do fs.delete(fs.combine(RESULTS,table.remove(names,1)))end end function M.status()ensure(ROOT);ensure(COMMANDS);ensure(RESULTS)local function count(directory)local total=0 for _,name in ipairs(fs.list(directory))do if name:match(\"^[%w_%-%.]+%.lua$\")then total=total+1 end end return total end return{commands=count(COMMANDS),results=count(RESULTS)}end return M",
  ["ceetos/lib/auth_client.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local networkIpc=require(\"ceetos.lib.network_ipc\")local M={}local REPLIES=\"/ceetos/data/auth-replies.lua\"local sequence=0 local function now()return os.epoch(\"utc\")end local function authority()store.invalidate(\"/ceetos/data/auth-authority.lua\")local value=store.read(\"/ceetos/data/auth-authority.lua\",nil)return type(value)==\"table\"and value.active==true and value or nil end local function requestId(kind)sequence=sequence+1 return table.concat({\"auth\",kind,tostring(os.getComputerID()),tostring(now()),tostring(sequence)},\"-\")end local function take(id)store.invalidate(REPLIES)local replies=store.read(REPLIES,{})local row=replies[id]if row then replies[id]=nil;store.write(REPLIES,replies)end return row end function M.receive(body)if type(body)~=\"table\"or type(body.request_id)~=\"string\"or#body.request_id>160 then return false,\"invalid authority reply\"end local replies=store.read(REPLIES,{})replies[body.request_id]={ok=body.ok==true,result=body.result,error=body.error,at=now()}local rows={}for id,row in pairs(replies)do rows[#rows+1]={id=id,at=tonumber(row.at)or 0}end table.sort(rows,function(a,b)return a.at>b.at end)while#rows>32 do replies[table.remove(rows).id]=nil end return store.write(REPLIES,replies)end local function send(typeName,body,timeout)local server=authority()if not server then return nil,\"no Auth Server is reachable\"end local id=body.request_id or requestId(typeName)body.request_id=id local command={id=\"auth-\"..id,action=\"auth_send\",target=server.id,type=typeName,body=body}local ok,err=networkIpc.submit(command)if not ok then return nil,err or\"could not reach CeetOS network service\"end local deadline=now()+(timeout or 6000)while now()<deadline do local ack=networkIpc.poll(command.id,true)if ack and ack.ok~=true then return nil,ack.error or\"Auth Server request was not sent\"end local reply=take(id)if reply then return reply.ok and reply.result or nil,reply.error or\"Auth Server rejected request\"end sleep(0.05)end return nil,\"Auth Server did not respond\"end local function loginProof(verifier,server,request,challenge,expires)return password.hmacSha256(verifier,table.concat({\"ceetos/auth/login/v1\",tostring(server),tostring(os.getComputerID()),tostring(request),tostring(challenge),tostring(expires)},\"|\"))end function M.login(name,plainPassword)if type(name)~=\"string\"or type(plainPassword)~=\"string\"then return false,\"invalid credentials\"end local cloud=require(\"ceetos.lib.cloud_sync\")if cloud.authOnline()then return cloud.login(name,plainPassword)end local request=requestId(\"begin\")local begin,beginErr=send(\"auth_login_begin\",{request_id=request,username=name,node=tostring(os.getComputerID())})if not begin then return false,beginErr end local verifier,deriveErr=password.derive(plainPassword,begin.salt,begin.workFactor)if not verifier then return false,deriveErr end local proof=loginProof(verifier,begin.authority,request,begin.challenge,begin.expires)local result,proofErr=send(\"auth_login_proof\",{request_id=request,username=name,node=tostring(os.getComputerID()),challenge=begin.challenge,proof=proof})if not result then return false,proofErr end local auth=require((\"ceetos.lib.auth\"))local saved,saveErr=auth.saveCentralSession(result.session)if not saved then return false,saveErr end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end function M.mutate(action,fields)local auth=require((\"ceetos.lib.auth\"))local cloud=require(\"ceetos.lib.cloud_sync\")if cloud.authOnline()then return cloud.mutate(action,fields)end local current,server=auth.refreshSession(),authority()if not current or not current.central or not server then return false,\"an Auth Server login is required\"end local result,err=send(\"auth_mutate\",{action=action,fields=fields,session=current.nonce,node=tostring(os.getComputerID()),revision=current.accountRevision})if not result then return false,err end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end return M",
  ["ceetos/lib/jobs.lua"] = "local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local M={}local PATH,WORKERS_PATH=\"/ceetos/data/jobs.lua\",\"/ceetos/data/job-workers.lua\"local HISTORY_LIMIT,OUTPUT_LIMIT=48,4096 local HEARTBEAT_TIMEOUT,DEFAULT_CAPACITY=15000,1 local DEFAULT_TIMEOUT,DEFAULT_ATTEMPTS=60000,2 local context=nil local function now()if context and context.now then return context.now()end return os.epoch(\"utc\")end local function localId()if context and(context.id~=nil or context.nodeId~=nil)then return tostring(context.id or context.nodeId)end return tostring(os.getComputerID())end local function backend()return context and context.store or store end local function paths()return context and context.path or PATH,context and context.workersPath or WORKERS_PATH end local function log(action,detail)if not(context and context.noAudit~=false)then audit.log(\"system\",action,detail)end end local function copy(value,seen)if type(value)~=\"table\"then return value end seen=seen or{}if seen[value]then return seen[value]end local result={};seen[value]=result for key,item in pairs(value)do result[copy(key,seen)]=copy(item,seen)end return result end local function clampNumber(value,low,high,fallback)value=tonumber(value)if not value then return fallback end return math.max(low,math.min(high,math.floor(value)))end local function cleanOutput(value)value=tostring(value or\"\")if#value>OUTPUT_LIMIT then return value:sub(1,OUTPUT_LIMIT)..\"\\n[output truncated]\"end return value end local function defaultState()return{controller=(context and context.controllerId and tostring(context.controllerId))or localId(),capacity=DEFAULT_CAPACITY,workers={},templates={},queue={},running={},schedules={},history={},sequence=0,fair=0,}end local function normalise(data)data=type(data)==\"table\"and data or defaultState()local defaults=defaultState()for key,value in pairs(defaults)do if data[key]==nil then data[key]=value end end data.controller=tostring(data.controller or localId())data.capacity=clampNumber(data.capacity,1,32,DEFAULT_CAPACITY)data.workers,data.templates,data.queue=data.workers or{},data.templates or{},data.queue or{}data.running,data.schedules,data.history=data.running or{},data.schedules or{},data.history or{}data.sequence,data.fair=tonumber(data.sequence)or 0,tonumber(data.fair)or 0 return data end local function load()local mainPath,workersPath=paths()local disk=backend()if disk.invalidate then disk.invalidate(mainPath);disk.invalidate(workersPath)end local data=normalise(disk.read(mainPath,defaultState()))data.workers=disk.read(workersPath,data.workers or{})or{}return normalise(data)end local function save(data)local mainPath,workersPath=paths()local disk=backend()local workers=data.workers or{}local main=copy(data);main.workers=nil disk.write(mainPath,main)disk.write(workersPath,copy(workers))end local function nextId(data,prefix)data.sequence=data.sequence+1 return string.format(\"%s-%s-%d\",prefix,tostring(now()),data.sequence)end local function findQueue(data,jobId)for index,job in ipairs(data.queue)do if job.id==jobId then return index,job end end end local function finish(data,job,status,result)data.running[job.id]=nil local worker=job.worker and data.workers[tostring(job.worker)]if worker then worker.inFlight=math.max(0,(tonumber(worker.inFlight)or 0)-1)end job.status,job.finished,job.result=status,now(),result or{}job.result.output=cleanOutput(job.result.output or job.result.stdout or\"\")data.history[#data.history+1]=job local limit=(context and tonumber(context.historyLimit))or HISTORY_LIMIT while#data.history>limit do table.remove(data.history,1)end end local function addJob(data,templateName,scheduleId)local template=data.templates[templateName]assert(template and template.enabled~=false,\"template unavailable\")local job={id=nextId(data,\"job\"),template=templateName,revision=template.revision,command=template.command,scheduleId=scheduleId,created=now(),status=\"queued\",attempts=0,retrySafe=template.retrySafe==true,maxAttempts=template.maxAttempts,}data.queue[#data.queue+1]=job return job end function M.state()return copy(load())end function M.setController(value)assert(value~=nil and tostring(value)~=\"\",\"controller id required\")local data=load();data.controller=tostring(value);save(data)log(\"jobs_controller\",data.controller)return data.controller end function M.controller()return load().controller end function M.isController()return M.controller()==localId()end local function requireController()assert(M.isController(),\"controller required\")end function M.setCapacity(value)local data=load();data.capacity=clampNumber(value,1,32,DEFAULT_CAPACITY);save(data)return data.capacity end function M.heartbeat(peer,status)assert(peer~=nil and tostring(peer)~=\"\",\"worker id required\")status=type(status)==\"table\"and status or{}local data,id=load(),tostring(peer)local old=data.workers[id]or{}data.workers[id]={id=id,label=status.label or old.label or id,capacity=clampNumber(status.capacity,1,32,old.capacity or DEFAULT_CAPACITY),inFlight=clampNumber(status.inFlight,0,32,old.inFlight or 0),queueDepth=clampNumber(status.queueDepth,0,1024,0),route=status.route or old.route,hops=clampNumber(status.hops or status.routeHops,0,32,old.hops or 99),available=status.available~=false,lastSeen=now(),lastError=status.lastError,}save(data)return copy(data.workers[id])end M.updateWorker=M.heartbeat function M.workers()local data,at,result=load(),now(),{}for id,worker in pairs(data.workers)do local row=copy(worker)row.healthy=row.available~=false and at-(row.lastSeen or 0)<=HEARTBEAT_TIMEOUT row.slots=math.max(0,(row.capacity or DEFAULT_CAPACITY)-(row.inFlight or 0))result[id]=row end return result end function M.addTemplate(name,command,options)requireController()if type(name)==\"table\"then options,command,name=name,name.command,name.id or name.name end assert(type(name)==\"string\"and name:match(\"^[%w_%-]+$\"),\"invalid template name\")assert(type(command)==\"string\"and#command>0 and#command<=512,\"invalid fixed command\")options=type(options)==\"table\"and options or{}local data=load()assert(not data.templates[name],\"template already exists\")data.templates[name]={name=name,command=command,enabled=options.enabled~=false,timeout=clampNumber(options.timeout,1000,600000,DEFAULT_TIMEOUT),retrySafe=options.retrySafe==true,maxAttempts=clampNumber(options.maxAttempts,1,5,DEFAULT_ATTEMPTS),revision=nextId(data,\"template\"),created=now(),}save(data);log(\"jobs_template_added\",name)return copy(data.templates[name])end function M.listTemplates()return copy(load().templates)end function M.setTemplateRetrySafe(name,enabled)requireController()local data=load();assert(data.templates[name],\"unknown template\")data.templates[name].retrySafe=enabled==true;save(data)return copy(data.templates[name])end function M.setTemplateEnabled(name,enabled)requireController()local data=load();assert(data.templates[name],\"unknown template\")data.templates[name].enabled=enabled~=false;save(data)return copy(data.templates[name])end function M.removeTemplate(name)requireController()local data=load();assert(data.templates[name],\"unknown template\")for _,job in ipairs(data.queue)do assert(job.template~=name,\"template has queued jobs\")end for _,job in pairs(data.running)do assert(job.template~=name,\"template has running jobs\")end for _,schedule in pairs(data.schedules)do assert(schedule.template~=name or not schedule.enabled,\"template has active schedule\")end data.templates[name]=nil;save(data);log(\"jobs_template_removed\",name)return true end function M.enqueue(templateName,scheduleId)requireController()local data,job=load(),nil job=addJob(data,templateName,scheduleId)save(data)return copy(job)end function M.selectWorker()local data,at,candidates=load(),now(),{}for id,worker in pairs(data.workers)do local healthy=worker.available~=false and at-(worker.lastSeen or 0)<=HEARTBEAT_TIMEOUT local capacity,inFlight=worker.capacity or DEFAULT_CAPACITY,worker.inFlight or 0 if healthy and inFlight<capacity then candidates[#candidates+1]={id=id,worker=worker,load=inFlight/capacity,hops=tonumber(worker.hops)or tonumber(worker.routeHops)or 99}end end table.sort(candidates,function(a,b)if a.load~=b.load then return a.load<b.load end if a.hops~=b.hops then return a.hops<b.hops end return a.id<b.id end)if#candidates==0 then return nil end local best,count=candidates[1],1 while candidates[count+1]and candidates[count+1].load==best.load and candidates[count+1].hops==best.hops do count=count+1 end local chosen=candidates[(data.fair%count)+1]return copy(chosen.worker)end function M.dispatchNext()local job,worker=M.nextDispatch(),M.selectWorker()if not job or not worker then return nil,job and\"no healthy worker\"or\"no queued job\"end local assigned=M.assign(job,worker.id)if context and type(context.execute)==\"function\"then local template=M.listTemplates()[assigned.template]local ok,first,second=pcall(context.execute,copy(worker),copy(template),copy(assigned))if not ok then return M.fail(assigned.id,first)end if first==false then return M.fail(assigned.id,second or\"worker rejected job\")end if type(first)==\"table\"then return M.complete(assigned.id,first)end end return assigned end function M.run(templateName,scheduleId)assert(scheduleId==nil or type(scheduleId)==\"string\",\"runtime job arguments are not allowed\")local job=M.enqueue(templateName,scheduleId)local dispatched,reason=M.dispatchNext()return dispatched or job,reason end function M.nextDispatch()local data=load()for _,job in ipairs(data.queue)do if job.status==\"queued\"then return copy(job)end end return nil end function M.assign(jobValue,workerValue)local data,jobId,workerId=load(),type(jobValue)==\"table\"and jobValue.id or jobValue,tostring(workerValue)local index,job=findQueue(data,jobId)assert(job and job.status==\"queued\",\"job is not queued\")local worker=data.workers[workerId]assert(worker,\"unknown worker\")assert(worker.available~=false and now()-(worker.lastSeen or 0)<=HEARTBEAT_TIMEOUT,\"worker unavailable\")assert((worker.inFlight or 0)<(worker.capacity or DEFAULT_CAPACITY),\"worker saturated\")table.remove(data.queue,index)job.status,job.worker,job.started=\"running\",workerId,now()job.attempts=(job.attempts or 0)+1 job.deadline=job.started+(data.templates[job.template].timeout or DEFAULT_TIMEOUT)data.running[job.id]=job;worker.inFlight=(worker.inFlight or 0)+1 data.fair=data.fair+1 save(data)return copy(job)end function M.complete(jobId,result,stdout,stderr)local data,job=load(),nil job=data.running[jobId];assert(job,\"unknown running job\")if result==false then return M.fail(jobId,stderr or stdout or\"worker failed\")end local payload if type(result)==\"table\"then payload=copy(result)elseif stdout~=nil or stderr~=nil then payload={ok=result~=false,stdout=tostring(stdout or\"\"),stderr=tostring(stderr or\"\"),output=tostring(stdout or\"\")}else payload={output=tostring(result or\"\")}end finish(data,job,\"complete\",payload)save(data)return copy(job)end function M.fail(jobId,reason)local data,job=load(),nil job=data.running[jobId];assert(job,\"unknown running job\")data.running[job.id]=nil local worker=job.worker and data.workers[tostring(job.worker)]if worker then worker.inFlight=math.max(0,(worker.inFlight or 0)-1)end if job.retrySafe and(job.attempts or 0)<(job.maxAttempts or DEFAULT_ATTEMPTS)then job.status,job.worker,job.deadline=\"queued\",nil,nil job.lastError,job.updated=tostring(reason or\"failed\"),now()data.queue[#data.queue+1]=job save(data)return copy(job),true end finish(data,job,\"failed\",{error=tostring(reason or\"failed\")})save(data)return copy(job),false end function M.schedule(templateName,interval)requireController()interval=tonumber(interval)assert(interval and interval>=1 and interval<=86400,\"interval must be 1..86400 seconds\")local data=load()assert(data.templates[templateName],\"unknown template\")local id=nextId(data,\"schedule\")data.schedules[id]={id=id,template=templateName,interval=interval*1000,enabled=true,nextRun=now()+interval*1000,created=now()}save(data);log(\"jobs_schedule_added\",id)return copy(data.schedules[id])end function M.cancel(scheduleId)requireController()local data=load();assert(data.schedules[scheduleId],\"unknown schedule\")data.schedules[scheduleId].enabled=false;data.schedules[scheduleId].cancelled=now();save(data)return true end function M.history()return copy(load().history)end function M.queue()return copy(load().queue)end function M.running()return copy(load().running)end function M.localStatus()local data=load()return{id=localId(),controller=data.controller,capacity=data.capacity,inFlight=(function()local total=0;for _ in pairs(data.running)do total=total+1 end;return total end)(),queueDepth=#data.queue}end function M.syncTemplates(controllerId,templates)assert(controllerId~=nil and tostring(controllerId)~=\"\",\"controller id required\")assert(type(templates)==\"table\",\"template snapshot required\")local data=load();data.controller,data.templates=tostring(controllerId),{}for name,template in pairs(templates)do assert(type(name)==\"string\"and type(template)==\"table\"and type(template.command)==\"string\",\"invalid template snapshot\")data.templates[name]={name=name,command=template.command,enabled=template.enabled~=false,timeout=clampNumber(template.timeout,1000,600000,DEFAULT_TIMEOUT),retrySafe=template.retrySafe==true,maxAttempts=clampNumber(template.maxAttempts,1,5,DEFAULT_ATTEMPTS),revision=template.revision or\"synced\",created=template.created or now(),}end save(data)return copy(data.templates)end M.scheduleInterval=M.schedule function M.tick()local data,at,added,timedOut,stale=load(),now(),0,0,0 for _,schedule in pairs(data.schedules)do if M.isController()and schedule.enabled and at>=(schedule.nextRun or at)then addJob(data,schedule.template,schedule.id);added=added+1 repeat schedule.nextRun=(schedule.nextRun or at)+schedule.interval until schedule.nextRun>at end end for _,worker in pairs(data.workers)do if worker.available~=false and at-(worker.lastSeen or 0)>HEARTBEAT_TIMEOUT then worker.stale=true;stale=stale+1 end end local expired={}for id,job in pairs(data.running)do if at>=(job.deadline or at)then expired[#expired+1]=id end end for _,id in ipairs(expired)do local job=data.running[id]if job then timedOut=timedOut+1;data.running[id]=nil local worker=job.worker and data.workers[tostring(job.worker)]if worker then worker.inFlight=math.max(0,(worker.inFlight or 0)-1)end if job.retrySafe and(job.attempts or 0)<(job.maxAttempts or DEFAULT_ATTEMPTS)then job.status,job.worker,job.deadline,job.lastError=\"queued\",nil,nil,\"timeout\";data.queue[#data.queue+1]=job else finish(data,job,\"failed\",{error=\"timeout\"})end end end if added>0 or timedOut>0 or stale>0 then save(data)end if context and type(context.execute)==\"function\"then M.dispatchNext()end return{enqueued=added,timedOut=timedOut,staleWorkers=stale}end function M.new(options)options=options or{}local service={}local names={\"state\",\"setController\",\"controller\",\"isController\",\"setCapacity\",\"heartbeat\",\"updateWorker\",\"workers\",\"addTemplate\",\"listTemplates\",\"setTemplateRetrySafe\",\"setTemplateEnabled\",\"removeTemplate\",\"syncTemplates\",\"enqueue\",\"run\",\"nextDispatch\",\"selectWorker\",\"dispatchNext\",\"assign\",\"complete\",\"fail\",\"tick\",\"schedule\",\"scheduleInterval\",\"cancel\",\"history\",\"queue\",\"running\",\"localStatus\",}local function invoke(fn,...)local prior=context;context=options local result={pcall(fn,...)}context=prior if not result[1]then error(result[2],0)end return table.unpack(result,2)end for _,name in ipairs(names)do service[name]=function(...)local args={...}if args[1]==service then table.remove(args,1)end return invoke(M[name],table.unpack(args))end end return service end return M",
  ["ceetos/lib/peripherals.lua"] = "local store=require(\"ceetos.lib.store\")local audit=require(\"ceetos.lib.audit\")local M={}local PATH=\"/ceetos/data/shares.lua\"local SAFE={getItemDetail=true,list=true,size=true,getMetadata=true,getType=true,getMethods=true,getInput=true,getOutput=true,getAngles=true,getVelocity=true,getHeight=true,getAirPressure=true,getSpeed=true,getStress=true,getStressCapacity=true,stock=true,getStockItemDetail=true,getConfiguration=true,getAddress=true,}local function requestMatchesGrid(request,slots)if type(request)~=\"table\"then return false,\"redstone requester did not return its encoded request\"end local exact=true for slot=1,9 do local expected=slots[slot]if expected and expected~=\"minecraft:air\"then local actual=request[slot]or request[tostring(slot)]if type(actual)~=\"table\"or actual.name~=expected then exact=false;break end end end if exact then return true end local expected,actual={},{}for slot=1,9 do if slots[slot]and slots[slot]~=\"minecraft:air\"then expected[#expected+1]=slots[slot]end end for key,value in pairs(request)do local index=tonumber(key)if index and type(value)==\"table\"and type(value.name)==\"string\"and value.name~=\"minecraft:air\"then actual[#actual+1]={index=index,name=value.name}end end table.sort(actual,function(a,b)return a.index<b.index end)if#actual~=#expected then return false,\"redstone requester retained an incomplete crafting request\"end for index,item in ipairs(actual)do if item.name~=expected[index]then return false,\"redstone requester retained different crafting ingredients\"end end return true end local function shares()return store.read(PATH,{})end local function save(s)store.write(PATH,s)end local function safeMethods(name)local out={}local available=peripheral.getMethods and peripheral.getMethods(name)or nil if available then for _,method in ipairs(available)do if SAFE[method]then out[#out+1]=method end end else for method in pairs(SAFE)do out[#out+1]=method end end table.sort(out)return out end function M.listLocal()local result={}for _,name in ipairs(peripheral.getNames())do result[#result+1]={name=name,type=peripheral.getType(name)}end return result end function M.share(name,mode)assert(peripheral.isPresent(name),\"peripheral is not present\")assert(mode==\"peer\"or mode==\"master\",\"mode must be peer or master\")local s=shares()s[name]={mode=mode,methods=SAFE}save(s)audit.log(\"local\",\"peripheral.share\",{name=name,mode=mode})end function M.unshare(name)local s=shares();s[name]=nil;save(s)audit.log(\"local\",\"peripheral.unshare\",{name=name})end function M.shareAll(mode)assert(mode==\"peer\"or mode==\"master\",\"mode must be peer or master\")local count=0 for _,item in ipairs(M.listLocal())do M.share(item.name,mode);count=count+1 end audit.log(\"local\",\"peripheral.share_all\",{mode=mode,count=count})return count end function M.unshareAll()local s,count=shares(),0 for name in pairs(s)do s[name],count=nil,count+1 end save(s)audit.log(\"local\",\"peripheral.unshare_all\",{count=count})return count end function M.describe()local s,result=shares(),{}for name,spec in pairs(s)do if peripheral.isPresent(name)then result[#result+1]={name=name,type=peripheral.getType(name),mode=spec.mode,methods=safeMethods(name)}end end return result end function M.call(peerIsMaster,name,method,args)local spec=shares()[name]if not spec or not peripheral.isPresent(name)then return false,\"not shared\"end if spec.mode==\"master\"and not peerIsMaster then return false,\"master-only peripheral\"end if not spec.methods[method]then return false,\"method not allowed\"end local api=peripheral.wrap(name)if type(api[method])~=\"function\"then return false,\"method unavailable\"end local ok,result=pcall(api[method],table.unpack(args or{}))return ok,result end function M.craftRequest(peerIsMaster,name,address,filters)local spec=shares()[name]local localAccess=peerIsMaster==\"local\"if not peripheral.isPresent(name)then return false,\"stock ticker is unavailable\"end if not localAccess and not spec then return false,\"stock ticker is not shared\"end if not localAccess and spec.mode==\"master\"and not peerIsMaster then return false,\"master-only peripheral\"end if type(address)~=\"string\"or#address<1 or#address>64 or address:find(\"[%z\\1-\\31\\127]\")then return false,\"invalid destination address\"end if type(filters)~=\"table\"or#filters<1 or#filters>32 then return false,\"invalid craft filters\"end local clean={}for index,filter in ipairs(filters)do if type(filter)~=\"table\"or type(filter.name)~=\"string\"or#filter.name>128 then return false,\"invalid item filter \"..tostring(index)end local count=tonumber(filter._requestCount or filter.count)if not count or count<1 or count>256 or count~=math.floor(count)then return false,\"invalid request count\"end clean[index]={name=filter.name,_requestCount=count}end local api=peripheral.wrap(name)if not api or type(api.requestFiltered)~=\"function\"then return false,\"stock ticker requestFiltered is unavailable\"end local ok,result=pcall(api.requestFiltered,address,table.unpack(clean))if ok then audit.log(\"network\",\"peripheral.craft_request\",{name=name,address=address,filters=#clean})end return ok,result end function M.craftingRecipeRequest(peerIsMaster,name,address,batches,grid)local spec=shares()[name]local localAccess=peerIsMaster==\"local\"if not peripheral.isPresent(name)then return false,\"redstone requester is unavailable\"end if not localAccess and not spec then return false,\"redstone requester is not shared\"end if not localAccess and spec.mode==\"master\"and not peerIsMaster then return false,\"master-only peripheral\"end if type(address)~=\"string\"or#address<1 or#address>64 or address:find(\"[%z\\1-\\31\\127]\")then return false,\"invalid craft address\"end batches=tonumber(batches)if not batches or batches<1 or batches>256 or batches~=math.floor(batches)then return false,\"invalid craft batches\"end if type(grid)~=\"table\"then return false,\"invalid crafting grid\"end local slots={}for slot=1,9 do local value=grid[slot]if value~=nil and value~=false and(type(value)~=\"string\"or#value>128)then return false,\"invalid craft grid slot\"end if type(value)==\"string\"and value:sub(1,1)==\"#\"then return false,\"Create Redstone Requester requires concrete item IDs; resolve recipe tags first\"end slots[slot]=(value==nil or value==false)and\"minecraft:air\"or value end local api=peripheral.wrap(name)if not api or type(api.setCraftingRequest)~=\"function\"or type(api.setAddress)~=\"function\"or type(api.request)~=\"function\"then return false,\"redstone requester crafting API is unavailable\"end local ok,result=pcall(function()if type(api.setConfiguration)==\"function\"then api.setConfiguration(\"strict\")end api.setCraftingRequest(batches,slots[1],slots[2],slots[3],slots[4],slots[5],slots[6],slots[7],slots[8],slots[9])api.setAddress(address)local configured=nil if type(api.getRequest)==\"function\"then configured=api.getRequest()local retained,retainError=requestMatchesGrid(configured,slots)if not retained then error(retainError)end end if type(api.getAddress)==\"function\"and api.getAddress()~=address then error(\"redstone requester did not retain the craft address\")end local submitted=api.request()if submitted==false then error(\"redstone requester rejected the crafting request\")end return{submitted=true,strict=type(api.setConfiguration)==\"function\",configured=configured~=nil,address=address}end)if ok then audit.log(\"network\",\"peripheral.crafting_recipe_request\",{name=name,address=address,batches=batches})end return ok,result end return M",
  ["ceetos/lib/telemetry.lua"] = "local store=require(\"ceetos.lib.store\")local M={}local PATH=\"/ceetos/data/config.lua\"local activity=\"desktop\"local function text(value,limit)if type(value)~=\"string\"then return nil end value=value:gsub(\"[%z\\1-\\31\\127]\",\" \")if value==\"\"then return nil end return value:sub(1,limit)end local function config()local value=store.read(PATH,{})if type(value)~=\"table\"then value={}end if value.telemetry==nil then value.telemetry=true store.write(PATH,value)end return value end function M.setEnabled(value)assert(type(value)==\"boolean\",\"telemetry state must be boolean\")require(\"ceetos.lib.auth\").require(\"admin\")local valueForSave=config()valueForSave.telemetry=value return store.write(PATH,valueForSave)end function M.status()return config().telemetry==true end function M.configuration()return{enabled=M.status()}end function M.markActivity(value)activity=text(value,48)or activity return activity end function M.activity()return activity end function M.snapshot(currentActivity)if currentActivity then M.markActivity(currentActivity)end local data={ts=os.epoch(\"utc\"),id=os.getComputerID(),label=text(os.getComputerLabel(),96),activity=activity,}if turtle and type(turtle.getFuelLevel)==\"function\"then local ok,fuel=pcall(turtle.getFuelLevel)if ok and type(fuel)==\"number\"then data.fuel=fuel end end if gps and type(gps.locate)==\"function\"then local ok,x,y,z=pcall(gps.locate,0.2)if ok and type(x)==\"number\"and type(y)==\"number\"and type(z)==\"number\"then data.gps={x=x,y=y,z=z}end end return data end return M",
  ["ceetos/lib/cloud.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local profile=require(\"ceetos.lib.profile\")local M={}M.PATH=\"/ceetos/data/cloud.lua\"M.MAX_BODY=48*1024 M.MAX_RESPONSE=64*1024 M.DEFAULTS={auth=\"https://auth.ceet.uk\",recipe=\"https://recipe.ceet.uk\",dashboard=\"https://dash.ceet.uk\",}local function now()return os.epoch(\"utc\")end local function validUrl(value)if type(value)~=\"string\"or#value>160 then return false end return value:match(\"^https://[%w%-%.]+%.ceet%.uk$\")~=nil end local function validId(value)return type(value)==\"string\"and value:match(\"^[%w_.%-]+$\")~=nil and#value<=96 end local function copy(value)local out={}for key,item in pairs(value or{})do out[key]=item end return out end local function normalise(value)value=type(value)==\"table\"and value or{}local urls=type(value.urls)==\"table\"and value.urls or{}local result={schema=1,enabled=value.enabled==true,urls={auth=validUrl(urls.auth)and urls.auth or M.DEFAULTS.auth,recipe=validUrl(urls.recipe)and urls.recipe or M.DEFAULTS.recipe,dashboard=validUrl(urls.dashboard)and urls.dashboard or M.DEFAULTS.dashboard,},node=type(value.node)==\"table\"and copy(value.node)or nil,}if result.node and(not validId(result.node.id)or type(result.node.secret)~=\"string\"or#result.node.secret<32 or#result.node.secret>192)then result.node=nil end return result end function M.load()store.invalidate(M.PATH)return normalise(store.read(M.PATH,{}))end function M.save(value)local clean=normalise(value)return store.write(M.PATH,clean)end function M.configure(urls)local value=M.load()urls=type(urls)==\"table\"and urls or{}for key in pairs(M.DEFAULTS)do if urls[key]~=nil then if not validUrl(urls[key])then return false,\"invalid \"..key..\" cloud URL\"end value.urls[key]=urls[key]end end return M.save(value)end function M.clear()local value=M.load();value.enabled,value.node=false,nil return M.save(value)end function M.publicStatus()local value=M.load()return{enabled=value.enabled,enrolled=value.node~=nil,node=value.node and value.node.id or nil,urls=copy(value.urls),profile=profile.id()}end local function readBounded(handle,limit)local chunks,total={},0 while true do local part=handle.read(math.min(4096,limit-total+1))if not part or part==\"\"then break end total=total+#part if total>limit then return nil,\"cloud response is too large\"end chunks[#chunks+1]=part end return table.concat(chunks)end local function json(value)local ok,result=pcall(textutils.unserialiseJSON,value)return ok and type(result)==\"table\"and result or nil end local function canonical(node,timestamp,nonce,method,path,body)local digest=assert(password.sha256(body))return table.concat({\"ceetos-cloud-node-v1\",node,tostring(timestamp),nonce,method,path,digest},\"\\n\")end local nonceCounter=0 local function nonce()nonceCounter=nonceCounter+1 return password.newSalt(\"cloud:\"..tostring(nonceCounter))end local function perform(url,method,path,body,headers)if not http or type(http.post)~=\"function\"then return nil,\"HTTP is unavailable\"end local response local ok,err=pcall(function()response=http.post(url..path,body,headers)end)if not ok or not response then return nil,tostring(err or\"cloud request failed\")end local raw,readErr=readBounded(response,M.MAX_RESPONSE)pcall(response.close)if not raw then return nil,readErr end local decoded=json(raw)if not decoded then return nil,\"cloud returned invalid JSON\"end if decoded.ok==false then return nil,tostring(decoded.error or\"cloud rejected request\"):sub(1,180)end return decoded end function M.enroll(code)if type(code)~=\"string\"or#code<12 or#code>128 or code:find(\"[%z\\1-\\31\\127]\")then return nil,\"invalid enrollment code\"end local value=M.load()local payload=textutils.serialiseJSON({code=code,profile=profile.id(),label=os.getComputerLabel()or(\"Computer \"..tostring(os.getComputerID())),computerId=tostring(os.getComputerID())})if#payload>M.MAX_BODY then return nil,\"enrollment request is too large\"end local result,err=perform(value.urls.auth,\"POST\",\"/v1/nodes/enroll\",payload,{[\"Content-Type\"]=\"application/json\"})if not result then return nil,err end if type(result.node)~=\"table\"or not validId(result.node.id)or type(result.node.secret)~=\"string\"or#result.node.secret<32 then return nil,\"cloud returned invalid enrollment\"end value.enabled,value.node=true,{id=result.node.id,secret=result.node.secret,enrolledAt=now()}local saved,saveErr=M.save(value)if not saved then return nil,saveErr or\"could not save cloud enrollment\"end return M.publicStatus()end function M.call(service,path,payload)local value=M.load()if not value.enabled or not value.node then return nil,\"cloud node is not enrolled\"end if not M.DEFAULTS[service]or type(path)~=\"string\"or not path:match(\"^/v1/[%w%-%._/]+$\")or#path>128 then return nil,\"invalid cloud endpoint\"end local body=textutils.serialiseJSON(type(payload)==\"table\"and payload or{})if#body>M.MAX_BODY then return nil,\"cloud request is too large\"end local timestamp,requestNonce=now(),nonce()local signature=password.hmacSha256(value.node.secret,canonical(value.node.id,timestamp,requestNonce,\"POST\",path,body))if not signature then return nil,\"could not sign cloud request\"end return perform(value.urls[service],\"POST\",path,body,{[\"Content-Type\"]=\"application/json\",[\"X-CeetOS-Node\"]=value.node.id,[\"X-CeetOS-Time\"]=tostring(timestamp),[\"X-CeetOS-Nonce\"]=requestNonce,[\"X-CeetOS-Signature\"]=signature,})end return M",
  ["ceetos/lib/cloud_sync.lua"] = "local cloud=require(\"ceetos.lib.cloud\")local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local profile=require(\"ceetos.lib.profile\")local telemetryService=require(\"ceetos.lib.telemetry\")local RECIPE_SERVICE_MODULE=\"ceetos.lib.\"..\"recipe_service\"local M={}local STATE=\"/ceetos/data/cloud-state.lua\"local INTERVALS={telemetry=24*60*60*1000,authority=30000,recipes=30000}local TELEMETRY_RETRIES={15*60*1000,60*60*1000,4*60*60*1000}local function now()return os.epoch(\"utc\")end local function defaults()return{schema=2,revision=0,auth={online=false,next=0},recipe={online=false,next=0,revision=0},telemetry={enabled=nil,next=0,lastSuccess=nil,failures=0,lastError=nil},lastError=nil}end local function state()store.invalidate(STATE)local value=store.read(STATE,defaults())if type(value)~=\"table\"then value=defaults()end if type(value.auth)~=\"table\"then value.auth={}end if type(value.recipe)~=\"table\"then value.recipe={}end if type(value.telemetry)~=\"table\"then value.telemetry={}end for key,fallback in pairs(defaults())do if value[key]==nil then value[key]=fallback end end for key,fallback in pairs(defaults().recipe)do if value.recipe[key]==nil then value.recipe[key]=fallback end end for key,fallback in pairs(defaults().telemetry)do if value.telemetry[key]==nil then value.telemetry[key]=fallback end end return value end local function save(value)value.revision=(tonumber(value.revision)or 0)+1 return store.write(STATE,value)end local function errorState(value,message)value.lastError=tostring(message or\"cloud request failed\"):sub(1,180)end function M.status()local value,cfg=state(),cloud.publicStatus()return{enabled=cfg.enabled,enrolled=cfg.enrolled,node=cfg.node,urls=cfg.urls,authOnline=value.auth.online==true,recipeOnline=value.recipe.online==true,telemetryNext=tonumber(value.telemetry and value.telemetry.next)or 0,telemetryInterval=INTERVALS.telemetry,telemetryEnabled=telemetryService.status(),telemetryLastSuccess=value.telemetry and value.telemetry.lastSuccess or nil,telemetryLastError=value.telemetry and value.telemetry.lastError or nil,telemetryFailures=math.max(0,math.floor(tonumber(value.telemetry and value.telemetry.failures)or 0)),lastSync=value.lastSync,lastError=value.lastError,}end function M.configure(urls)return cloud.configure(urls)end function M.enroll(code)local enrolled,err=cloud.enroll(code)if not enrolled then return nil,err end local value=state()value.telemetry.next,value.telemetry.failures,value.telemetry.lastError=0,0,nil save(value)return enrolled end function M.clear()local ok,err=cloud.clear();if ok then store.write(STATE,defaults())end return ok,err end function M.authOnline()return M.status().authOnline==true end function M.recipeOnline()return M.status().recipeOnline==true end local function cloudAuthority(result)local auth=require(\"ceetos.lib.auth\")if type(result)~=\"table\"or type(result.directory)~=\"table\"then return false,\"invalid cloud authority response\"end local cfg=cloud.publicStatus()local record={id=\"cloud:\"..tostring(cfg.urls.auth),term=tonumber(result.term)or 0,revision=tonumber(result.revision)or 0,directory=result.directory}return pcall(auth.acceptAuthority,record)end function M.login(name,plainPassword)if type(name)~=\"string\"or type(plainPassword)~=\"string\"then return false,\"invalid credentials\"end local begin,beginErr=cloud.call(\"auth\",\"/v1/auth/login/begin\",{username=name,node=tostring(os.getComputerID())})if not begin then return false,beginErr end if type(begin.salt)~=\"string\"or type(begin.workFactor)~=\"number\"or type(begin.challenge)~=\"string\"or type(begin.expires)~=\"number\"then return false,\"invalid cloud login challenge\"end local verifier,deriveErr=password.derive(plainPassword,begin.salt,begin.workFactor)if not verifier then return false,deriveErr end local proof=password.hmacSha256(verifier,table.concat({\"ceetos/auth/login/v1\",tostring(begin.authority),tostring(os.getComputerID()),tostring(begin.requestId),tostring(begin.challenge),tostring(begin.expires)},\"|\"))local result,resultErr=cloud.call(\"auth\",\"/v1/auth/login/proof\",{username=name,node=tostring(os.getComputerID()),requestId=begin.requestId,challenge=begin.challenge,proof=proof})if not result then return false,resultErr end local auth=require(\"ceetos.lib.auth\")local saved,saveErr=auth.saveCentralSession(result.session)if not saved then return false,saveErr end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end function M.mutate(action,fields)local auth=require(\"ceetos.lib.auth\")local current=auth.refreshSession()if not current or not current.central then return false,\"cloud login is required\"end local result,err=cloud.call(\"auth\",\"/v1/auth/mutate\",{action=action,fields=fields,session=current.nonce,node=tostring(os.getComputerID()),revision=current.accountRevision})if not result then return false,err end if type(result.directory)==\"table\"then auth.updateDirectory(result.directory,result.revision)end return true end function M.recipePlan(item,quantity,stock)if not M.recipeOnline()then return nil,\"cloud Recipe Server is unavailable\"end local result,err=cloud.call(\"recipe\",\"/v1/recipe/plan\",{item=item,quantity=quantity,stock=stock})if not result then return nil,err end return result.plan,result.error end local function telemetry()local snapshot=telemetryService.snapshot()local net=require(\"ceetos.lib.net\")local transport=net.statusSnapshot and net.statusSnapshot().transport or{}snapshot.health={profile=profile.id(),version=require(\"ceetos.lib.version\").string,uptime=os.clock(),freeSpace=fs.getFreeSpace(\"/\"),peers=#(net.peers and net.peers()or{}),healthyLinks=transport and transport.healthyLinks or 0,lastError=M.status().lastError,}local result,err=cloud.call(\"dashboard\",\"/v1/telemetry/ingest\",snapshot)return result~=nil,err end local function syncAuth()if profile.is(\"auth-server\")then local auth=require(\"ceetos.lib.auth\")local snapshot=auth.authoritySnapshot()local pushed,pushErr=cloud.call(\"auth\",\"/v1/auth/replica/merge\",{snapshot=snapshot,source=\"mesh\"})if not pushed then return false,pushErr end if type(pushed.snapshot)==\"table\"then auth.merge(pushed.snapshot,true)end local ok,authErr=cloudAuthority(pushed)if not ok then return false,authErr end return true end local result,err=cloud.call(\"auth\",\"/v1/auth/directory\",{})if not result then return false,err end local ok,authErr=cloudAuthority(result)if not ok then return false,authErr end return true end local function syncRecipes()if not profile.is(\"recipe-server\")then local result,err=cloud.call(\"recipe\",\"/v1/recipe/status\",{})return result~=nil,err end local service=require(RECIPE_SERVICE_MODULE)if type(service.exportOverlay)~=\"function\"then return false,\"recipe export unavailable\"end local payload,exportErr=service.exportOverlay()if not payload then return false,exportErr end local value=state()value.recipe=value.recipe or{revision=0}local result,err=cloud.call(\"recipe\",\"/v1/recipe/replica/merge\",{overlay=payload,baseRevision=math.max(0,math.floor(tonumber(value.recipe.revision)or 0)),})if not result then return false,err end if type(result.overlay)==\"table\"and type(service.replaceOverlay)==\"function\"then local applied,applyErr=service.replaceOverlay(result.overlay)if not applied then return false,applyErr end end return true,nil,math.max(0,math.floor(tonumber(result.revision)or 0))end function M.tick(activity,timestampOverride)local cfg=cloud.publicStatus();if not cfg.enabled or not cfg.enrolled then return false,\"cloud node is not enrolled\"end local value,timestamp=state(),tonumber(timestampOverride)or now()local changed=false if timestamp>=(tonumber(value.auth.next)or 0)then local ok,err=syncAuth();value.auth.online,value.auth.next=ok==true,timestamp+INTERVALS.authority if not ok then errorState(value,err)else value.lastError=nil end changed=true end if timestamp>=(tonumber(value.recipe.next)or 0)then local ok,err,recipeRevision=syncRecipes();value.recipe.online,value.recipe.next=ok==true,timestamp+INTERVALS.recipes if recipeRevision~=nil then value.recipe.revision=recipeRevision end if not ok then errorState(value,err)end changed=true end local telemetryEnabled=telemetryService.status()if not telemetryEnabled then if value.telemetry.enabled~=false or value.telemetry.next~=0 then value.telemetry.enabled,value.telemetry.next,value.telemetry.failures,value.telemetry.lastError=false,0,0,nil changed=true end elseif value.telemetry.enabled~=true then value.telemetry.enabled,value.telemetry.next,value.telemetry.failures,value.telemetry.lastError=true,0,0,nil changed=true elseif timestamp>=(tonumber(value.telemetry.next)or 0)then local ok,err=telemetry()if ok then value.telemetry.next,value.telemetry.lastSuccess,value.telemetry.failures,value.telemetry.lastError=timestamp+INTERVALS.telemetry,timestamp,0,nil else local failures=math.max(0,math.floor(tonumber(value.telemetry.failures)or 0))+1 value.telemetry.failures,value.telemetry.lastError=failures,tostring(err or\"telemetry upload failed\"):sub(1,180)value.telemetry.next=timestamp+(TELEMETRY_RETRIES[failures]or INTERVALS.telemetry)errorState(value,value.telemetry.lastError)end changed=true end if changed then value.lastSync=timestamp;save(value)end return true end return M",
  ["ceetos/lib/owner_service.lua"] = "local store=require(\"ceetos.lib.store\")local password=require(\"ceetos.lib.password\")local telemetry=require(\"ceetos.lib.telemetry\")local M={}local PATH=\"/ceetos/data/owner-service.lua\"M.VERSION=1 M.MAX_AGE_MS=60*1000 M.MAX_USED_NONCES=64 local actions={snapshot=true,status=true}local function now()return os.epoch(\"utc\")end local function state()local value=store.read(PATH,{})if type(value)~=\"table\"then value={}end if value.enabled==nil then value.enabled=true end value.version=M.VERSION if type(value.used)~=\"table\"then value.used={}end return value end local function save(value)return store.write(PATH,value)end local function validToken(token)return type(token)==\"string\"and#token>=32 and#token<=128 and not token:find(\"[%z\\1-\\31\\127]\")end local function validId(value)return type(value)==\"string\"and value:match(\"^[%w_%-]+$\")and#value>=8 and#value<=96 end local function validNonce(value)return type(value)==\"string\"and value:match(\"^[%x]+$\")and#value>=16 and#value<=128 end local function canonical(node,request)return table.concat({\"ceetos-owner-service-v1\",tostring(node),tostring(request.id),tostring(request.action),tostring(math.floor(tonumber(request.ts)or-1)),tostring(request.nonce),},\"\\n\")end local function prune(value,time)local kept,rows={},{}for nonce,expires in pairs(value.used or{})do expires=tonumber(expires)if validNonce(nonce)and expires and expires>time then rows[#rows+1]={nonce=nonce,expires=expires}end end table.sort(rows,function(a,b)return a.expires>b.expires end)for index,row in ipairs(rows)do if index<=M.MAX_USED_NONCES then kept[row.nonce]=row.expires end end value.used=kept end function M.status()local value=state()prune(value,now())return{enabled=value.enabled~=false,provisioned=validToken(value.token),owner=type(value.owner)==\"string\"and value.owner or nil,actions={\"snapshot\",\"status\"},}end function M.setEnabled(enabled)local value=state();value.enabled=enabled==true;prune(value,now());save(value)return M.status()end function M.provision(token,owner)assert(validToken(token),\"owner-service token must be 32-128 printable characters\")assert(type(owner)==\"string\"and owner:match(\"^[%w_%-]+$\")and#owner<=32,\"invalid owner\")local value=state()value.token,value.owner,value.enabled,value.used=token,owner,true,{}assert(save(value),\"could not save owner-service configuration\")return M.status()end function M.rotate(owner)local token=password.newSalt(\"owner-service-a\")..password.newSalt(\"owner-service-b\")M.provision(token,owner)return token end function M.signature(token,node,request)assert(validToken(token),\"invalid owner-service token\")return assert(password.hmacSha256(token,canonical(node,request)))end function M.verify(request)if type(request)~=\"table\"then return false,\"service request must be an object\"end local value,time=state(),now()prune(value,time)if value.enabled==false then return false,\"owner service is disabled\"end if not validToken(value.token)then return false,\"owner service has not been provisioned\"end if not validId(request.id)or not actions[request.action]or not validNonce(request.nonce)then return false,\"invalid service request\"end local timestamp=tonumber(request.ts)if not timestamp or math.floor(timestamp)~=timestamp or math.abs(time-timestamp)>M.MAX_AGE_MS then return false,\"service request expired\"end if value.used[request.nonce]then return false,\"service request was already used\"end if type(request.tag)~=\"string\"or not request.tag:match(\"^[%x]+$\")or#request.tag~=64 then return false,\"invalid service authenticator\"end local expected=M.signature(value.token,os.getComputerID(),request)if not password.constantTimeEqual(expected,request.tag:lower())then return false,\"service authentication failed\"end value.used[request.nonce]=timestamp+M.MAX_AGE_MS prune(value,time)assert(save(value),\"could not persist service replay state\")return true,value end function M.dispatch(request)local ok,value=M.verify(request)if not ok then return false,value end if request.action==\"snapshot\"then return true,{action=\"snapshot\",telemetry=telemetry.snapshot(\"owner-service\"),owner=value.owner}end return true,{action=\"status\",service=M.status(),telemetryEnabled=telemetry.status()}end return M",
  ["ceetos/lib/gui.lua"] = "local M={}local store=require(\"ceetos.lib.store\")local terminalUi=require(\"ceetos.lib.terminal_ui\")M.pages={home=\"Desktop\",peers=\"Peers\",peripherals=\"Devices\",telemetry=\"Telemetry\",updates=\"Updates\",admin=\"Administration\",audit=\"Audit log\",jobs=\"Jobs\",files=\"Explorer\"}local function add(items,allowed,item)if allowed then items[#items+1]=item end end local function role(deps,required)return deps.auth.allowed(required)end local function colour(item)if item.kind==\"directory\"then return colors.lightBlue end if item.kind==\"program\"then return colors.lime end if item.kind==\"file\"then return colors.white end return colors.lightGray end local function system(id,label)return{id=id,label=label,kind=\"system\",action=id}end local function count(value)if type(value)~=\"table\"then return 0 end local total=0 for _ in pairs(value)do total=total+1 end return total end local function entries(value)if type(value)~=\"table\"then return{}end local out={}for key,item in pairs(value)do if type(item)==\"table\"then local copy={}for field,fieldValue in pairs(item)do copy[field]=fieldValue end copy._ceetosKey=tostring(key)item=copy else item={value=item,_ceetosKey=tostring(key)}end out[#out+1]=item end table.sort(out,function(left,right)return tostring(left.name or left.id or left._ceetosKey)<tostring(right.name or right.id or right._ceetosKey)end)return out end local function short(value,limit)value=terminalUi.clean(value or\"-\")return#value>limit and value:sub(1,math.max(1,limit-3))..\"...\"or value end function M.newState()return{selected=nil,desktopPage=1,menu=nil,path=\"/\",history={},trash=false,peripheralScroll=1}end function M.model(page,deps,state)state=state or M.newState()local items,lines={},{}local auth,net,peripherals,telemetry,cloud=deps.auth,deps.net,deps.peripherals,deps.telemetry,deps.cloud local account=auth.current and(auth.current.name..\" (\"..auth.current.role..\")\")or\"not logged in\"local liveNetwork=store.read(\"/ceetos/data/network-status.lua\",{})local visiblePeers=liveNetwork.peers or net.peers()local craftState=store.read(\"/ceetos/data/crafting-state.lua\",{})local craftSources=craftState.sources or{}local selectedTicker=craftState.config and craftState.config.ticker local craftingAvailable=selectedTicker~=nil or#(craftSources.tickers or{})>0 if not craftingAvailable and peripheral and peripheral.getNames then for _,name in ipairs(peripheral.getNames())do if tostring(peripheral.getType(name)or\"\"):lower():find(\"stockticker\",1,true)then craftingAvailable=true;break end end end if page==\"home\"then add(items,role(deps,\"operator\"),system(\"terminal\",\"Terminal\"))if role(deps,\"viewer\")then for _,program in ipairs(deps.files.programs())do items[#items+1]={id=\"file:\"..program.path,label=program.name,kind=\"program\",path=program.path,runnable=true,canRun=true,canModify=role(deps,\"operator\"),protected=program.protected,action=\"run:\"..program.path}end end if craftingAvailable then items[#items+1]=system(\"crafting\",\"Crafting\")end if role(deps,\"operator\")then items[#items+1]=system(\"page:files\",\"Files\")items[#items+1]=system(\"page:peers\",\"Peers\")items[#items+1]=system(\"page:peripherals\",\"Devices\")items[#items+1]=system(\"page:telemetry\",\"Telemetry\")items[#items+1]=system(\"page:jobs\",\"Jobs\")items[#items+1]=system(\"page:updates\",\"Updates\")end items[#items+1]=system(\"page:admin\",\"Admin\")return{page=page,title=\"CeetOS Desktop\",desktop=true,items=items,subtitle=account..\"  |  \"..#visiblePeers..\" network peers  |  \"..#peripherals.describe()..\" shared  |  telemetry \"..(telemetry.status()and\"on\"or\"off\"),}elseif page==\"files\"then local source=state.trash and deps.files.trashList()or deps.files.list(state.path)for _,entry in ipairs(source)do local kind=entry.directory and\"directory\"or(entry.runnable and\"program\"or\"file\")items[#items+1]={id=(entry.trashed and\"trash:\"..entry.id or\"file:\"..entry.path),label=entry.name,kind=kind,path=entry.path,original=entry.original,trashId=entry.id,parent=entry.parent,directory=entry.directory,runnable=entry.runnable,protected=entry.protected,trashed=entry.trashed,canRun=role(deps,\"viewer\"),canModify=role(deps,\"operator\"),action=entry.parent and\"up:\"..entry.path or(entry.directory and\"dir:\"..entry.path or(entry.runnable and role(deps,\"viewer\")and\"run:\"..entry.path or nil)),}end return{page=page,title=\"CeetOS Explorer\",items=items,path=state.trash and\"Trash\"or state.path,trash=state.trash}elseif page==\"peers\"then local live=liveNetwork local diag=live.discovery or(net.discoveryStatus and net.discoveryStatus()or{})local session,transport=diag.session,diag.transport or live.transport or{}local peerList,directCount,routedCount,rekeyCount=visiblePeers,0,0,0 for _,peer in ipairs(peerList)do if peer.routed then routedCount=routedCount+1 else directCount=directCount+1 end if peer.rekeyRequired then rekeyCount=rekeyCount+1 end end local discoveryActive=diag.active==true or session~=nil local discoveryState=discoveryActive and tostring((session and session.state)or diag.state or\"inactive\")or\"inactive\"local discoveryText=\"Discovery: \"..discoveryState if session and tonumber(session.expires)then local remaining=math.max(0,math.ceil((tonumber(session.expires)-os.epoch(\"utc\"))/1000))discoveryText=discoveryText..\" (\"..tostring(remaining)..\"s remaining)\"end if session and session.retries then discoveryText=discoveryText..\" (retries \"..tostring(session.retries)..\")\"end if session and session.candidate then discoveryText=discoveryText..\" - candidate \"..tostring(session.candidate.label or session.candidate.id)end local modemText=transport.wireless and(\"wireless links: \"..tostring(transport.wirelessLinkCount or 1))or\"no wireless modem\"local mesh=transport.mesh or{}lines={\"Network peers: \"..(directCount+routedCount)..\" (\"..directCount..\" direct, \"..routedCount..\" routed)\",discoveryText,modemText,\"Protocol: v\"..tostring(live.protocol or transport.protocol or 2)..\" | Rekey required: \"..tostring(rekeyCount),\"Links: \"..tostring(transport.healthyLinks or 0)..\" healthy / \"..tostring(transport.degradedLinks or 0)..\" degraded / \"..tostring(transport.offlineLinks or 0)..\" offline\",\"Mesh: \"..(mesh.enrolled and(\"enrolled e\"..tostring(mesh.epoch))or\"enrollment pending\"),\"Last receive distance: \"..tostring(transport.lastDistance or\"-\")}for _,peer in ipairs(peerList)do local kind=peer.routed and\"Routed\"or\"Direct\"local route=peer.routed and(\" via \"..tostring(peer.next or\"?\")..\" (\"..tostring(peer.hops or\"?\")..\" hop)\")or(peer.auto and\" mesh edge\"or\"\")lines[#lines+1]=kind..\": \"..tostring(peer.label or(\"Computer \"..tostring(peer.id)))..\" (\"..tostring(peer.id)..\")\"..route..\" [\"..tostring(peer.health or\"unknown\")..\"]\"end if not discoveryActive and diag.lastState and diag.lastState~=\"inactive\"then lines[#lines+1]=\"Previous discovery: \"..tostring(diag.lastState)..(diag.lastMessage and(\" - \"..tostring(diag.lastMessage))or\"\")elseif diag.message then lines[#lines+1]=\"Network: \"..tostring(diag.message)end local canBegin=not discoveryActive add(items,role(deps,\"operator\")and canBegin,system(\"start_discovery\",\"Start discovery\"))add(items,role(deps,\"operator\")and canBegin,system(\"join_discovery\",\"Join discovery\"))add(items,role(deps,\"operator\")and discoveryState==\"candidate\",system(\"confirm_discovery\",\"Confirm pairing\"))add(items,role(deps,\"operator\")and not canBegin,system(\"cancel_discovery\",\"Cancel discovery\"))add(items,role(deps,\"operator\"),system(\"remote_refresh\",\"Refresh remote peripherals\"))elseif page==\"peripherals\"then local shared={}for _,item in ipairs(peripherals.describe())do shared[item.name]=item.mode end local detected=peripherals.listLocal()lines={\"Detected devices: \"..#detected,\"Shared devices: \"..#peripherals.describe()}if not state.peripheralView then add(items,role(deps,\"operator\"),system(\"peripheral_view\",\"View peripherals\"))end for _,item in ipairs(detected)do local mode=shared[item.name]items[#items+1]={id=\"peripheral_check:\"..item.name..\":peer\",name=item.name,label=item.name,type=item.type,kind=\"peripheral\",sharedMode=mode,mode=\"peer\",checked=mode==\"peer\",toggle=true,action=\"peripheral_set:\"..item.name..\":peer\"}items[#items+1]={id=\"peripheral_check:\"..item.name..\":master\",name=item.name,label=item.name,type=item.type,kind=\"peripheral\",sharedMode=mode,mode=\"master\",checked=mode==\"master\",toggle=true,action=\"peripheral_set:\"..item.name..\":master\"}end add(items,role(deps,\"operator\"),system(\"share_all:peer\",\"Share all - peers\"))add(items,role(deps,\"operator\"),system(\"share_all:master\",\"Share all - master only\"))add(items,role(deps,\"operator\"),system(\"unshare_all\",\"Unshare all\"))add(items,role(deps,\"operator\"),system(\"remote_cache\",\"View remote cache\"))add(items,role(deps,\"operator\"),system(\"remote_call\",\"Call remote peripheral\"))local shown={}for _,entry in ipairs(items)do local checkbox=entry.id:sub(1,17)==\"peripheral_check:\"local bulk=entry.action==\"share_all:peer\"or entry.action==\"share_all:master\"or entry.action==\"unshare_all\"if state.peripheralView or(not checkbox and not bulk)then shown[#shown+1]=entry end end items=shown elseif page==\"telemetry\"then local c=telemetry.configuration()local cloudStatus=cloud and cloud.status and cloud.status()or{}lines={\"Telemetry: \"..(c.enabled and\"enabled\"or\"disabled\"),\"Cloud node: \"..(cloudStatus.enrolled and(\"enrolled as \"..tostring(cloudStatus.node))or\"not enrolled\"),\"Cloud auth: \"..(cloudStatus.authOnline and\"online\"or\"offline\")..\" | recipes: \"..(cloudStatus.recipeOnline and\"online\"or\"offline\"),cloudStatus.enrolled and(\"Last report: \"..tostring(cloudStatus.telemetryLastSuccess or\"pending\")..\" | next: \"..tostring(cloudStatus.telemetryNext or\"pending\"))or\"Enroll this computer before it can appear on dash.ceet.uk.\",cloudStatus.telemetryLastError and(\"Telemetry error: \"..short(cloudStatus.telemetryLastError,58))or\"Cloud telemetry uploads daily and does not block this UI.\",}add(items,role(deps,\"admin\"),system(\"telemetry_toggle\",c.enabled and\"Disable telemetry\"or\"Enable telemetry\"))add(items,role(deps,\"admin\")and not cloudStatus.enrolled,system(\"cloud_enroll\",\"Enroll this computer with CeetOS Cloud\"))add(items,role(deps,\"operator\")and cloudStatus.enrolled,system(\"cloud_retry\",\"Retry cloud sync now\"))add(items,role(deps,\"admin\")and cloudStatus.enrolled,system(\"cloud_clear\",\"Remove cloud enrollment\"))elseif page==\"updates\"then local update=store.read(\"/ceetos/data/update-status.lua\",{})local cache,transfer=update.cache,update.transfer lines={\"Installed: \"..tostring(update.version or\"unknown\")..\"  |  \"..tostring(update.status or\"idle\"),update.message and short(update.message,72)or\"Only locally confirmed signed releases can be applied.\",cache and(\"Verified cache: \"..tostring(cache.version)..\"  \"..tostring(cache.fingerprint or\"-\")..\"  key \"..tostring(cache.keyId or\"-\"))or\"Verified cache: none\",transfer and(\"Downloading: \"..tostring(transfer.received or 0)..\"/\"..tostring(transfer.size or\"?\")..\" bytes from \"..tostring(transfer.label or transfer.source))or\"No active download\",}add(items,role(deps,\"operator\"),system(\"update_check\",\"Check for signed releases\"))add(items,role(deps,\"operator\"),system(\"update_install_latest\",\"Install latest signed release\"))for _,offer in ipairs(update.offers or{})do local route=offer.transport==\"cloud\"and\"cloud\"or(offer.transport==\"routed\"and\"routed\"or\"direct\")items[#items+1]={id=\"update-source:\"..tostring(offer.key or offer.id),label=\"Download \"..tostring(offer.version)..\" from \"..short(offer.label or offer.id,18)..\" (\"..route..\")\",kind=\"update\",action=\"update_download:\"..tostring(offer.key or offer.id),offer=offer}end add(items,role(deps,\"operator\")and transfer~=nil,system(\"update_cancel\",\"Cancel download\"))add(items,role(deps,\"operator\")and cache~=nil,system(\"update_apply\",\"Apply verified cached release\"))add(items,role(deps,\"operator\")and cache~=nil and transfer==nil,system(\"update_clear\",\"Clear release cache\"))elseif page==\"admin\"then lines={\"Session: \"..account}add(items,auth.current==nil,system(\"login\",\"Login\"))add(items,auth.current~=nil,system(\"logout\",\"Logout\"))if role(deps,\"operator\")then for _,user in ipairs(auth.list())do items[#items+1]={id=\"account:\"..user.name,label=user.name..\"  (\"..user.role..\")\",kind=\"account\",name=user.name,userRole=user.role,canGrantAdmin=role(deps,\"admin\"),active=auth.current and auth.current.name==user.name}end add(items,true,system(\"user_add\",\"Create user\"))add(items,true,system(\"recovery_enable\",\"Enable recovery window\"))add(items,true,system(\"recovery_reset\",\"Recovery reset\"))add(items,true,system(\"page:audit\",\"View audit log\"))add(items,true,system(\"page:jobs\",\"Jobs\"))end elseif page==\"audit\"then lines={\"Latest audit events:\"}for _,event in ipairs(deps.audit.recent(10))do lines[#lines+1]=event.actor..\" - \"..event.action end elseif page==\"jobs\"then store.invalidate(\"/ceetos/data/jobs.lua\")store.invalidate(\"/ceetos/data/job-workers.lua\")local jobState=store.read(\"/ceetos/data/jobs.lua\",{})local workerState=store.read(\"/ceetos/data/job-workers.lua\",{})local controller=jobState.controllerId or jobState.masterId or workerState.controllerId or workerState.masterId local workers=workerState.workers or jobState.workers or{}local queue=jobState.queue or{}local schedules=jobState.schedules or{}local history=jobState.history or jobState.results or{}lines={\"Controller: \"..tostring(controller or\"electing / unavailable\"),\"Workers: \"..count(workers)..\"  |  Queue: \"..count(queue),\"Schedules: \"..count(schedules)..\"  |  Recent results: \"..count(history),role(deps,\"admin\")and\"Administrator view: scheduler controls are available through nx jobs.\"or\"Operator view: scheduler state is read-only.\",}for _,worker in ipairs(entries(workers))do local name=worker.label or worker.name or worker.id or worker._ceetosKey local active=worker.inFlight or worker.active or 0 local capacity=worker.capacity or 1 local health=worker.available==false and\"offline\"or(worker.health or\"ready\")items[#items+1]={id=\"job-worker:\"..tostring(worker.id or worker._ceetosKey),label=\"Worker  \"..short(name,18)..\"  \"..tostring(active)..\"/\"..tostring(capacity)..\"  \"..short(health,10),kind=\"job\"}end for _,schedule in ipairs(entries(schedules))do local name=schedule.name or schedule.template or schedule.id or schedule._ceetosKey local interval=schedule.interval or schedule.every or\"once\"local status=schedule.enabled==false and\"paused\"or(schedule.status or\"scheduled\")items[#items+1]={id=\"job-schedule:\"..tostring(schedule.id or schedule._ceetosKey),label=\"Schedule  \"..short(name,17)..\"  \"..short(interval,10)..\"  \"..short(status,10),kind=\"job\"}end for _,result in ipairs(entries(history))do local name=result.template or result.name or result.jobId or result.id or result._ceetosKey local status=result.status or(result.ok==false and\"failed\"or\"complete\")local worker=result.worker or result.workerId or\"-\"items[#items+1]={id=\"job-result:\"..tostring(result.id or result._ceetosKey),label=\"Result  \"..short(name,15)..\"  \"..short(status,10)..\"  \"..short(worker,10),kind=\"job\"}end end return{page=page,title=\"CeetOS | \"..(M.pages[page]or page),items=items,lines=lines,remoteResult=page==\"peripherals\"and state.remoteResult or nil}end local function indexOf(model,id)for index,item in ipairs(model.items)do if item.id==id then return index end end end function M.selected(model,state)if#model.items==0 then return nil end local index=indexOf(model,state.selected)if not index then index=1;state.selected=model.items[1].id end return model.items[index],index end function M.select(model,state,item)if item then state.selected=item.id end return item end function M.move(model,state,direction)local _,index=M.selected(model,state)if not index then return end local delta=direction==\"left\"and-1 or direction==\"right\"and 1 or direction==\"up\"and-(model.columns or 1)or(model.columns or 1)local nextIndex=math.max(1,math.min(#model.items,index+delta))state.selected=model.items[nextIndex].id end function M.context(item)if not item or item.parent then return{}end local copy=item.label and{system(\"copy_label:\"..(item.id or\"\"),\"Copy text\")}or{}if item.kind==\"account\"then local actions={system(\"user_role:\"..item.name..\":viewer\",\"Set role: viewer\"),system(\"user_role:\"..item.name..\":operator\",\"Set role: operator\")}if item.canGrantAdmin then actions[#actions+1]=system(\"user_role:\"..item.name..\":admin\",\"Set role: admin\")end actions[#actions+1]=system(\"user_reset:\"..item.name,\"Reset password\")actions[#actions+1]=system(\"user_delete:\"..item.name,\"Delete user\")for _,action in ipairs(copy)do actions[#actions+1]=action end return actions end if item.kind==\"peripheral\"then local actions={}if item.sharedMode then actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":peer\",\"Share with peers\")actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":master\",\"Share with master only\")actions[#actions+1]=system(\"peripheral_unshare:\"..item.name,\"Stop sharing\")else actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":peer\",\"Share with peers\")actions[#actions+1]=system(\"peripheral_set:\"..item.name..\":master\",\"Share with master only\")end return actions end if item.trashed then copy[#copy+1]=system(\"restore:\"..item.trashId,\"Restore\");copy[#copy+1]=system(\"delete_trash:\"..item.trashId,\"Delete permanently\");return copy end if not item.path then if item.action then copy[#copy+1]=system(item.action,\"Open\")end;return copy end local actions={}if item.action and(not item.runnable or item.canRun~=false)then actions[#actions+1]=system(item.action,item.directory and\"Open\"or\"Run\")end if not item.protected and item.canModify then if not item.directory then actions[#actions+1]=system(\"edit:\"..item.path,\"Edit\")end actions[#actions+1]=system(\"rename:\"..item.path,\"Rename\")actions[#actions+1]=system(\"trash:\"..item.path,\"Move to Trash\")end for _,action in ipairs(copy)do actions[#actions+1]=action end return actions end local function drawHeader(model,banner,width,height)term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,model.title,colors.white,colors.blue,width-2)if height>=2 then terminalUi.write(2,2,model.subtitle or model.path or\"\",colors.lightGray,colors.black,width-2)end if banner and height>=3 then terminalUi.write(2,3,banner.text,banner.error and colors.red or colors.lightGray,colors.black,width-2)end return banner and 4 or 3 end local function drawRemoteResult(result,top,width,height,targets)if not result or top>=height then return top end local pending=result.pending==true or result.status==\"pending\"local failed=result.error==true or result.ok==false or result.status==\"error\"local label=pending and\"Remote request pending\"or(failed and\"Remote request failed\"or\"Remote result\")if result.peer then label=label..\" | \"..tostring(result.peer)end if result.device then label=label..\" | \"..tostring(result.device)end if result.method then label=label..\".\"..tostring(result.method)end terminalUi.clearLine(top,failed and colors.black or colors.gray)terminalUi.write(2,top,label,failed and colors.red or colors.white,failed and colors.black or colors.gray,width-4)if not pending then local clearLabel,copyLabel=\"[Clear]\",\"[Copy]\"local clearX,copyX=width-#clearLabel-1,width-#clearLabel-#copyLabel-3 terminalUi.write(copyX,top,copyLabel,colors.lightBlue,colors.gray)terminalUi.write(clearX,top,clearLabel,colors.lightBlue,colors.gray)targets[#targets+1]={kind=\"item\",item=system(\"remote_result_copy\",\"Copy remote result\"),x1=copyX,x2=copyX+#copyLabel-1,y1=top,y2=top}targets[#targets+1]={kind=\"item\",item=system(\"remote_result_clear\",\"Clear remote result\"),x1=clearX,x2=clearX+#clearLabel-1,y1=top,y2=top}end if top+1<height then terminalUi.write(2,top+1,result.text or result.message or result.value or\"\",failed and colors.red or colors.lightGray,colors.black,width-3)end return top+2 end local function drawMenu(menu,width,height)if not menu or#menu.items==0 then return{}end local longest=0 for _,item in ipairs(menu.items)do longest=math.max(longest,#terminalUi.clean(item.label))end local boxWidth,x=math.max(8,math.min(width-2,longest+4)),math.max(1,width-math.max(8,math.min(width-2,longest+4)))local y=math.max(2,height-#menu.items-1)local targets={}for index,item in ipairs(menu.items)do local selected=index==menu.selected terminalUi.fill(x,y+index-1,boxWidth,1,selected and colors.gray or colors.black)terminalUi.write(x+1,y+index-1,item.label,selected and colors.white or colors.lightGray,selected and colors.gray or colors.black,boxWidth-2)targets[#targets+1]={kind=\"menu\",item=item,x1=x,x2=x+boxWidth-1,y1=y+index-1,y2=y+index-1}end return targets end local function drawDesktop(model,state,banner,width,height)if width<24 or height<9 then return terminalUi.minimum(model.title,\"Desktop needs 24x9\",\"Resize | Backspace\")end local top=drawHeader(model,banner,width,height)+1 local columns=math.max(2,math.floor((width-2)/14))local cellWidth,cellHeight=math.floor((width-2)/columns),4 local rows,capacity=math.max(1,math.floor((height-top-1)/cellHeight)),9 capacity=math.min(capacity,columns*rows)model.columns=columns local item,selectedIndex=M.selected(model,state)local totalPages=math.max(1,math.ceil(#model.items/capacity))state.desktopPage=math.max(1,math.min(math.floor((selectedIndex-1)/capacity)+1,totalPages))local first,last=(state.desktopPage-1)*capacity+1,math.min(#model.items,state.desktopPage*capacity)local targets={}for index=first,last do local slot,entry=index-first,model.items[index]local x,y=2+(slot%columns)*cellWidth,top+math.floor(slot/columns)*cellHeight local selected=entry.id==state.selected terminalUi.fill(x,y,cellWidth,3,selected and colors.gray or colors.black)terminalUi.write(x+1,y+1,entry.label,colour(entry),selected and colors.gray or colors.black,cellWidth-2)targets[#targets+1]={kind=\"item\",item=entry,x1=x,x2=x+cellWidth-1,y1=y,y2=y+2}end terminalUi.write(2,height,\"Arrows select | Enter open | M menu | [\"..state.desktopPage..\"/\"..totalPages..\"] | Q close\",colors.gray,colors.black,width-2)return targets end local function drawList(model,state,banner,width,height)if width<24 or height<8 then return terminalUi.minimum(model.title,\"Screen needs 24x8\",\"Resize | Backspace\")end local targets={}local top,footer=drawHeader(model,banner,width,height)+1,height-1 if model.page==\"peripherals\"then top=drawRemoteResult(model.remoteResult,top,width,footer,targets)+1 end for _,line in ipairs(model.lines or{})do if top>=footer-2 then break end terminalUi.write(2,top,line,colors.lightGray,colors.black,width-2);top=top+1 end local _,selectedIndex=M.selected(model,state)selectedIndex=selectedIndex or 1 local visible=math.max(1,footer-top)local first=math.max(1,math.min(math.max(1,#model.items-visible+1),selectedIndex-math.floor(visible/2)))model.columns=1 for row=0,visible-1 do local entry=model.items[first+row]if not entry then break end local y,selected=top+row,entry.id==state.selected terminalUi.clearLine(y,selected and colors.gray or colors.black)terminalUi.write(3,y,entry.label,colour(entry),selected and colors.gray or colors.black,width-4)targets[#targets+1]={kind=\"item\",item=entry,x1=1,x2=width,y1=y,y2=y}end local footerText if model.page==\"files\"then footerText=model.trash and\"Enter select | M menu | Backspace Explorer | E empty Trash\"or\"Enter open | M menu | N new folder | T Trash | Backspace up\"else footerText=\"Arrows select | Enter open | Backspace desktop | Q close\"end terminalUi.write(2,height,footerText,colors.gray,colors.black,width-2)return targets end local function drawPeripheralMatrix(model,state,banner,width,height)if width<36 or height<15 then return terminalUi.minimum(model.title,\"Devices matrix needs 36x15\",\"Resize | Backspace\")end local targets={}local top,footer=drawHeader(model,banner,width,height)+1,height-1 for _,line in ipairs(model.lines or{})do if top>=footer-1 then break end terminalUi.write(2,top,line,colors.lightGray,colors.black,width-2);top=top+1 end top=drawRemoteResult(model.remoteResult,top,width,footer,targets)+1 local devices,byKey={},{}for _,item in ipairs(model.items)do if item.id:sub(1,17)==\"peripheral_check:\"then if not byKey[item.name]then devices[#devices+1]={name=item.name,type=item.type or\"unknown\"};byKey[item.name]={}end byKey[item.name][item.mode]=item end end local controls={}for _,item in ipairs(model.items)do if item.kind==\"system\"and(item.action==\"share_all:peer\"or item.action==\"share_all:master\"or item.action==\"unshare_all\"or item.action==\"remote_cache\"or item.action==\"remote_call\")then controls[#controls+1]=item end end local nameX,masterX,peerX=2,width-11,width-17 local typeX=math.max(14,math.floor(width*0.45))local deviceRows=math.max(1,footer-top-#controls-2)local selectedDevice for index,device in ipairs(devices)do local row=byKey[device.name]if(row.peer and row.peer.id==state.selected)or(row.master and row.master.id==state.selected)then selectedDevice=index;break end end if selectedDevice then state.peripheralScroll=math.max(1,math.min(math.max(1,#devices-deviceRows+1),selectedDevice-math.floor(deviceRows/2)))end state.peripheralScroll=math.max(1,math.min(math.max(1,#devices-deviceRows+1),state.peripheralScroll or 1))terminalUi.write(nameX,top,\"Name\",colors.lightGray,colors.black,typeX-nameX-1)terminalUi.write(typeX,top,\"Type\",colors.lightGray,colors.black,peerX-typeX-1)terminalUi.write(peerX,top,\"Peer\",colors.lightGray,colors.black,5)terminalUi.write(masterX,top,\"Master\",colors.lightGray,colors.black,7)for row=0,deviceRows-1 do local device=devices[state.peripheralScroll+row]if not device then break end local y=top+row+1 terminalUi.write(nameX,y,device.name,colors.white,colors.black,typeX-nameX-1)terminalUi.write(typeX,y,device.type,colors.lightGray,colors.black,peerX-typeX-1)for _,mode in ipairs({\"peer\",\"master\"})do local item=byKey[device.name][mode]local selected,x=item and state.selected==item.id,mode==\"peer\"and peerX or masterX terminalUi.write(x,y,item and(item.checked and\"[x]\"or\"[ ]\")or\"   \",item and item.checked and colors.lime or colors.lightGray,selected and colors.gray or colors.black,3)if item then targets[#targets+1]={kind=\"item\",item=item,x1=x,x2=x+2,y1=y,y2=y}end end end local y=top+deviceRows+1 for _,item in ipairs(controls)do if y>=footer then break end local selected=state.selected==item.id terminalUi.clearLine(y,selected and colors.gray or colors.black)terminalUi.write(2,y,item.label,selected and colors.white or colors.lightGray,selected and colors.gray or colors.black,width-2)targets[#targets+1]={kind=\"item\",item=item,x1=1,x2=width,y1=y,y2=y}y=y+1 end terminalUi.write(2,height,\"Arrows select | Enter toggle | Click checkbox | Backspace devices\",colors.gray,colors.black,width-2)return targets end function M.draw(model,state,banner)local width,height=term.getSize()local targets=model.desktop and drawDesktop(model,state,banner,width,height)or(model.page==\"peripherals\"and state.peripheralView and drawPeripheralMatrix(model,state,banner,width,height)or drawList(model,state,banner,width,height))local menuTargets=drawMenu(state.menu,width,height)for _,target in ipairs(menuTargets)do targets[#targets+1]=target end term.setBackgroundColor(colors.black);term.setTextColor(colors.white)return targets end function M.actionFor(model,number)if model.page==\"peers\"and number==2 then return{id=\"pair_offer\",label=\"Start discovery\"}end return model.items[number]end return M",
  ["ceetos/lib/terminal_ui.lua"] = "local M={}local function size()local width,height=term.getSize()return math.max(1,width or 1),math.max(1,height or 1)end function M.clean(value)return tostring(value or\"\"):gsub(\"%c\",\" \")end function M.clip(value,width,suffix)value,width=M.clean(value),math.max(0,math.floor(tonumber(width)or 0))if width==0 then return\"\"end if#value<=width then return value end suffix=suffix==nil and\"...\"or tostring(suffix)if#suffix>=width then return suffix:sub(1,width)end return value:sub(1,width-#suffix)..suffix end function M.write(x,y,value,foreground,background,width)local terminalWidth,terminalHeight=size()x,y=math.floor(tonumber(x)or 1),math.floor(tonumber(y)or 1)if y<1 or y>terminalHeight or x>terminalWidth then return false end if x<1 then value=M.clean(value):sub(2-x)x=1 end local available=math.max(0,terminalWidth-x+1)if width~=nil then available=math.min(available,math.max(0,math.floor(width)))end if available<=0 then return false end if foreground then term.setTextColor(foreground)end if background then term.setBackgroundColor(background)end term.setCursorPos(x,y)term.write(M.clip(value,available,\"\"))return true end function M.clearLine(y,background)local width,height=size()y=math.floor(tonumber(y)or 0)if y<1 or y>height then return false end term.setCursorPos(1,y)if background then term.setBackgroundColor(background)end term.clearLine()return width>0 end function M.fill(x,y,width,height,background)local terminalWidth,terminalHeight=size()x,y=math.max(1,math.floor(tonumber(x)or 1)),math.max(1,math.floor(tonumber(y)or 1))width,height=math.max(0,math.floor(tonumber(width)or 0)),math.max(0,math.floor(tonumber(height)or 0))width,height=math.min(width,terminalWidth-x+1),math.min(height,terminalHeight-y+1)if width<=0 or height<=0 then return false end term.setBackgroundColor(background or colors.black)for row=y,y+height-1 do term.setCursorPos(x,row);term.write((\" \"):rep(width))end return true end function M.box(x1,y1,x2,y2,title,border,titleColour)local width,height=size()x1,y1=math.max(1,math.floor(x1 or 1)),math.max(1,math.floor(y1 or 1))x2,y2=math.min(width,math.floor(x2 or width)),math.min(height,math.floor(y2 or height))if x2-x1<2 or y2-y1<2 then return false end border=border or colors.gray term.setBackgroundColor(colors.black);term.setTextColor(border)M.write(x1,y1,\"+\"..(\"-\"):rep(x2-x1-1)..\"+\",border,colors.black)for row=y1+1,y2-1 do M.write(x1,row,\"|\",border,colors.black);M.write(x2,row,\"|\",border,colors.black)end M.write(x1,y2,\"+\"..(\"-\"):rep(x2-x1-1)..\"+\",border,colors.black)if title and title~=\"\"then M.write(x1+2,y1,\" \"..M.clean(title)..\" \",titleColour or colors.lightBlue,colors.black,math.max(0,x2-x1-3))end return true end function M.minimum(title,message,footer)local width,height=size()term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()M.clearLine(1,colors.blue);M.write(2,1,title or\"CeetOS\",colors.white,colors.blue,width-2)M.write(2,math.max(2,math.floor(height/2)),message or\"Terminal is too small\",colors.red,colors.black,width-2)M.write(2,height,footer or\"Resize terminal or press Backspace\",colors.gray,colors.black,width-2)return{}end function M.hit(targets,x,y)for index=#(targets or{}),1,-1 do local target=targets[index]if x>=target.x1 and x<=target.x2 and y>=target.y1 and y<=target.y2 then return target end end end return M",
  ["ceetos/lib/files.lua"] = "local store=require(\"ceetos.lib.store\")local auth=require(\"ceetos.lib.auth\")local disks=require(\"ceetos.lib.disks\")local M={}local TRASH_DIR=\"/ceetos/data/trash\"local TRASH_INDEX=\"/ceetos/data/trash-index.lua\"local protectedRoots={\"/ceetos\",\"/rom\"}local protectedFiles={[\"/startup.lua\"]=true}local function absolute(path)if not path or path==\"\"or path==\"/\"then return\"/\"end return path:sub(1,1)==\"/\"and path or\"/\"..path end local function sort(items)table.sort(items,function(a,b)if a.directory~=b.directory then return a.directory end return a.name:lower()<b.name:lower()end)return items end local function availablePath(directory,name)name=fs.getName(name)local base,extension=name:match(\"^(.*)(%.[^.]*)$\")base,extension=base or name,extension or\"\"local path,index=fs.combine(directory,name),2 while fs.exists(path)do path=fs.combine(directory,base..\"-\"..index..extension)index=index+1 end return absolute(path)end local function rawRead(path,fallback)local handle=fs.exists(path)and fs.open(path,\"r\")or nil if not handle then return fallback end local text=handle.readAll();handle.close()local value=textutils.unserialise(text)return type(value)==\"table\"and value or fallback end local function rawWrite(path,value)local temporary=path..\".tmp\"if fs.exists(temporary)then fs.delete(temporary)end local handle=assert(fs.open(temporary,\"w\"));handle.write(textutils.serialise(value));handle.close()if fs.exists(path)then fs.delete(path)end fs.move(temporary,path)end local function volumeFor(path)return disks.forPath(absolute(path))end local function writable(path)local volume=volumeFor(path)return not volume or volume.writable==true end function M.isProtected(path)path=absolute(path)if protectedFiles[path]then return true end for _,root in ipairs(protectedRoots)do if path==root or path:sub(1,#root+1)==root..\"/\"then return true end end return false end function M.describe(path)path=absolute(path)local volume=volumeFor(path)return{name=fs.getName(path),path=path,directory=fs.exists(path)and fs.isDir(path)or false,runnable=fs.exists(path)and not fs.isDir(path)and path:sub(-4):lower()==\".lua\",protected=M.isProtected(path),volume=volume and volume.key or nil,removable=volume~=nil,writable=writable(path),}end function M.list(path)path=absolute(path==\"\"and\"/\"or(path or\"/\"))local result={}if path~=\"/\"then local parent=absolute(fs.getDir(path))result[#result+1]={name=\"..\",path=parent,directory=true,parent=true,protected=M.isProtected(parent)}end for _,name in ipairs(fs.list(path))do if name~=\".ceetos-trash\"then result[#result+1]=M.describe(absolute(fs.combine(path,name)))end end if path==\"/\"then local seen={}for _,item in ipairs(result)do seen[item.path]=true end for _,volume in ipairs(disks.volumes())do if not seen[volume.mount]then result[#result+1]={name=volume.label,path=volume.mount,directory=true,removable=true,volume=volume.key,writable=volume.writable,disk=volume}else for _,item in ipairs(result)do if item.path==volume.mount then item.name,item.removable,item.volume,item.writable,item.disk=volume.label,true,volume.key,volume.writable,volume end end end end end return sort(result)end local function collect(path,depth,result)if depth<0 or not fs.exists(path)or not fs.isDir(path)then return end for _,item in ipairs(M.list(path))do if not item.parent then if item.directory then collect(item.path,depth-1,result)elseif item.runnable then result[#result+1]=item end end end end function M.programs()local result={}collect(\"/programs\",2,result)for _,volume in ipairs(disks.volumes())do local before=#result collect(volume.mount,3,result)for index=before+1,#result do result[index].removable,result[index].volume,result[index].disk=true,volume.key,volume result[index].name=volume.label..\": \"..result[index].name end end return result end function M.volumes()return disks.volumes()end function M.handleDiskEvent(event,drive)return disks.handleEvent(event,drive)end function M.runnable(path)return M.describe(path).runnable end function M.path(directory,name)return absolute(fs.combine(directory,fs.getName(name)))end local function assertMutable(path)path=absolute(path)assert(path~=\"/\"and fs.exists(path),\"file not found\")assert(not M.isProtected(path),\"CeetOS system files cannot be changed from Explorer\")assert(writable(path),\"this removable disk is read-only\")return path end function M.rename(path,name)path=assertMutable(path)assert(name and fs.getName(name)==name and name~=\"\",\"invalid file name\")local target=M.path(fs.getDir(path),name)assert(not M.isProtected(target),\"CeetOS system files cannot be changed from Explorer\")assert(not fs.exists(target),\"a file with that name already exists\")fs.move(path,target)return target end function M.makeDirectory(directory,name)directory=absolute(directory)assert(not M.isProtected(directory),\"CeetOS system folders cannot be changed from Explorer\")assert(writable(directory),\"this removable disk is read-only\")assert(name and fs.getName(name)==name and name~=\"\",\"invalid folder name\")local target=M.path(directory,name)assert(not fs.exists(target),\"a file with that name already exists\")fs.makeDir(target)return target end function M.readText(path)path=absolute(path)assert(fs.exists(path)and not fs.isDir(path),\"file not found\")local handle=assert(fs.open(path,\"r\"))local contents=handle.readAll()handle.close()return contents end function M.writeText(path,contents)path=absolute(path)assert(not M.isProtected(path),\"CeetOS system files cannot be changed from Editor\")assert(writable(path),\"this removable disk is read-only\")local parent=absolute(fs.getDir(path))assert(fs.exists(parent)and fs.isDir(parent),\"parent folder does not exist\")local temporary,backup=path..\".ceetos-tmp\",path..\".ceetos-backup\"if fs.exists(temporary)then fs.delete(temporary)end if fs.exists(backup)then fs.delete(backup)end local handle=assert(fs.open(temporary,\"w\"));handle.write(contents);handle.close()if fs.exists(path)then fs.move(path,backup)end local ok,err=pcall(fs.move,temporary,path)if not ok then if fs.exists(backup)then fs.move(backup,path)end error(err,0)end if fs.exists(backup)then fs.delete(backup)end return path end local function trashRoot(path)local volume=volumeFor(path)if volume then local root=fs.combine(volume.mount,\".ceetos-trash\")return{key=volume.key,root=root,index=fs.combine(root,\"index.lua\"),items=fs.combine(root,\"items\"),volume=volume}end return{key=\"local\",root=TRASH_DIR,index=TRASH_INDEX,items=TRASH_DIR}end local function trashIndex(ref)return ref.key==\"local\"and store.read(ref.index,{})or rawRead(ref.index,{})end local function saveTrashIndex(ref,index)if ref.key==\"local\"then store.write(ref.index,index)else rawWrite(ref.index,index)end end local function trashId(ref)return ref.key..\":\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(math.random(1000,9999))end local function refForId(id)local key=tostring(id or\"\"):match(\"^([^:]+):\")if not key or key==\"local\"then return trashRoot(\"/\")end for _,volume in ipairs(disks.volumes())do if volume.key==key then return trashRoot(volume.mount)end end return nil,\"the source disk is not mounted\"end function M.moveToTrash(path)path=assertMutable(path)local ref=trashRoot(path)if not fs.exists(ref.items)then fs.makeDir(ref.items)end local index=trashIndex(ref)local id=trashId(ref)while index[id]do id=id..\"x\"end local stored=absolute(fs.combine(ref.items,id))fs.move(path,stored)index[id]={original=path,name=fs.getName(path),directory=fs.isDir(stored),deletedAt=os.epoch(\"utc\"),volume=ref.key}saveTrashIndex(ref,index)return id end function M.trashList()local refs,result={trashRoot(\"/\")},{}for _,volume in ipairs(disks.volumes())do refs[#refs+1]=trashRoot(volume.mount)end for _,ref in ipairs(refs)do local index=trashIndex(ref)for id,entry in pairs(index)do local stored=absolute(fs.combine(ref.items,id))if fs.exists(stored)then result[#result+1]={id=id,path=stored,name=entry.name,original=entry.original,directory=entry.directory,trashed=true,deletedAt=entry.deletedAt,runnable=not entry.directory and entry.name:sub(-4):lower()==\".lua\",removable=ref.key~=\"local\",volume=ref.key}else index[id]=nil end end saveTrashIndex(ref,index)end table.sort(result,function(a,b)return(a.deletedAt or 0)>(b.deletedAt or 0)end)return result end function M.restore(id)local ref,refErr=refForId(id);assert(ref,refErr)local index=trashIndex(ref)local entry=index[id]assert(entry,\"trash item not found\")local stored=absolute(fs.combine(ref.items,id))assert(fs.exists(stored),\"trash item no longer exists\")local parent=absolute(fs.getDir(entry.original))assert(not M.isProtected(entry.original),\"cannot restore into a protected system path\")assert(writable(entry.original),\"this removable disk is read-only\")if not fs.exists(parent)then fs.makeDir(parent)end local target=availablePath(parent,fs.getName(entry.original))fs.move(stored,target)index[id]=nil;saveTrashIndex(ref,index)return target end function M.deleteTrash(id)local ref,refErr=refForId(id);assert(ref,refErr)local index,entry=trashIndex(ref),trashIndex(ref)[id]assert(entry,\"trash item not found\")local stored=absolute(fs.combine(ref.items,id))if fs.exists(stored)then fs.delete(stored)end index[id]=nil;saveTrashIndex(ref,index)end function M.emptyTrash()local refs={trashRoot(\"/\")}for _,volume in ipairs(disks.volumes())do refs[#refs+1]=trashRoot(volume.mount)end for _,ref in ipairs(refs)do if ref.key==\"local\"or ref.volume.writable then if fs.exists(ref.root)then fs.delete(ref.root)end saveTrashIndex(ref,{})end end end function M.import(transfers,directory)auth.require(\"operator\")directory=directory or\"/programs/imports\"assert(writable(directory),\"this removable disk is read-only\")if not fs.exists(directory)then fs.makeDir(directory)end local imported={}for _,transfer in ipairs(transfers or{})do local name=transfer.getName and transfer.getName()if name and name~=\"\"then local path=availablePath(directory,name)local handle=assert(fs.open(path,\"wb\"))while true do local chunk=transfer.read(8192)if not chunk then break end handle.write(chunk)end handle.close()imported[#imported+1]=path end end return imported end return M",
  ["ceetos/lib/disks.lua"] = "local store=require(\"ceetos.lib.store\")local M={}local cached,dirty={},true local MAX_VOLUMES=32 local MOUNT_STATE=\"/ceetos/data/disk-volumes.lua\"local mountState local function generations()if mountState then return mountState end mountState=store.readFresh(MOUNT_STATE,{schema=1,generations={}})if type(mountState)~=\"table\"then mountState={schema=1,generations={}}end if type(mountState.generations)~=\"table\"then mountState.generations={}end return mountState end local function mountKey(id,drive)return(id~=nil and\"disk-\"..tostring(id)or\"drive-\"..tostring(drive)):gsub(\"[^%w%-%_]\",\"_\")end local function bumpGeneration(key)local value=generations()value.generations[key]=math.max(0,math.floor(tonumber(value.generations[key])or 0))+1 store.write(MOUNT_STATE,value)return value.generations[key]end local function absolute(path)if type(path)~=\"string\"or path==\"\"then return nil end return path:sub(1,1)==\"/\"and path or\"/\"..path end local function safe(fn,...)if type(fn)~=\"function\"then return nil end local ok,value=pcall(fn,...)if ok then return value end return nil end local function clean(value,limit)value=tostring(value or\"\")value=value:gsub(\"[%c]\",\" \")return value:sub(1,limit or 96)end local function driveNames()local names,result=peripheral and peripheral.getNames and peripheral.getNames()or{},{}for _,name in ipairs(names or{})do if peripheral.getType(name)==\"drive\"then result[#result+1]=name end end table.sort(result)return result end function M.refresh()local result={}if not disk then cached,dirty=result,false;return cached end for _,drive in ipairs(driveNames())do if#result>=MAX_VOLUMES then break end local present=safe(disk.isPresent,drive)local hasData=present and safe(disk.hasData,drive)local mount=hasData and absolute(safe(disk.getMountPath,drive))or nil if mount and fs.exists(mount)and fs.isDir(mount)then local id=safe(disk.getID,drive)local label=clean(safe(disk.getLabel,drive),48)local readonly=safe(fs.isReadOnly,mount)==true local key=mountKey(id,drive)local state=generations()if state.generations[key]==nil then state.generations[key]=1;store.write(MOUNT_STATE,state)end result[#result+1]={drive=tostring(drive),id=id~=nil and tostring(id)or nil,key=key,token=key..\":\"..tostring(state.generations[key]),label=label~=\"\"and label or(\"Disk \"..tostring(id or drive)),mount=mount,available=true,writable=not readonly,}end end table.sort(result,function(a,b)return a.label:lower()<b.label:lower()end)cached,dirty=result,false return cached end function M.volumes()if dirty then M.refresh()end local copy={}for index,item in ipairs(cached)do copy[index]={}for key,value in pairs(item)do copy[index][key]=value end end return copy end function M.invalidate()dirty=true end function M.forPath(path)path=absolute(path)if not path then return nil end for _,volume in ipairs(M.volumes())do if path==volume.mount or path:sub(1,#volume.mount+1)==volume.mount..\"/\"then return volume end end return nil end function M.isMounted(volume)if type(volume)~=\"table\"or type(volume.mount)~=\"string\"then return false end for _,candidate in ipairs(M.volumes())do if candidate.key==volume.key and candidate.mount==volume.mount then return true end end return false end function M.handleEvent(event,drive)if event==\"disk\"or event==\"disk_eject\"or event==\"peripheral\"or event==\"peripheral_detach\"then if(event==\"disk\"or event==\"disk_eject\")and drive then if event==\"disk\"then M.refresh()end for _,volume in ipairs(cached)do if volume.drive==tostring(drive)then bumpGeneration(volume.key)end end end M.invalidate()return true end return false end return M",
  ["ceetos/lib/editor.lua"] = "local M={}local selection=require(\"ceetos.lib.selection\")local function clamp(value,low,high)return math.max(low,math.min(high,value))end local function split(text)text=(text or\"\"):gsub(\"\\r\\n\",\"\\n\"):gsub(\"\\r\",\"\\n\")local lines={}for line in(text..\"\\n\"):gmatch(\"(.-)\\n\")do lines[#lines+1]=line end if#lines==0 then lines[1]=\"\"end return lines end function M.new(text)local lines=split(text)return{lines=lines,line=1,column=0,changed=false,preferredColumn=nil,selection=selection.new(lines)}end function M.text(buffer)return table.concat(buffer.lines,\"\\n\")end function M.current(buffer)return buffer.lines[buffer.line]end function M.clampCursor(buffer)buffer.line=clamp(buffer.line,1,#buffer.lines)buffer.column=clamp(buffer.column,0,#buffer.lines[buffer.line])end function M.move(buffer,lineDelta,columnDelta)buffer.line=clamp(buffer.line+(lineDelta or 0),1,#buffer.lines)buffer.column=clamp((buffer.preferredColumn or buffer.column)+(columnDelta or 0),0,#buffer.lines[buffer.line])if lineDelta and lineDelta~=0 and columnDelta==0 then buffer.column=clamp(buffer.preferredColumn or buffer.column,0,#buffer.lines[buffer.line])end buffer.preferredColumn=buffer.column end function M.gotoLine(buffer,line,column)buffer.line=clamp(tonumber(line)or 1,1,#buffer.lines)buffer.column=clamp(tonumber(column)or 0,0,#buffer.lines[buffer.line])buffer.preferredColumn=buffer.column end function M.selectStart(buffer)buffer.selection.lines=buffer.lines;selection.start(buffer.selection,buffer.line,buffer.column);return buffer end function M.selectTo(buffer,line,column)buffer.selection.lines=buffer.lines;selection.update(buffer.selection,line,column);return buffer end function M.clearSelection(buffer)selection.clear(buffer.selection);return buffer end function M.selectionText(buffer)buffer.selection.lines=buffer.lines;return selection.text(buffer.selection)end function M.copySelection(buffer,clipboard)buffer.selection.lines=buffer.lines;return selection.copy(buffer.selection,clipboard)end function M.deleteSelection(buffer)local range=selection.range(buffer.selection);if not range then return false end local first,last=range.first,range.last local startText=(buffer.lines[first.line]or\"\"):sub(1,first.column)local endText=(buffer.lines[last.line]or\"\"):sub(last.column+1)buffer.lines[first.line]=startText..endText for _=first.line+1,last.line do table.remove(buffer.lines,first.line+1)end buffer.line,buffer.column,buffer.preferredColumn=first.line,first.column,first.column buffer.selection.lines=buffer.lines;selection.clear(buffer.selection);buffer.changed=true;return true end function M.insert(buffer,value)value=value or\"\"if selection.range(buffer.selection)then M.deleteSelection(buffer)end local before,after=M.current(buffer):sub(1,buffer.column),M.current(buffer):sub(buffer.column+1)local parts=split(value)if#parts==1 then buffer.lines[buffer.line]=before..value..after buffer.column=buffer.column+#value else buffer.lines[buffer.line]=before..parts[1]for index=2,#parts-1 do table.insert(buffer.lines,buffer.line+index-1,parts[index])end table.insert(buffer.lines,buffer.line+#parts-1,parts[#parts]..after)buffer.line,buffer.column=buffer.line+#parts-1,#parts[#parts]end buffer.changed,buffer.preferredColumn=true,buffer.column end function M.backspace(buffer)if buffer.column>0 then local line=M.current(buffer)buffer.lines[buffer.line]=line:sub(1,buffer.column-1)..line:sub(buffer.column+1)buffer.column=buffer.column-1 elseif buffer.line>1 then local previous=buffer.lines[buffer.line-1]buffer.lines[buffer.line-1]=previous..M.current(buffer)table.remove(buffer.lines,buffer.line);buffer.line,buffer.column=buffer.line-1,#previous else return false end buffer.changed,buffer.preferredColumn=true,buffer.column;return true end function M.delete(buffer)local line=M.current(buffer)if buffer.column<#line then buffer.lines[buffer.line]=line:sub(1,buffer.column)..line:sub(buffer.column+2)elseif buffer.line<#buffer.lines then buffer.lines[buffer.line]=line..buffer.lines[buffer.line+1];table.remove(buffer.lines,buffer.line+1)else return false end buffer.changed=true;return true end function M.find(buffer,needle,startLine)if not needle or needle==\"\"then return nil end for line=startLine or buffer.line,#buffer.lines do local column=buffer.lines[line]:find(needle,line==buffer.line and buffer.column+1 or 1,true)if column then buffer.line,buffer.column,buffer.preferredColumn=line,column-1,column-1;return line,column-1 end end return nil end local keywords={[\"and\"]=true,[\"break\"]=true,[\"do\"]=true,[\"else\"]=true,[\"elseif\"]=true,[\"end\"]=true,[\"false\"]=true,[\"for\"]=true,[\"function\"]=true,[\"if\"]=true,[\"in\"]=true,[\"local\"]=true,[\"nil\"]=true,[\"not\"]=true,[\"or\"]=true,[\"repeat\"]=true,[\"return\"]=true,[\"then\"]=true,[\"true\"]=true,[\"until\"]=true,[\"while\"]=true}local builtins={print=true,pairs=true,ipairs=true,tonumber=true,tostring=true,type=true,error=true,assert=true,fs=true,term=true,shell=true,peripheral=true,os=true,textutils=true}function M.tokens(line,lua)if not lua then return{{text=line,kind=\"text\"}}end local out,index={},1 local function add(text,kind)if text~=\"\"then out[#out+1]={text=text,kind=kind}end end while index<=#line do local rest=line:sub(index)if rest:sub(1,2)==\"--\"then add(rest,\"comment\");break end local quote=rest:sub(1,1)if quote==\"'\"or quote=='\"'then local finish,escaped=2,false while finish<=#rest do if rest:sub(finish,finish)==quote and not escaped then break end;escaped=rest:sub(finish,finish)==\"\\\\\"and not escaped;if rest:sub(finish,finish)~=\"\\\\\"then escaped=false end;finish=finish+1 end add(rest:sub(1,finish),\"string\");index=index+finish else local word=rest:match(\"^[%a_][%w_]*\")local number=rest:match(\"^%d+%.?%d*\")if word then add(word,keywords[word]and\"keyword\"or(builtins[word]and\"builtin\"or\"text\"));index=index+#word elseif number then add(number,\"number\");index=index+#number else add(rest:sub(1,1),\"text\");index=index+1 end end end return out end return M",
  ["ceetos/lib/terminal.lua"] = "local store=require(\"ceetos.lib.store\")local M,PATH,LIMIT={},\"/ceetos/data/terminal-history.lua\",50 function M.history()return store.read(PATH,{})end function M.add(command)if not command or command==\"\"then return end local history=M.history()if history[#history]~=command then history[#history+1]=command end while#history>LIMIT do table.remove(history,1)end store.write(PATH,history)end function M.complete(prefix,candidates)local result,seen={},{}for _,candidate in ipairs(candidates or{})do if candidate:sub(1,#prefix)==prefix and not seen[candidate]then result[#result+1],seen[candidate]=candidate,true end end table.sort(result);return result end return M",
  ["ceetos/lib/selection.lua"] = "local M={}local function point(line,column)return{line=math.max(1,tonumber(line)or 1),column=math.max(0,tonumber(column)or 0)}end local function before(a,b)return a.line<b.line or(a.line==b.line and a.column<=b.column)end local function norm(a,b)return before(a,b)and a or b,before(a,b)and b or a end function M.new(lines)return{lines=lines or{\"\"},anchor=nil,active=nil}end function M.position(line,column,maxLine,maxColumn)line=math.max(1,math.min(tonumber(maxLine)or line or 1,tonumber(line)or 1))column=math.max(0,tonumber(column)or 0)if maxColumn and line==maxLine then column=math.min(column,maxColumn)end return line,column end function M.start(s,line,column)s.anchor,s.active=point(line,column),point(line,column);return s end function M.update(s,line,column)if s.anchor then s.active=point(line,column)end;return s end function M.clear(s)s.anchor,s.active=nil,nil;return s end function M.range(s)if not s.anchor or not s.active then return nil end local first,last=norm(s.anchor,s.active)if first.line==last.line and first.column==last.column then return nil end return{first=first,last=last}end function M.text(s)local r=M.range(s);if not r then return\"\"end local out={}for line=r.first.line,r.last.line do local value=s.lines[line]or\"\"local from=line==r.first.line and r.first.column+1 or 1 local to=line==r.last.line and r.last.column or#value out[#out+1]=value:sub(from,to)end return table.concat(out,\"\\n\")end function M.copy(s,clipboard)local text=M.text(s);if text~=\"\"and clipboard then clipboard.set(text)end;return text end return M",
  ["ceetos/lib/clipboard.lua"] = "local store=require(\"ceetos.lib.store\")local M,PATH,OUTBOX,LIMIT={},\"/ceetos/data/clipboard.lua\",\"/ceetos-dev/clipboard-out.lua\",16384 local memory local function trim(value)return tostring(value or\"\"):sub(1,LIMIT)end function M.get()if memory~=nil then return memory end local value=store.read(PATH,{text=\"\"})memory=value and value.text or\"\"return memory end function M.set(value)local text=trim(value)memory=text pcall(store.write,PATH,{text=text})if fs and fs.makeDir and fs.open then pcall(function()if not fs.exists(\"/ceetos-dev\")then pcall(fs.makeDir,\"/ceetos-dev\")end local handle=fs.open(OUTBOX,\"w\")if handle then handle.write(textutils.serialize({text=text,queued=os.epoch and os.epoch(\"utc\")or 0}));handle.close()end end)end return text end function M.clear()return M.set(\"\")end function M.copy(value)return M.set(value)end function M.limit()return LIMIT end return M",
  ["ceetos/lib/input.lua"] = "local M={}function M.modifiers()return{ctrl=false,shift=false}end local function nameOf(name)name=tostring(name or\"\")local lower=name:lower()if lower==\"leftctrl\"or lower==\"rightctrl\"or lower==\"ctrl\"then return\"ctrl\"end if lower==\"leftshift\"or lower==\"rightshift\"or lower==\"shift\"then return\"shift\"end return lower end function M.key(state,name)name=nameOf(name)if name==\"ctrl\"then state.ctrl=true elseif name==\"shift\"then state.shift=true end return state end function M.keyUp(state,name)name=nameOf(name)if name==\"ctrl\"then state.ctrl=false elseif name==\"shift\"then state.shift=false end return state end function M.shortcut(state,name)name=nameOf(name)local active=state.ctrl and state.shift and(name==\"c\"or name==\"v\")if active then state.ctrl,state.shift=false,false end return active,name end return M",
  ["ceetos/lib/version.lua"] = "return{major=0,minor=17,patch=1,string=\"0.17.1\"}",
  ["ceetos/lib/crafting.lua"] = "local M={}M.RECIPE_PACK_MAX_BYTES=64*1024 function M.isLocalPeer(peer,computerId)return tostring(peer)==tostring(computerId)end function M.normalise(rows)local out={}for _,row in pairs(type(rows)==\"table\"and rows or{})do if type(row)==\"table\"then local name,count=row.name or row.id,tonumber(row.count or row.amount or row.quantity or 0)or 0 if type(name)==\"string\"and count>0 then out[name]=(out[name]or 0)+math.floor(count)end end end return out end function M.rows(stock,query,filter,recipes)local output,needle,available={},tostring(query or\"\"):lower(),M.normalise(stock)local names={}for name in pairs(available)do names[name]=true end for name in pairs(type(recipes)==\"table\"and recipes or{})do names[name]=true end for name in pairs(names)do local count=available[name]or 0 local craftable=type(recipes)==\"table\"and recipes[name]~=nil local include=needle==\"\"or name:lower():find(needle,1,true)if filter==\"craftable\"then include=include and craftable elseif filter==\"stocked\"then include=include and count>0 end if include then output[#output+1]={name=name,count=count,craftable=craftable,stocked=count>0}end end table.sort(output,function(a,b)return a.name<b.name end)return output end function M.addToCart(cart,name,count)if type(cart)~=\"table\"or type(name)~=\"string\"or name==\"\"then return nil,\"invalid cart item\"end count=tonumber(count)if not count or count<1 then return nil,\"invalid cart quantity\"end count=math.floor(count)for _,row in ipairs(cart)do if row.name==name then row.count=(tonumber(row.count)or 0)+count;return row end end local row={name=name,count=count}cart[#cart+1]=row return row end function M.cartTotals(cart)local items,quantity=0,0 for _,row in ipairs(type(cart)==\"table\"and cart or{})do items=items+1 quantity=quantity+math.max(0,math.floor(tonumber(row.count)or 0))end return items,quantity end function M.acceptedCount(result,requested)local accepted=tonumber(result)requested=tonumber(requested)if not accepted or not requested or requested<1 then return nil,\"invalid request result\"end accepted=math.floor(accepted)if accepted<1 then return nil,\"Stock Ticker accepted no items\"end return math.min(accepted,math.floor(requested))end function M.displayRow(name,count,width)local suffix=\" x\"..tostring(count)width=math.max(#suffix+1,math.floor(tonumber(width)or#suffix+1))if#name+#suffix<=width then return name..suffix end return name:sub(1,math.max(1,width-#suffix-1))..\"…\"..suffix end function M.cancellationStatus(issued)return issued and\"cancelled-unconfirmed\"or\"cancelled\"end local function validReference(name)return type(name)==\"string\"and name:match(\"^#?[%w_.:%-]+$\")~=nil and not name:find(\"##\",1,true)end local function recipeIngredients(recipe,batches)local combined={}local declared=type(recipe.ingredients)==\"table\"and#recipe.ingredients>0 if declared then for _,ingredient in ipairs(recipe.ingredients)do local name=type(ingredient)==\"table\"and ingredient.id or ingredient local count=type(ingredient)==\"table\"and tonumber(ingredient.count or 1)or 1 if validReference(name)then combined[name]=(combined[name]or 0)+batches*math.max(1,math.floor(count or 1))end end else for slot=1,9 do local name=recipe.grid and recipe.grid[slot]if name and name~=false then combined[name]=(combined[name]or 0)+batches end end end local out={}for name,count in pairs(combined)do out[#out+1]={name=name,count=count}end table.sort(out,function(a,b)return a.name<b.name end)return out end function M.recipeInputs(recipe,batches)return recipeIngredients(recipe or{},math.max(1,math.floor(tonumber(batches)or 1)))end function M.validateRecipes(recipes)if type(recipes)~=\"table\"then return nil,\"recipes must return a table\"end for name,recipe in pairs(recipes)do if type(name)~=\"string\"or not name:match(\"^[%w_.:%-]+$\")or type(recipe)~=\"table\"then return nil,\"invalid recipe item id\"end if type(recipe.alternatives)==\"table\"then if#recipe.alternatives<1 then return nil,\"recipe \"..name..\" has no alternatives\"end for _,alternative in ipairs(recipe.alternatives)do local valid,err=M.validateRecipes({[name]=alternative});if not valid then return nil,err end end else if recipe.mode~=\"crafting\"then return nil,\"recipe \"..name..\" must use mode = crafting\"end if type(recipe.address)~=\"string\"or recipe.address==\"\"or#recipe.address>64 then return nil,\"recipe \"..name..\" requires an address\"end local crafter=recipe.address==\"Crafter\"if crafter and type(recipe.grid)~=\"table\"then return nil,\"recipe \"..name..\" requires a 9-slot grid for Crafter\"end if not crafter and type(recipe.ingredients)~=\"table\"and type(recipe.grid)~=\"table\"then return nil,\"recipe \"..name..\" requires ingredients\"end local output=tonumber(recipe.output or 1)if not output or output<1 or output~=math.floor(output)then return nil,\"invalid output for \"..name end for slot=1,9 do local value=recipe.grid and recipe.grid[slot]if value~=nil and value~=false and not validReference(value)then return nil,\"invalid grid slot in \"..name end end for _,ingredient in ipairs(type(recipe.ingredients)==\"table\"and recipe.ingredients or{})do local id,count=type(ingredient)==\"table\"and ingredient.id or ingredient,type(ingredient)==\"table\"and ingredient.count or 1 if not validReference(id)or not tonumber(count)or tonumber(count)<1 then return nil,\"invalid ingredient in \"..name end end end end return recipes end local function dataParser(source,maximum)if type(source)~=\"string\"then return nil,\"recipe data must be text\"end if#source==0 or#source>(maximum or M.RECIPE_PACK_MAX_BYTES)then return nil,\"recipe data exceeds the 64 KiB import limit\"end local state={source=source,index=1,length=#source,depth=0,nodes=0}local function skip()while state.index<=state.length do local char=state.source:sub(state.index,state.index)if char:match(\"%s\")then state.index=state.index+1 elseif state.source:sub(state.index,state.index+1)==\"--\"then local ending=state.source:find(\"\\n\",state.index+2,true)state.index=ending and ending+1 or state.length+1 else return true end end return true end local function fail(message)return nil,message..\" near byte \"..tostring(state.index)end local function identifier()local name=state.source:match(\"^[%a_][%w_]*\",state.index)if name then state.index=state.index+#name end return name end local parseValue local function parseString()local quote=state.source:sub(state.index,state.index);state.index=state.index+1 local out={}while state.index<=state.length do local char=state.source:sub(state.index,state.index);state.index=state.index+1 if char==quote then return table.concat(out)end if char==\"\\\\\"then local escaped=state.source:sub(state.index,state.index);state.index=state.index+1 local values={n=\"\\n\",r=\"\\r\",t=\"\\t\",[\"\\\\\"]=\"\\\\\",[\"\\\"\"]=\"\\\"\",[\"'\"]=\"'\"}if not values[escaped]then return fail(\"unsupported string escape\")end out[#out+1]=values[escaped]elseif char:byte()<32 then return fail(\"control character in string\")else out[#out+1]=char end end return fail(\"unterminated string\")end local function parseTable()state.depth=state.depth+1 if state.depth>32 then return fail(\"recipe data is nested too deeply\")end state.index=state.index+1 local out,nextIndex,keys={},1,{}skip()while state.index<=state.length and state.source:sub(state.index,state.index)~=\"}\"do state.nodes=state.nodes+1 if state.nodes>4096 then return fail(\"recipe data has too many values\")end local key,value,err local start=state.index if state.source:sub(state.index,state.index)==\"[\"then state.index=state.index+1;key,err=parseValue();if err then return nil,err end skip();if state.source:sub(state.index,state.index)~=\"]\"then return fail(\"missing closing recipe key bracket\")end state.index=state.index+1;skip();if state.source:sub(state.index,state.index)~=\"=\"then return fail(\"missing recipe key assignment\")end state.index=state.index+1;skip();value,err=parseValue();if err then return nil,err end else local named=identifier();skip()if named and state.source:sub(state.index,state.index)==\"=\"then key,state.index=named,state.index+1;skip();value,err=parseValue();if err then return nil,err end else state.index=start;value,err=parseValue();if err then return nil,err end key,nextIndex=nextIndex,nextIndex+1 end end if type(key)~=\"string\"and type(key)~=\"number\"then return fail(\"recipe table key must be text or a number\")end local signature=type(key)..\":\"..tostring(key)if keys[signature]then return fail(\"duplicate recipe table key\")end keys[signature],out[key]=true,value skip();local separator=state.source:sub(state.index,state.index)if separator==\",\"or separator==\";\"then state.index=state.index+1;skip()elseif separator~=\"}\"then return fail(\"expected recipe table separator\")end end if state.source:sub(state.index,state.index)~=\"}\"then return fail(\"unterminated recipe table\")end state.index,state.depth=state.index+1,state.depth-1 return out end parseValue=function()skip();local char=state.source:sub(state.index,state.index)if char==\"{\"then return parseTable()end if char==\"\\\"\"or char==\"'\"then return parseString()end local number=state.source:match(\"^-?%d+\",state.index)if number then state.index=state.index+#number;return tonumber(number)end local name=identifier()if name==\"true\"then return true elseif name==\"false\"then return false elseif name==\"nil\"then return nil elseif name then return fail(\"bare recipe values are not allowed\")end return fail(\"invalid recipe value\")end skip()if identifier()~=\"return\"then return fail(\"recipe data must start with return\")end local value,err=parseValue();if err then return nil,err end skip();if state.index<=state.length then return fail(\"unexpected content after recipe table\")end return value end local function validTags(tags)if tags==nil then return{}end if type(tags)~=\"table\"then return nil,\"recipe tags must be a table\"end local out={}for tag,members in pairs(tags)do local key=tostring(tag):gsub(\"^#\",\"\")if not key:match(\"^[%w_.:%-]+$\")or type(members)~=\"table\"or#members<1 then return nil,\"invalid recipe tag \"..tostring(tag)end out[key]={}for _,member in ipairs(members)do if not validReference(member)or tostring(member):sub(1,1)==\"#\"then return nil,\"invalid member of #\"..key end out[key][#out[key]+1]=member end table.sort(out[key])end return out end function M.validateRecipeGraph(recipes,tags)local tagMap,tagErr=validTags(tags);if not tagMap then return nil,tagErr end local visiting,complete={},{}local function visit(name)if complete[name]then return true end if visiting[name]then return nil,\"recipe cycle at \"..name end local recipe=recipes[name]if type(recipe)==\"table\"and type(recipe.alternatives)==\"table\"then recipe=recipe.alternatives[1]end if not recipe then return true end visiting[name]=true for _,input in ipairs(recipeIngredients(recipe,1))do local ingredient=input.name local members=ingredient:sub(1,1)==\"#\"and tagMap[ingredient:sub(2)]or{ingredient}for _,member in ipairs(members or{})do if recipes[member]then local ok,err=visit(member);if not ok then return nil,err end end end end visiting[name],complete[name]=nil,true return true end for name in pairs(recipes)do local ok,err=visit(name);if not ok then return nil,err end end return true end function M.parseRecipeOverlay(source)local value,err=dataParser(source,M.RECIPE_PACK_MAX_BYTES)if not value then return nil,err end if type(value)~=\"table\"then return nil,\"recipe overlay must return a table\"end local recipes,tags if value.schema==1 and type(value.recipes)==\"table\"then recipes,tags=value.recipes,value.tags or{}else recipes,tags=value,{}end local valid,validationErr=M.validateRecipes(recipes)if not valid then return nil,validationErr end local tagMap,tagsErr=validTags(tags);if not tagMap then return nil,tagsErr end local graphOk,graphErr=M.validateRecipeGraph(recipes,tagMap)if not graphOk then return nil,graphErr end return{schema=1,recipes=recipes,tags=tagMap}end function M.parseRecipeFile(source)local overlay,err=M.parseRecipeOverlay(source)return overlay and overlay.recipes or nil,err end function M.parseRecipePack(source)local pack,err=dataParser(source,M.RECIPE_PACK_MAX_BYTES)if not pack then return nil,err end if type(pack)~=\"table\"or pack.schema~=1 or type(pack.recipes)~=\"table\"then return nil,\"recipe pack must return { schema = 1, recipes = { ... } }\"end local valid,validationErr=M.validateRecipes(pack.recipes)if not valid then return nil,validationErr end local tagMap,tagsErr=validTags(pack.tags or{});if not tagMap then return nil,tagsErr end local graphOk,graphErr=M.validateRecipeGraph(pack.recipes,tagMap)if not graphOk then return nil,graphErr end return{schema=1,recipes=pack.recipes,tags=tagMap}end function M.recipeEqual(left,right)if type(left)~=\"table\"or type(right)~=\"table\"then return false end if type(left.alternatives)==\"table\"then left=left.alternatives[1]end if type(right.alternatives)==\"table\"then right=right.alternatives[1]end if not left or not right or left.mode~=right.mode or left.kind~=right.kind or left.output~=right.output or left.address~=right.address then return false end for slot=1,9 do if left.grid and right.grid and left.grid[slot]~=right.grid[slot]then return false end end local a,b=recipeIngredients(left,1),recipeIngredients(right,1)if#a~=#b then return false end for index=1,#a do if a[index].name~=b[index].name or a[index].count~=b[index].count then return false end end return true end function M.reviewRecipePack(existing,incoming)local validExisting,existingErr=M.validateRecipes(existing)if not validExisting then return nil,existingErr end local validIncoming,incomingErr=M.validateRecipes(incoming)if not validIncoming then return nil,incomingErr end local rows,counts={},{new=0,unchanged=0,conflict=0,invalid=0}for name,recipe in pairs(incoming)do local prior=existing[name]local status=not prior and\"new\"or(M.recipeEqual(prior,recipe)and\"unchanged\"or\"conflict\")counts[status]=counts[status]+1 rows[#rows+1]={name=name,status=status,incoming=recipe,existing=prior,selected=status==\"new\"}end table.sort(rows,function(a,b)return a.name<b.name end)return{rows=rows,counts=counts}end local function cloneRecipe(recipe)if type(recipe)==\"table\"and type(recipe.alternatives)==\"table\"then recipe=recipe.alternatives[1]end local copy={mode=recipe.mode,kind=recipe.kind,output=recipe.output,address=recipe.address,grid={},ingredients={}}for slot=1,9 do copy.grid[slot]=recipe.grid and recipe.grid[slot]end for _,input in ipairs(recipe.ingredients or{})do copy.ingredients[#copy.ingredients+1]={id=input.id,count=input.count,tag=input.tag}end return copy end function M.mergeRecipePack(existing,review,existingTags,incomingTags)if type(existing)~=\"table\"or type(review)~=\"table\"or type(review.rows)~=\"table\"then return nil,\"invalid recipe import review\"end local merged,imported={},0 for name,recipe in pairs(existing)do merged[name]=cloneRecipe(recipe)end for _,row in ipairs(review.rows)do if row.status==\"new\"and row.selected==true then merged[row.name],imported=cloneRecipe(row.incoming),imported+1 elseif row.status==\"conflict\"and row.selected==true then merged[row.name],imported=cloneRecipe(row.incoming),imported+1 end end local tags={}for name,members in pairs(existingTags or{})do tags[name]=members end for name,members in pairs(incomingTags or{})do tags[name]=members end local valid,err=M.validateRecipes(merged);if not valid then return nil,err end local graphOk,graphErr=M.validateRecipeGraph(merged,tags);if not graphOk then return nil,graphErr end return merged,imported,tags end function M.encodeRecipeFile(recipes,tags)local valid,err=M.validateRecipes(recipes);if not valid then return nil,err end local tagMap,tagsErr=validTags(tags or{});if not tagMap then return nil,tagsErr end local graphOk,graphErr=M.validateRecipeGraph(recipes,tagMap);if not graphOk then return nil,graphErr end local ok,encoded=pcall(textutils.serialise,{schema=1,recipes=recipes,tags=tagMap},{compact=true})if not ok or type(encoded)~=\"string\"then return nil,\"could not serialise recipes\"end return\"return \"..encoded..\"\\n\"end function M.writeRecipeFile(path,recipes,tags)if type(path)~=\"string\"or path==\"\"then return false,\"invalid recipe file path\"end local raw,encodeErr=M.encodeRecipeFile(recipes,tags);if not raw then return false,encodeErr end local parent=fs.getDir(path);if parent~=\"\"and not fs.exists(parent)then fs.makeDir(parent)end local temporary,backup=path..\".new\",path..\".bak\"if fs.exists(temporary)then fs.delete(temporary)end local handle=fs.open(temporary,\"w\");if not handle then return false,\"could not stage recipes\"end handle.write(raw);handle.close()local check=fs.open(temporary,\"r\");local staged=check and check.readAll()or nil;if check then check.close()end if not M.parseRecipeOverlay(staged or\"\")then if fs.exists(temporary)then fs.delete(temporary)end;return false,\"could not validate staged recipes\"end if fs.exists(backup)then fs.delete(backup)end if fs.exists(path)then fs.move(path,backup)end local moved,moveErr=pcall(fs.move,temporary,path)if not moved then if fs.exists(backup)and not fs.exists(path)then fs.move(backup,path)end;if fs.exists(temporary)then fs.delete(temporary)end;return false,tostring(moveErr)end if fs.exists(backup)then fs.delete(backup)end return true end local function selectedRecipe(entry)if type(entry)==\"table\"and type(entry.alternatives)==\"table\"then return entry.alternatives[1]end return entry end local function tagMembers(tags,reference)if reference:sub(1,1)~=\"#\"then return{reference}end local members=tags[reference:sub(2)]if type(members)~=\"table\"or#members==0 then return nil,\"no known members for \"..reference end return members end local function chooseMember(reference,tags,available,recipes)local members,err=tagMembers(tags,reference);if not members then return nil,err end local best for _,member in ipairs(members)do if(available[member]or 0)>0 then return member end if recipes[member]and not best then best=member end end return best,best and nil or(\"no stocked or craftable member for \"..reference)end local function requesterGrid(recipe,resolved,tags,available,recipes)local grid={}for slot=1,9 do local value=recipe.grid and recipe.grid[slot]if type(value)==\"string\"and value:sub(1,1)==\"#\"then local concrete=resolved[value]if not concrete then concrete=select(1,chooseMember(value,tags,available,recipes))end if not concrete then return nil,\"no concrete item available for requester tag \"..value end grid[slot]=concrete else grid[slot]=value end end return grid end function M.plan(recipes,stock,item,quantity,options)quantity=tonumber(quantity)if type(item)~=\"string\"or item==\"\"or not quantity or quantity<1 or quantity~=math.floor(quantity)then return nil,\"invalid item or quantity\"end local valid,errorText=M.validateRecipes(recipes)if not valid then return nil,errorText end options=type(options)==\"table\"and options or{}local available,plan,visiting,tags=M.normalise(stock),{},{},type(options.tags)==\"table\"and options.tags or{}local function requireItem(name,needed)local used=options.forceRoot==true and name==item and 0 or math.min(available[name]or 0,needed)available[name]=(available[name]or 0)-used local missing=needed-used if missing<=0 then return true end if visiting[name]then return nil,\"recipe cycle at \"..name end local recipe=selectedRecipe(recipes[name])if not recipe then return nil,\"missing recipe for \"..name..\" (need \"..tostring(missing)..\")\"end if recipe.special or not recipe.output or not recipe.address then return nil,\"recipe \"..name..\" is not supported by Crafting Queue\"end visiting[name]=true local batches=math.ceil(missing/recipe.output)local inputs,resolved={},{}for _,ingredient in ipairs(recipeIngredients(recipe,batches))do local concrete,resolveErr=chooseMember(ingredient.name,tags,available,recipes)if not concrete then return nil,resolveErr end inputs[#inputs+1]={name=concrete,count=ingredient.count,source=ingredient.name,tag=ingredient.name:sub(1,1)==\"#\"and ingredient.name or nil}if ingredient.name:sub(1,1)==\"#\"then resolved[ingredient.name]=concrete end local ok,err=requireItem(concrete,ingredient.count)if not ok then return nil,err end end visiting[name]=nil local produced=batches*recipe.output available[name]=(available[name]or 0)+produced-missing local dispatch=recipe.address==\"Crafter\"and\"requester\"or\"package\"if dispatch==\"requester\"and type(recipe.grid)~=\"table\"then return nil,\"Crafter recipe \"..name..\" has no 3x3 grid\"end local grid,gridErr=recipe.grid,nil if dispatch==\"requester\"then grid,gridErr=requesterGrid(recipe,resolved,tags,available,recipes)if not grid then return nil,gridErr end end plan[#plan+1]={name=name,batches=batches,produced=produced,requested=missing,address=recipe.address,kind=recipe.kind,dispatch=dispatch,grid=grid,sourceGrid=recipe.grid,inputs=inputs,}return true end local ok,err=requireItem(item,quantity)return ok and plan or nil,err end function M.validateExecutionPlan(plan)if type(plan)~=\"table\"or#plan<1 or#plan>96 then return nil,\"invalid remote recipe plan\"end for _,step in ipairs(plan)do if type(step)~=\"table\"or not validReference(step.name)or tostring(step.name):sub(1,1)==\"#\"then return nil,\"invalid remote recipe output\"end if type(step.address)~=\"string\"or step.address==\"\"or#step.address>64 or step.address:find(\"[%c]\")then return nil,\"invalid remote recipe address\"end if step.dispatch~=\"requester\"and step.dispatch~=\"package\"then return nil,\"invalid remote recipe route\"end if(step.address==\"Crafter\")~=(step.dispatch==\"requester\")then return nil,\"invalid remote recipe executor\"end for _,field in ipairs({\"batches\",\"produced\",\"requested\"})do local value=tonumber(step[field])if not value or value<1 or value~=math.floor(value)or value>65536 then return nil,\"invalid remote recipe quantity\"end end if step.dispatch==\"requester\"then if type(step.grid)~=\"table\"then return nil,\"remote Crafter recipe has no grid\"end for slot=1,9 do local value=step.grid[slot]if value~=nil and value~=false and not validReference(value)then return nil,\"invalid remote recipe grid\"end if type(value)==\"string\"and value:sub(1,1)==\"#\"then return nil,\"remote requester grid contains unresolved tag\"end end end if type(step.inputs)~=\"table\"or#step.inputs>64 then return nil,\"invalid remote recipe inputs\"end for _,input in ipairs(step.inputs)do if type(input)~=\"table\"or not validReference(input.name)or tostring(input.name):sub(1,1)==\"#\"then return nil,\"invalid remote recipe input\"end local count=tonumber(input.count)if not count or count<1 or count~=math.floor(count)or count>65536 then return nil,\"invalid remote recipe input quantity\"end if input.source~=nil and not validReference(input.source)then return nil,\"invalid remote recipe input source\"end end end return plan end return M",
  ["ceetos/lib/craft_sources.lua"] = "local M={}local function isType(value,needle)return tostring(value or\"\"):lower():find(needle,1,true)~=nil end function M.kind(value)if type(value)==\"string\"then return{transport=\"local\",name=value}end return type(value)==\"table\"and value or nil end function M.key(value)value=M.kind(value)if not value then return nil end return tostring(value.transport or\"local\")..\":\"..tostring(value.peer or\"\")..\":\"..tostring(value.name or\"\")end function M.label(value)value=M.kind(value)if not value then return\"Not selected\"end if value.transport==\"peer\"then return\"Peer \"..tostring(value.peer)..\" / \"..tostring(value.name)end return tostring(value.name)end function M.discoverLocal()local tickers,requesters={},{}for _,name in ipairs(peripheral.getNames())do local typeName=peripheral.getType(name)if isType(typeName,\"stockticker\")then tickers[#tickers+1]={transport=\"local\",name=name,type=typeName,label=\"Local / \"..name}elseif isType(typeName,\"redstonerequester\")then requesters[#requesters+1]={transport=\"local\",name=name,type=typeName,label=\"Local / \"..name}end end table.sort(tickers,function(a,b)return a.name<b.name end)table.sort(requesters,function(a,b)return a.name<b.name end)return tickers,requesters end function M.matches(value,kind)value=M.kind(value)if not value or type(value.name)~=\"string\"then return false end local needle=(kind==\"ticker\"or kind==\"stockticker\")and\"stockticker\"or\"redstonerequester\"return isType(value.type,needle)end return M",
  ["ceetos/lib/program_capabilities.lua"] = "local store=require(\"ceetos.lib.store\")local auth=require(\"ceetos.lib.auth\")local audit=require(\"ceetos.lib.audit\")local M={}local PATH=\"/ceetos/data/program-capabilities.lua\"local SCHEMA=1 local SCRATCH_ROOT=\"/ceetos/data/programs\"local PROTECTED_ROOTS={\"/ceetos\",\"/ceetos-dev\",\"/rom\",}local READ_ONLY_METHODS={getAngles=true,getSpeed=true,getStress=true,getStressCapacity=true,getTargetSpeed=true,getItemDetail=true,getInventoryName=true,getMetadata=true,getFluidDetail=true,getEnergy=true,getCursorPos=true,getSize=true,getTextScale=true,isRunning=true,isPresent=true,list=true,size=true,}local function now()return os.epoch(\"utc\")end local function copy(value,seen)if type(value)~=\"table\"then return value end seen=seen or{}if seen[value]then return seen[value]end local result={}seen[value]=result for key,item in pairs(value)do result[copy(key,seen)]=copy(item,seen)end return result end local function defaultConfig()return{schema=SCHEMA,programs={}}end local function normalise(path)if type(path)~=\"string\"or path==\"\"or#path>240 or path:find(\"[%z\\1-\\31]\")then return nil,\"invalid program path\"end local parts={}for part in path:gmatch(\"[^/]+\")do if part==\"..\"then if#parts>0 then table.remove(parts)end elseif part~=\".\"and part~=\"\"then parts[#parts+1]=part end end return\"/\"..table.concat(parts,\"/\")end local function readSource(path)local handle,err=fs.open(path,\"r\")if not handle then return nil,err or\"could not read program\"end local source=handle.readAll()handle.close()return source end local function legacyHash(source)local hash=2166136261 for index=1,#source do hash=bit32.bxor(hash,source:byte(index))hash=(hash*16777619)%4294967296 end return string.format(\"fnv1a32:%08x\",hash)end local function programId(path)return\"p-\"..legacyHash(path):match(\":(%x+)$\")end local function loadConfig()local config=store.readFresh(PATH,defaultConfig())if type(config)~=\"table\"then return defaultConfig()end if type(config.programs)~=\"table\"then config.programs={}end config.schema=SCHEMA return config end local function saveConfig(config)local ok,err=store.writeAtomic(PATH,config)assert(ok,\"could not save program capabilities: \"..tostring(err))end local function adminActor()if auth.refreshSession then auth.refreshSession()end auth.require(\"admin\")return auth.current and auth.current.name or\"admin\"end local function pathWithin(path,root)return path==root or path:sub(1,#root+1)==root..\"/\"end local function protectedProgramPath(path)if path==\"/startup.lua\"then return true end for _,root in ipairs(PROTECTED_ROOTS)do if pathWithin(path,root)then return true end end return false end local function normaliseProgramPath(path)local normalized,err=normalise(path)if not normalized then return nil,err end if protectedProgramPath(normalized)then return nil,\"protected CeetOS/CraftOS program path\"end if normalized:sub(-4):lower()~=\".lua\"then return nil,\"program must be a Lua file\"end if not fs.exists(normalized)or fs.isDir(normalized)then return nil,\"program file not found\"end return normalized end local function defaultRecord(path,source,owner)return{path=path,id=programId(path),sourceHash=legacyHash(source),hashKind=\"fnv1a32-legacy-integrity-marker\",owner=owner or\"unassigned\",trust=\"sandboxed\",capabilities={scratch=true,peripherals={}},createdAt=now(),updatedAt=now(),}end local function cleanMethods(methods)if type(methods)~=\"table\"then return nil,\"methods must be a list\"end local seen,result={},{}for _,method in ipairs(methods)do if type(method)~=\"string\"or not READ_ONLY_METHODS[method]then return nil,\"method is not an approved read-only capability\"end if not seen[method]then seen[method]=true;result[#result+1]=method end end if#result==0 then return nil,\"at least one read-only method is required\"end table.sort(result)return result end local function recordIdAvailable(config,id,path)for savedPath,saved in pairs(config.programs)do if savedPath~=path and type(saved)==\"table\"and saved.id==id then return false end end return true end local function recordFrom(config,path,source)local saved=config.programs[path]local currentHash=legacyHash(source)local id=programId(path)if not recordIdAvailable(config,id,path)then return nil,nil,\"program capability ID collision; choose a different program path\"end if type(saved)==\"table\"and saved.sourceHash==currentHash and saved.path==path then local record=copy(saved)record.id=id record.hashKind=\"fnv1a32-legacy-integrity-marker\"record.capabilities=type(record.capabilities)==\"table\"and record.capabilities or{}record.capabilities.scratch=true record.capabilities.peripherals=type(record.capabilities.peripherals)==\"table\"and record.capabilities.peripherals or{}return record,false,nil end local record=defaultRecord(path,source,type(saved)==\"table\"and saved.owner or nil)record.stale=type(saved)==\"table\"return record,record.stale,nil end local function scratchPath(record)return SCRATCH_ROOT..\"/\"..record.id end local function normaliseScratch(path,root)if type(path)~=\"string\"or#path>240 or path:find(\"[%z\\1-\\31]\")then return nil end local candidate=path:sub(1,1)==\"/\"and path or root..\"/\"..path local normalized=normalise(candidate)if not normalized or not pathWithin(normalized,root)then return nil end return normalized end local function safeTerm()local source=term return{write=source.write,blit=source.blit,clear=source.clear,clearLine=source.clearLine,scroll=source.scroll,getSize=source.getSize,getCursorPos=source.getCursorPos,setCursorPos=source.setCursorPos,getCursorBlink=source.getCursorBlink,setCursorBlink=source.setCursorBlink,setTextColor=source.setTextColor,setTextColour=source.setTextColour,getTextColor=source.getTextColor,getTextColour=source.getTextColour,setBackgroundColor=source.setBackgroundColor,setBackgroundColour=source.setBackgroundColour,getBackgroundColor=source.getBackgroundColor,getBackgroundColour=source.getBackgroundColour,isColor=source.isColor,isColour=source.isColour,}end local function safeTextutils()return{serialise=textutils.serialise,serialize=textutils.serialize,serialiseJSON=textutils.serialiseJSON,serializeJSON=textutils.serializeJSON,unserialiseJSON=textutils.unserialiseJSON,unserializeJSON=textutils.unserializeJSON,formatTime=textutils.formatTime,urlEncode=textutils.urlEncode,}end local function tableCopy(value)local output={}for key,item in pairs(value or{})do output[key]=item end return output end local function safeFilesystem(record,actor,deny)local root=scratchPath(record)if not fs.exists(root)then local made,makeErr=pcall(fs.makeDir,root)if not made or makeErr==false then error(\"could not initialise program scratch storage\",2)end end local function target(path)local value=normaliseScratch(path,root)if not value then deny(\"filesystem path\")end return value end local function mutable(path)local value=target(path)if value==root then deny(\"program scratch root\")end return value end local proxy={}function proxy.exists(path)return fs.exists(target(path))end function proxy.isDir(path)return fs.isDir(target(path))end function proxy.list(path)return fs.list(target(path))end function proxy.getSize(path)return fs.getSize(target(path))end function proxy.open(path,mode)mode=tostring(mode or\"r\")if mode~=\"r\"and mode~=\"rb\"and mode~=\"w\"and mode~=\"wb\"and mode~=\"a\"and mode~=\"ab\"then deny(\"filesystem mode\")end return fs.open((mode==\"r\"or mode==\"rb\")and target(path)or mutable(path),mode)end function proxy.makeDir(path)return fs.makeDir(mutable(path))end function proxy.delete(path)return fs.delete(mutable(path))end function proxy.move(from,to)return fs.move(mutable(from),mutable(to))end function proxy.copy(from,to)return fs.copy(mutable(from),mutable(to))end function proxy.combine(a,b)local value=normaliseScratch(tostring(a or\"\")..\"/\"..tostring(b or\"\"),root)if not value then deny(\"filesystem path\")end return value end function proxy.getDir(path)return fs.getDir(target(path))end function proxy.getName(path)return fs.getName(target(path))end return proxy end local function safePeripheral(record,deny)local grants=record.trust==\"trusted\"and record.capabilities and record.capabilities.peripherals or{}local function methodsFor(name)local grant=type(grants)==\"table\"and grants[name]or nil local allowed={}for _,method in ipairs(type(grant)==\"table\"and grant.methods or{})do if READ_ONLY_METHODS[method]then allowed[method]=true end end return allowed end local proxy={}function proxy.getNames()local result={}for name in pairs(grants or{})do local methods=methodsFor(name)if next(methods)and peripheral.isPresent(name)then result[#result+1]=name end end table.sort(result)return result end function proxy.isPresent(name)return next(methodsFor(name))~=nil and peripheral.isPresent(name)or false end function proxy.getType(name)if next(methodsFor(name))==nil then deny(\"peripheral \"..tostring(name))end return peripheral.getType(name)end function proxy.getMethods(name)local result={}for method in pairs(methodsFor(name))do result[#result+1]=method end if#result==0 then deny(\"peripheral \"..tostring(name))end table.sort(result)return result end function proxy.wrap(name)local allowed=methodsFor(name)if next(allowed)==nil then deny(\"peripheral \"..tostring(name))end local wrapped={}for method in pairs(allowed)do wrapped[method]=function(...)local raw=peripheral.wrap(name)if not raw or type(raw[method])~=\"function\"then error(\"granted peripheral is unavailable\",2)end local args={...}if args[1]==wrapped then table.remove(args,1)end return raw[method](table.unpack(args))end end return wrapped end return proxy end function M.normaliseProgramPath(path)return normaliseProgramPath(path)end function M.legacySourceHash(source)assert(type(source)==\"string\",\"source must be a string\")return legacyHash(source)end function M.isReadOnlyMethod(method)return READ_ONLY_METHODS[method]==true end function M.describe(path)local normalized,err=normaliseProgramPath(path)if not normalized then return nil,err end local source,readErr=readSource(normalized)if not source then return nil,readErr end local record,_,recordErr=recordFrom(loadConfig(),normalized,source)if not record then return nil,recordErr end return copy(record)end function M.create(path,owner)local actor=adminActor()local normalized,err=normaliseProgramPath(path)assert(normalized,err)if owner~=nil then assert(type(owner)==\"string\"and owner:match(\"^[%w_.%-]+$\")and#owner<=64,\"invalid program owner\")end local source=assert(readSource(normalized))local config=loadConfig()assert(recordIdAvailable(config,programId(normalized),normalized),\"program capability ID collision; choose a different program path\")local record=defaultRecord(normalized,source,owner or actor)config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.capability_create\",{path=normalized,owner=record.owner})return copy(record)end function M.setTrust(path,trust)local actor=adminActor()assert(trust==\"sandboxed\"or trust==\"trusted\",\"invalid program trust state\")local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)record.trust,record.updatedAt=trust,now()if trust~=\"trusted\"then record.capabilities.peripherals={}end config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.trust\",{path=normalized,trust=trust})return copy(record)end function M.setPortableTrust(path,mountToken,durationMs)local actor=adminActor()local normalized,err=normaliseProgramPath(path)assert(normalized,err)assert(type(mountToken)==\"string\"and(mountToken:match(\"^disk%-%w[%w%-%_]*:%d+$\")or mountToken:match(\"^drive%-%w[%w%-%_]*:%d+$\")),\"invalid removable-media mount token\")durationMs=math.max(60000,math.min(8*60*60*1000,math.floor(tonumber(durationMs)or 15*60*1000)))local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)record.portable={token=mountToken,expiresAt=now()+durationMs,grantedBy=actor}record.updatedAt=now()config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.portable_trust\",{path=normalized,durationMs=durationMs})return copy(record)end function M.hasPortableTrust(path,mountToken)if type(mountToken)~=\"string\"then return false end local record,err=M.describe(path)if not record then return false,err end local portable=type(record.portable)==\"table\"and record.portable or nil return portable~=nil and portable.token==mountToken and tonumber(portable.expiresAt or 0)>now(),record end function M.setOwner(path,owner)local actor=adminActor()assert(type(owner)==\"string\"and owner:match(\"^[%w_.%-]+$\")and#owner<=64,\"invalid program owner\")local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)record.owner,record.updatedAt=owner,now()config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.owner\",{path=normalized,owner=owner})return copy(record)end function M.grantReadOnlyPeripheral(path,name,methods)local actor=adminActor()assert(type(name)==\"string\"and name~=\"\"and#name<=128 and not name:find(\"[%z\\1-\\31]\"),\"invalid peripheral name\")local clean,methodErr=cleanMethods(methods)assert(clean,methodErr)local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)assert(record.trust==\"trusted\",\"admin must trust the program before granting peripherals\")record.capabilities.peripherals[name]={methods=clean}record.updatedAt=now()config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.peripheral_grant\",{path=normalized,peripheral=name,methods=clean})return copy(record)end function M.revokePeripheral(path,name)local actor=adminActor()local normalized,err=normaliseProgramPath(path)assert(normalized,err)local source=assert(readSource(normalized))local config=loadConfig()local record,_,recordErr=recordFrom(config,normalized,source)assert(record,recordErr)record.capabilities.peripherals[name]=nil record.updatedAt=now()config.programs[normalized]=record saveConfig(config)audit.log(actor,\"program.peripheral_revoke\",{path=normalized,peripheral=tostring(name)})return copy(record)end function M.viewerEnvironment(path,actor)local record,err=M.describe(path)if not record then return nil,err end actor=actor or\"viewer\"local denied={}local function deny(action)if not denied[action]then denied[action]=true audit.log(actor,\"program.denied\",{path=record.path,action=action})end error(\"permission denied: \"..action,3)end local function pullEvent(filter)while true do local event={os.pullEventRaw(filter)}if event[1]~=\"terminate\"then return table.unpack(event)end end end local safeOs={pullEvent=pullEvent,startTimer=os.startTimer,cancelTimer=os.cancelTimer,clock=os.clock,time=os.time,day=os.day,epoch=os.epoch,getComputerID=os.getComputerID,getComputerLabel=os.getComputerLabel,}local environment={_VERSION=_VERSION,assert=assert,error=error,ipairs=ipairs,next=next,pairs=pairs,pcall=pcall,select=select,tonumber=tonumber,tostring=tostring,type=type,xpcall=xpcall,print=print,printError=printError,read=read,write=write,math=tableCopy(math),string=tableCopy(string),table=tableCopy(table),coroutine=tableCopy(coroutine),bit32=tableCopy(bit32),utf8=tableCopy(utf8),keys=tableCopy(keys),colors=tableCopy(colors),colours=tableCopy(colours or colors),term=safeTerm(),textutils=safeTextutils(),os=safeOs,fs=safeFilesystem(record,actor,deny),peripheral=safePeripheral(record,deny),}return setmetatable(environment,{__index=function()return nil end}),record end function M.loadViewer(path,actor)local environment,record=M.viewerEnvironment(path,actor)if not environment then return nil,record end local chunk,err=loadfile(record.path,nil,environment)if not chunk then audit.log(actor or\"viewer\",\"program.denied\",{path=record.path,action=\"load\"})return nil,err end return chunk,record end function M.scratchPath(path)local record,err=M.describe(path)if not record then return nil,err end return scratchPath(record)end M.PATH=PATH M.SCHEMA=SCHEMA M.HASH_KIND=\"fnv1a32-legacy-integrity-marker\"return M",
  ["ceetos/bin/ceetver.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local ok,version=pcall(require,\"ceetos.lib.version\")print(\"CeetOS \"..(ok and version.string or\"0.12.0\"))",
  ["ceetos/bin/ceetdevices.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local peripherals=require(\"ceetos.lib.peripherals\")local shared={}for _,item in ipairs(peripherals.describe())do shared[item.name]=item.mode end for _,item in ipairs(peripherals.listLocal())do print(item.name..\"\\t\"..tostring(item.type or\"unknown\")..\"\\t\"..(shared[item.name]or\"not shared\"))end",
  ["ceetos/bin/ceetcraft.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth,store,crafting=require(\"ceetos.lib.auth\"),require(\"ceetos.lib.store\"),require(\"ceetos.lib.crafting\")local telemetryOk,telemetry=pcall(require,\"ceetos.lib.telemetry\")if telemetryOk and telemetry and telemetry.markActivity then telemetry.markActivity(\"crafting queue\")end local terminalUi=require(\"ceetos.lib.terminal_ui\")local canMutate=auth.allowed(\"operator\")local STATE,COMMANDS=\"/ceetos/data/crafting-state.lua\",\"/ceetos/data/crafting-commands\"local query,filter,focus,selectedStock,selectedCart,buttonIndex,actionPage=\"\",\"all\",\"stock\",1,1,1,1 local RECIPE_FILE,RECIPE_IMPORTS=\"/ceetos/data/recipes.lua\",\"/ceetos/data/recipe-imports.lua\"local modal,pending,serial,armedAction,lastRowClick,feedback=nil,{},0,nil,nil,nil local importReview,importScroll,importArmed=nil,0,nil local actions={{label=\"Add\",action=\"add\"},{label=\"Edit\",action=\"edit\"},{label=\"Del\",action=\"delete\"},{label=\"Craft\",action=\"mode\"},{label=\"Ord D\",action=\"destination\"},{label=\"Sources\",action=\"sources\"},{label=\"Find\",action=\"search\"},{label=\"Filt\",action=\"filter\"},{label=\"R\",action=\"refresh\"},{label=\"Send O\",action=\"submit\"},{label=\"Retry\",action=\"retry\"},{label=\"Can C\",action=\"cancel\"},{label=\"Back\",action=\"back\"},}local function state()store.invalidate(STATE)return store.read(STATE,{stock={},cart={},queue={},retries={},acknowledgements={},config={orderAddress=\"Order\"},history={}})end local function clipped(value,width)return terminalUi.clip(value,math.max(1,tonumber(width)or 1),\"~\")end local function queueCommand(action,data,label)feedback=nil serial=serial+1 local token=\"craft-ui-\"..tostring(os.epoch(\"utc\"))..\"-\"..tostring(serial)if not fs.exists(COMMANDS)then fs.makeDir(COMMANDS)end data=data or{};data.action,data.token=action,token local handle=fs.open(fs.combine(COMMANDS,token..\".lua\"),\"w\")if not handle then return false,\"could not queue \"..tostring(label or action)end handle.write(textutils.serialise(data));handle.close()pending[token]={label=label or action,at=os.epoch(\"utc\")}return true end local function cleanPending(s)for token,row in pairs(pending)do local acknowledgement=(s.acknowledgements or{})[token]if acknowledgement then pending[token]=nil if acknowledgement.ok~=true then feedback=\"Cannot \"..row.label..\": \"..tostring(acknowledgement.error or\"request was rejected\")end elseif os.epoch(\"utc\")-row.at>5000 then pending[token]=nil;feedback=\"Crafting service did not acknowledge \"..row.label end end end local function pendingText()for _,row in pairs(pending)do return\"Pending: \"..row.label end return feedback end local function startModal(kind,label,value,replaceOnInput)modal={kind=kind,label=label,value=tostring(value or\"\"),replaceOnInput=replaceOnInput==true}end local function recordRecipeImport(entry)local history=store.read(RECIPE_IMPORTS,{})history[#history+1]=entry while#history>16 do table.remove(history,1)end store.write(RECIPE_IMPORTS,history)end local function currentOverlay(s)local handle=fs.exists(RECIPE_FILE)and fs.open(RECIPE_FILE,\"r\")or nil local source=handle and handle.readAll()or nil if handle then handle.close()end if source then local overlay,err=crafting.parseRecipeOverlay(source)if overlay then return overlay end return nil,err end return{schema=1,recipes={},tags={}}end local function beginRecipeImport(event,s)if not canMutate then feedback=\"Recipe import requires operator access\";return end local transfers=event and event.getFiles and event.getFiles()or nil if type(transfers)~=\"table\"or#transfers~=1 then feedback=\"Drop exactly one recipe pack into Crafting Queue\";return end local transfer,chunks,total=transfers[1],{},0 if not transfer or type(transfer.read)~=\"function\"then feedback=\"Dropped file is not readable\";return end while true do local chunk=transfer.read(4096)if not chunk then break end if type(chunk)~=\"string\"then feedback=\"Dropped recipe pack has invalid data\";return end total=total+#chunk if total>crafting.RECIPE_PACK_MAX_BYTES then feedback=\"Recipe pack exceeds the 64 KiB import limit\";return end chunks[#chunks+1]=chunk end local pack,packErr=crafting.parseRecipePack(table.concat(chunks))if not pack then feedback=\"Recipe pack rejected: \"..tostring(packErr);recordRecipeImport({at=os.epoch(\"utc\"),source=transfer.getName and transfer.getName()or\"dropped file\",status=\"rejected\",error=tostring(packErr):sub(1,120)});return end local overlay,overlayErr=currentOverlay(s)if not overlay then feedback=\"Could not read local recipe overlay: \"..tostring(overlayErr);return end local review,reviewErr=crafting.reviewRecipePack(s.recipes or{},pack.recipes)if not review then feedback=\"Recipe pack rejected: \"..tostring(reviewErr);return end importReview={source=tostring(transfer.getName and transfer.getName()or\"recipe pack\"):sub(1,96),overlay=overlay,incomingTags=pack.tags or{},review=review,selected=1}importScroll,importArmed,feedback=0,nil,nil end local function importSelection(row)if row and(row.status==\"new\"or row.status==\"conflict\")then row.selected=not row.selected end end local function applyImportAction(action)if not importReview then return end local rows=importReview.review.rows if action==\"all_new\"then for _,row in ipairs(rows)do if row.status==\"new\"then row.selected=true end end elseif action==\"keep_conflicts\"then for _,row in ipairs(rows)do if row.status==\"conflict\"then row.selected=false end end elseif action==\"replace_conflicts\"then for _,row in ipairs(rows)do if row.status==\"conflict\"then row.selected=true end end elseif action==\"cancel_import\"then recordRecipeImport({at=os.epoch(\"utc\"),source=importReview.source,status=\"cancelled\",counts=importReview.review.counts})importReview=nil elseif action==\"apply_import\"then local merged,importedOrErr,tags=crafting.mergeRecipePack(importReview.overlay.recipes,importReview.review,importReview.overlay.tags,importReview.incomingTags)if not merged then feedback=\"Recipe import rejected: \"..tostring(importedOrErr);return end local saved,saveErr=crafting.writeRecipeFile(RECIPE_FILE,merged,tags)if not saved then feedback=\"Could not save recipes: \"..tostring(saveErr);return end recordRecipeImport({at=os.epoch(\"utc\"),source=importReview.source,status=\"imported\",imported=importedOrErr,counts=importReview.review.counts})importReview,feedback=nil,nil end end local function finishModal(s,rows)local kind,value=modal.kind,modal.value;modal=nil if kind==\"search\"then query=value elseif kind==\"destination\"and value~=\"\"then queueCommand(\"destination\",{value=value},\"Order address\")elseif kind==\"add\"then local n=tonumber(value);if n and n>0 and rows[selectedStock]then queueCommand(\"add\",{name=rows[selectedStock].name,count=n},\"Add\")end elseif kind==\"edit\"then local n=tonumber(value);if n and n>0 and s.cart[selectedCart]then queueCommand(\"edit\",{index=selectedCart,count=n},\"Edit\")end elseif kind==\"cancel_confirm\"then queueCommand(\"cancel_active\",{},\"Cancel craft\")end end local function sourceChoices(s,target)local choices={}if target==\"requester\"then choices[#choices+1]={label=\"No Redstone Requester\",value=false}end local key=target==\"recipes\"and\"recipeServers\"or(target..\"s\")for _,source in ipairs(((s.sources or{})[key]or{}))do choices[#choices+1]={label=tostring(source.label or((source.transport==\"peer\"and\"Peer \"..tostring(source.peer)..\" / \")or\"Local / \")..tostring(source.name)),value=source}end return choices end local function chooseSource(s,target)local choices,selected=sourceChoices(s,target),1 if#choices==0 then return end while true do local w,h=term.getSize()term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()term.setBackgroundColor(colors.blue);term.setCursorPos(1,1);term.clearLine();term.setCursorPos(2,1);term.write(\"CeetOS Crafting Queue | Select \"..target)term.setTextColor(colors.lightGray);term.setCursorPos(2,3);term.write(\"Use arrows/Enter or click a source. Backspace cancels.\")local targets={}for index,choice in ipairs(choices)do local y=4+index-1;if y>=h then break end term.setBackgroundColor(index==selected and colors.gray or colors.black);term.setTextColor(index==selected and colors.white or colors.lightGray);term.setCursorPos(2,y);term.clearLine();term.write(choice.label:sub(1,w-3))targets[#targets+1]={y=y,index=index}end local event,a,b,c=os.pullEvent()if event==\"key\"then local key=keys.getName(a)if key==\"backspace\"or key==\"q\"then return elseif key==\"up\"then selected=math.max(1,selected-1)elseif key==\"down\"then selected=math.min(#choices,selected+1)elseif key==\"enter\"then queueCommand(\"source\",{target=target,value=choices[selected].value},target..\" source\");return end elseif event==\"mouse_click\"and a==1 then for _,hit in ipairs(targets)do if c==hit.y then selected=hit.index;break end end elseif event==\"mouse_up\"and a==1 then for _,hit in ipairs(targets)do if c==hit.y then queueCommand(\"source\",{target=target,value=choices[hit.index].value},target..\" source\");return end end end end end local function applyAction(action,s,rows)if action==\"back\"then return\"exit\"end if action==\"more\"then actionPage=actionPage+1;buttonIndex=1;return end if not canMutate and action~=\"search\"and action~=\"filter\"and action~=\"refresh\"then return end if action==\"search\"then startModal(\"search\",\"Find ticker items\",query)elseif action==\"filter\"then filter=filter==\"all\"and\"craftable\"or(filter==\"craftable\"and\"stocked\"or\"all\")elseif action==\"refresh\"then queueCommand(\"refresh\",{},\"Refresh\")elseif action==\"mode\"then if(s.config or{}).requester then queueCommand(\"mode\",{value=not s.craftMode},\"Craft mode\")end elseif action==\"destination\"then startModal(\"destination\",\"Order address\",(s.config or{}).orderAddress or\"Order\")elseif action==\"sources\"then chooseSource(s,\"ticker\");s=state();chooseSource(s,\"requester\");s=state();chooseSource(s,\"recipes\")elseif action==\"submit\"then queueCommand(\"submit\",{},\"Submit\")elseif action==\"retry\"and#(s.retries or{})>0 then queueCommand(\"retry\",{index=1},\"Retry\")elseif action==\"cancel\"and s.active then startModal(\"cancel_confirm\",\"Cancel active craft? Issued Create packages may still arrive\",\"\")elseif action==\"delete\"and focus==\"cart\"then queueCommand(\"remove\",{index=selectedCart},\"Remove\")elseif action==\"add\"and focus==\"stock\"and rows[selectedStock]then startModal(\"add\",\"Add \"..rows[selectedStock].name..\" quantity\",\"1\",true)elseif action==\"edit\"and focus==\"cart\"and s.cart[selectedCart]then startModal(\"edit\",\"Set \"..s.cart[selectedCart].name..\" quantity\",s.cart[selectedCart].count,true)end end local function frame(x1,y1,x2,y2,title)return terminalUi.box(x1,y1,x2,y2,title,colors.gray,colors.lightBlue)end local function drawButton(x,y,entry,selected,armed,targets)local text=\"[\"..entry.label..\"]\"local width=select(1,term.getSize())if x+#text-1>width then return x end local background=armed and colors.yellow or(selected and colors.gray or colors.black)local enabled=canMutate or entry.action==\"search\"or entry.action==\"filter\"or entry.action==\"refresh\"or entry.action==\"back\"terminalUi.write(x,y,text,armed and colors.black or(enabled and(selected and colors.white or colors.lightGray)or colors.gray),background)targets[#targets+1]={x1=x,x2=x+#text-1,y1=y,y2=y,action=entry.action}return x+#text+1 end local function visibleActions(w)local pageSize=w>=48 and 7 or 5 local pages=math.max(1,math.ceil(#actions/pageSize))actionPage=math.max(1,math.min(pages,actionPage))local out,first,last={},(actionPage-1)*pageSize+1,math.min(#actions,actionPage*pageSize)for index=first,last do out[#out+1]=actions[index]end if pages>1 then out[#out+1]={label=\"More \"..actionPage..\"/\"..pages,action=\"more\"}end buttonIndex=math.max(1,math.min(#out,buttonIndex))return out end local function drawActionRows(w,h,targets)local entries=visibleActions(w)local firstCount=math.ceil(#entries/2)terminalUi.clearLine(h-2,colors.black);terminalUi.clearLine(h-1,colors.black)local x,row=2,h-2 for index,entry in ipairs(entries)do if index==firstCount+1 then x,row=2,h-1 end x=drawButton(x,row,entry,focus==\"actions\"and buttonIndex==index,armedAction==entry.action,targets)end return entries end local function drawModal(w,h)if not modal then return end terminalUi.clearLine(h-2,colors.gray);terminalUi.write(2,h-2,modal.label,colors.white,colors.gray,w-3)if modal.kind==\"cancel_confirm\"then terminalUi.clearLine(h-1,colors.gray);terminalUi.write(2,h-1,\"[Confirm cancel] [Keep running]\",colors.white,colors.gray,w-3)else terminalUi.clearLine(h-1,colors.gray)if modal.replaceOnInput then terminalUi.write(2,h-1,modal.value,colors.black,colors.lightBlue,w-4)else terminalUi.write(2,h-1,\"> \"..modal.value,colors.white,colors.gray,w-4)end term.setCursorPos(math.min(w-1,4+#modal.value),h-1)terminalUi.clearLine(h,colors.gray);terminalUi.write(2,h,\"[Save] [Cancel]\",colors.white,colors.gray,w-3)end end local function drawImportReview()local w,h=term.getSize()term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()if w<36 or h<15 then terminalUi.minimum(\"Recipe import\",\"Recipe review needs 36x15\",\"Resize | Backspace\")return{targets={},rows={}}end local review,counts=importReview.review,importReview.review.counts terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,\"CeetOS Crafting Queue | Review recipe pack\",colors.white,colors.blue,w-2)terminalUi.write(2,3,\"File: \"..clipped(importReview.source,w-8),colors.lightGray,colors.black,w-3)terminalUi.write(2,4,(\"New: %d  Conflicts: %d  Unchanged: %d  Invalid: %d\"):format(counts.new or 0,counts.conflict or 0,counts.unchanged or 0,counts.invalid or 0),colors.white,colors.black,w-3)frame(1,5,w,h-4,\"Recipes\")local capacity=math.max(1,h-10)importReview.selected=math.max(1,math.min(math.max(1,#review.rows),importReview.selected or 1))if importReview.selected<=importScroll then importScroll=importReview.selected-1 end if importReview.selected>importScroll+capacity then importScroll=importReview.selected-capacity end importScroll=math.max(0,math.min(math.max(0,#review.rows-capacity),importScroll))local targets,visible={},{}for offset=1,capacity do local index,row,y=importScroll+offset,review.rows[importScroll+offset],5+offset if row then local marker=row.status==\"new\"and(row.selected and\"[+]\"or\"[ ]\")or row.status==\"conflict\"and(row.selected and\"[Replace]\"or\"[Keep]\")or\"[Same]\"local colour=row.status==\"new\"and colors.lime or row.status==\"conflict\"and colors.yellow or colors.gray terminalUi.write(3,y,marker..\" \"..row.name,colour,index==importReview.selected and colors.gray or colors.black,w-5)targets[#targets+1]={x1=2,x2=w-1,y1=y,y2=y,action=\"select_recipe\",index=index}visible[#visible+1]=row end end local selected=review.rows[importReview.selected]if selected then local localText=selected.existing and(\"Local: \"..tostring(selected.existing.output)..\" via \"..tostring(selected.existing.address))or\"Local: none\"local incomingText=\"Incoming: \"..tostring(selected.incoming.output)..\" via \"..tostring(selected.incoming.address)terminalUi.write(2,h-3,clipped(localText..\" | \"..incomingText,w-3),colors.lightGray,colors.black,w-3)end local buttons={{label=\"Import\",action=\"apply_import\"},{label=\"All new\",action=\"all_new\"},{label=\"Keep conflicts\",action=\"keep_conflicts\"},{label=\"Replace conflicts\",action=\"replace_conflicts\"},{label=\"Cancel\",action=\"cancel_import\"},}local x,buttonRow=2,h-2 for _,button in ipairs(buttons)do local text=\"[\"..button.label..\"]\"if x+#text-1>w-1 and buttonRow==h-2 then x,buttonRow=2,h-1 end if x+#text-1<=w-1 then terminalUi.write(x,buttonRow,text,importArmed==button.action and colors.black or colors.white,importArmed==button.action and colors.yellow or colors.gray)targets[#targets+1]={x1=x,x2=x+#text-1,y1=buttonRow,y2=buttonRow,action=button.action}x=x+#text+1 end end terminalUi.write(2,h,\"Arrows select | Space toggle | Enter import | A/K/X | Backspace cancel\",colors.gray,colors.black,w-3)return{targets=targets,rows=visible}end local function draw(s,rows)local w,h=term.getSize();term.setBackgroundColor(colors.black);term.setTextColor(colors.white);term.clear()if w<36 or h<15 then return{targets=terminalUi.minimum(\"CeetOS Crafting Queue\",\"Crafting Queue needs 36x15\",\"Resize | Backspace\")or{},compact=true,actions={}}end local config=s.config or{}local tickerLabel=config.ticker and tostring(config.ticker.label or config.ticker.name)or\"not selected\"local requesterLabel=config.requester and tostring(config.requester.label or config.requester.name)or\"none\"local recipeLabel=config.recipeServer and tostring(config.recipeServer.label or(\"Peer \"..tostring(config.recipeServer.peer)))or\"local\"terminalUi.clearLine(1,colors.blue);terminalUi.write(2,1,\"CeetOS Crafting Queue | Ticker: \"..tickerLabel..\" | Recipes: \"..recipeLabel,colors.white,colors.blue,w-2)local items,total=crafting.cartTotals(s.cart)frame(1,2,w,5,\"Order\")terminalUi.write(3,3,\"Destination: \"..tostring(config.orderAddress or\"Order\")..\"   Craft mode: \"..(s.craftMode and\"ON\"or\"OFF\")..(config.requester and\"\"or\" (requires requester)\"),colors.white,colors.black,w-5)terminalUi.write(3,4,(\"Cart: %d items / %d units    Filter: %s    Find: %s\"):format(items,total,filter,query==\"\"and\"all\"or query),colors.lightGray,colors.black,w-5)local active,status=s.active,pendingText()or\"Ready\"if active then local item=active.items and active.items[active.index]if active.phase==\"await_crafted_output\"then local route=active.stepRoute or\"recipe route\"status=(\"%s; waiting for +%s %s in Stock Ticker\"):format(route,tostring(active.expectedOutput or\"?\"),tostring(active.waitingFor or item and item.name or\"recipe\"))elseif active.phase==\"craft\"and active.pendingCraftRequests then status=(\"Requester batching %s; %s craft request%s remaining\"):format(tostring(item and item.name or\"recipe\"),tostring(active.pendingCraftRequests),active.pendingCraftRequests==1 and\"\"or\"s\")elseif active.phase==\"await_package_confirmation\"or active.phase==\"await_peer_package\"then status=(\"Stock Ticker -> %s; package %s/%s: waiting for %s\"):format(tostring(active.stepAddress or\"destination\"),tostring(active.packageIndex or 1),tostring(active.packageCount or\"?\"),tostring(active.waitingFor or\"ingredient\"))elseif active.phase==\"await_delivery_confirmation\"then status=(\"Order submitted to %s; waiting for ticker decrease of %s\"):format(tostring(active.destination),tostring(active.accepted or\"?\"))else status=(\"%s | %s  requested:%s accepted:%s dispatched:%s remaining:%s\"):format(tostring(active.phase),tostring(item and item.name or\"finishing\"),tostring(active.requested or(item and item.count)or 0),tostring(active.accepted or\"-\"),tostring(active.delivered or 0),tostring(active.remaining or\"-\"))end end frame(1,6,w,8,active and\"Active job\"or\"Status\")terminalUi.write(3,7,s.error or status,(s.error or feedback)and colors.red or(active and colors.yellow or colors.lightGray),colors.black,w-5)local split,top,bottom=math.max(24,math.floor(w*.57)),10,h-4 frame(1,9,split,bottom,\"Items & recipes\")frame(split+1,9,w,bottom,\"Request list\")local lines=math.max(0,bottom-top)for i=1,lines do local y,item,cart=top+i-1,rows[i],(s.cart or{})[i]if item then terminalUi.write(3,y,crafting.displayRow(item.name,item.count,split-4),item.craftable and colors.lime or colors.white,focus==\"stock\"and selectedStock==i and colors.gray or colors.black,split-4)end if cart then terminalUi.write(split+3,y,crafting.displayRow(cart.name,cart.count,w-split-4),colors.white,focus==\"cart\"and selectedCart==i and colors.gray or colors.black,w-split-4)end end local history,retry=(s.history or{})[#(s.history or{})],(s.retries or{})[1]local detail=s.recoveryNotice or(history and(\"Last: \"..tostring(history.status)..\" \"..tostring(history.name or\"job\")..\" \"..tostring(history.dispatched or history.delivered or 0)..\"/\"..tostring(history.requested or 0)..(history.error and(\" - \"..tostring(history.error))or\"\"))or\"No dispatched orders yet\")if retry then detail=detail..\" | Retry: \"..tostring(retry.items[1].name)..\" x\"..tostring(retry.items[1].count)end terminalUi.write(2,bottom+1,detail,colors.gray,colors.black,w-2)local targets={};local actionEntries=drawActionRows(w,h,targets);if modal then drawModal(w,h)end return{split=split,top=top,bottom=bottom-1,targets=targets,actions=actionEntries}end local function hit(targets,x,y)return terminalUi.hit(targets,x,y)end local timer=os.startTimer(0.2)while true do local s=state();cleanPending(s)local rows=crafting.rows(s.stock,query,filter,s.recipes)selectedStock=math.max(1,math.min(math.max(1,#rows),selectedStock));selectedCart=math.max(1,math.min(math.max(1,#s.cart),selectedCart))local layout=importReview and drawImportReview()or draw(s,rows)local event,a,b,c=os.pullEvent()if event==\"timer\"and a==timer then timer=os.startTimer(0.2)elseif importReview then if event==\"key\"then local key=keys.getName(a)if key==\"backspace\"or key==\"q\"then applyImportAction(\"cancel_import\")elseif key==\"up\"then importReview.selected=math.max(1,(importReview.selected or 1)-1)elseif key==\"down\"then importReview.selected=math.min(#importReview.review.rows,(importReview.selected or 1)+1)elseif key==\"space\"or key==\"left\"or key==\"right\"then importSelection(importReview.review.rows[importReview.selected])elseif key==\"a\"then applyImportAction(\"all_new\")elseif key==\"k\"then applyImportAction(\"keep_conflicts\")elseif key==\"x\"then applyImportAction(\"replace_conflicts\")elseif key==\"enter\"then applyImportAction(\"apply_import\")end elseif event==\"mouse_click\"and a==1 then local target=hit(layout.targets,b,c)if target and target.action==\"select_recipe\"then importReview.selected=target.index elseif target then importArmed=target.action end elseif event==\"mouse_drag\"and a==1 then local target=hit(layout.targets,b,c);importArmed=target and target.action or nil elseif event==\"mouse_up\"and a==1 then local target=hit(layout.targets,b,c)if target and target.action==\"select_recipe\"then importReview.selected=target.index;importSelection(importReview.review.rows[target.index])elseif target and target.action==importArmed then applyImportAction(target.action)end importArmed=nil end elseif modal then if event==\"char\"and modal.kind~=\"cancel_confirm\"then modal.value=(modal.replaceOnInput and\"\"or modal.value)..a;modal.replaceOnInput=false elseif event==\"paste\"and modal.kind~=\"cancel_confirm\"then modal.value=(modal.replaceOnInput and\"\"or modal.value)..tostring(a):gsub(\"[\\r\\n]\",\"\");modal.replaceOnInput=false elseif event==\"key\"then local key=keys.getName(a)if key==\"enter\"then finishModal(s,rows)elseif key==\"backspace\"then if modal.kind==\"cancel_confirm\"or#modal.value==0 then modal=nil else modal.value=modal.value:sub(1,-2);modal.replaceOnInput=false end end elseif event==\"mouse_up\"and a==1 then local _,h=term.getSize()if modal.kind==\"cancel_confirm\"then if c==h-1 and b>=2 and b<=17 then finishModal(s,rows)elseif c==h-1 then modal=nil end elseif c==h and b>=2 and b<=7 then finishModal(s,rows)elseif c==h and b>=9 then modal=nil end end elseif event==\"key\"then local key=keys.getName(a)if key==\"backspace\"or key==\"q\"then return elseif key==\"tab\"then focus=focus==\"stock\"and\"cart\"or(focus==\"cart\"and\"actions\"or\"stock\")elseif key==\"up\"then if focus==\"stock\"then selectedStock=math.max(1,selectedStock-1)elseif focus==\"cart\"then selectedCart=math.max(1,selectedCart-1)end elseif key==\"down\"then if focus==\"stock\"then selectedStock=math.min(math.max(1,#rows),selectedStock+1)elseif focus==\"cart\"then selectedCart=math.min(math.max(1,#s.cart),selectedCart+1)end elseif key==\"left\"and focus==\"actions\"then buttonIndex=math.max(1,buttonIndex-1)elseif key==\"right\"and focus==\"actions\"then buttonIndex=math.min(#layout.actions,buttonIndex+1)elseif key==\"s\"then applyAction(\"search\",s,rows)elseif key==\"f\"then applyAction(\"filter\",s,rows)elseif key==\"r\"then applyAction(\"refresh\",s,rows)elseif key==\"space\"then applyAction(\"mode\",s,rows)elseif key==\"d\"then applyAction(\"destination\",s,rows)elseif key==\"o\"then applyAction(\"submit\",s,rows)elseif key==\"c\"then applyAction(\"cancel\",s,rows)elseif key==\"delete\"then applyAction(\"delete\",s,rows)elseif key==\"enter\"then local action=focus==\"actions\"and layout.actions[buttonIndex]and layout.actions[buttonIndex].action or(focus==\"stock\"and\"add\"or\"edit\")if action and applyAction(action,s,rows)==\"exit\"then return end end elseif event==\"mouse_click\"and a==1 then local target=hit(layout.targets,b,c)if target then armedAction=target.action elseif c>=layout.top and c<=layout.bottom then local index=c-layout.top+1 if b<=layout.split and rows[index]then focus,selectedStock=\"stock\",index local now=os.epoch(\"utc\")if lastRowClick and lastRowClick.side==\"stock\"and lastRowClick.index==index and now-lastRowClick.at<=450 then startModal(\"add\",\"Add \"..rows[index].name..\" quantity\",\"1\",true);lastRowClick=nil else lastRowClick={side=\"stock\",index=index,at=now}end elseif b>layout.split and s.cart[index]then focus,selectedCart=\"cart\",index local now=os.epoch(\"utc\")if lastRowClick and lastRowClick.side==\"cart\"and lastRowClick.index==index and now-lastRowClick.at<=450 then startModal(\"edit\",\"Set \"..s.cart[index].name..\" quantity\",s.cart[index].count,true);lastRowClick=nil else lastRowClick={side=\"cart\",index=index,at=now}end end end elseif event==\"mouse_drag\"and a==1 then local target=hit(layout.targets,b,c);armedAction=target and target.action or nil elseif event==\"mouse_up\"and a==1 then local target=hit(layout.targets,b,c)if target and target.action==armedAction then if applyAction(target.action,s,rows)==\"exit\"then return end end armedAction=nil elseif event==\"file_transfer\"then feedback=\"Recipe packs must be imported on the selected Recipe Server\"end end",
  ["ceetos/bin/ceetshareall.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local peripherals=require(\"ceetos.lib.peripherals\")local mode=(...)==\"master\"and\"master\"or\"peer\"auth.require(\"operator\")print(\"Shared \"..peripherals.shareAll(mode)..\" peripherals (\"..mode..\")\")",
  ["ceetos/bin/ceetunshareall.lua"] = "package.path=\"/?.lua;/?/init.lua;\"..package.path local auth=require(\"ceetos.lib.auth\")local peripherals=require(\"ceetos.lib.peripherals\")auth.require(\"operator\")print(\"Unshared \"..peripherals.unshareAll()..\" peripherals\")",
}
local CEETOS_RELEASE_INSTALLER = true
local CEETOS_PROFILE = "desktop"

-- `wget --install` may run inside a deliberately restricted CeetShell child
-- environment. Self-cleaning is optional there: never require the shell API
-- merely to install the runtime.
local args = { ... }
local automated = args[1] == "--ceetos-apply"
local self = shell and shell.getRunningProgram and shell.getRunningProgram()
local cache = "/ceetos-updates/release.lua"
-- A signed release launched directly is retained outside the replaceable
-- runtime tree for verified recovery. Development installers deliberately do
-- not become propagation sources. Do this before removing the downloaded
-- program itself, but avoid copying the cache onto itself during recovery.
if CEETOS_RELEASE_INSTALLER and not automated and self and fs.exists(self) and self ~= cache then
  if not fs.exists("/ceetos-updates") then fs.makeDir("/ceetos-updates") end
  if fs.exists(cache) then fs.delete(cache) end
  pcall(fs.copy, self, cache)
end
if self and self ~= cache and fs.exists(self) then pcall(fs.delete, self) end

local bytes = 0
for _, contents in pairs(files) do bytes = bytes + #contents end
print("CeetOS " .. CEETOS_PROFILE .. " installer (" .. bytes .. " bytes)")
if not automated then
  print("This will replace /ceetos and /startup.lua. Continue? [y/N]")
  if read():lower() ~= "y" then print("Cancelled."); return end
end

local backup, migrate, migrationData = nil, false, {}
-- Public signed installers intentionally do not create an enrolled Cloud node
-- by themselves. A completely fresh computer must obtain its one-use node
-- credential from a nearby, explicitly promoted broker before any runtime is
-- replaced. The tiny temporary module tree is removed on every outcome.
if CEETOS_RELEASE_INSTALLER and not automated and not fs.exists("ceetos") then
  local temporary = "/ceetos-bootstrap"
  if fs.exists(temporary) then fs.delete(temporary) end
  fs.makeDir(temporary); fs.makeDir(temporary .. "/ceetos"); fs.makeDir(temporary .. "/ceetos/lib")
  for _, path in ipairs({ "ceetos/lib/password.lua", "ceetos/lib/mesh_crypto.lua", "ceetos/lib/broker_bootstrap.lua" }) do
    local contents = files[path]
    if not contents then fs.delete(temporary); error("installer is missing bootstrap dependency " .. path, 0) end
    local handle = assert(fs.open(temporary .. "/" .. path, "w")); handle.write(contents); handle.close()
  end
  local oldPath = package.path
  package.path = temporary .. "/?.lua;" .. temporary .. "/?/init.lua;" .. package.path
  local loaded, bootstrap = pcall(require, "ceetos.lib.broker_bootstrap")
  local grant, bootstrapErr
  if loaded then grant, bootstrapErr = bootstrap.enroll(CEETOS_PROFILE) else bootstrapErr = bootstrap end
  package.loaded["ceetos.lib.broker_bootstrap"], package.loaded["ceetos.lib.mesh_crypto"], package.loaded["ceetos.lib.password"] = nil, nil, nil
  package.path = oldPath
  if fs.exists(temporary) then fs.delete(temporary) end
  if not grant then printError(tostring(bootstrapErr or "trusted broker enrollment failed")); return end
  migrationData["cloud.lua"] = textutils.serialize({ schema = 1, enabled = true, urls = grant.urls, node = grant.node })
  migrate = true
  print("Trusted broker enrollment received. Installing signed release...")
end
-- Clean stale full-tree backups from older installers before measuring space.
for _, name in ipairs(fs.list(".")) do
  if name:match("^ceetos%.backup") or name == "ceetos-migrate" then fs.delete(name) end
end
-- Development transactions can be much larger than the runtime. Preserve
-- only the reconnect record; staged payloads, test data, and rollback trees
-- are disposable and must not prevent an install from starting.
for _, name in ipairs({ "staging", "backups", "test-data" }) do
  local path = fs.combine("ceetos-dev", name)
  if fs.exists(path) then fs.delete(path) end
end
if fs.exists("ceetos") then
  if automated then migrate = true else
    print("Migrate saved CeetOS configuration? [Y/n]")
    local choice = read():lower()
    migrate = choice ~= "n" and choice ~= "no"
  end
  -- Copy only durable configuration to a small migration area, then remove
  -- the old tree before writing the new one. This works on nearly-full CC
  -- drives where retaining a complete backup would make installation fail.
  if migrate then
    local durable = { "users.lua", "network.lua", "shares.lua", "config.lua", "owner-service.lua", "seen-peers.lua", "jobs.lua", "job-workers.lua", "crafting-state.lua", "auth-authority.lua", "auth-authority-state.lua", "auth-directory.lua", "auth-session.lua", "cloud.lua", "cloud-state.lua" }
    if CEETOS_PROFILE == "recipe-server" then durable[#durable + 1] = "recipes.lua" end
    for _, name in ipairs(durable) do
      local source = fs.combine("ceetos/data", name)
      if fs.exists(source) then
        local input = fs.open(source, "r")
        if input then migrationData[name] = input.readAll(); input.close() end
      end
    end
  end
  fs.delete("ceetos")
end

for path, contents in pairs(files) do
  local parent = fs.getDir(path)
  if parent ~= "" and not fs.exists(parent) then fs.makeDir(parent) end
  local handle = assert(fs.open(path, "w"))
  handle.write(contents)
  handle.close()
end

if migrate then
  -- Preserve durable configuration, but never preserve an active session,
  -- temporary recovery window, remote result cache, or stale audit entries.
  local durable = { "users.lua", "network.lua", "shares.lua", "config.lua", "owner-service.lua", "seen-peers.lua", "jobs.lua", "job-workers.lua", "crafting-state.lua", "auth-authority.lua", "auth-authority-state.lua", "auth-directory.lua", "auth-session.lua", "cloud.lua", "cloud-state.lua" }
  if CEETOS_PROFILE == "recipe-server" then durable[#durable + 1] = "recipes.lua" end
  for _, name in ipairs(durable) do
    local contents = migrationData[name]
    if contents then
      if not fs.exists("ceetos/data") then fs.makeDir("ceetos/data") end
      local output = assert(fs.open(fs.combine("ceetos/data", name), "w"))
      output.write(contents); output.close()
    end
  end
  print("Saved CeetOS configuration migrated. Please log in again.")
end

-- The installer is intentionally transactional while it runs, but retaining
-- a full tree backup after a successful install quickly exhausts small CC
-- drives. Durable data has already been copied, so remove the old tree.
if automated then
  -- The root startup launcher sees this marker and boots the freshly written
  -- runtime rather than replaying the installer. The runtime verifies its
  -- loaded version before clearing it.
  if not fs.exists("/ceetos-updates") then fs.makeDir("/ceetos-updates") end
  local marker = fs.open("/ceetos-updates/pending.lua", "w")
  if marker then marker.write("return {state='verify',version=" .. "0.17.1" .. ",profile=" .. "\"desktop\"" .. "}"); marker.close() end
  print("CeetOS installed. Rebooting to verify the update.")
  os.reboot()
end
print("CeetOS installed. Reboot to start it.")

-- CEETOS_RELEASE_PAYLOAD_END
