@nativestudio/cli 0.3.0-rc.14 → 0.3.0-rc.15
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/COMPATIBILITY.json +11 -11
- package/components/runtime.json +7 -7
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-2AI3WF2O.js → chunk-5UJEP7FY.js} +1 -1
- package/dist/_chunks/chunk-AAGFHT2D.js +1 -0
- package/dist/_chunks/{chunk-ROBBF33U.js → chunk-BBTZJB2G.js} +1 -1
- package/dist/_chunks/chunk-BX2SNMA4.js +1 -0
- package/dist/_chunks/chunk-CFZNDURD.js +1 -0
- package/dist/_chunks/{chunk-3AVC742O.js → chunk-FX5UVDTH.js} +1 -1
- package/dist/_chunks/{chunk-U7ECMITP.js → chunk-H6EZKOYR.js} +1 -1
- package/dist/_chunks/chunk-I5KYSPUJ.js +1 -0
- package/dist/_chunks/chunk-KOCUZ3AE.js +1 -0
- package/dist/_chunks/{chunk-RDIMORUT.js → chunk-NPDLPC5B.js} +1 -1
- package/dist/_chunks/{chunk-RK2P3UVF.js → chunk-NQVUVPW5.js} +1 -1
- package/dist/_chunks/{chunk-VD3OQ743.js → chunk-O47YYPL7.js} +1 -1
- package/dist/_chunks/{chunk-6LY4JYSG.js → chunk-OVIR77ET.js} +1 -1
- package/dist/_chunks/{chunk-VDNNFVTZ.js → chunk-OW6R4MAQ.js} +1 -1
- package/dist/_chunks/{chunk-VKLS4QK5.js → chunk-PB2HLRXG.js} +1 -1
- package/dist/_chunks/chunk-RUPH3HZ2.js +1 -0
- package/dist/_chunks/chunk-SAPEOZ2V.js +1 -0
- package/dist/_chunks/chunk-SKAVQ4UW.js +1 -0
- package/dist/_chunks/{chunk-C62JAWRQ.js → chunk-TTB7CYC5.js} +1 -1
- package/dist/_chunks/chunk-U5FT4VBR.js +1 -0
- package/dist/_chunks/chunk-VOGKKZQH.js +1 -0
- package/dist/_chunks/chunk-YV447AB5.js +1 -0
- package/dist/_chunks/{chunk-W6C63ZN7.js → chunk-ZADAXKKY.js} +1 -1
- package/dist/_chunks/{chunk-S74X4KIC.js → chunk-ZOODOQBH.js} +1 -1
- package/dist/_chunks/{connect-6UH7ZFAC.js → connect-RIODOO3C.js} +1 -1
- package/dist/_chunks/{device-management-H3NIDIPY.js → device-management-VECG3RA4.js} +1 -1
- package/dist/_chunks/{device-preflight-LHFLPVAB.js → device-preflight-73KVSHZG.js} +1 -1
- package/dist/_chunks/{devices-inventory-I2E3Q4DA.js → devices-inventory-E6TE4H7T.js} +1 -1
- package/dist/_chunks/{devices-main-VV2VYU4T.js → devices-main-7JHMJNGV.js} +1 -1
- package/dist/_chunks/{files-TTIQ7LYJ.js → files-72BEXD7E.js} +1 -1
- package/dist/_chunks/{host-main-3JFGVU5P.js → host-main-KDORT44Q.js} +1 -1
- package/dist/_chunks/http-profile-QINBH2FP.js +1 -0
- package/dist/_chunks/{library-main-CTBW7DAI.js → library-main-AWUEMZFQ.js} +1 -1
- package/dist/_chunks/local-main-BNFNAPRG.js +1 -0
- package/dist/_chunks/{local-mcp-XB6E3V2W.js → local-mcp-HU6MII3G.js} +1 -1
- package/dist/_chunks/main-BSMCHALI.js +2 -0
- package/dist/_chunks/mcp-3VZZFXNG.js +1 -0
- package/dist/_chunks/oauth-QBJ62PIA.js +1 -0
- package/dist/_chunks/observe-entry-D7F6OQ7Y.js +1 -0
- package/dist/_chunks/remote-client-XIJ6RQLU.js +1 -0
- package/dist/_chunks/{render-main-VTM6WGFP.js → render-main-O3IN6EFV.js} +1 -1
- package/dist/_chunks/{source-import-KKV2UWJO.js → source-import-Y2Z3BVWY.js} +1 -1
- package/dist/_chunks/src-3S6CAUSJ.js +1 -0
- package/dist/_chunks/{stdio-main-Y7N4NVKU.js → stdio-main-T4WMBNKB.js} +1 -1
- package/dist/_chunks/workspace-main-KWFTVTZG.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +1 -1
- package/dist/_types/cli/local/desktop-device-contract.d.ts +2 -2
- package/dist/_types/cli/local/desktop-device-owner.d.ts +1 -1
- package/dist/_types/cli/local/desktop-owner.d.ts +1 -1
- package/dist/_types/contracts/index.d.ts +2 -0
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +15 -0
- package/dist/_types/contracts/lifecycle-events.d.ts +53 -1
- package/dist/_types/contracts/production-feedback.d.ts +452 -0
- package/dist/_types/contracts/shares.d.ts +135 -0
- package/dist/_types/contracts/workspace.d.ts +21 -0
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/dist/native/helper.exe +0 -0
- package/dist/native/helper.json +1 -0
- package/package.json +1 -1
- package/dist/_chunks/chunk-5DY7LSZZ.js +0 -1
- package/dist/_chunks/chunk-6LU6GJKW.js +0 -1
- package/dist/_chunks/chunk-77IAHNM2.js +0 -1
- package/dist/_chunks/chunk-FU3524Z6.js +0 -1
- package/dist/_chunks/chunk-HY7NXJYX.js +0 -1
- package/dist/_chunks/chunk-KB2GVAN7.js +0 -1
- package/dist/_chunks/chunk-PUNG4ND7.js +0 -1
- package/dist/_chunks/chunk-SV3NF7GO.js +0 -1
- package/dist/_chunks/chunk-TLPI6P7L.js +0 -1
- package/dist/_chunks/chunk-ZRSYOFMX.js +0 -1
- package/dist/_chunks/http-profile-NIQDCFPU.js +0 -1
- package/dist/_chunks/local-main-227MNGEC.js +0 -1
- package/dist/_chunks/main-W6NNZFLK.js +0 -2
- package/dist/_chunks/mcp-EXQ5UAHB.js +0 -1
- package/dist/_chunks/oauth-HC6TI7HB.js +0 -1
- package/dist/_chunks/src-OIY5TBQT.js +0 -1
- package/dist/_chunks/workspace-main-Y7ZVBRJJ.js +0 -1
- package/dist/native/Bootstrap.ps1 +0 -90
- package/dist/native/JobNative.cs +0 -137
- package/dist/native/JobRunner.cs +0 -381
- package/dist/native/NativeMain.cs +0 -161
- package/dist/native/PipeBridge.cs +0 -260
- package/dist/native/PrivateAccess.cs +0 -152
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NativeStudioLocalRuntimeClient,catalogue}from"./chunk-
|
|
1
|
+
import{NativeStudioLocalRuntimeClient,catalogue}from"./chunk-H6EZKOYR.js";import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalLibraryGetSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalMcpOutputSchemas}from"./chunk-PDQYFIQQ.js";import{fail,optional}from"./chunk-RUPH3HZ2.js";import{z}from"zod";import{join}from"node:path";var localTools={local_library_list:{description:"Read bounded metadata projections of this device library in an explicitly authorized Project. No paths, bytes, import or native admission.",input:LocalLibraryProjectionQuerySchema},local_library_get:{description:"Read metadata for one exact authorized local-file version. This does not inspect/decode bytes or create a Job.",input:LocalLibraryGetSchema.omit({ownerKey:true})},local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalExecutionInspectInputSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home,library=false){this.client=client;this.home=home;this.library=library}client;home;library;static async open(connector,home,library=false){const client=await NativeStudioLocalRuntimeClient.fromConnector(connector);let enabled=false;if(library){try{enabled=(await client.library.capability()).available}catch{}}return new _LocalMcpTools(client,home,enabled)}get names(){return Object.keys(localTools).filter(name=>this.library||!name.startsWith("local_library_"))}schema(name){if(!this.names.includes(name))fail("CAPABILITY_UNAVAILABLE");return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"output",reused:"ref"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_library_list"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",...LocalLibraryProjectionPageSchema.parse(await this.client.library.call({...input,action:"scoped-list"},signal))}}if(name==="local_library_get"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",item:await this.client.library.call({...input,action:"scoped-get"},signal)}}if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal,true)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,...status.deviceAuthority?{deviceAuthority:status.deviceAuthority}:{},groups:[...this.library?[{id:"library",label:"Scoped local media metadata",tools:["local_library_list","local_library_get"]}]:[],{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalExecutionInspectInputSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,isAbsolute}from"node:path";var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory2=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/cli/package.json")));const read2=async(name,maximum)=>{const path=join(directory2,name),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size<1||stat.size>maximum)throw Error("WINDOWS_HELPER_INVALID");const bytes2=await readFile(path);if(bytes2.length!==stat.size)throw Error("WINDOWS_HELPER_INVALID");return bytes2};const m=JSON.parse((await read2("helper.json",4096)).toString());const bytes=await read2("helper.exe",2*1024*1024);if(m.protocol!=="NVS_WINDOWS_HELPER_V1"||m.format!=="PE_AMD64_NETFRAMEWORK48"||m.byteSize!==bytes.length||!/^[a-f0-9]{64}$/.test(m.sha256)||createHash("sha256").update(bytes).digest("hex")!==m.sha256)throw Error("WINDOWS_HELPER_INVALID");return realpath(join(directory2,"helper.exe"))}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}async function syncDirectory(path){if(process.platform==="win32")return;const d=await open(path,"r");try{await d.sync()}finally{await d.close()}}async function atomicMove(source,target,exclusive=false){if(dirname(source)!==dirname(target))throw Error("LOCAL_ATOMIC_MOVE_INVALID");if(process.platform==="win32"){try{await windowsRequest({operation:"move",source,target,exclusive})}catch(error){if(error.message==="EXISTS")throw Object.assign(Error("EXISTS"),{code:"EEXIST"});throw error}}else{if(exclusive){await link(source,target);await unlink(source)}else await rename(source,target);await syncDirectory(dirname(target))}}async function assertExecutable(path){const s=await lstat2(path);if(!isAbsolute2(path)||!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw Error("LOCAL_EXECUTABLE_INVALID");if(process.platform==="win32"){if(!path.toLowerCase().endsWith(".exe"))throw Error("LOCAL_EXECUTABLE_INVALID");await windowsRequest({operation:"executable",path})}else if(!(s.mode&73)||s.mode&18)throw Error("LOCAL_EXECUTABLE_INVALID")}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{constants}from"node:fs";import{open as open2,realpath as realpath2,rename as rename2,unlink as unlink2,link as link2,readdir}from"node:fs/promises";import{isAbsolute as isAbsolute3,join as join3,dirname as dirname2}from"node:path";import{randomUUID as randomUUID2,createHash as createHash3}from"node:crypto";var sha256=v=>createHash3("sha256").update(v).digest("hex");var sha512=v=>createHash3("sha512").update(v).digest("hex");var LocalClientError=class extends Error{constructor(code){super("NativeStudio local "+code);this.code=code}code};function fail(code){throw new LocalClientError(code)}async function directory(path){if(!isAbsolute3(path))fail("LOCATION_UNSUPPORTED");try{await privateDirectory(path,true)}catch{fail("PRIVATE_LOCATION_REQUIRED")}const root=await realpath2(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))fail("PRIVATE_LOCATION_REQUIRED");return root}async function read(path,maximum=65536,ledger=false){try{await privateAccess(path,"file")}catch(e){if(e.code==="ENOENT")throw e;fail("PRIVATE_FILE_REQUIRED")}const f=await open2(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const s=await f.stat();if(!s.isFile()||process.platform!=="win32"&&(s.uid!==process.getuid?.()||s.mode&63)||s.size>maximum||(ledger?s.nlink>2:s.nlink!==1))fail("PRIVATE_FILE_REQUIRED");const bytes=Buffer.alloc(Math.min(maximum+1,s.size+1));let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>s.size)fail("FILE_CHANGED");if(used>maximum)fail("FILE_LIMIT");return bytes.subarray(0,used)}finally{await f.close()}}async function write(path,value,exclusive=false){const temporary=join3(dirname2(path),".tmp-"+randomUUID2());const f=await open2(temporary,"wx",384);try{await f.writeFile(value);await f.sync()}finally{await f.close()}try{if(process.platform==="win32")await atomicMove(temporary,path,exclusive);else if(exclusive)await link2(temporary,path);else{try{await read(path,64*1024*1024)}catch(e){if(e.code!=="ENOENT")throw e}await rename2(temporary,path)}}finally{await unlink2(temporary).catch(e=>{if(e.code!=="ENOENT")throw e})}await syncDirectory(dirname2(path))}async function entries(path){const values=await readdir(path);if(values.length>1e4)fail("HISTORY_LIMIT");return values}async function optional(path){try{return JSON.parse((await read(path)).toString())}catch(e){if(e.code==="ENOENT")return null;throw e}}async function verifyBackup(path,stateDirectory){const base=await realpath2(join3(stateDirectory,"backups")),actual=await realpath2(path);if(dirname2(actual)!==base||!/[0-9a-f-]{36}\.sqlite$/.test(actual))fail("JOURNAL_BACKUP_REQUIRED");try{await privateAccess(actual,"file")}catch{fail("JOURNAL_BACKUP_REQUIRED")}const f=await open2(actual,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await f.stat(),header=Buffer.alloc(16);if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size<100)fail("JOURNAL_BACKUP_REQUIRED");const n=await f.read(header,0,16,0);if(n.bytesRead!==16||header.toString()!=="SQLite format 3\0")fail("JOURNAL_BACKUP_REQUIRED")}finally{await f.close()}}export{localSocketPath,privateAccess,privateDirectory,atomicMove,assertExecutable,sha256,sha512,LocalClientError,fail,directory,read,write,entries,optional,verifyBackup};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{tenantConnection}from"./chunk-AAGFHT2D.js";import{FileOAuthProvider,withProfileLock}from"./chunk-SKAVQ4UW.js";import{remoteResponse,secureEndpoint}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";async function apiMetadata(url,signal){let response;try{response=await remoteResponse(url,{headers:{accept:"application/json"},signal:signal?AbortSignal.any([signal,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)});if(!response.ok)return void 0;const parts=[];let size=0;for await(const part of response.body??[]){size+=part.byteLength;if(size>16384)return void 0;parts.push(part)}const data=JSON.parse(Buffer.concat(parts).toString());return data&&typeof data==="object"&&!Array.isArray(data)?data:void 0}catch{signal?.throwIfAborted();return void 0}finally{await response?.body?.cancel().catch(()=>{})}}async function profileHttpOrigin(path,resource,signal){signal?.throwIfAborted();return withProfileLock(path,async()=>{const provider=await FileOAuthProvider.load(path);signal?.throwIfAborted();const deny=()=>{throw new NativeStudioSdkError("API_ORIGIN_UNTRUSTED","BLOCKED","NO_WRITE")};if(provider.data.resource!==resource)deny();if(provider.data.pendingExchange)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");tenantConnection(resource);const endpoint=secureEndpoint(resource);const metadataUrl=endpoint.origin+"/.well-known/oauth-protected-resource"+endpoint.pathname;const fresh=await apiMetadata(metadataUrl,signal);signal?.throwIfAborted();if(fresh&&fresh.resource!==resource)deny();const metadata=fresh??provider.data.discovery?.resourceMetadata;const configured=metadata?.nativestudio_api_origin;if(configured===void 0){if(fresh&&provider.data.discovery){const saved={...provider.data.discovery.resourceMetadata,resource};Reflect.deleteProperty(saved,"nativestudio_api_origin");provider.data.discovery.resourceMetadata=saved;provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return endpoint.origin}try{if(typeof configured!=="string")return deny();const sourceUrl=metadata===fresh?metadataUrl:provider.data.discovery?.resourceMetadataUrl;if(typeof sourceUrl!=="string"||secureEndpoint(sourceUrl).origin!==endpoint.origin||metadata?.resource!==resource||configured.length>2048)deny();const api=secureEndpoint(configured);if(api.pathname!=="/"||endpoint.protocol==="https:"&&api.protocol!=="https:")deny();if(metadata===fresh&&provider.data.discovery){provider.data.discovery.resourceMetadata={...provider.data.discovery.resourceMetadata,resource,nativestudio_api_origin:api.origin};provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return api.origin}catch{return deny()}})}export{profileHttpOrigin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{privateAccess,privateDirectory,write}from"./chunk-RUPH3HZ2.js";import{secureEndpoint}from"./chunk-KOCUZ3AE.js";import{randomBytes}from"node:crypto";import{open,unlink,constants}from"node:fs/promises";import{dirname,resolve}from"node:path";var FileOAuthProvider=class _FileOAuthProvider{constructor(path,data){this.path=path;this.data=data}path;data;static async create(path,resource,redirect,scope){secureEndpoint(resource);secureEndpoint(redirect);if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const data={version:1,resource,redirect,scope,state:randomBytes(24).toString("base64url")};await write(resolve(path),JSON.stringify(data),true);return new _FileOAuthProvider(path,data)}static async load(path){if(process.platform==="win32")await privateAccess(resolve(path),"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let data;try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&63)!==0)||stat.size>65536)throw Error();const bytes=Buffer.alloc(65537);const{bytesRead}=await file.read(bytes,0,bytes.length,0);if(bytesRead>65536)throw Error();data=JSON.parse(bytes.subarray(0,bytesRead).toString("utf8"))}finally{await file.close()}if(![1,2].includes(data.version)||typeof data.state!=="string"||data.state.length<16)throw Error();if(data.pendingExchange!==void 0&&!["CODE","REFRESH"].includes(data.pendingExchange))throw Error();if(data.version===2!==(data.pendingExchange!==void 0))throw Error();secureEndpoint(data.resource);secureEndpoint(data.redirect);if(!["nvs:read","nvs:read nvs:write"].includes(data.scope))throw Error();return new _FileOAuthProvider(path,data)}async save(){if(process.platform==="win32")await privateDirectory(dirname(resolve(this.path)));await write(resolve(this.path),JSON.stringify(this.data))}get redirectUrl(){return this.data.redirect}get clientMetadata(){return{client_name:"NativeStudio CLI",redirect_uris:[this.data.redirect],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],scope:this.data.scope,application_type:"native"}}state(){return this.data.state}clientInformation(){return this.data.client}async saveClientInformation(value){this.data.client=value;await this.save()}tokens(){return this.data.token}async saveTokens(value){const metadataOnly=this.data.pendingExchange==="REFRESH"&&value.access_token===this.data.token?.access_token&&value.refresh_token===this.data.token?.refresh_token;this.data.token=value;if(!metadataOnly){this.data.expiresAt=Date.now()+(value.expires_in??600)*1e3;this.data.version=1;delete this.data.pendingExchange}await this.save()}async redirectToAuthorization(url){this.data.authorizationUrl=url.href;await this.save()}async saveCodeVerifier(value){this.data.verifier=value;await this.save()}codeVerifier(){if(!this.data.verifier)throw Error();return this.data.verifier}async saveDiscoveryState(value){this.data.discovery=value;await this.save()}discoveryState(){return this.data.discovery}};async function withProfileLock(path,action){if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const file=await open(path+".lock","wx",384);try{return await action()}finally{await file.close();await unlink(path+".lock")}}export{FileOAuthProvider,withProfileLock};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{desktopAutomation,desktopInstallationIdentity}from"./chunk-
|
|
1
|
+
import{desktopAutomation,desktopInstallationIdentity}from"./chunk-OVIR77ET.js";import{LocalInstallationManager,ownerClient,socketAbsent}from"./chunk-BX2SNMA4.js";import{LocalLibraryCallSchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryReferenceSchema,LocalLibraryUsageSchema}from"./chunk-PDQYFIQQ.js";import{LocalClientError,fail}from"./chunk-RUPH3HZ2.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{z}from"zod";import{isAbsolute}from"node:path";import{constants}from"node:fs";import{open}from"node:fs/promises";import{createHash}from"node:crypto";var same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs;async function captureLibraryImport(path,seed){const file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});try{const before=await file2.stat(),hash=createHash("sha256");if(!before.isFile()||before.size>128*1024*1024)fail("LOCAL_LIBRARY_FILE_INVALID");let size=0;for await(const bytes of file2.createReadStream({autoClose:false,start:0})){size+=bytes.length;if(size>before.size)fail("LOCAL_LIBRARY_FILE_CHANGED");hash.update(bytes)}if(size!==before.size||!same(before,await file2.stat()))fail("LOCAL_LIBRARY_FILE_CHANGED");const{tenantId,projectId,deviceId,contentType,...fields}=seed;return LocalLibraryImportSchema.parse({...fields,reference:{tenantId,projectId,deviceId,fileId:seed.requestId,versionId:seed.requestId,contentType,byteSize:size,checksumSha256:hash.digest("hex")}})}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")}finally{await file2.close()}}async function importLibraryFile(library,path,raw){const input=LocalLibraryImportSchema.parse(raw),file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});let dispatched=false;try{const before=await file2.stat();if(!before.isFile()||before.size!==input.reference.byteSize)fail("LOCAL_LIBRARY_FILE_CHANGED");dispatched=true;const result=await library.import(input,file2.createReadStream({autoClose:false,start:0}));if(!same(before,await file2.stat()))fail("LOCAL_LIBRARY_IMPORT_UNKNOWN");return result}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_IMPORT_UNAVAILABLE","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{await file2.close()}}var file=z.string().min(1).max(4096).refine(isAbsolute);var DesktopLibraryImportSeedSchema=LocalLibraryImportSchema.omit({reference:true}).extend({...LocalLibraryReferenceSchema.pick({tenantId:true,projectId:true,deviceId:true,contentType:true}).shape});var DesktopLibraryRequestSchema=z.strictObject({operation:z.literal("library"),call:LocalLibraryCallSchema});var DesktopLibraryImportRequestSchema=z.strictObject({operation:z.literal("library-import"),input:LocalLibraryImportSchema,file});var DesktopLibraryPrepareRequestSchema=z.strictObject({operation:z.literal("library-import-prepare"),seed:DesktopLibraryImportSeedSchema,file});var DesktopLibraryMediaRequestSchema=z.strictObject({operation:z.literal("library-media"),input:LocalLibraryGetSchema,method:z.enum(["GET","HEAD"]).default("GET"),range:z.string().min(1).max(100).optional()});var DesktopLibraryReplySchema=z.union([LocalLibraryItemSchema.nullable(),LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryUsageSchema,LocalLibraryReadReplySchema]);async function client(home){const manager=await LocalInstallationManager.open(home),config=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(config.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}return ownerClient(config.stateDirectory)}async function runDesktopLibraryRequest(home,raw){const input=DesktopLibraryRequestSchema.parse(raw);return(await client(home)).library.call(input.call)}async function prepareDesktopLibraryImport(raw){const input=DesktopLibraryPrepareRequestSchema.parse(raw);return DesktopLibraryImportRequestSchema.parse({operation:"library-import",file:input.file,input:await captureLibraryImport(input.file,input.seed)})}async function runDesktopLibraryImport(home,raw){const input=DesktopLibraryImportRequestSchema.parse(raw);return importLibraryFile((await client(home)).library,input.file,input.input)}async function runDesktopLibraryMedia(home,raw){const input=DesktopLibraryMediaRequestSchema.parse(raw);return(await client(home)).library.media(input.input,{method:input.method,...input.range?{range:input.range}:{}})}export{DesktopLibraryImportSeedSchema,DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryReplySchema,runDesktopLibraryRequest,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{privateAccess}from"./chunk-RUPH3HZ2.js";import{open,constants}from"node:fs/promises";import{resolve}from"node:path";var limit=18*1024*1024;async function readInput(path,stdin,privateInput=false,signal){let bytes;if(path==="-"){const chunks=[];let size=0;const iterator=stdin[Symbol.asyncIterator]();try{while(true){signal?.throwIfAborted();let stopped;const pending=iterator.next();if(signal?.aborted){void pending.catch(()=>{});signal.throwIfAborted()}const next=signal?await Promise.race([pending,new Promise((_,reject)=>{stopped=()=>reject(signal.reason);signal.addEventListener("abort",stopped,{once:true})})]).finally(()=>{if(stopped)signal.removeEventListener("abort",stopped)}):await pending;if(next.done)break;size+=next.value.byteLength;if(size>limit)throw Error();chunks.push(Buffer.from(next.value))}}finally{void iterator.return?.().catch(()=>{})}bytes=Buffer.concat(chunks)}else{if(privateInput&&process.platform==="win32")await privateAccess(resolve(path),"file");const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>limit||privateInput&&process.platform!=="win32"&&((stat.mode&63)!==0||process.getuid&&stat.uid!==process.getuid()))throw Error();bytes=Buffer.alloc(limit+1);let used=0;while(used<bytes.byteLength){const read=await handle.read(bytes,used,bytes.byteLength-used,null);if(!read.bytesRead)break;used+=read.bytesRead}if(used>limit)throw Error();bytes=bytes.subarray(0,used)}finally{await handle.close()}}const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();return value}async function readCredential(options,environment){if(options.has("--token-file")===options.has("--token-env"))throw Error();let token;const key=options.get("--token-env");if(key){if(!/^[A-Z][A-Z0-9_]{0,127}$/.test(key))throw Error();token=environment[key]??""}else{if(process.platform==="win32")await privateAccess(resolve(options.get("--token-file")),"file");const handle=await open(options.get("--token-file"),constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||process.platform!=="win32"&&(stat.mode&63)!==0||stat.size>8192)throw Error();const bytes=Buffer.alloc(8193);const{bytesRead}=await handle.read(bytes,0,bytes.length,0);if(bytesRead>8192)throw Error();token=bytes.subarray(0,bytesRead).toString("utf8").trim()}finally{await handle.close()}}if(!/^[A-Za-z0-9._~-]{1,8192}$/.test(token))throw Error();return"Bearer "+token}export{readInput,readCredential};
|