@zortexhq/indra-v2.5 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-sync.js +1 -1
- package/dist/content-find.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/public-tool.js +1 -1
- package/dist/read-route.js +1 -1
- package/dist/resident-platform.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/package.json +6 -6
- package/release-provenance.json +22 -22
- package/update-manifest.json +108 -72
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity,residentRuntimePolicy}from"./resident-runtime-identity.js";import{residentStartupDisabled,setResidentStartupDisabled}from"./resident-startup-preference.js";import{createUpdateRecovery,installedStartupVersion}from"./update-recovery.js";import{markResidentInterruption,residentInterruption}from"./update-handover.js";import{RESIDENT_STOP_TIMEOUT_MS}from"./resident-shutdown.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";import{currentOperationalExecution,isOperationalContext,withOperationalContext,withoutOperationalContext}from"@zortexhq/plugin-telemetry/api";import{observeResidentHandlers,traceResidentControl}from"./resident-telemetry.js";const execute=promisify(execFile);const loadedRuntime=residentRuntimeIdentity().then(current=>{const version=installedStartupVersion();return version&&version!==current.version?{installationPath:current.installationPath,policy:current.policy,version}:current});const installationRecovery=createUpdateRecovery();const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=4;const REQUEST_BYTES=2*1024*1024,RESPONSE_BYTES=4*1024*1024;const RESIDENT_MANAGEMENT=new Set(["plugins","plugin.set-enabled","status","sources","onboarding","startup"]);export function isResidentGatewayRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value,args=request2.args;if(Object.keys(request2).some(key=>key!=="operation"&&key!=="args")||!args||typeof args!=="object"||Array.isArray(args))return false;const fields=args;return request2.operation==="action"&&fields.name==="connector.find"&&Object.keys(fields).every(key=>key==="name"||key==="params")&&!!fields.params&&typeof fields.params==="object"&&!Array.isArray(fields.params)||request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(fields.what))}function validUpdateOwner(value){if(!value||typeof value!=="object")return false;const owner=value;return Number.isSafeInteger(owner.pid)&&owner.pid>0&&typeof owner.startedAt==="string"&&owner.startedAt.length<100&&!!owner.runtime&&typeof owner.runtime.installationPath==="string"&&isAbsolute(owner.runtime.installationPath)&&typeof owner.runtime.version==="string"&&/^[0-9A-Za-z.+-]{1,80}$/.test(owner.runtime.version)}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3,guard){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){if(guard&&(item.pid!==guard.pid||item.startedAt!==guard.startedAt))return{running:true,deferred:true,reason:"resident_changed"};try{return await requestOnce(id,item,command,timeout,guard)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout,guard){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;const finish=(result,error,disconnected=false)=>{if(settled)return;if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;socket.destroy();if(error)reject(error);else done(result)};const incompatible=()=>finish(null,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));socket.setTimeout(timeout,()=>finish(null));socket.on("error",error=>finish(null,!connected&&error.code!=="ENOENT"&&error.code!=="ECONNREFUSED"?error:void 0,true));socket.on("end",()=>finish(null,void 0,true));socket.on("connect",()=>{connected=true;if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();socket.write(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,command,nonce:item.nonce,...guard?{guard}:{},...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n")});socket.on("data",chunk=>{text+=chunk.toString();if(text.length>65536)return finish(null);if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();finish(typeof value.running==="boolean"?value:null)}catch{finish(null)}})})}export async function residentStatus(root){return await request(await identity(root),"status")??{running:false}}async function residentRpc(root,message,signal){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="",settled=false;const finish=(value,error)=>{if(settled)return;settled=true;signal?.removeEventListener("abort",abort);socket.destroy();if(error)reject(error);else done(value)};const abort=()=>finish(void 0,new Error("Resident request was cancelled"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)return abort();socket.setTimeout(11*6e4,()=>finish(void 0,new Error("Resident request timed out")));socket.on("error",error=>finish(void 0,error));socket.on("end",()=>finish(void 0,new Error("Resident sync ended without a result")));socket.on("connect",()=>{if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return finish(void 0,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));const payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,nonce:item.nonce,...message,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n";if(Buffer.byteLength(payload)>REQUEST_BYTES)return finish(void 0,new Error("Resident request was too large"));socket.write(payload)});socket.on("data",chunk=>{text+=chunk.toString();if(Buffer.byteLength(text)>RESPONSE_BYTES)return finish(void 0,new Error("Resident response was too large"));if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||!value.result)return finish(void 0,new Error("Resident response was invalid"));finish(value.result)}catch{finish(void 0,new Error("Resident response was invalid"))}})})}export function residentLocalCloudControl(root,request2){if(!isLocalCloudControlRequest(request2))return Promise.reject(new Error("Invalid Local Cloud control request"));return residentRpc(root,{command:"local-cloud-control",request:request2})}export function residentSync(root,source,requestId,options={}){return residentRpc(root,{command:"sync",source,requestId,...options.bindingId?{bindingId:options.bindingId}:{}},options.signal)}export function residentGatewayCall(root,request2,signal){return residentRpc(root,{command:"gateway",request:request2},signal)}export function residentEnsureReady(root,source,signal){return residentRpc(root,{command:"ensure-ready",source},signal)}export function residentCheck(root,source,signal){return residentRpc(root,{command:"check",source},signal)}export function residentRead(root,source,request2={},signal){return residentRpc(root,{command:"read",source,request:request2},signal)}export function residentInvoke(root,request2,signal){return residentRpc(root,{command:"invoke",request:request2},signal)}export function residentConnect(root,source,requestId,signal,settings={automatic:false}){return residentRpc(root,{command:"connect",source,requestId,automatic:settings.automatic,...settings.manualPresentation?{manualPresentation:settings.manualPresentation}:{}},signal)}export function residentConnectJob(root,requestId,signal){return residentRpc(root,{command:"connect-job",requestId},signal)}export function residentOnboard(root,signal){return residentRpc(root,{command:"onboard"},signal)}export async function residentPauseConnectionAutomation(root,signal){await markResidentInterruption(root,"pause");return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){handlers=observeResidentHandlers(handlers);const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});let ownership;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,operationalContextVersion:1,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime={...await loadedRuntime,policy:residentRuntimePolicy()};const sockets=new Set;let activeRequests=0;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{let active=false;try{const envelope=JSON.parse(input.split("\n")[0]);if(envelope.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof envelope.nonce!=="string"||envelope.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(envelope.nonce),Buffer.from(item.nonce))){socket.destroy();return}const{operationalContext,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}async function configureSelection(valid,configure){if(!configure||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!valid(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await configure(message.selection))}const dispatch=async()=>{if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command!=="status"&&message.command!=="stop"){active=true;activeRequests++}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,update,...safe}=traceResidentControl(handlers.telemetry,{phase:"runtime",action:"status",operationId:"resident.status"},status,{plainResult:true});const updateState=update;socket.end(JSON.stringify({...safe,update:{...typeof updateState?.idle==="boolean"&&typeof updateState.paused==="boolean"?{idle:updateState.idle&&activeRequests===0,paused:updateState.paused}:{},guardedStop:true},runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="onboard"){if(!handlers.onboard||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.onboard(disconnected.signal))}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="ensure-ready"){if(!handlers.ensureReady||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());reply(await handlers.ensureReady(message.source,disconnected.signal))}else if(message.command==="check"){if(!handlers.check||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.check(message.source,disconnected.signal))}else if(message.command==="read"){if(!handlers.read||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||!message.request||typeof message.request!=="object"||Array.isArray(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.read(message.source,message.request,disconnected.signal);reply(result)}else if(message.command==="invoke"){const request2=message.request;if(!handlers.invoke||!request2||typeof request2!=="object"||Array.isArray(request2)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.invoke(request2,disconnected.signal);reply(result)}else if(message.command==="connect"){if(!handlers.connect||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||typeof message.automatic!=="boolean"){socket.destroy();return}const manualPresentation=message.manualPresentation==="return-url"?"return-url":message.manualPresentation==="open"?"open":void 0;socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connect(message.source,message.requestId,disconnected.signal,{automatic:message.automatic,...manualPresentation?{manualPresentation}:{}});reply(result)}else if(message.command==="connect-manual"){if(!handlers.connectManual||typeof message.source!=="string"||!HELP_MANUAL_SOURCES.has(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectManual(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="reconnect-saved"){if(!handlers.reconnectSaved||typeof message.source!=="string"||!supportsSavedReconnect(message.source)||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source"].includes(key))){socket.destroy();return}socket.setTimeout(9e4,()=>socket.destroy());const result=await handlers.reconnectSaved(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-gmail-write"){if(!handlers.connectGmailWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectGmailWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-readwise-mcp-write"){if(!handlers.connectReadwiseMcpWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReadwiseMcpWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-reauthorize"){if(!handlers.connectReauthorize||typeof message.source!=="string"||!["todoist","linear"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReauthorize(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-recovery"){if(!handlers.connectRecovery||typeof message.source!=="string"||!["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectRecovery(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-automatic"){if(!handlers.connectAutomatic||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectAutomatic(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-job"){if(!handlers.connectJob||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}const result=await handlers.connectJob(message.requestId);reply(result)}else if(message.command==="connect-cancel"){if(!handlers.cancelConnect||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||!Number.isSafeInteger(message.generation)||message.generation<0||typeof message.challengeRef!=="string"||!message.challengeRef||message.challengeRef.length>200){socket.destroy();return}const result=await handlers.cancelConnect(message.requestId,message.generation,message.challengeRef);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wechat"){if(!handlers.configureWeChat||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWeChat({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-joplin"){if(!handlers.configureJoplin||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{validateJoplinSelection(message.selection)}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureJoplin(message.selection,disconnected.signal);reply(result)}else if(message.command==="configure-thunderbird"){if(!handlers.configureThunderbird||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureThunderbird({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-discord"){if(!handlers.configureDiscord||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{const selection=message.selection;if(!selection||typeof selection!=="object"||Array.isArray(selection)||Reflect.ownKeys(selection).some(key=>typeof key!=="string"||!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...selection})}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDiscord(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-proton-mail"){if(!handlers.configureProtonMail||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureProtonMail({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zulip"){await configureSelection(validZulipSelection,handlers.configureZulip?.bind(handlers))}else if(message.command==="configure-freshrss"){await configureSelection(validFreshRSSSelection,handlers.configureFreshRSS?.bind(handlers))}else if(message.command==="configure-miniflux"){await configureSelection(validMinifluxSelection,handlers.configureMiniflux?.bind(handlers))}else if(message.command==="configure-mattermost"){await configureSelection(validMattermostSelection,handlers.configureMattermost?.bind(handlers))}else if(message.command==="configure-wallabag"){await configureSelection(validWallabagSelection,handlers.configureWallabag?.bind(handlers))}else if(message.command==="configure-calcom"){await configureSelection(validCalcomSelection,handlers.configureCalcom?.bind(handlers))}else if(message.command==="configure-wakatime"){await configureSelection(validWakatimeSelection,handlers.configureWakatime?.bind(handlers))}else if(message.command==="configure-nextcloud"){if(!handlers.configureNextcloud||Object.keys(message).some(key=>!["protocolVersion","nonce","command","instanceUrl"].includes(key))||!validNextcloudInstanceUrl(message.instanceUrl)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNextcloud({instanceUrl:message.instanceUrl});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-dropbox"){const selection=message.selection;if(!handlers.configureDropbox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDropbox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-box"){const selection=message.selection;if(!handlers.configureBox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureBox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-front"){const selection=message.selection;if(!handlers.configureFront||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFront({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-hubspot"){const selection=message.selection;if(!handlers.configureHubSpot||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureHubSpot({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-contacts"){const selection=message.selection;if(!handlers.configureGoogleContacts||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleContacts({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-chat"){const selection=message.selection;if(!handlers.configureGoogleChat||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleChat({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-salesforce"){const selection=message.selection;if(!handlers.configureSalesforce||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==3||Object.keys(selection).some(key=>!["environment","clientId","loopbackPort"].includes(key))||!["production","sandbox"].includes(selection.environment)||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSalesforce({environment:selection.environment,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zendesk"){const selection=message.selection;if(!handlers.configureZendesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZendeskSelection(selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZendesk({subdomain:selection.subdomain,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zoom"){const selection=message.selection;if(!handlers.configureZoom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==1||Object.keys(selection).some(key=>key!=="clientId")||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZoom({clientId:selection.clientId});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-smartsheet"){if(!handlers.configureSmartsheet||Object.keys(message).some(key=>!["protocolVersion","nonce","command","region"].includes(key))||!["us","eu","au"].includes(message.region)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSmartsheet({region:message.region});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-figma"){if(!handlers.configureFigma||Object.keys(message).some(key=>!["protocolVersion","nonce","command","mode"].includes(key))||!["fields","oauth"].includes(message.mode)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFigma(message.mode);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshdesk"){if(!handlers.configureFreshdesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","subdomain"].includes(key))||typeof message.subdomain!=="string"||message.subdomain.length>63||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(message.subdomain)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshdesk({subdomain:message.subdomain});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-copyq"){if(!handlers.configureCopyQ||typeof message.executable!=="string"||message.executable.length<1||message.executable.length>512||typeof message.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(message.session)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCopyQ({executable:message.executable,session:message.session});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-owntracks"){if(!handlers.configureOwnTracks||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureOwnTracks({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zotero"){if(!handlers.configureZotero||typeof message.libraryId!=="string"||!["user","group"].includes(message.libraryType)||!/^[1-9][0-9]{0,19}$/.test(message.libraryId)&&!(message.libraryType==="user"&&message.libraryId==="0")){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZotero({libraryId:message.libraryId,libraryType:message.libraryType});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-native-files"){const sources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"];if(!handlers.configureNativeFiles||!sources.includes(message.source)||!Array.isArray(message.roots)||message.roots.length<1||message.roots.length>16||!message.roots.every(root2=>typeof root2==="string"&&root2.length>0&&root2.length<=4096)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNativeFiles({source:message.source,roots:message.roots});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-status"){if(!handlers.connectorStatus){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorStatus();if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-check"){if(!handlers.connectorCheck||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorCheck(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-read"){if(!handlers.connectorRead||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorRead(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());await markResidentInterruption(id.root,"pause");reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){if(message.guard!==void 0){if(!validUpdateOwner(message.guard)){socket.destroy();return}const guard=message.guard,path=value=>process.platform==="win32"?value.toLowerCase():value;const current=status().update;const reason=stopping||closing||guard.pid!==item.pid||guard.startedAt!==item.startedAt||guard.runtime.version!==runtime.version||path(guard.runtime.installationPath)!==path(runtime.installationPath)?"resident_changed":typeof current?.idle!=="boolean"||typeof current.paused!=="boolean"?"resident_guard_unavailable":current.paused?"resident_paused":!current.idle||activeRequests!==0?"resident_busy":void 0;if(reason){socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,deferred:true,reason})+"\n");return}}else await markResidentInterruption(id.root,"stop");socket.setTimeout(RESIDENT_STOP_TIMEOUT_MS,()=>socket.destroy());stopping??=Promise.resolve().then(()=>traceResidentControl(handlers.telemetry,{phase:"runtime",action:"cleanup",operationId:"resident.stop"},onStop,{plainResult:true}));try{await stopping}catch{stopping=void 0;socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,error:"resident_cleanup_failed"})+"\n");return}socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:false,stopped:true})+"\n");void close()}else socket.destroy()};if(operationalContext)await withOperationalContext(operationalContext,dispatch);else await withoutOperationalContext(dispatch)}catch{socket.destroy()}finally{if(active)activeRequests--}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{const claimed=await installationRecovery.withResidentClaim(async()=>{ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return false;const intent=process.env.ZORTEX_UPDATE_INTENT;if(intent!==void 0&&await residentInterruption(id.root)!==intent)throw Error("The resident was stopped or paused after this update began.");try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return false}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return false}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}if(intent!==void 0&&await residentInterruption(id.root)!==intent)throw Error("The resident was stopped or paused after this update began.");return true},runtime.version);if(!claimed)return null}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const connectDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_CONNECT??"").trim());const lookupPath=platform==="darwin"&&environment.PATH&&!/[\x00-\x1f]/.test(environment.PATH)?[...new Set(environment.PATH.split(":").filter(isAbsolute))].join(":"):void 0;const startupEnvironment={...syncDisabled?{ZORTEX_AUTO_SYNC:"0"}:{},...connectDisabled?{ZORTEX_AUTO_CONNECT:"0"}:{},...lookupPath?{PATH:lookupPath}:{}};const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
|
|
1
|
+
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity,residentRuntimePolicy}from"./resident-runtime-identity.js";import{residentStartupDisabled,setResidentStartupDisabled}from"./resident-startup-preference.js";import{createUpdateRecovery,installedStartupVersion}from"./update-recovery.js";import{markResidentInterruption,residentInterruption}from"./update-handover.js";import{RESIDENT_STOP_TIMEOUT_MS}from"./resident-shutdown.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";import{currentOperationalExecution,isOperationalContext,withOperationalContext,withoutOperationalContext}from"@zortexhq/plugin-telemetry/api";import{observeResidentHandlers,traceResidentControl}from"./resident-telemetry.js";const execute=promisify(execFile);const loadedRuntime=residentRuntimeIdentity().then(current=>{const version=installedStartupVersion();return version&&version!==current.version?{installationPath:current.installationPath,policy:current.policy,version}:current});const installationRecovery=createUpdateRecovery();const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=4;const REQUEST_BYTES=2*1024*1024,RESPONSE_BYTES=4*1024*1024;const RESIDENT_MANAGEMENT=new Set(["plugins","plugin.set-enabled","status","sources","onboarding","startup"]);export function isResidentGatewayRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value,args=request2.args;if(Object.keys(request2).some(key=>key!=="operation"&&key!=="args")||!args||typeof args!=="object"||Array.isArray(args))return false;const fields=args;return request2.operation==="action"&&["connector.find","connector.acquire"].includes(String(fields.name))&&Object.keys(fields).every(key=>key==="name"||key==="params")&&!!fields.params&&typeof fields.params==="object"&&!Array.isArray(fields.params)||request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(fields.what))}function validUpdateOwner(value){if(!value||typeof value!=="object")return false;const owner=value;return Number.isSafeInteger(owner.pid)&&owner.pid>0&&typeof owner.startedAt==="string"&&owner.startedAt.length<100&&!!owner.runtime&&typeof owner.runtime.installationPath==="string"&&isAbsolute(owner.runtime.installationPath)&&typeof owner.runtime.version==="string"&&/^[0-9A-Za-z.+-]{1,80}$/.test(owner.runtime.version)}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3,guard){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){if(guard&&(item.pid!==guard.pid||item.startedAt!==guard.startedAt))return{running:true,deferred:true,reason:"resident_changed"};try{return await requestOnce(id,item,command,timeout,guard)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout,guard){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;const finish=(result,error,disconnected=false)=>{if(settled)return;if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;socket.destroy();if(error)reject(error);else done(result)};const incompatible=()=>finish(null,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));socket.setTimeout(timeout,()=>finish(null));socket.on("error",error=>finish(null,!connected&&error.code!=="ENOENT"&&error.code!=="ECONNREFUSED"?error:void 0,true));socket.on("end",()=>finish(null,void 0,true));socket.on("connect",()=>{connected=true;if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();socket.write(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,command,nonce:item.nonce,...guard?{guard}:{},...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n")});socket.on("data",chunk=>{text+=chunk.toString();if(text.length>65536)return finish(null);if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();finish(typeof value.running==="boolean"?value:null)}catch{finish(null)}})})}export async function residentStatus(root){return await request(await identity(root),"status")??{running:false}}async function residentRpc(root,message,signal){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="",settled=false;const finish=(value,error)=>{if(settled)return;settled=true;signal?.removeEventListener("abort",abort);socket.destroy();if(error)reject(error);else done(value)};const abort=()=>finish(void 0,new Error("Resident request was cancelled"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)return abort();socket.setTimeout(11*6e4,()=>finish(void 0,new Error("Resident request timed out")));socket.on("error",error=>finish(void 0,error));socket.on("end",()=>finish(void 0,new Error("Resident sync ended without a result")));socket.on("connect",()=>{if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return finish(void 0,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));const payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,nonce:item.nonce,...message,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n";if(Buffer.byteLength(payload)>REQUEST_BYTES)return finish(void 0,new Error("Resident request was too large"));socket.write(payload)});socket.on("data",chunk=>{text+=chunk.toString();if(Buffer.byteLength(text)>RESPONSE_BYTES)return finish(void 0,new Error("Resident response was too large"));if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||!value.result)return finish(void 0,new Error("Resident response was invalid"));finish(value.result)}catch{finish(void 0,new Error("Resident response was invalid"))}})})}export function residentLocalCloudControl(root,request2){if(!isLocalCloudControlRequest(request2))return Promise.reject(new Error("Invalid Local Cloud control request"));return residentRpc(root,{command:"local-cloud-control",request:request2})}export function residentSync(root,source,requestId,options={}){return residentRpc(root,{command:"sync",source,requestId,...options.bindingId?{bindingId:options.bindingId}:{}},options.signal)}export function residentGatewayCall(root,request2,signal){return residentRpc(root,{command:"gateway",request:request2},signal)}export function residentEnsureReady(root,source,signal){return residentRpc(root,{command:"ensure-ready",source},signal)}export function residentCheck(root,source,signal){return residentRpc(root,{command:"check",source},signal)}export function residentRead(root,source,request2={},signal){return residentRpc(root,{command:"read",source,request:request2},signal)}export function residentInvoke(root,request2,signal){return residentRpc(root,{command:"invoke",request:request2},signal)}export function residentConnect(root,source,requestId,signal,settings={automatic:false}){return residentRpc(root,{command:"connect",source,requestId,automatic:settings.automatic,...settings.manualPresentation?{manualPresentation:settings.manualPresentation}:{}},signal)}export function residentConnectJob(root,requestId,signal){return residentRpc(root,{command:"connect-job",requestId},signal)}export function residentOnboard(root,signal){return residentRpc(root,{command:"onboard"},signal)}export async function residentPauseConnectionAutomation(root,signal){await markResidentInterruption(root,"pause");return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){handlers=observeResidentHandlers(handlers);const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});let ownership;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,operationalContextVersion:1,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime={...await loadedRuntime,policy:residentRuntimePolicy()};const sockets=new Set;let activeRequests=0;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{let active=false;try{const envelope=JSON.parse(input.split("\n")[0]);if(envelope.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof envelope.nonce!=="string"||envelope.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(envelope.nonce),Buffer.from(item.nonce))){socket.destroy();return}const{operationalContext,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}async function configureSelection(valid,configure){if(!configure||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!valid(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await configure(message.selection))}const dispatch=async()=>{if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command!=="status"&&message.command!=="stop"){active=true;activeRequests++}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,update,...safe}=traceResidentControl(handlers.telemetry,{phase:"runtime",action:"status",operationId:"resident.status"},status,{plainResult:true});const updateState=update;socket.end(JSON.stringify({...safe,update:{...typeof updateState?.idle==="boolean"&&typeof updateState.paused==="boolean"?{idle:updateState.idle&&activeRequests===0,paused:updateState.paused}:{},guardedStop:true},runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="onboard"){if(!handlers.onboard||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.onboard(disconnected.signal))}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="ensure-ready"){if(!handlers.ensureReady||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());reply(await handlers.ensureReady(message.source,disconnected.signal))}else if(message.command==="check"){if(!handlers.check||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.check(message.source,disconnected.signal))}else if(message.command==="read"){if(!handlers.read||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||!message.request||typeof message.request!=="object"||Array.isArray(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.read(message.source,message.request,disconnected.signal);reply(result)}else if(message.command==="invoke"){const request2=message.request;if(!handlers.invoke||!request2||typeof request2!=="object"||Array.isArray(request2)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.invoke(request2,disconnected.signal);reply(result)}else if(message.command==="connect"){if(!handlers.connect||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||typeof message.automatic!=="boolean"){socket.destroy();return}const manualPresentation=message.manualPresentation==="return-url"?"return-url":message.manualPresentation==="open"?"open":void 0;socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connect(message.source,message.requestId,disconnected.signal,{automatic:message.automatic,...manualPresentation?{manualPresentation}:{}});reply(result)}else if(message.command==="connect-manual"){if(!handlers.connectManual||typeof message.source!=="string"||!HELP_MANUAL_SOURCES.has(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectManual(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="reconnect-saved"){if(!handlers.reconnectSaved||typeof message.source!=="string"||!supportsSavedReconnect(message.source)||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source"].includes(key))){socket.destroy();return}socket.setTimeout(9e4,()=>socket.destroy());const result=await handlers.reconnectSaved(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-gmail-write"){if(!handlers.connectGmailWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectGmailWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-readwise-mcp-write"){if(!handlers.connectReadwiseMcpWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReadwiseMcpWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-reauthorize"){if(!handlers.connectReauthorize||typeof message.source!=="string"||!["todoist","linear"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReauthorize(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-recovery"){if(!handlers.connectRecovery||typeof message.source!=="string"||!["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectRecovery(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-automatic"){if(!handlers.connectAutomatic||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectAutomatic(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-job"){if(!handlers.connectJob||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}const result=await handlers.connectJob(message.requestId);reply(result)}else if(message.command==="connect-cancel"){if(!handlers.cancelConnect||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||!Number.isSafeInteger(message.generation)||message.generation<0||typeof message.challengeRef!=="string"||!message.challengeRef||message.challengeRef.length>200){socket.destroy();return}const result=await handlers.cancelConnect(message.requestId,message.generation,message.challengeRef);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wechat"){if(!handlers.configureWeChat||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWeChat({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-joplin"){if(!handlers.configureJoplin||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{validateJoplinSelection(message.selection)}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureJoplin(message.selection,disconnected.signal);reply(result)}else if(message.command==="configure-thunderbird"){if(!handlers.configureThunderbird||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureThunderbird({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-discord"){if(!handlers.configureDiscord||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{const selection=message.selection;if(!selection||typeof selection!=="object"||Array.isArray(selection)||Reflect.ownKeys(selection).some(key=>typeof key!=="string"||!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...selection})}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDiscord(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-proton-mail"){if(!handlers.configureProtonMail||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureProtonMail({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zulip"){await configureSelection(validZulipSelection,handlers.configureZulip?.bind(handlers))}else if(message.command==="configure-freshrss"){await configureSelection(validFreshRSSSelection,handlers.configureFreshRSS?.bind(handlers))}else if(message.command==="configure-miniflux"){await configureSelection(validMinifluxSelection,handlers.configureMiniflux?.bind(handlers))}else if(message.command==="configure-mattermost"){await configureSelection(validMattermostSelection,handlers.configureMattermost?.bind(handlers))}else if(message.command==="configure-wallabag"){await configureSelection(validWallabagSelection,handlers.configureWallabag?.bind(handlers))}else if(message.command==="configure-calcom"){await configureSelection(validCalcomSelection,handlers.configureCalcom?.bind(handlers))}else if(message.command==="configure-wakatime"){await configureSelection(validWakatimeSelection,handlers.configureWakatime?.bind(handlers))}else if(message.command==="configure-nextcloud"){if(!handlers.configureNextcloud||Object.keys(message).some(key=>!["protocolVersion","nonce","command","instanceUrl"].includes(key))||!validNextcloudInstanceUrl(message.instanceUrl)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNextcloud({instanceUrl:message.instanceUrl});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-dropbox"){const selection=message.selection;if(!handlers.configureDropbox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDropbox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-box"){const selection=message.selection;if(!handlers.configureBox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureBox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-front"){const selection=message.selection;if(!handlers.configureFront||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFront({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-hubspot"){const selection=message.selection;if(!handlers.configureHubSpot||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureHubSpot({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-contacts"){const selection=message.selection;if(!handlers.configureGoogleContacts||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleContacts({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-chat"){const selection=message.selection;if(!handlers.configureGoogleChat||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleChat({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-salesforce"){const selection=message.selection;if(!handlers.configureSalesforce||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==3||Object.keys(selection).some(key=>!["environment","clientId","loopbackPort"].includes(key))||!["production","sandbox"].includes(selection.environment)||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSalesforce({environment:selection.environment,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zendesk"){const selection=message.selection;if(!handlers.configureZendesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZendeskSelection(selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZendesk({subdomain:selection.subdomain,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zoom"){const selection=message.selection;if(!handlers.configureZoom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==1||Object.keys(selection).some(key=>key!=="clientId")||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZoom({clientId:selection.clientId});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-smartsheet"){if(!handlers.configureSmartsheet||Object.keys(message).some(key=>!["protocolVersion","nonce","command","region"].includes(key))||!["us","eu","au"].includes(message.region)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSmartsheet({region:message.region});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-figma"){if(!handlers.configureFigma||Object.keys(message).some(key=>!["protocolVersion","nonce","command","mode"].includes(key))||!["fields","oauth"].includes(message.mode)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFigma(message.mode);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshdesk"){if(!handlers.configureFreshdesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","subdomain"].includes(key))||typeof message.subdomain!=="string"||message.subdomain.length>63||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(message.subdomain)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshdesk({subdomain:message.subdomain});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-copyq"){if(!handlers.configureCopyQ||typeof message.executable!=="string"||message.executable.length<1||message.executable.length>512||typeof message.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(message.session)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCopyQ({executable:message.executable,session:message.session});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-owntracks"){if(!handlers.configureOwnTracks||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureOwnTracks({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zotero"){if(!handlers.configureZotero||typeof message.libraryId!=="string"||!["user","group"].includes(message.libraryType)||!/^[1-9][0-9]{0,19}$/.test(message.libraryId)&&!(message.libraryType==="user"&&message.libraryId==="0")){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZotero({libraryId:message.libraryId,libraryType:message.libraryType});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-native-files"){const sources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"];if(!handlers.configureNativeFiles||!sources.includes(message.source)||!Array.isArray(message.roots)||message.roots.length<1||message.roots.length>16||!message.roots.every(root2=>typeof root2==="string"&&root2.length>0&&root2.length<=4096)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNativeFiles({source:message.source,roots:message.roots});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-status"){if(!handlers.connectorStatus){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorStatus();if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-check"){if(!handlers.connectorCheck||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorCheck(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-read"){if(!handlers.connectorRead||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorRead(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());await markResidentInterruption(id.root,"pause");reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){if(message.guard!==void 0){if(!validUpdateOwner(message.guard)){socket.destroy();return}const guard=message.guard,path=value=>process.platform==="win32"?value.toLowerCase():value;const current=status().update;const reason=stopping||closing||guard.pid!==item.pid||guard.startedAt!==item.startedAt||guard.runtime.version!==runtime.version||path(guard.runtime.installationPath)!==path(runtime.installationPath)?"resident_changed":typeof current?.idle!=="boolean"||typeof current.paused!=="boolean"?"resident_guard_unavailable":current.paused?"resident_paused":!current.idle||activeRequests!==0?"resident_busy":void 0;if(reason){socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,deferred:true,reason})+"\n");return}}else await markResidentInterruption(id.root,"stop");socket.setTimeout(RESIDENT_STOP_TIMEOUT_MS,()=>socket.destroy());stopping??=Promise.resolve().then(()=>traceResidentControl(handlers.telemetry,{phase:"runtime",action:"cleanup",operationId:"resident.stop"},onStop,{plainResult:true}));try{await stopping}catch{stopping=void 0;socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,error:"resident_cleanup_failed"})+"\n");return}socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:false,stopped:true})+"\n");void close()}else socket.destroy()};if(operationalContext)await withOperationalContext(operationalContext,dispatch);else await withoutOperationalContext(dispatch)}catch{socket.destroy()}finally{if(active)activeRequests--}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{const claimed=await installationRecovery.withResidentClaim(async()=>{ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return false;const intent=process.env.ZORTEX_UPDATE_INTENT;if(intent!==void 0&&await residentInterruption(id.root)!==intent)throw Error("The resident was stopped or paused after this update began.");try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return false}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return false}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}if(intent!==void 0&&await residentInterruption(id.root)!==intent)throw Error("The resident was stopped or paused after this update began.");return true},runtime.version);if(!claimed)return null}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const connectDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_CONNECT??"").trim());const lookupPath=platform==="darwin"&&environment.PATH&&!/[\x00-\x1f]/.test(environment.PATH)?[...new Set(environment.PATH.split(":").filter(isAbsolute))].join(":"):void 0;const startupEnvironment={...syncDisabled?{ZORTEX_AUTO_SYNC:"0"}:{},...connectDisabled?{ZORTEX_AUTO_CONNECT:"0"}:{},...lookupPath?{PATH:lookupPath}:{}};const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
|
|
2
2
|
CreateObject("WScript.Shell").Run "${command.replaceAll('"','""')}", 0, False\r
|
|
3
3
|
`;const registryCommand=[windowsQuote("%SystemRoot%\\System32\\wscript.exe"),"//B","//NoLogo",windowsQuote(launcherPath)].join(" ");const label=`com.zortex.indra.${hash}`;const plist=`<?xml version="1.0" encoding="UTF-8"?>
|
|
4
4
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID,createHash}from"node:crypto";import{request as httpRequest}from"node:http";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,validateRead,captureLocalReadAuthority,checkLocalReadAuthority}from"@zortexhq/plugin-connector-core/api";export const defaultActivityWatchUrl="http://127.0.0.1:5600";const SOURCE="activitywatch",SCOPES=["local-activity.read"],MAX_BODY=8*1024*1024,TIMEOUT_MS=8e3,DAILY_DAYS=7,MAX_RANGE_DAYS=31,MAX_SCAN=1e3;const loopback=new Set(["127.0.0.1","[::1]"]);class Unreachable extends Error{}class Refused extends Error{result;constructor(result){super(result.err.message);this.result=result}}function requireOk(result){if(!("ok"in result))throw new Refused("err"in result?result:businessError("data_loss","ActivityWatch custody returned no authority receipt.","storage"));return result.ok}const deny=message=>new Refused(businessError("permission_denied",message,"auth"));const malformed=message=>new Refused(businessError("data_loss",message,"connector"));const bounded=(value,max=512)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);function plain(value,keys){if(!object(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid ActivityWatch native selection.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid ActivityWatch native selection.")}}export function validateActivityWatchConfig(value){plain(value,["baseUrl","deviceId","bucketIds","authority","apiKeyResourceId"])}function localBase(value){if(!bounded(value,2048))throw Error("ActivityWatch requires an exact loopback http origin.");const url=new URL(value);if(url.protocol!=="http:"||!loopback.has(url.hostname)||url.port==="0"||url.username||url.password||url.search||url.hash||url.pathname!=="/"||![url.origin,url.origin+"/"].includes(value))throw Error("ActivityWatch requires an exact loopback http origin.");return url}function selectedBuckets(value){if(!Array.isArray(value)||value.length<1||value.length>32||Reflect.ownKeys(value).length!==value.length+1)throw Error("Select 1\u201332 explicit ActivityWatch bucket IDs.");const ids=[];for(let i=0;i<value.length;i++){const descriptor=Object.getOwnPropertyDescriptor(value,String(i));if(!descriptor||!descriptor.enumerable||!("value"in descriptor)||!bounded(descriptor.value,480)||/[\/\\]/u.test(descriptor.value)||[".",".."].includes(descriptor.value))throw Error("Select valid native ActivityWatch bucket IDs.");ids.push(descriptor.value)}if(new Set(ids).size!==ids.length)throw Error("ActivityWatch bucket IDs must be distinct.");return ids.sort()}export function activityWatchReadAudience(baseUrl,deviceId,bucketIds){const base=localBase(baseUrl),ids=selectedBuckets(bucketIds);if(!bounded(deviceId))throw Error("An explicit native ActivityWatch device ID is required.");return`indra-local-activitywatch:${createHash("sha256").update(JSON.stringify([base.origin,deviceId,ids])).digest("hex")}`}function waitForCustody(work,signal){const cancelled=()=>businessError("aborted","ActivityWatch custody read was cancelled.","auth");if(signal.aborted)return Promise.resolve(cancelled());return new Promise(resolve=>{let settled=false;const finish=value=>{if(settled)return;settled=true;signal.removeEventListener("abort",abort);resolve(value)};const abort=()=>finish(cancelled());signal.addEventListener("abort",abort,{once:true});if(signal.aborted){abort();return}try{void work().then(value=>finish(signal.aborted?cancelled():value),()=>finish(signal.aborted?cancelled():businessError("unavailable","ActivityWatch protected custody could not be read.","storage")))}catch{finish(signal.aborted?cancelled():businessError("unavailable","ActivityWatch protected custody could not be read.","storage"))}})}export function redact(text){return text.replace(/\b(bearer)\s+\S+/gi,"$1 \u2026").replace(/([?&#;](?:[a-z_]*(?:token|key|secret|password|passwd|auth|session|code|sig|signature|otp)[a-z_]*))=[^&\s#;]+/gi,"$1=\u2026").replace(/[A-Za-z0-9_\-+/=]{40,}/g,"\u2026").slice(0,300)}function scalar(value){return typeof value==="string"?redact(value.trim()):typeof value==="number"||typeof value==="boolean"?String(value):""}function page(url){if(typeof url!=="string")return"";try{const parsed=new URL(url);return parsed.protocol==="http:"||parsed.protocol==="https:"?redact(parsed.host+parsed.pathname):""}catch{return""}}export function formatDuration(seconds){if(!Number.isFinite(seconds)||seconds<1)return"<1 s";if(seconds<60)return`${Math.round(seconds)} s`;const minutes=Math.round(seconds/60);return minutes<60?`${minutes} min`:`${Math.floor(minutes/60)} h ${minutes%60} min`}export function renderEvent(type,event){const data=event.data??{},spent=formatDuration(event.duration??0);if(type==="currentwindow"){const app=scalar(data.app)||"Unknown app",title=scalar(data.title);return{kind:"window",body:`${app}${title?` \u2014 ${title}`:""} \xB7 ${spent}`}}if(type==="afkstatus")return{kind:"afk",body:`${data.status==="afk"?"Away from computer":"Active at computer"} \xB7 ${spent}`};if(type.startsWith("web.tab")){const title=scalar(data.title),where=page(data.url);return{kind:"web",body:`${title||where||"Browser tab"}${title&&where?` \u2014 ${where}`:""}${data.audible===true?" (playing audio)":""} \xB7 ${spent}`}}const pairs=Object.entries(data).filter(([key])=>!/url|path|file/i.test(key)).map(([key,value])=>[key,scalar(value)]).filter(([,value])=>value).slice(0,4);return{kind:"event",body:`${type||"activity"}: ${pairs.map(([key,value])=>`${key} ${value}`).join(", ")||"event"} \xB7 ${spent}`}}const localDay=date=>`${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,"0")}-${String(date.getDate()).padStart(2,"0")}`;const startOfDay=date=>new Date(date.getFullYear(),date.getMonth(),date.getDate());function getJson(base,method,path,signal,body,token){return new Promise((resolve,reject)=>{const payload=body===void 0?void 0:Buffer.from(JSON.stringify(body)),deadline=AbortSignal.timeout(TIMEOUT_MS),wireSignal=AbortSignal.any([signal,deadline]);const req=httpRequest({host:base.hostname.replace(/^\[|\]$/g,""),port:base.port||80,method,path,signal:wireSignal,agent:false,headers:{accept:"application/json",...token?{authorization:`Bearer ${token}`}:{},...payload?{"content-type":"application/json","content-length":payload.length}:{}}},response=>{const chunks=[];let size=0;response.on("data",chunk=>{size+=chunk.length;if(size>MAX_BODY){const error=malformed("ActivityWatch response exceeded the bounded read size.");reject(error);req.destroy(error);return}chunks.push(chunk)});response.on("end",()=>{const status=response.statusCode??0;if(status!==200){resolve({status,json:null});return}try{resolve({status,json:JSON.parse(Buffer.concat(chunks).toString("utf8"))})}catch{reject(malformed("ActivityWatch returned a non-JSON read response."))}});response.on("aborted",()=>reject(new Unreachable("ActivityWatch interrupted the selected read.")));response.on("error",reject)});req.on("error",error=>reject(deadline.aborted||error.code==="ECONNREFUSED"?new Unreachable("ActivityWatch did not answer the selected read."):error));req.end(payload)})}export function createActivityWatchProvider(dependencies){plain(dependencies,["vault","baseUrl","deviceId","bucketIds","authority","apiKeyResourceId","now"]);if(dependencies.authority!==void 0)plain(dependencies.authority,["resourceId","issuer","subject","tenant"]);const{vault,deviceId,apiKeyResourceId}=dependencies,base=localBase(dependencies.baseUrl??defaultActivityWatchUrl),now=dependencies.now??(()=>new Date);if(typeof now!=="function")throw Error("Invalid ActivityWatch clock.");if(deviceId!==void 0&&!bounded(deviceId))throw Error("An explicit native ActivityWatch device ID is required.");if(apiKeyResourceId!==void 0&&!bounded(apiKeyResourceId,256))throw Error("Select a protected ActivityWatch API-key reference.");const ids=dependencies.bucketIds===void 0?void 0:Object.freeze(selectedBuckets(dependencies.bucketIds));const policy=dependencies.authority&&deviceId&&ids?{...dependencies.authority,audience:activityWatchReadAudience(base.origin,deviceId,ids),requiredScopes:SCOPES}:void 0;if(apiKeyResourceId&&apiKeyResourceId===policy?.resourceId)throw Error("ActivityWatch native permission and API-key references must be distinct.");const info={source:SOURCE,label:"ActivityWatch",group:"Connector / \u7535\u8111\u6D3B\u52A8",auth:"none"},jobs=new Map;let closed=false;const stop=new AbortController,signalFor=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;function active(signal){if(signal.aborted)throw new Refused(businessError("aborted","ActivityWatch read was cancelled.","connector"));if(closed)throw new Refused(businessError("unavailable","ActivityWatch source is inactive.","plugin"))}async function nativeGuard(native,signal){active(signal);requireOk(await checkLocalReadAuthority(native,vault,signal));active(signal)}function apiSnapshot(native,found){const{binding,grant,resource,material}=found;if(resource.id!==apiKeyResourceId||resource.kind!=="rest-token"||resource.owner.kind!=="resident"||material.kind!=="rest-token")throw new Refused(businessError("failed_precondition","The selected API key is not resident REST-token custody.","auth"));if(binding.id!==native.binding.id||binding.revision!==native.binding.revision||binding.state!=="connected"||grant.id!==native.grant.id||grant.bindingId!==native.binding.id||grant.revision!==native.grant.revision||grant.scopeEpoch!==native.grant.scopeEpoch||grant.state!=="active"||grant.purpose!=="L1"||grant.audience!==native.policy.audience||resource.bindingId!==native.binding.id)throw deny("The ActivityWatch API key belongs to a different native permission.");if(!Number.isSafeInteger(resource.revision)||resource.revision<1)throw malformed("ActivityWatch API-key custody has an invalid revision.");if(typeof material.token!=="string"||!material.token||material.token.length>8192||!/^[\x21-\x7e]+$/u.test(material.token))throw new Refused(businessError("failed_precondition","The protected ActivityWatch bearer key cannot be used as an HTTP credential.","auth"));return{resource:Object.freeze({...resource,owner:Object.freeze({...resource.owner})}),token:material.token}}async function guard(access,signal){await nativeGuard(access.native,signal);if(access.api){const found=apiSnapshot(access.native,requireOk(await waitForCustody(()=>vault.bindingCustody.credentialSnapshot(access.api.resource.id,{purpose:"L1",audience:access.native.policy.audience}),signal)));if(found.resource.revision!==access.api.resource.revision||found.token!==access.api.token)throw deny("The selected ActivityWatch API key changed while the read was pending.");await nativeGuard(access.native,signal);const c=vault.bindingCustody,[binding,grant,nativeResource,apiResource]=await Promise.all([waitForCustody(()=>c.binding(access.native.binding.id),signal),waitForCustody(()=>c.grant(access.native.grant.id),signal),waitForCustody(()=>c.resource(access.native.resource.id),signal),waitForCustody(()=>c.resource(access.api.resource.id),signal)]);const b=requireOk(binding),g=requireOk(grant),n=requireOk(nativeResource),a=requireOk(apiResource);if(!b||b.state!=="connected"||b.revision!==access.native.binding.revision||!g||g.state!=="active"||g.revision!==access.native.grant.revision||g.scopeEpoch!==access.native.grant.scopeEpoch||!n||n.revision!==access.native.resource.revision||n.kind!=="local-no-secret"||!a||a.revision!==access.api.resource.revision||a.kind!=="rest-token")throw deny("The selected ActivityWatch permission changed while the read was pending.")}active(signal)}async function capture(signal){active(signal);if(!policy||!vault?.bindingCustody)throw new Refused(businessError("failed_precondition","Select verified native OS-user permission, the exact ActivityWatch device, and approved bucket IDs before reading.","auth"));const native=requireOk(await captureLocalReadAuthority(SOURCE,policy,vault,signal)),access={native};if(apiKeyResourceId){const metadata=requireOk(await waitForCustody(()=>vault.bindingCustody.resource(apiKeyResourceId),signal));if(!metadata||metadata.kind!=="rest-token"||metadata.owner.kind!=="resident"||metadata.bindingId!==native.binding.id)throw new Refused(businessError("failed_precondition","The selected API key is not resident REST-token custody for this native account.","auth"));await nativeGuard(native,signal);access.api=apiSnapshot(native,requireOk(await waitForCustody(()=>vault.bindingCustody.credentialSnapshot(apiKeyResourceId,{purpose:"L1",audience:native.policy.audience}),signal)));if(metadata.revision!==access.api.resource.revision)throw deny("The selected ActivityWatch API key changed while being read.")}await guard(access,signal);return access}async function call(access,method,path,signal,body){await guard(access,signal);const response=await getJson(base,method,path,signal,body,path==="/api/0/info"?void 0:access.api?.token);await guard(access,signal);if(response.status===401||response.status===403)throw deny("ActivityWatch refused the selected protected API permission.");if(response.status===404)throw new Refused(businessError("not_found","The selected ActivityWatch resource is unavailable.","connector"));if(response.status!==200)throw new Refused(businessError("unavailable","ActivityWatch did not complete the selected local read.","connector"));if(access.api){const encoded=JSON.stringify(response.json),token=access.api.token;if(encoded.includes(token)||encoded.includes(JSON.stringify(token).slice(1,-1)))throw malformed("ActivityWatch returned protected credential material in selected data.")}return response.json}async function identity(access,signal){const found=await call(access,"GET","/api/0/info",signal);if(!object(found)||!bounded(found.device_id))throw malformed("ActivityWatch did not report its native device identity.");if(found.device_id!==deviceId)throw deny("The ActivityWatch server does not match the explicitly approved native device.")}async function payload(access,method,path,signal,body){await identity(access,signal);return call(access,method,path,signal,body)}async function buckets(access,signal){const all=[];for(const id of ids){const found=await payload(access,"GET",`/api/0/buckets/${encodeURIComponent(id)}`,signal);if(!object(found)||found.id!==id||!bounded(found.type,256)||found.hostname!==void 0&&(typeof found.hostname!=="string"||found.hostname.length>512)||found.created!==void 0&&(typeof found.created!=="string"||!Number.isFinite(Date.parse(found.created))))throw malformed("ActivityWatch returned invalid selected-bucket metadata.");all.push({id,type:found.type,...typeof found.hostname==="string"?{hostname:found.hostname}:{},...typeof found.created==="string"?{created:found.created}:{}})}return all}function event(value){if(!object(value)||!Number.isSafeInteger(value.id)||Number(value.id)<0||typeof value.timestamp!=="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u.test(value.timestamp)||!Number.isFinite(Date.parse(value.timestamp))||typeof value.duration!=="number"||!Number.isFinite(value.duration)||value.duration<0||value.duration>Number.MAX_SAFE_INTEGER||!object(value.data))throw malformed("ActivityWatch returned an invalid native event identity or value.");return value}async function events(access,bucket,limit,since,until,signal){const query=new URLSearchParams({limit:String(limit)});if(since)query.set("start",since.toISOString());if(until)query.set("end",until.toISOString());const found=await payload(access,"GET",`/api/0/buckets/${encodeURIComponent(bucket.id)}/events?${query}`,signal);if(!Array.isArray(found)||found.length>limit)throw malformed("ActivityWatch events did not respect the selected read shape or limit.");const seen=new Set;return found.map(value=>{const row=event(value);if(seen.has(row.id))throw malformed("ActivityWatch returned duplicate native event IDs.");seen.add(row.id);const shown=renderEvent(bucket.type,row);return{source:SOURCE,stream:"sample",sourceId:`${bucket.id}:${row.id}`,kind:shown.kind,ts:new Date(row.timestamp).toISOString(),body:shown.body,fields:{bucketType:bucket.type,durationSeconds:Math.round(row.duration)}}})}async function daily(access,all,since,until,signal){const window=all.find(bucket=>bucket.type==="currentwindow");if(!window)return[];const afk=window.hostname?all.find(bucket=>bucket.type==="afkstatus"&&bucket.hostname===window.hostname):void 0;const last=startOfDay(until??now()),first=startOfDay(since??new Date(last.getFullYear(),last.getMonth(),last.getDate()-(DAILY_DAYS-1)));if(!Number.isFinite(last.getTime())||!Number.isFinite(first.getTime()))throw malformed("ActivityWatch daily query has an invalid time range.");const days=[];for(let day=first;day<=last&&days.length<MAX_RANGE_DAYS;day=new Date(day.getFullYear(),day.getMonth(),day.getDate()+1))days.push(day);if(!days.length)return[];const periods=days.map(day=>`${day.toISOString()}/${new Date(day.getFullYear(),day.getMonth(),day.getDate()+1).toISOString()}`);const lines=[`win = flood(query_bucket(${JSON.stringify(window.id)}));`,...afk?[`afk = flood(query_bucket(${JSON.stringify(afk.id)}));`,'win = filter_period_intersect(win, filter_keyvals(afk, "status", ["not-afk"]));']:[],'RETURN = sort_by_duration(merge_events_by_keys(win, ["app"]));'];const found=await payload(access,"POST","/api/0/query/",signal,{query:lines,timeperiods:periods});if(!Array.isArray(found)||found.length!==days.length)throw malformed("ActivityWatch daily query has an unexpected shape.");return days.flatMap((day,index)=>{const values=found[index];if(!Array.isArray(values)||values.length>MAX_SCAN)throw malformed("ActivityWatch daily query did not return a bounded result.");const apps=values.map(value=>{if(!object(value)||!object(value.data)||typeof value.duration!=="number"||!Number.isFinite(value.duration)||value.duration<0||value.duration>Number.MAX_SAFE_INTEGER)throw malformed("ActivityWatch daily query returned an invalid duration or app.");return{app:scalar(value.data.app)||"Unknown app",seconds:value.duration}}).filter(row=>row.seconds>=60);if(!apps.length)return[];const total=apps.reduce((sum,row)=>sum+row.seconds,0),date=localDay(day);if(!Number.isFinite(total)||total>Number.MAX_SAFE_INTEGER)throw malformed("ActivityWatch daily duration exceeded its supported range.");return[{source:SOURCE,stream:"daily",sourceId:`daily:${window.id}:${date}`,kind:"daily",ts:day.toISOString(),body:`${date} computer use ${formatDuration(total)}: ${apps.slice(0,15).map(row=>`${row.app} ${formatDuration(row.seconds)}`).join(", ")}`,fields:{date,activeSeconds:Math.round(total),apps:apps.length}}]})}async function collect(request,access,signal){const limit=request.limit??1,since=request.since?new Date(request.since):void 0,until=request.until?new Date(request.until):void 0,needle=request.query?.toLowerCase();const all=await buckets(access,signal),perBucket=needle?MAX_SCAN:Math.min(limit,100),rows=[...await daily(access,all,since,until,signal)];for(const bucket of all)rows.push(...await events(access,bucket,perBucket,since,until,signal));const matched=rows.filter(row=>!needle||row.body.toLowerCase().includes(needle)).sort((a,b)=>Date.parse(b.ts)-Date.parse(a.ts)||a.sourceId.localeCompare(b.sourceId)),chosen=matched.slice(0,limit);await identity(access,signal);await guard(access,signal);requireOk(await cache(vault,SOURCE,chosen,{source:SOURCE,account:access.native.binding.account,accountId:access.native.binding.identity.subject,requiredScopes:SCOPES,signal}));await guard(access,signal);await identity(access,signal);await guard(access,signal);return{source:SOURCE,records:chosen,returned:chosen.length,scanned:rows.length,matched:matched.length,warnings:[]}}const failure=(error,signal,doing)=>signal.aborted?businessError("aborted",`ActivityWatch ${doing} was cancelled.`,"connector"):error instanceof Refused?error.result:error instanceof Unreachable?businessError("unavailable","ActivityWatch is not running or did not answer on this computer. Open ActivityWatch, then try again.","connector"):businessError("unavailable",`ActivityWatch ${doing} did not complete.`,"connector");return{info,async status(){if(closed)return businessError("unavailable","ActivityWatch source is inactive.","plugin");const signal=signalFor();try{const access=await capture(signal);await identity(access,signal);await guard(access,signal);return ok({...info,state:"connected",account:access.native.binding.account})}catch{return ok({...info,state:"not-connected",message:"Verified native OS-user/device/bucket permission and the matching local ActivityWatch server are required."})}},job:id=>jobs.has(id)?ok({...jobs.get(id)}):businessError("not_found","ActivityWatch connection job not found.","plugin"),async connect(options={}){if(closed)return businessError("unavailable","ActivityWatch source is inactive.","plugin");const signal=signalFor(options.signal);try{const access=await capture(signal),target=options.expectedBinding;if(target&&(target.kind==="binding"?target.bindingId!==access.native.binding.id:target.source!==SOURCE))throw deny("The requested binding does not match the approved ActivityWatch native permission.");await collect({limit:1},access,signal);await guard(access,signal);const job={id:randomUUID(),source:SOURCE,state:"connected",startedAt:new Date().toISOString(),account:access.native.binding.account};jobs.set(job.id,job);return ok({...job})}catch(error){return failure(error,signal,"verification")}},async read(request={},options={}){if(closed)return businessError("unavailable","ActivityWatch source is inactive.","plugin");const invalid=validateRead(request);if(invalid)return invalid;const signal=signalFor(options.signal);try{const access=await capture(signal);return ok(await collect(request,access,signal))}catch(error){return failure(error,signal,"read")}},async close(){closed=true;stop.abort()}}}
|
|
1
|
+
import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID,createHash}from"node:crypto";import{request as httpRequest}from"node:http";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,validateRead,captureLocalReadAuthority,checkLocalReadAuthority}from"@zortexhq/plugin-connector-core/api";export const defaultActivityWatchUrl="http://127.0.0.1:5600";const SOURCE="activitywatch",SCOPES=["local-activity.read"],MAX_BODY=8*1024*1024,TIMEOUT_MS=8e3,DAILY_DAYS=7,MAX_RANGE_DAYS=31,MAX_SCAN=1e3;const loopback=new Set(["127.0.0.1","[::1]"]);class Unreachable extends Error{}class Refused extends Error{result;constructor(result){super(result.err.message);this.result=result}}function requireOk(result){if(!("ok"in result))throw new Refused("err"in result?result:businessError("data_loss","ActivityWatch custody returned no authority receipt.","storage"));return result.ok}const deny=message=>new Refused(businessError("permission_denied",message,"auth"));const malformed=message=>new Refused(businessError("data_loss",message,"connector"));const bounded=(value,max=512)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);function plain(value,keys){if(!object(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid ActivityWatch native selection.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid ActivityWatch native selection.")}}export function validateActivityWatchConfig(value){plain(value,["baseUrl","deviceId","bucketIds","authority","apiKeyResourceId"])}function localBase(value){if(!bounded(value,2048))throw Error("ActivityWatch requires an exact loopback http origin.");const url=new URL(value);if(url.protocol!=="http:"||!loopback.has(url.hostname)||url.port==="0"||url.username||url.password||url.search||url.hash||url.pathname!=="/"||![url.origin,url.origin+"/"].includes(value))throw Error("ActivityWatch requires an exact loopback http origin.");return url}function selectedBuckets(value){if(!Array.isArray(value)||value.length<1||value.length>32||Reflect.ownKeys(value).length!==value.length+1)throw Error("Select 1\u201332 explicit ActivityWatch bucket IDs.");const ids=[];for(let i=0;i<value.length;i++){const descriptor=Object.getOwnPropertyDescriptor(value,String(i));if(!descriptor||!descriptor.enumerable||!("value"in descriptor)||!bounded(descriptor.value,480)||/[\/\\]/u.test(descriptor.value)||[".",".."].includes(descriptor.value))throw Error("Select valid native ActivityWatch bucket IDs.");ids.push(descriptor.value)}if(new Set(ids).size!==ids.length)throw Error("ActivityWatch bucket IDs must be distinct.");return ids.sort()}export function activityWatchReadAudience(baseUrl,deviceId,bucketIds){const base=localBase(baseUrl),ids=selectedBuckets(bucketIds);if(!bounded(deviceId))throw Error("An explicit native ActivityWatch device ID is required.");return`indra-local-activitywatch:${createHash("sha256").update(JSON.stringify([base.origin,deviceId,ids])).digest("hex")}`}function waitForCustody(work,signal){const cancelled=()=>businessError("aborted","ActivityWatch custody read was cancelled.","auth");if(signal.aborted)return Promise.resolve(cancelled());return new Promise(resolve=>{let settled=false;const finish=value=>{if(settled)return;settled=true;signal.removeEventListener("abort",abort);resolve(value)};const abort=()=>finish(cancelled());signal.addEventListener("abort",abort,{once:true});if(signal.aborted){abort();return}try{void work().then(value=>finish(signal.aborted?cancelled():value),()=>finish(signal.aborted?cancelled():businessError("unavailable","ActivityWatch protected custody could not be read.","storage")))}catch{finish(signal.aborted?cancelled():businessError("unavailable","ActivityWatch protected custody could not be read.","storage"))}})}export function redact(text){return text.replace(/\b(bearer)\s+\S+/gi,"$1 \u2026").replace(/([?&#;](?:[a-z_]*(?:token|key|secret|password|passwd|auth|session|code|sig|signature|otp)[a-z_]*))=[^&\s#;]+/gi,"$1=\u2026").replace(/[A-Za-z0-9_\-+/=]{40,}/g,"\u2026").slice(0,300)}function scalar(value){return typeof value==="string"?redact(value.trim()):typeof value==="number"||typeof value==="boolean"?String(value):""}function page(url){if(typeof url!=="string")return"";try{const parsed=new URL(url);return parsed.protocol==="http:"||parsed.protocol==="https:"?redact(parsed.host+parsed.pathname):""}catch{return""}}export function formatDuration(seconds){if(!Number.isFinite(seconds)||seconds<1)return"<1 s";if(seconds<60)return`${Math.round(seconds)} s`;const minutes=Math.round(seconds/60);return minutes<60?`${minutes} min`:`${Math.floor(minutes/60)} h ${minutes%60} min`}export function renderEvent(type,event){const data=event.data??{},spent=formatDuration(event.duration??0);if(type==="currentwindow"){const app=scalar(data.app)||"Unknown app",title=scalar(data.title);return{kind:"window",body:`${app}${title?` \u2014 ${title}`:""} \xB7 ${spent}`}}if(type==="afkstatus")return{kind:"afk",body:`${data.status==="afk"?"Away from computer":"Active at computer"} \xB7 ${spent}`};if(type.startsWith("web.tab")){const title=scalar(data.title),where=page(data.url);return{kind:"web",body:`${title||where||"Browser tab"}${title&&where?` \u2014 ${where}`:""}${data.audible===true?" (playing audio)":""} \xB7 ${spent}`}}const pairs=Object.entries(data).filter(([key])=>!/url|path|file/i.test(key)).map(([key,value])=>[key,scalar(value)]).filter(([,value])=>value).slice(0,4);return{kind:"event",body:`${type||"activity"}: ${pairs.map(([key,value])=>`${key} ${value}`).join(", ")||"event"} \xB7 ${spent}`}}const localDay=date=>`${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,"0")}-${String(date.getDate()).padStart(2,"0")}`;const startOfDay=date=>new Date(date.getFullYear(),date.getMonth(),date.getDate());function getJson(base,method,path,signal,body,token){return new Promise((resolve,reject)=>{const payload=body===void 0?void 0:Buffer.from(JSON.stringify(body)),deadline=AbortSignal.timeout(TIMEOUT_MS),wireSignal=AbortSignal.any([signal,deadline]);const req=httpRequest({host:base.hostname.replace(/^\[|\]$/g,""),port:base.port||80,method,path,signal:wireSignal,agent:false,headers:{accept:"application/json",...token?{authorization:`Bearer ${token}`}:{},...payload?{"content-type":"application/json","content-length":payload.length}:{}}},response=>{const chunks=[];let size=0;response.on("data",chunk=>{size+=chunk.length;if(size>MAX_BODY){const error=malformed("ActivityWatch response exceeded the bounded read size.");reject(error);req.destroy(error);return}chunks.push(chunk)});response.on("end",()=>{const status=response.statusCode??0;if(status!==200){resolve({status,json:null});return}try{resolve({status,json:JSON.parse(Buffer.concat(chunks).toString("utf8"))})}catch{reject(malformed("ActivityWatch returned a non-JSON read response."))}});response.on("aborted",()=>reject(new Unreachable("ActivityWatch interrupted the selected read.")));response.on("error",reject)});req.on("error",error=>reject(deadline.aborted||error.code==="ECONNREFUSED"?new Unreachable("ActivityWatch did not answer the selected read."):error));req.end(payload)})}export function createActivityWatchProvider(dependencies){plain(dependencies,["vault","baseUrl","deviceId","bucketIds","authority","apiKeyResourceId","now"]);if(dependencies.authority!==void 0)plain(dependencies.authority,["resourceId","issuer","subject","tenant"]);const{vault,deviceId,apiKeyResourceId}=dependencies,base=localBase(dependencies.baseUrl??defaultActivityWatchUrl),now=dependencies.now??(()=>new Date);if(typeof now!=="function")throw Error("Invalid ActivityWatch clock.");if(deviceId!==void 0&&!bounded(deviceId))throw Error("An explicit native ActivityWatch device ID is required.");if(apiKeyResourceId!==void 0&&!bounded(apiKeyResourceId,256))throw Error("Select a protected ActivityWatch API-key reference.");const ids=dependencies.bucketIds===void 0?void 0:Object.freeze(selectedBuckets(dependencies.bucketIds));const policy=dependencies.authority&&deviceId&&ids?{...dependencies.authority,audience:activityWatchReadAudience(base.origin,deviceId,ids),requiredScopes:SCOPES}:void 0;if(apiKeyResourceId&&apiKeyResourceId===policy?.resourceId)throw Error("ActivityWatch native permission and API-key references must be distinct.");const info={content:[acquiredReadCapability(["plugins/connector-activitywatch/README.md"]),unreviewedActionContent(["plugins/connector-activitywatch/README.md"])],source:SOURCE,label:"ActivityWatch",group:"Connector / \u7535\u8111\u6D3B\u52A8",auth:"none"},jobs=new Map;let closed=false;const stop=new AbortController,signalFor=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;function active(signal){if(signal.aborted)throw new Refused(businessError("aborted","ActivityWatch read was cancelled.","connector"));if(closed)throw new Refused(businessError("unavailable","ActivityWatch source is inactive.","plugin"))}async function nativeGuard(native,signal){active(signal);requireOk(await checkLocalReadAuthority(native,vault,signal));active(signal)}function apiSnapshot(native,found){const{binding,grant,resource,material}=found;if(resource.id!==apiKeyResourceId||resource.kind!=="rest-token"||resource.owner.kind!=="resident"||material.kind!=="rest-token")throw new Refused(businessError("failed_precondition","The selected API key is not resident REST-token custody.","auth"));if(binding.id!==native.binding.id||binding.revision!==native.binding.revision||binding.state!=="connected"||grant.id!==native.grant.id||grant.bindingId!==native.binding.id||grant.revision!==native.grant.revision||grant.scopeEpoch!==native.grant.scopeEpoch||grant.state!=="active"||grant.purpose!=="L1"||grant.audience!==native.policy.audience||resource.bindingId!==native.binding.id)throw deny("The ActivityWatch API key belongs to a different native permission.");if(!Number.isSafeInteger(resource.revision)||resource.revision<1)throw malformed("ActivityWatch API-key custody has an invalid revision.");if(typeof material.token!=="string"||!material.token||material.token.length>8192||!/^[\x21-\x7e]+$/u.test(material.token))throw new Refused(businessError("failed_precondition","The protected ActivityWatch bearer key cannot be used as an HTTP credential.","auth"));return{resource:Object.freeze({...resource,owner:Object.freeze({...resource.owner})}),token:material.token}}async function guard(access,signal){await nativeGuard(access.native,signal);if(access.api){const found=apiSnapshot(access.native,requireOk(await waitForCustody(()=>vault.bindingCustody.credentialSnapshot(access.api.resource.id,{purpose:"L1",audience:access.native.policy.audience}),signal)));if(found.resource.revision!==access.api.resource.revision||found.token!==access.api.token)throw deny("The selected ActivityWatch API key changed while the read was pending.");await nativeGuard(access.native,signal);const c=vault.bindingCustody,[binding,grant,nativeResource,apiResource]=await Promise.all([waitForCustody(()=>c.binding(access.native.binding.id),signal),waitForCustody(()=>c.grant(access.native.grant.id),signal),waitForCustody(()=>c.resource(access.native.resource.id),signal),waitForCustody(()=>c.resource(access.api.resource.id),signal)]);const b=requireOk(binding),g=requireOk(grant),n=requireOk(nativeResource),a=requireOk(apiResource);if(!b||b.state!=="connected"||b.revision!==access.native.binding.revision||!g||g.state!=="active"||g.revision!==access.native.grant.revision||g.scopeEpoch!==access.native.grant.scopeEpoch||!n||n.revision!==access.native.resource.revision||n.kind!=="local-no-secret"||!a||a.revision!==access.api.resource.revision||a.kind!=="rest-token")throw deny("The selected ActivityWatch permission changed while the read was pending.")}active(signal)}async function capture(signal){active(signal);if(!policy||!vault?.bindingCustody)throw new Refused(businessError("failed_precondition","Select verified native OS-user permission, the exact ActivityWatch device, and approved bucket IDs before reading.","auth"));const native=requireOk(await captureLocalReadAuthority(SOURCE,policy,vault,signal)),access={native};if(apiKeyResourceId){const metadata=requireOk(await waitForCustody(()=>vault.bindingCustody.resource(apiKeyResourceId),signal));if(!metadata||metadata.kind!=="rest-token"||metadata.owner.kind!=="resident"||metadata.bindingId!==native.binding.id)throw new Refused(businessError("failed_precondition","The selected API key is not resident REST-token custody for this native account.","auth"));await nativeGuard(native,signal);access.api=apiSnapshot(native,requireOk(await waitForCustody(()=>vault.bindingCustody.credentialSnapshot(apiKeyResourceId,{purpose:"L1",audience:native.policy.audience}),signal)));if(metadata.revision!==access.api.resource.revision)throw deny("The selected ActivityWatch API key changed while being read.")}await guard(access,signal);return access}async function call(access,method,path,signal,body){await guard(access,signal);const response=await getJson(base,method,path,signal,body,path==="/api/0/info"?void 0:access.api?.token);await guard(access,signal);if(response.status===401||response.status===403)throw deny("ActivityWatch refused the selected protected API permission.");if(response.status===404)throw new Refused(businessError("not_found","The selected ActivityWatch resource is unavailable.","connector"));if(response.status!==200)throw new Refused(businessError("unavailable","ActivityWatch did not complete the selected local read.","connector"));if(access.api){const encoded=JSON.stringify(response.json),token=access.api.token;if(encoded.includes(token)||encoded.includes(JSON.stringify(token).slice(1,-1)))throw malformed("ActivityWatch returned protected credential material in selected data.")}return response.json}async function identity(access,signal){const found=await call(access,"GET","/api/0/info",signal);if(!object(found)||!bounded(found.device_id))throw malformed("ActivityWatch did not report its native device identity.");if(found.device_id!==deviceId)throw deny("The ActivityWatch server does not match the explicitly approved native device.")}async function payload(access,method,path,signal,body){await identity(access,signal);return call(access,method,path,signal,body)}async function buckets(access,signal){const all=[];for(const id of ids){const found=await payload(access,"GET",`/api/0/buckets/${encodeURIComponent(id)}`,signal);if(!object(found)||found.id!==id||!bounded(found.type,256)||found.hostname!==void 0&&(typeof found.hostname!=="string"||found.hostname.length>512)||found.created!==void 0&&(typeof found.created!=="string"||!Number.isFinite(Date.parse(found.created))))throw malformed("ActivityWatch returned invalid selected-bucket metadata.");all.push({id,type:found.type,...typeof found.hostname==="string"?{hostname:found.hostname}:{},...typeof found.created==="string"?{created:found.created}:{}})}return all}function event(value){if(!object(value)||!Number.isSafeInteger(value.id)||Number(value.id)<0||typeof value.timestamp!=="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u.test(value.timestamp)||!Number.isFinite(Date.parse(value.timestamp))||typeof value.duration!=="number"||!Number.isFinite(value.duration)||value.duration<0||value.duration>Number.MAX_SAFE_INTEGER||!object(value.data))throw malformed("ActivityWatch returned an invalid native event identity or value.");return value}async function events(access,bucket,limit,since,until,signal){const query=new URLSearchParams({limit:String(limit)});if(since)query.set("start",since.toISOString());if(until)query.set("end",until.toISOString());const found=await payload(access,"GET",`/api/0/buckets/${encodeURIComponent(bucket.id)}/events?${query}`,signal);if(!Array.isArray(found)||found.length>limit)throw malformed("ActivityWatch events did not respect the selected read shape or limit.");const seen=new Set;return found.map(value=>{const row=event(value);if(seen.has(row.id))throw malformed("ActivityWatch returned duplicate native event IDs.");seen.add(row.id);const shown=renderEvent(bucket.type,row);return{source:SOURCE,stream:"sample",sourceId:`${bucket.id}:${row.id}`,kind:shown.kind,ts:new Date(row.timestamp).toISOString(),body:shown.body,fields:{bucketType:bucket.type,durationSeconds:Math.round(row.duration)}}})}async function daily(access,all,since,until,signal){const window=all.find(bucket=>bucket.type==="currentwindow");if(!window)return[];const afk=window.hostname?all.find(bucket=>bucket.type==="afkstatus"&&bucket.hostname===window.hostname):void 0;const last=startOfDay(until??now()),first=startOfDay(since??new Date(last.getFullYear(),last.getMonth(),last.getDate()-(DAILY_DAYS-1)));if(!Number.isFinite(last.getTime())||!Number.isFinite(first.getTime()))throw malformed("ActivityWatch daily query has an invalid time range.");const days=[];for(let day=first;day<=last&&days.length<MAX_RANGE_DAYS;day=new Date(day.getFullYear(),day.getMonth(),day.getDate()+1))days.push(day);if(!days.length)return[];const periods=days.map(day=>`${day.toISOString()}/${new Date(day.getFullYear(),day.getMonth(),day.getDate()+1).toISOString()}`);const lines=[`win = flood(query_bucket(${JSON.stringify(window.id)}));`,...afk?[`afk = flood(query_bucket(${JSON.stringify(afk.id)}));`,'win = filter_period_intersect(win, filter_keyvals(afk, "status", ["not-afk"]));']:[],'RETURN = sort_by_duration(merge_events_by_keys(win, ["app"]));'];const found=await payload(access,"POST","/api/0/query/",signal,{query:lines,timeperiods:periods});if(!Array.isArray(found)||found.length!==days.length)throw malformed("ActivityWatch daily query has an unexpected shape.");return days.flatMap((day,index)=>{const values=found[index];if(!Array.isArray(values)||values.length>MAX_SCAN)throw malformed("ActivityWatch daily query did not return a bounded result.");const apps=values.map(value=>{if(!object(value)||!object(value.data)||typeof value.duration!=="number"||!Number.isFinite(value.duration)||value.duration<0||value.duration>Number.MAX_SAFE_INTEGER)throw malformed("ActivityWatch daily query returned an invalid duration or app.");return{app:scalar(value.data.app)||"Unknown app",seconds:value.duration}}).filter(row=>row.seconds>=60);if(!apps.length)return[];const total=apps.reduce((sum,row)=>sum+row.seconds,0),date=localDay(day);if(!Number.isFinite(total)||total>Number.MAX_SAFE_INTEGER)throw malformed("ActivityWatch daily duration exceeded its supported range.");return[{source:SOURCE,stream:"daily",sourceId:`daily:${window.id}:${date}`,kind:"daily",ts:day.toISOString(),body:`${date} computer use ${formatDuration(total)}: ${apps.slice(0,15).map(row=>`${row.app} ${formatDuration(row.seconds)}`).join(", ")}`,fields:{date,activeSeconds:Math.round(total),apps:apps.length}}]})}async function collect(request,access,signal){const limit=request.limit??1,since=request.since?new Date(request.since):void 0,until=request.until?new Date(request.until):void 0,needle=request.query?.toLowerCase();const all=await buckets(access,signal),perBucket=needle?MAX_SCAN:Math.min(limit,100),rows=[...await daily(access,all,since,until,signal)];for(const bucket of all)rows.push(...await events(access,bucket,perBucket,since,until,signal));const matched=rows.filter(row=>!needle||row.body.toLowerCase().includes(needle)).sort((a,b)=>Date.parse(b.ts)-Date.parse(a.ts)||a.sourceId.localeCompare(b.sourceId)),chosen=matched.slice(0,limit);await identity(access,signal);await guard(access,signal);requireOk(await cache(vault,SOURCE,chosen,{source:SOURCE,account:access.native.binding.account,accountId:access.native.binding.identity.subject,requiredScopes:SCOPES,signal}));await guard(access,signal);await identity(access,signal);await guard(access,signal);return{source:SOURCE,records:chosen,returned:chosen.length,scanned:rows.length,matched:matched.length,warnings:[]}}const failure=(error,signal,doing)=>signal.aborted?businessError("aborted",`ActivityWatch ${doing} was cancelled.`,"connector"):error instanceof Refused?error.result:error instanceof Unreachable?businessError("unavailable","ActivityWatch is not running or did not answer on this computer. Open ActivityWatch, then try again.","connector"):businessError("unavailable",`ActivityWatch ${doing} did not complete.`,"connector");return{info,async status(){if(closed)return businessError("unavailable","ActivityWatch source is inactive.","plugin");const signal=signalFor();try{const access=await capture(signal);await identity(access,signal);await guard(access,signal);return ok({...info,state:"connected",account:access.native.binding.account})}catch{return ok({...info,state:"not-connected",message:"Verified native OS-user/device/bucket permission and the matching local ActivityWatch server are required."})}},job:id=>jobs.has(id)?ok({...jobs.get(id)}):businessError("not_found","ActivityWatch connection job not found.","plugin"),async connect(options={}){if(closed)return businessError("unavailable","ActivityWatch source is inactive.","plugin");const signal=signalFor(options.signal);try{const access=await capture(signal),target=options.expectedBinding;if(target&&(target.kind==="binding"?target.bindingId!==access.native.binding.id:target.source!==SOURCE))throw deny("The requested binding does not match the approved ActivityWatch native permission.");await collect({limit:1},access,signal);await guard(access,signal);const job={id:randomUUID(),source:SOURCE,state:"connected",startedAt:new Date().toISOString(),account:access.native.binding.account};jobs.set(job.id,job);return ok({...job})}catch(error){return failure(error,signal,"verification")}},async read(request={},options={}){if(closed)return businessError("unavailable","ActivityWatch source is inactive.","plugin");const invalid=validateRead(request);if(invalid)return invalid;const signal=signalFor(options.signal);try{const access=await capture(signal);return ok(await collect(request,access,signal))}catch(error){return failure(error,signal,"read")}},async close(){closed=true;stop.abort()}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{};
|
|
1
|
+
export function connectorContentGaps(content){if(!content?.length)return[{resource:"*",status:"unreviewed",missingFields:[]}];return content.map(row=>{const missingFields=row.readFields.filter(field=>!row.storedFields.includes(field));const status=row.read==="unsupported"?"unsupported":row.read==="unimplemented"?"read-missing":row.read==="unreviewed"?"unreviewed":row.persistence==="durable"&&!missingFields.length?"aligned":"persistence-missing";return{resource:row.resource,status,missingFields:[...missingFields]}})}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{businessError,canonicalJson,ok}from"@zortexhq/plugin-connector-framework/api";export const acquiredReadCapability=evidence=>({resource:"connector.read",read:"implemented",acquisition:"lookup",persistence:"durable",readFields:["record"],storedFields:["record"],updates:"lookup",evidence,limitations:["Only the reviewed normalized read result is acquired. No collection enumeration, arbitrary Action parity or deletion detection is implied."]});export const unreviewedActionContent=evidence=>({resource:"actions.read",read:"unreviewed",acquisition:"unreviewed",persistence:"unreviewed",readFields:[],storedFields:[],updates:"none",evidence,limitations:["Action discovery does not establish content mapping or persistence. Operational commands are not content collections."]});export const acquiredActionCapability=evidence=>({resource:"actions.read",read:"implemented",acquisition:"lookup",persistence:"durable",readFields:["response"],storedFields:["response"],updates:"lookup",evidence,limitations:["Explicit selected readonly Action only. One complete text/JSON response document, not item-level or account-wide synchronization. Credentials, media and incomplete responses are refused. No automatic tool selection or background execution."]});export function validAcquisitionAction(source,action){if(!action||typeof action!=="object"||Array.isArray(action))return false;const row=action;if(Object.keys(row).some(key=>!["name","params"].includes(key))||typeof row.name!=="string"||!row.name.startsWith(source+".")||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(row.name.slice(source.length+1))||!row.params||typeof row.params!=="object"||Array.isArray(row.params))return false;try{return Buffer.byteLength(canonicalJson(row.params))<=65536}catch{return false}}export function acquiredContentRecord(source,row){if(row.source!==source||typeof row.sourceId!=="string"||!row.sourceId)throw Error("A provider-owned stable record identity is required.");const record=Object.fromEntries(Object.entries(row).filter(([,value])=>value!==void 0));const fields=JSON.parse(canonicalJson(record)),title=row.fields?.title??row.fields?.subject??row.fields?.name;return{id:row.sourceId,body:row.body??"",fields:{record:fields,...typeof title==="string"?{title}:{}},...row.ts?{ts:new Date(row.ts).toISOString()}:{}}}export async function acquireConnectorContent(deps,source,request={},options={}){if(request.action!==void 0&&(!validAcquisitionAction(source,request.action)||["query","since","until","fileId"].some(key=>request[key]!==void 0)))return businessError("invalid_argument","Action acquisition requires one source-qualified Action and params; do not combine it with content filters.","plugin");const resource=request.action?"actions.read":"connector.read";const info=deps.hub.describe?.(source),capability=info?.content?.find(row=>row.resource===resource);if(!info||capability?.read!=="implemented"||capability.persistence!=="durable")return businessError("failed_precondition","This source has no reviewed content acquisition mapping. Actions may still be available; this is an implementation gap.","plugin");if(options.signal?.aborted)return businessError("aborted","Acquisition cancelled.","plugin");const port=deps.vault.beginContentAcquisition(source,resource);if(!("ok"in port))return port;const reply=await deps.hub.read(source,{...request,limit:request.limit??100},{...options,retention:"transient"});if(!("ok"in reply))return reply;if(deps.hub.describe?.(source)!==info)return businessError("aborted","Source registration changed during acquisition.","plugin");let records;try{records=reply.ok.records.map(row=>acquiredContentRecord(source,row))}catch{return businessError("data_loss","Provider content cannot be preserved as complete identified JSON records.","plugin")}const saved=port.ok.append(records,options.signal);return"ok"in saved?ok({receipt:saved.ok,warnings:[...reply.ok.warnings,"Only this acquired batch is stored; account-wide coverage is not established."]}):saved}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./connections.js";export*from"./connection-feedback.js";export*from"./wait-authorization.js";export*from"./connector-utils.js";export*from"./connector-v3.js";export*from"./connectors.js";export*from"./local-read-custody.js";export*from"./selected-account.js";export{isTransientConnectorAction,withTransientConnectorAction}from"../transient-action-context.js";export{currentNativePrincipal,saveNativeReadPermission}from"../native-principal.js";export{readNativeUserFileRoots}from"../native-file-roots.js";export{createPinnedLoopbackHttp}from"../transport.js";
|
|
1
|
+
export*from"./connections.js";export*from"./connection-feedback.js";export*from"./wait-authorization.js";export*from"./connector-utils.js";export*from"./connector-v3.js";export*from"./connectors.js";export*from"./local-read-custody.js";export*from"./selected-account.js";export{isTransientConnectorAction,withTransientConnectorAction}from"../transient-action-context.js";export{currentNativePrincipal,saveNativeReadPermission}from"../native-principal.js";export{readNativeUserFileRoots}from"../native-file-roots.js";export{createPinnedLoopbackHttp}from"../transport.js";export*from"./content-acquisition.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash}from"node:crypto";import{canonicalJson}from"@zortexhq/plugin-connector-framework/api";const secretKey=/^(?:access_?token|refresh_?token|id_?token|client_?secret|api_?key|password|passwd|authorization|cookie|set-cookie|private_?key|credential(?:s)?)$/i;export function contentActionAllowed(name){return!/(?:^|[_.-])(?:auth|oauth|login|logout|token|tokens|secret|secrets|password|credential|credentials|cookie|cookies|environment|env|config|configuration|settings|session|sessions)(?:$|[_.-])/i.test(name.replace(/([a-z])([A-Z])/g,"$1_$2"))}function inspect(value,depth=0){if(depth>64)throw Error("Content response nesting exceeds the preservation bound.");if(typeof value==="string"){if(/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/.test(value))throw Error("Credential material is not content.");if(depth<64&&/^[\s]*[\[{]/.test(value)){let parsed;try{parsed=JSON.parse(value)}catch{return}inspect(parsed,depth+1)}}else if(value&&typeof value==="object"){for(const[key,item]of Object.entries(value)){if(secretKey.test(key))throw Error("Credential fields are not content.");inspect(item,depth+1)}}}export function actionContentRecord(source,action,response){if(!contentActionAllowed(action.name.slice(source.length+1)))throw Error("This Action reads configuration or authorization state.");if(response.content!==void 0&&(!Array.isArray(response.content)||response.content.some(block=>!block||typeof block!=="object"||!["text","resource"].includes(block.type)||block.type==="resource"&&(typeof block.resource?.text!=="string"||block.resource?.blob!==void 0))))throw Error("Non-text MCP content needs a format-specific mapper.");const data=response.structured;if(data&&typeof data==="object"&&!Array.isArray(data)){const row=data;if(row.success===false||row.error||Array.isArray(row.errors)&&row.errors.length)throw Error("Provider returned a failed content response.")}inspect(response);const payload=JSON.parse(canonicalJson(response)),scope=createHash("sha256").update(canonicalJson(action.params)).digest("hex");const embedded=Array.isArray(response.content)?response.content.filter(block=>block.type==="resource").map(block=>block.resource.text):[];return{source,sourceId:action.name+":"+scope,kind:"mcp-response",body:[response.text,...embedded,data===void 0?"":canonicalJson(data)].filter(Boolean).join("\n"),fields:{title:action.name,action:action.name,response:payload,scope:"acquired-response"}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function publicRecords(source,structured,_text){if(!structured||typeof structured!=="object"||Array.isArray(structured))return;const value=structured;if(Object.keys(value).some(key=>key!=="records")||!Array.isArray(value.records)||value.records.length>20)return;const ids=new Set,records=[];for(const row of value.records){if(!row||typeof row!=="object"||Array.isArray(row)||Object.keys(row).some(key=>!["id","title","detail","url"].includes(key))||typeof row.id!=="string"||!row.id.trim()||row.id.length>512||ids.has(row.id)||typeof row.title!=="string"||!row.title.trim()||row.title.length>1024||row.detail!==void 0&&(typeof row.detail!=="string"||row.detail.length>2048))return;if(row.url!==void 0){try{const url=new URL(row.url);if(typeof row.url!=="string"||row.url.length>2048||url.protocol!=="https:"||url.username||url.password)return}catch{return}}ids.add(row.id);records.push({source,sourceId:row.id,kind:"public-record",body:[row.title,row.detail??""].filter(Boolean).join("\n"),fields:{...row}})}return records}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fileURLToPath}from"node:url";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{reviewedToolSchemaHash}from"../custodied.js";import{proxyEnv}from"../shallow.js";import{publicProviders}from"./catalog.js";import{publicUrl}from"./read.js";import{lookupSchema}from"./schema.js";export const publicDataSources=publicProviders.map(provider=>({source:provider.id,label:provider.label,group:"Connector / Public data",auth:{kind:"none"},readOnly:true,publicTools:["lookup"],allowedTools:["lookup"],reviewedReadTools:{lookup:{inputSchemaSha256:reviewedToolSchemaHash(lookupSchema)}},server:{transport:"stdio",command:process.execPath,args:[fileURLToPath(new URL("./server.js",import.meta.url)),provider.id],env:()=>proxyEnv()},origin:{official:false,repo:"ZortexHQ/indra",artifact:"zortex-public-data-bridge@1.0.0",check:"Pinned MCP SDK wraps GET requests to the official public endpoint on "+provider.hosts.join(", ")+"."},validateParams(tool,args){try{if(tool!=="lookup")throw Error();publicUrl(provider,args);return ok(void 0)}catch{return businessError("invalid_argument",provider.description+" Example: "+provider.example,"plugin")}}}));
|
|
1
|
+
import{fileURLToPath}from"node:url";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{reviewedToolSchemaHash}from"../custodied.js";import{proxyEnv}from"../shallow.js";import{publicProviders}from"./catalog.js";import{publicUrl}from"./read.js";import{publicRecords}from"./content.js";import{lookupSchema}from"./schema.js";export const publicDataSources=publicProviders.map(provider=>({source:provider.id,label:provider.label,group:"Connector / Public data",auth:{kind:"none"},readOnly:true,publicTools:["lookup"],allowedTools:["lookup"],reviewedReadTools:{lookup:{inputSchemaSha256:reviewedToolSchemaHash(lookupSchema)}},server:{transport:"stdio",command:process.execPath,args:[fileURLToPath(new URL("./server.js",import.meta.url)),provider.id],env:()=>proxyEnv()},origin:{official:false,repo:"ZortexHQ/indra",artifact:"zortex-public-data-bridge@1.0.0",check:"Pinned MCP SDK wraps GET requests to the official public endpoint on "+provider.hosts.join(", ")+"."},liveRead:{tool:"lookup",queryArgs(query){const args={query};publicUrl(provider,args);return args},records:publicRecords},validateParams(tool,args){try{if(tool!=="lookup")throw Error();publicUrl(provider,args);return ok(void 0)}catch{return businessError("invalid_argument",provider.description+" Example: "+provider.example,"plugin")}}}));
|